blob: 5a6891d01abb17f5eea2915d9c98cfe0db86f381 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataeve3727102018-04-18 15:57:46 +000038static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000039 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000045enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000049};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000057/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000058/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000059class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataeve3727102018-04-18 15:57:46 +000061 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000062 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000064 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000065 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000071 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000073 };
Alexey Bataeve3727102018-04-18 15:57:46 +000074 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000076 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000078
Alexey Bataev758e55e2013-09-06 18:03:48 +000079private:
Alexey Bataeve3727102018-04-18 15:57:46 +000080 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000081 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000084 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000085 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086 };
Alexey Bataeve3727102018-04-18 15:57:46 +000087 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000092 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
Alexey Bataeve3727102018-04-18 15:57:46 +000098 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118
Alexey Bataeve3727102018-04-18 15:57:46 +0000119 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000121 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000122 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000123 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000124 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000126 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000129 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000137 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000141 unsigned AssociatedLoops = 1;
142 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000143 bool NowaitRegion = false;
144 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000145 bool LoopStart = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000146 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000147 /// Reference to the taskgroup task_reduction reference expression.
148 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000149 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeved09d242014-05-28 05:53:51 +0000150 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000151 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000152 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
153 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000154 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000155 };
156
Alexey Bataeve3727102018-04-18 15:57:46 +0000157 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000158
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000159 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000160 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000161 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
162 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000163 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000164 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000165 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000166 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000167 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000168 /// true if all the vaiables in the target executable directives must be
169 /// captured by reference.
170 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000171 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000172
Alexey Bataeve3727102018-04-18 15:57:46 +0000173 using iterator = StackTy::const_reverse_iterator;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000174
Alexey Bataeve3727102018-04-18 15:57:46 +0000175 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
Alexey Bataevec3da872014-01-31 05:15:34 +0000176
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000177 /// Checks if the variable is a local for OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000178 bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
Alexey Bataeved09d242014-05-28 05:53:51 +0000179
Alexey Bataev4b465392017-04-26 15:06:24 +0000180 bool isStackEmpty() const {
181 return Stack.empty() ||
182 Stack.back().second != CurrentNonCapturingFunctionScope ||
183 Stack.back().first.empty();
184 }
185
Kelvin Li1408f912018-09-26 04:28:39 +0000186 /// Vector of previously declared requires directives
187 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
188
Alexey Bataev758e55e2013-09-06 18:03:48 +0000189public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000190 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000191
Alexey Bataevaac108a2015-06-23 04:51:00 +0000192 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000193 OpenMPClauseKind getClauseParsingMode() const {
194 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
195 return ClauseKindMode;
196 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000197 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000198
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000199 bool isForceVarCapturing() const { return ForceCapturing; }
200 void setForceVarCapturing(bool V) { ForceCapturing = V; }
201
Alexey Bataev60705422018-10-30 15:50:12 +0000202 void setForceCaptureByReferenceInTargetExecutable(bool V) {
203 ForceCaptureByReferenceInTargetExecutable = V;
204 }
205 bool isForceCaptureByReferenceInTargetExecutable() const {
206 return ForceCaptureByReferenceInTargetExecutable;
207 }
208
Alexey Bataev758e55e2013-09-06 18:03:48 +0000209 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000210 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000211 if (Stack.empty() ||
212 Stack.back().second != CurrentNonCapturingFunctionScope)
213 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
214 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
215 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000216 }
217
218 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000219 assert(!Stack.back().first.empty() &&
220 "Data-sharing attributes stack is empty!");
221 Stack.back().first.pop_back();
222 }
223
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000224 /// Marks that we're started loop parsing.
225 void loopInit() {
226 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
227 "Expected loop-based directive.");
228 Stack.back().first.back().LoopStart = true;
229 }
230 /// Start capturing of the variables in the loop context.
231 void loopStart() {
232 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
233 "Expected loop-based directive.");
234 Stack.back().first.back().LoopStart = false;
235 }
236 /// true, if variables are captured, false otherwise.
237 bool isLoopStarted() const {
238 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
239 "Expected loop-based directive.");
240 return !Stack.back().first.back().LoopStart;
241 }
242 /// Marks (or clears) declaration as possibly loop counter.
243 void resetPossibleLoopCounter(const Decl *D = nullptr) {
244 Stack.back().first.back().PossiblyLoopCounter =
245 D ? D->getCanonicalDecl() : D;
246 }
247 /// Gets the possible loop counter decl.
248 const Decl *getPossiblyLoopCunter() const {
249 return Stack.back().first.back().PossiblyLoopCounter;
250 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000251 /// Start new OpenMP region stack in new non-capturing function.
252 void pushFunction() {
253 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
254 assert(!isa<CapturingScopeInfo>(CurFnScope));
255 CurrentNonCapturingFunctionScope = CurFnScope;
256 }
257 /// Pop region stack for non-capturing function.
258 void popFunction(const FunctionScopeInfo *OldFSI) {
259 if (!Stack.empty() && Stack.back().second == OldFSI) {
260 assert(Stack.back().first.empty());
261 Stack.pop_back();
262 }
263 CurrentNonCapturingFunctionScope = nullptr;
264 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
265 if (!isa<CapturingScopeInfo>(FSI)) {
266 CurrentNonCapturingFunctionScope = FSI;
267 break;
268 }
269 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000270 }
271
Alexey Bataeve3727102018-04-18 15:57:46 +0000272 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000273 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000274 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000275 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000276 getCriticalWithHint(const DeclarationNameInfo &Name) const {
277 auto I = Criticals.find(Name.getAsString());
278 if (I != Criticals.end())
279 return I->second;
280 return std::make_pair(nullptr, llvm::APSInt());
281 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000282 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000283 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000284 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000285 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000286
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000287 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000288 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000289 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000290 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000291 /// \return The index of the loop control variable in the list of associated
292 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000293 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000294 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000295 /// parent region.
296 /// \return The index of the loop control variable in the list of associated
297 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000298 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000299 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000300 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000301 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000302
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000303 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000304 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000305 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000306
Alexey Bataevfa312f32017-07-21 18:48:21 +0000307 /// Adds additional information for the reduction items with the reduction id
308 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000309 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000310 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000311 /// Adds additional information for the reduction items with the reduction id
312 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000313 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000314 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000315 /// Returns the location and reduction operation from the innermost parent
316 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000317 const DSAVarData
318 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
319 BinaryOperatorKind &BOK,
320 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000321 /// Returns the location and reduction operation from the innermost parent
322 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000323 const DSAVarData
324 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
325 const Expr *&ReductionRef,
326 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000327 /// Return reduction reference expression for the current taskgroup.
328 Expr *getTaskgroupReductionRef() const {
329 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
330 "taskgroup reference expression requested for non taskgroup "
331 "directive.");
332 return Stack.back().first.back().TaskgroupReductionRef;
333 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000334 /// Checks if the given \p VD declaration is actually a taskgroup reduction
335 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000336 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Alexey Bataev88202be2017-07-27 13:20:36 +0000337 return Stack.back().first[Level].TaskgroupReductionRef &&
338 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
339 ->getDecl() == VD;
340 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000341
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000342 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000343 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000344 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000345 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000346 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000347 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000348 /// match specified \a CPred predicate in any directive which matches \a DPred
349 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000350 const DSAVarData
351 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
352 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
353 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000354 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000355 /// match specified \a CPred predicate in any innermost directive which
356 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000357 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000358 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000359 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
360 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000361 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000362 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000363 /// attributes which match specified \a CPred predicate at the specified
364 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000365 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000366 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000367 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000368
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000369 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000370 /// specified \a DPred predicate.
371 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000372 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000373 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000374
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000375 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000376 bool hasDirective(
377 const llvm::function_ref<bool(
378 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
379 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000380 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000382 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000383 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000384 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000385 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000386 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000387 OpenMPDirectiveKind getDirective(unsigned Level) const {
388 assert(!isStackEmpty() && "No directive at specified level.");
389 return Stack.back().first[Level].Directive;
390 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000391 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000392 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000393 if (isStackEmpty() || Stack.back().first.size() == 1)
394 return OMPD_unknown;
395 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000396 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000397
Kelvin Li1408f912018-09-26 04:28:39 +0000398 /// Add requires decl to internal vector
399 void addRequiresDecl(OMPRequiresDecl *RD) {
400 RequiresDecls.push_back(RD);
401 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000402
Kelvin Li1408f912018-09-26 04:28:39 +0000403 /// Checks for a duplicate clause amongst previously declared requires
404 /// directives
405 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
406 bool IsDuplicate = false;
407 for (OMPClause *CNew : ClauseList) {
408 for (const OMPRequiresDecl *D : RequiresDecls) {
409 for (const OMPClause *CPrev : D->clauselists()) {
410 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
411 SemaRef.Diag(CNew->getBeginLoc(),
412 diag::err_omp_requires_clause_redeclaration)
413 << getOpenMPClauseName(CNew->getClauseKind());
414 SemaRef.Diag(CPrev->getBeginLoc(),
415 diag::note_omp_requires_previous_clause)
416 << getOpenMPClauseName(CPrev->getClauseKind());
417 IsDuplicate = true;
418 }
419 }
420 }
421 }
422 return IsDuplicate;
423 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000425 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000426 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000427 assert(!isStackEmpty());
428 Stack.back().first.back().DefaultAttr = DSA_none;
429 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000430 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000431 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000432 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000433 assert(!isStackEmpty());
434 Stack.back().first.back().DefaultAttr = DSA_shared;
435 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000436 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000437 /// Set default data mapping attribute to 'tofrom:scalar'.
438 void setDefaultDMAToFromScalar(SourceLocation Loc) {
439 assert(!isStackEmpty());
440 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
441 Stack.back().first.back().DefaultMapAttrLoc = Loc;
442 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000443
444 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000445 return isStackEmpty() ? DSA_unspecified
446 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000448 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000449 return isStackEmpty() ? SourceLocation()
450 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000451 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000452 DefaultMapAttributes getDefaultDMA() const {
453 return isStackEmpty() ? DMA_unspecified
454 : Stack.back().first.back().DefaultMapAttr;
455 }
456 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
457 return Stack.back().first[Level].DefaultMapAttr;
458 }
459 SourceLocation getDefaultDMALocation() const {
460 return isStackEmpty() ? SourceLocation()
461 : Stack.back().first.back().DefaultMapAttrLoc;
462 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000463
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000464 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000465 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000466 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000467 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000468 }
469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000470 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000471 void setOrderedRegion(bool IsOrdered, const Expr *Param,
472 OMPOrderedClause *Clause) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000473 assert(!isStackEmpty());
Alexey Bataevf138fda2018-08-13 19:04:24 +0000474 if (IsOrdered)
475 Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
476 else
477 Stack.back().first.back().OrderedRegion.reset();
478 }
479 /// Returns true, if region is ordered (has associated 'ordered' clause),
480 /// false - otherwise.
481 bool isOrderedRegion() const {
482 if (isStackEmpty())
483 return false;
484 return Stack.back().first.rbegin()->OrderedRegion.hasValue();
485 }
486 /// Returns optional parameter for the ordered region.
487 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
488 if (isStackEmpty() ||
489 !Stack.back().first.rbegin()->OrderedRegion.hasValue())
490 return std::make_pair(nullptr, nullptr);
491 return Stack.back().first.rbegin()->OrderedRegion.getValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000492 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000494 /// 'ordered' clause), false - otherwise.
495 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000496 if (isStackEmpty() || Stack.back().first.size() == 1)
497 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000498 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000499 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000500 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000501 std::pair<const Expr *, OMPOrderedClause *>
502 getParentOrderedRegionParam() const {
503 if (isStackEmpty() || Stack.back().first.size() == 1 ||
504 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
505 return std::make_pair(nullptr, nullptr);
506 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
Alexey Bataev346265e2015-09-25 10:37:12 +0000507 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000509 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000510 assert(!isStackEmpty());
511 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000512 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000513 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000514 /// 'nowait' clause), false - otherwise.
515 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000516 if (isStackEmpty() || Stack.back().first.size() == 1)
517 return false;
518 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000519 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000521 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000522 if (!isStackEmpty() && Stack.back().first.size() > 1) {
523 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
524 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
525 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000526 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000527 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000528 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000529 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000530 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000531
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000532 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000533 void setAssociatedLoops(unsigned Val) {
534 assert(!isStackEmpty());
535 Stack.back().first.back().AssociatedLoops = Val;
536 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000537 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000538 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000539 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000540 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000541
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000543 /// region.
544 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000545 if (!isStackEmpty() && Stack.back().first.size() > 1) {
546 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
547 TeamsRegionLoc;
548 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000549 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000550 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000551 bool hasInnerTeamsRegion() const {
552 return getInnerTeamsRegionLoc().isValid();
553 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000554 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000555 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000556 return isStackEmpty() ? SourceLocation()
557 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000558 }
559
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000560 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000561 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000562 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000563 SourceLocation getConstructLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000564 return isStackEmpty() ? SourceLocation()
565 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000566 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000567
Samuel Antao4c8035b2016-12-12 18:00:20 +0000568 /// Do the check specified in \a Check to all component lists and return true
569 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000570 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000571 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000572 const llvm::function_ref<
573 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000574 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000575 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000576 if (isStackEmpty())
577 return false;
578 auto SI = Stack.back().first.rbegin();
579 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000580
581 if (SI == SE)
582 return false;
583
Alexey Bataeve3727102018-04-18 15:57:46 +0000584 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000585 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000586 else
587 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000588
589 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000590 auto MI = SI->MappedExprComponents.find(VD);
591 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000592 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
593 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000594 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000595 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000596 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000597 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000598 }
599
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000600 /// Do the check specified in \a Check to all component lists at a given level
601 /// and return true if any issue is found.
602 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000603 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000604 const llvm::function_ref<
605 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000606 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000607 Check) const {
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000608 if (isStackEmpty())
609 return false;
610
611 auto StartI = Stack.back().first.begin();
612 auto EndI = Stack.back().first.end();
613 if (std::distance(StartI, EndI) <= (int)Level)
614 return false;
615 std::advance(StartI, Level);
616
617 auto MI = StartI->MappedExprComponents.find(VD);
618 if (MI != StartI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000619 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
620 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000621 if (Check(L, MI->second.Kind))
622 return true;
623 return false;
624 }
625
Samuel Antao4c8035b2016-12-12 18:00:20 +0000626 /// Create a new mappable expression component list associated with a given
627 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000628 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000629 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000630 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
631 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000632 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000633 "Not expecting to retrieve components from a empty stack!");
Alexey Bataeve3727102018-04-18 15:57:46 +0000634 MappedExprComponentTy &MEC =
635 Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000636 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000637 MEC.Components.resize(MEC.Components.size() + 1);
638 MEC.Components.back().append(Components.begin(), Components.end());
639 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000640 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000641
642 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000643 assert(!isStackEmpty());
644 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000645 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000646 void addDoacrossDependClause(OMPDependClause *C,
647 const OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000648 assert(!isStackEmpty() && Stack.back().first.size() > 1);
Alexey Bataeve3727102018-04-18 15:57:46 +0000649 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000650 assert(isOpenMPWorksharingDirective(StackElem.Directive));
Alexey Bataeve3727102018-04-18 15:57:46 +0000651 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000652 }
653 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
654 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000655 assert(!isStackEmpty());
Alexey Bataeve3727102018-04-18 15:57:46 +0000656 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000657 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000658 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000659 return llvm::make_range(Ref.begin(), Ref.end());
660 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000661 return llvm::make_range(StackElem.DoacrossDepends.end(),
662 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000663 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000664
665 // Store types of classes which have been explicitly mapped
666 void addMappedClassesQualTypes(QualType QT) {
667 SharingMapTy &StackElem = Stack.back().first.back();
668 StackElem.MappedClassesQualTypes.insert(QT);
669 }
670
671 // Return set of mapped classes types
672 bool isClassPreviouslyMapped(QualType QT) const {
673 const SharingMapTy &StackElem = Stack.back().first.back();
674 return StackElem.MappedClassesQualTypes.count(QT) != 0;
675 }
676
Alexey Bataev758e55e2013-09-06 18:03:48 +0000677};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000678
679bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
680 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
681}
682
683bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
684 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000685}
Alexey Bataeve3727102018-04-18 15:57:46 +0000686
Alexey Bataeved09d242014-05-28 05:53:51 +0000687} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000688
Alexey Bataeve3727102018-04-18 15:57:46 +0000689static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000690 if (const auto *FE = dyn_cast<FullExpr>(E))
691 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000692
Alexey Bataeve3727102018-04-18 15:57:46 +0000693 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000694 E = MTE->GetTemporaryExpr();
695
Alexey Bataeve3727102018-04-18 15:57:46 +0000696 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000697 E = Binder->getSubExpr();
698
Alexey Bataeve3727102018-04-18 15:57:46 +0000699 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000700 E = ICE->getSubExprAsWritten();
701 return E->IgnoreParens();
702}
703
Alexey Bataeve3727102018-04-18 15:57:46 +0000704static Expr *getExprAsWritten(Expr *E) {
705 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
706}
707
708static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
709 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
710 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000711 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000712 const auto *VD = dyn_cast<VarDecl>(D);
713 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000714 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000715 VD = VD->getCanonicalDecl();
716 D = VD;
717 } else {
718 assert(FD);
719 FD = FD->getCanonicalDecl();
720 D = FD;
721 }
722 return D;
723}
724
Alexey Bataeve3727102018-04-18 15:57:46 +0000725static ValueDecl *getCanonicalDecl(ValueDecl *D) {
726 return const_cast<ValueDecl *>(
727 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
728}
729
730DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
731 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000732 D = getCanonicalDecl(D);
733 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000734 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000735 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000736 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000737 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
738 // in a region but not in construct]
739 // File-scope or namespace-scope variables referenced in called routines
740 // in the region are shared unless they appear in a threadprivate
741 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000742 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000743 DVar.CKind = OMPC_shared;
744
745 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
746 // in a region but not in construct]
747 // Variables with static storage duration that are declared in called
748 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000749 if (VD && VD->hasGlobalStorage())
750 DVar.CKind = OMPC_shared;
751
752 // Non-static data members are shared by default.
753 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000754 DVar.CKind = OMPC_shared;
755
Alexey Bataev758e55e2013-09-06 18:03:48 +0000756 return DVar;
757 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000758
Alexey Bataevec3da872014-01-31 05:15:34 +0000759 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
760 // in a Construct, C/C++, predetermined, p.1]
761 // Variables with automatic storage duration that are declared in a scope
762 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000763 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
764 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000765 DVar.CKind = OMPC_private;
766 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000767 }
768
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000769 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000770 // Explicitly specified attributes and local variables with predetermined
771 // attributes.
772 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000773 const DSAInfo &Data = Iter->SharingMap.lookup(D);
774 DVar.RefExpr = Data.RefExpr.getPointer();
775 DVar.PrivateCopy = Data.PrivateCopy;
776 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000777 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000778 return DVar;
779 }
780
781 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
782 // in a Construct, C/C++, implicitly determined, p.1]
783 // In a parallel or task construct, the data-sharing attributes of these
784 // variables are determined by the default clause, if present.
785 switch (Iter->DefaultAttr) {
786 case DSA_shared:
787 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000788 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000789 return DVar;
790 case DSA_none:
791 return DVar;
792 case DSA_unspecified:
793 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
794 // in a Construct, implicitly determined, p.2]
795 // In a parallel construct, if no default clause is present, these
796 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000797 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000798 if (isOpenMPParallelDirective(DVar.DKind) ||
799 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000800 DVar.CKind = OMPC_shared;
801 return DVar;
802 }
803
804 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
805 // in a Construct, implicitly determined, p.4]
806 // In a task construct, if no default clause is present, a variable that in
807 // the enclosing context is determined to be shared by all implicit tasks
808 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000809 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000810 DSAVarData DVarTemp;
Alexey Bataeve3727102018-04-18 15:57:46 +0000811 iterator I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000812 do {
813 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000814 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000815 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000816 // In a task construct, if no default clause is present, a variable
817 // whose data-sharing attribute is not determined by the rules above is
818 // firstprivate.
819 DVarTemp = getDSA(I, D);
820 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000821 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000822 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000823 return DVar;
824 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000825 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000826 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000827 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000828 return DVar;
829 }
830 }
831 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
832 // in a Construct, implicitly determined, p.3]
833 // For constructs other than task, if no default clause is present, these
834 // variables inherit their data-sharing attributes from the enclosing
835 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000836 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000837}
838
Alexey Bataeve3727102018-04-18 15:57:46 +0000839const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
840 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000841 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000842 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000843 SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000844 auto It = StackElem.AlignedMap.find(D);
845 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000846 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000847 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000848 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000849 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000850 assert(It->second && "Unexpected nullptr expr in the aligned map");
851 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000852}
853
Alexey Bataeve3727102018-04-18 15:57:46 +0000854void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000855 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000856 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000857 SharingMapTy &StackElem = Stack.back().first.back();
858 StackElem.LCVMap.try_emplace(
859 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +0000860}
861
Alexey Bataeve3727102018-04-18 15:57:46 +0000862const DSAStackTy::LCDeclInfo
863DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000864 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000865 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000866 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000867 auto It = StackElem.LCVMap.find(D);
868 if (It != StackElem.LCVMap.end())
869 return It->second;
870 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000871}
872
Alexey Bataeve3727102018-04-18 15:57:46 +0000873const DSAStackTy::LCDeclInfo
874DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000875 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
876 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000877 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000878 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000879 auto It = StackElem.LCVMap.find(D);
880 if (It != StackElem.LCVMap.end())
881 return It->second;
882 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000883}
884
Alexey Bataeve3727102018-04-18 15:57:46 +0000885const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000886 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
887 "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000888 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000889 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000890 return nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +0000891 for (const auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000892 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000893 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000894 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000895}
896
Alexey Bataeve3727102018-04-18 15:57:46 +0000897void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000898 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000899 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000900 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000901 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000902 Data.Attributes = A;
903 Data.RefExpr.setPointer(E);
904 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000905 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000906 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000907 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000908 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
909 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
910 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
911 (isLoopControlVariable(D).first && A == OMPC_private));
912 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
913 Data.RefExpr.setInt(/*IntVal=*/true);
914 return;
915 }
916 const bool IsLastprivate =
917 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
918 Data.Attributes = A;
919 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
920 Data.PrivateCopy = PrivateCopy;
921 if (PrivateCopy) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000922 DSAInfo &Data =
923 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000924 Data.Attributes = A;
925 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
926 Data.PrivateCopy = nullptr;
927 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000928 }
929}
930
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000931/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000932static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000933 StringRef Name, const AttrVec *Attrs = nullptr,
934 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000935 DeclContext *DC = SemaRef.CurContext;
936 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
937 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +0000938 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000939 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
940 if (Attrs) {
941 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
942 I != E; ++I)
943 Decl->addAttr(*I);
944 }
945 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000946 if (OrigRef) {
947 Decl->addAttr(
948 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
949 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000950 return Decl;
951}
952
953static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
954 SourceLocation Loc,
955 bool RefersToCapture = false) {
956 D->setReferenced();
957 D->markUsed(S.Context);
958 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
959 SourceLocation(), D, RefersToCapture, Loc, Ty,
960 VK_LValue);
961}
962
Alexey Bataeve3727102018-04-18 15:57:46 +0000963void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000964 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000965 D = getCanonicalDecl(D);
966 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000967 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000968 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000969 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000970 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000971 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000972 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000973 "Additional reduction info may be specified only once for reduction "
974 "items.");
975 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000976 Expr *&TaskgroupReductionRef =
977 Stack.back().first.back().TaskgroupReductionRef;
978 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000979 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
980 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000981 TaskgroupReductionRef =
982 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000983 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000984}
985
Alexey Bataeve3727102018-04-18 15:57:46 +0000986void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000987 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000988 D = getCanonicalDecl(D);
989 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000990 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000991 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000992 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000993 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000994 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000995 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000996 "Additional reduction info may be specified only once for reduction "
997 "items.");
998 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000999 Expr *&TaskgroupReductionRef =
1000 Stack.back().first.back().TaskgroupReductionRef;
1001 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001002 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1003 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001004 TaskgroupReductionRef =
1005 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001006 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001007}
1008
Alexey Bataeve3727102018-04-18 15:57:46 +00001009const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1010 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1011 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001012 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001013 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1014 if (Stack.back().first.empty())
1015 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001016 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1017 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001018 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001019 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001020 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001021 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001022 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001023 if (!ReductionData.ReductionOp ||
1024 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001025 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001026 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001027 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001028 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1029 "expression for the descriptor is not "
1030 "set.");
1031 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001032 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1033 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001034 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001035 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001036}
1037
Alexey Bataeve3727102018-04-18 15:57:46 +00001038const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1039 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1040 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001041 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001042 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1043 if (Stack.back().first.empty())
1044 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001045 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1046 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001047 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001048 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001049 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001050 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001051 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001052 if (!ReductionData.ReductionOp ||
1053 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001054 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001055 SR = ReductionData.ReductionRange;
1056 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001057 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1058 "expression for the descriptor is not "
1059 "set.");
1060 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001061 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1062 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001063 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001064 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001065}
1066
Alexey Bataeve3727102018-04-18 15:57:46 +00001067bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001068 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +00001069 if (!isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001070 iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001071 Scope *TopScope = nullptr;
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001072 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
Alexey Bataev852525d2018-03-02 17:17:12 +00001073 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +00001074 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001075 if (I == E)
1076 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001077 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001078 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001079 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +00001080 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +00001081 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001082 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001083 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001084}
1085
Joel E. Dennyd2649292019-01-04 22:11:56 +00001086static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1087 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001088 bool *IsClassType = nullptr) {
1089 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001090 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001091 bool IsConstant = Type.isConstant(Context);
1092 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001093 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1094 ? Type->getAsCXXRecordDecl()
1095 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001096 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1097 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1098 RD = CTD->getTemplatedDecl();
1099 if (IsClassType)
1100 *IsClassType = RD;
1101 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1102 RD->hasDefinition() && RD->hasMutableFields());
1103}
1104
Joel E. Dennyd2649292019-01-04 22:11:56 +00001105static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1106 QualType Type, OpenMPClauseKind CKind,
1107 SourceLocation ELoc,
1108 bool AcceptIfMutable = true,
1109 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001110 ASTContext &Context = SemaRef.getASTContext();
1111 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001112 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1113 unsigned Diag = ListItemNotVar
1114 ? diag::err_omp_const_list_item
1115 : IsClassType ? diag::err_omp_const_not_mutable_variable
1116 : diag::err_omp_const_variable;
1117 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1118 if (!ListItemNotVar && D) {
1119 const VarDecl *VD = dyn_cast<VarDecl>(D);
1120 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1121 VarDecl::DeclarationOnly;
1122 SemaRef.Diag(D->getLocation(),
1123 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1124 << D;
1125 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001126 return true;
1127 }
1128 return false;
1129}
1130
Alexey Bataeve3727102018-04-18 15:57:46 +00001131const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1132 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001133 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001134 DSAVarData DVar;
1135
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001136 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001137 auto TI = Threadprivates.find(D);
1138 if (TI != Threadprivates.end()) {
1139 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001140 DVar.CKind = OMPC_threadprivate;
1141 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001142 }
1143 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001144 DVar.RefExpr = buildDeclRefExpr(
1145 SemaRef, VD, D->getType().getNonReferenceType(),
1146 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1147 DVar.CKind = OMPC_threadprivate;
1148 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001149 return DVar;
1150 }
1151 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1152 // in a Construct, C/C++, predetermined, p.1]
1153 // Variables appearing in threadprivate directives are threadprivate.
1154 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1155 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1156 SemaRef.getLangOpts().OpenMPUseTLS &&
1157 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1158 (VD && VD->getStorageClass() == SC_Register &&
1159 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1160 DVar.RefExpr = buildDeclRefExpr(
1161 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1162 DVar.CKind = OMPC_threadprivate;
1163 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1164 return DVar;
1165 }
1166 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1167 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1168 !isLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001169 iterator IterTarget =
Alexey Bataev852525d2018-03-02 17:17:12 +00001170 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1171 [](const SharingMapTy &Data) {
1172 return isOpenMPTargetExecutionDirective(Data.Directive);
1173 });
1174 if (IterTarget != Stack.back().first.rend()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001175 iterator ParentIterTarget = std::next(IterTarget, 1);
1176 for (iterator Iter = Stack.back().first.rbegin();
1177 Iter != ParentIterTarget; std::advance(Iter, 1)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001178 if (isOpenMPLocal(VD, Iter)) {
1179 DVar.RefExpr =
1180 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1181 D->getLocation());
1182 DVar.CKind = OMPC_threadprivate;
1183 return DVar;
1184 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001185 }
1186 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1187 auto DSAIter = IterTarget->SharingMap.find(D);
1188 if (DSAIter != IterTarget->SharingMap.end() &&
1189 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1190 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1191 DVar.CKind = OMPC_threadprivate;
1192 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001193 }
1194 iterator End = Stack.back().first.rend();
1195 if (!SemaRef.isOpenMPCapturedByRef(
1196 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001197 DVar.RefExpr =
1198 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1199 IterTarget->ConstructLoc);
1200 DVar.CKind = OMPC_threadprivate;
1201 return DVar;
1202 }
1203 }
1204 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001205 }
1206
Alexey Bataev4b465392017-04-26 15:06:24 +00001207 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001208 // Not in OpenMP execution region and top scope was already checked.
1209 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001210
Alexey Bataev758e55e2013-09-06 18:03:48 +00001211 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001212 // in a Construct, C/C++, predetermined, p.4]
1213 // Static data members are shared.
1214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1215 // in a Construct, C/C++, predetermined, p.7]
1216 // Variables with static storage duration that are declared in a scope
1217 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001218 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001219 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001220 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001221 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001222 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001223
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001224 DVar.CKind = OMPC_shared;
1225 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001226 }
1227
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001228 // The predetermined shared attribute for const-qualified types having no
1229 // mutable members was removed after OpenMP 3.1.
1230 if (SemaRef.LangOpts.OpenMP <= 31) {
1231 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1232 // in a Construct, C/C++, predetermined, p.6]
1233 // Variables with const qualified type having no mutable member are
1234 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001235 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001236 // Variables with const-qualified type having no mutable member may be
1237 // listed in a firstprivate clause, even if they are static data members.
1238 DSAVarData DVarTemp = hasInnermostDSA(
1239 D,
1240 [](OpenMPClauseKind C) {
1241 return C == OMPC_firstprivate || C == OMPC_shared;
1242 },
1243 MatchesAlways, FromParent);
1244 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1245 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001246
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001247 DVar.CKind = OMPC_shared;
1248 return DVar;
1249 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001250 }
1251
Alexey Bataev758e55e2013-09-06 18:03:48 +00001252 // Explicitly specified attributes and local variables with predetermined
1253 // attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00001254 iterator I = Stack.back().first.rbegin();
1255 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001256 if (FromParent && I != EndI)
1257 std::advance(I, 1);
Alexey Bataeve3727102018-04-18 15:57:46 +00001258 auto It = I->SharingMap.find(D);
1259 if (It != I->SharingMap.end()) {
1260 const DSAInfo &Data = It->getSecond();
1261 DVar.RefExpr = Data.RefExpr.getPointer();
1262 DVar.PrivateCopy = Data.PrivateCopy;
1263 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001264 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001265 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001266 }
1267
1268 return DVar;
1269}
1270
Alexey Bataeve3727102018-04-18 15:57:46 +00001271const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1272 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001273 if (isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001274 iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001275 return getDSA(I, D);
1276 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001277 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001278 iterator StartI = Stack.back().first.rbegin();
1279 iterator EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001280 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001281 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001282 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001283}
1284
Alexey Bataeve3727102018-04-18 15:57:46 +00001285const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001286DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001287 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1288 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001289 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001290 if (isStackEmpty())
1291 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001292 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001293 iterator I = Stack.back().first.rbegin();
1294 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001295 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001296 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001297 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001298 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001299 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001300 iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001301 DSAVarData DVar = getDSA(NewI, D);
1302 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001303 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001304 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001305 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001306}
1307
Alexey Bataeve3727102018-04-18 15:57:46 +00001308const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001309 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1310 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001311 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001312 if (isStackEmpty())
1313 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001314 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001315 iterator StartI = Stack.back().first.rbegin();
1316 iterator EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001317 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001318 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001319 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001320 return {};
Alexey Bataeve3727102018-04-18 15:57:46 +00001321 iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001322 DSAVarData DVar = getDSA(NewI, D);
1323 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001324}
1325
Alexey Bataevaac108a2015-06-23 04:51:00 +00001326bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001327 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1328 unsigned Level, bool NotLastprivate) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001329 if (isStackEmpty())
1330 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001331 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001332 auto StartI = Stack.back().first.begin();
1333 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001334 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001335 return false;
1336 std::advance(StartI, Level);
Alexey Bataeve3727102018-04-18 15:57:46 +00001337 auto I = StartI->SharingMap.find(D);
Alexey Bataev92b33652018-11-21 19:41:10 +00001338 if ((I != StartI->SharingMap.end()) &&
Alexey Bataeve3727102018-04-18 15:57:46 +00001339 I->getSecond().RefExpr.getPointer() &&
1340 CPred(I->getSecond().Attributes) &&
Alexey Bataev92b33652018-11-21 19:41:10 +00001341 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1342 return true;
1343 // Check predetermined rules for the loop control variables.
1344 auto LI = StartI->LCVMap.find(D);
1345 if (LI != StartI->LCVMap.end())
1346 return CPred(OMPC_private);
1347 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001348}
1349
Samuel Antao4be30e92015-10-02 17:14:03 +00001350bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001351 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1352 unsigned Level) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001353 if (isStackEmpty())
1354 return false;
1355 auto StartI = Stack.back().first.begin();
1356 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001357 if (std::distance(StartI, EndI) <= (int)Level)
1358 return false;
1359 std::advance(StartI, Level);
1360 return DPred(StartI->Directive);
1361}
1362
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001363bool DSAStackTy::hasDirective(
1364 const llvm::function_ref<bool(OpenMPDirectiveKind,
1365 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001366 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001367 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001368 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001369 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001370 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001371 auto StartI = std::next(Stack.back().first.rbegin());
1372 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001373 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001374 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001375 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1376 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1377 return true;
1378 }
1379 return false;
1380}
1381
Alexey Bataev758e55e2013-09-06 18:03:48 +00001382void Sema::InitDataSharingAttributesStack() {
1383 VarDataSharingAttributesStack = new DSAStackTy(*this);
1384}
1385
1386#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1387
Alexey Bataev4b465392017-04-26 15:06:24 +00001388void Sema::pushOpenMPFunctionRegion() {
1389 DSAStack->pushFunction();
1390}
1391
1392void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1393 DSAStack->popFunction(OldFSI);
1394}
1395
Alexey Bataevc416e642019-02-08 18:02:25 +00001396static bool isOpenMPDeviceDelayedContext(Sema &S) {
1397 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1398 "Expected OpenMP device compilation.");
1399 return !S.isInOpenMPTargetExecutionDirective() &&
1400 !S.isInOpenMPDeclareTargetContext();
1401}
1402
1403/// Do we know that we will eventually codegen the given function?
1404static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1405 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1406 "Expected OpenMP device compilation.");
1407 // Templates are emitted when they're instantiated.
1408 if (FD->isDependentContext())
1409 return false;
1410
1411 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1412 FD->getCanonicalDecl()))
1413 return true;
1414
1415 // Otherwise, the function is known-emitted if it's in our set of
1416 // known-emitted functions.
1417 return S.DeviceKnownEmittedFns.count(FD) > 0;
1418}
1419
1420Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1421 unsigned DiagID) {
1422 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1423 "Expected OpenMP device compilation.");
1424 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1425 !isKnownEmitted(*this, getCurFunctionDecl()))
1426 ? DeviceDiagBuilder::K_Deferred
1427 : DeviceDiagBuilder::K_Immediate,
1428 Loc, DiagID, getCurFunctionDecl(), *this);
1429}
1430
1431void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1432 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1433 "Expected OpenMP device compilation.");
1434 assert(Callee && "Callee may not be null.");
1435 FunctionDecl *Caller = getCurFunctionDecl();
1436
1437 // If the caller is known-emitted, mark the callee as known-emitted.
1438 // Otherwise, mark the call in our call graph so we can traverse it later.
1439 if (!isOpenMPDeviceDelayedContext(*this) ||
1440 (Caller && isKnownEmitted(*this, Caller)))
1441 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1442 else if (Caller)
1443 DeviceCallGraph[Caller].insert({Callee, Loc});
1444}
1445
Alexey Bataeve3727102018-04-18 15:57:46 +00001446bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001447 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1448
Alexey Bataeve3727102018-04-18 15:57:46 +00001449 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001450 bool IsByRef = true;
1451
1452 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001453 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001454 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001455
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001456 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001457 // This table summarizes how a given variable should be passed to the device
1458 // given its type and the clauses where it appears. This table is based on
1459 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1460 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1461 //
1462 // =========================================================================
1463 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1464 // | |(tofrom:scalar)| | pvt | | | |
1465 // =========================================================================
1466 // | scl | | | | - | | bycopy|
1467 // | scl | | - | x | - | - | bycopy|
1468 // | scl | | x | - | - | - | null |
1469 // | scl | x | | | - | | byref |
1470 // | scl | x | - | x | - | - | bycopy|
1471 // | scl | x | x | - | - | - | null |
1472 // | scl | | - | - | - | x | byref |
1473 // | scl | x | - | - | - | x | byref |
1474 //
1475 // | agg | n.a. | | | - | | byref |
1476 // | agg | n.a. | - | x | - | - | byref |
1477 // | agg | n.a. | x | - | - | - | null |
1478 // | agg | n.a. | - | - | - | x | byref |
1479 // | agg | n.a. | - | - | - | x[] | byref |
1480 //
1481 // | ptr | n.a. | | | - | | bycopy|
1482 // | ptr | n.a. | - | x | - | - | bycopy|
1483 // | ptr | n.a. | x | - | - | - | null |
1484 // | ptr | n.a. | - | - | - | x | byref |
1485 // | ptr | n.a. | - | - | - | x[] | bycopy|
1486 // | ptr | n.a. | - | - | x | | bycopy|
1487 // | ptr | n.a. | - | - | x | x | bycopy|
1488 // | ptr | n.a. | - | - | x | x[] | bycopy|
1489 // =========================================================================
1490 // Legend:
1491 // scl - scalar
1492 // ptr - pointer
1493 // agg - aggregate
1494 // x - applies
1495 // - - invalid in this combination
1496 // [] - mapped with an array section
1497 // byref - should be mapped by reference
1498 // byval - should be mapped by value
1499 // null - initialize a local variable to null on the device
1500 //
1501 // Observations:
1502 // - All scalar declarations that show up in a map clause have to be passed
1503 // by reference, because they may have been mapped in the enclosing data
1504 // environment.
1505 // - If the scalar value does not fit the size of uintptr, it has to be
1506 // passed by reference, regardless the result in the table above.
1507 // - For pointers mapped by value that have either an implicit map or an
1508 // array section, the runtime library may pass the NULL value to the
1509 // device instead of the value passed to it by the compiler.
1510
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001511 if (Ty->isReferenceType())
1512 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001513
1514 // Locate map clauses and see if the variable being captured is referred to
1515 // in any of those clauses. Here we only care about variables, not fields,
1516 // because fields are part of aggregates.
1517 bool IsVariableUsedInMapClause = false;
1518 bool IsVariableAssociatedWithSection = false;
1519
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001520 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001521 D, Level,
1522 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1523 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001524 MapExprComponents,
1525 OpenMPClauseKind WhereFoundClauseKind) {
1526 // Only the map clause information influences how a variable is
1527 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001528 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001529 if (WhereFoundClauseKind != OMPC_map)
1530 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001531
1532 auto EI = MapExprComponents.rbegin();
1533 auto EE = MapExprComponents.rend();
1534
1535 assert(EI != EE && "Invalid map expression!");
1536
1537 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1538 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1539
1540 ++EI;
1541 if (EI == EE)
1542 return false;
1543
1544 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1545 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1546 isa<MemberExpr>(EI->getAssociatedExpression())) {
1547 IsVariableAssociatedWithSection = true;
1548 // There is nothing more we need to know about this variable.
1549 return true;
1550 }
1551
1552 // Keep looking for more map info.
1553 return false;
1554 });
1555
1556 if (IsVariableUsedInMapClause) {
1557 // If variable is identified in a map clause it is always captured by
1558 // reference except if it is a pointer that is dereferenced somehow.
1559 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1560 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001561 // By default, all the data that has a scalar type is mapped by copy
1562 // (except for reduction variables).
1563 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001564 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1565 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001566 !Ty->isScalarType() ||
1567 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1568 DSAStack->hasExplicitDSA(
1569 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001570 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001571 }
1572
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001573 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001574 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001575 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1576 !Ty->isAnyPointerType()) ||
1577 !DSAStack->hasExplicitDSA(
1578 D,
1579 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1580 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001581 // If the variable is artificial and must be captured by value - try to
1582 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001583 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1584 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001585 }
1586
Samuel Antao86ace552016-04-27 22:40:57 +00001587 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001588 // and alignment, because the runtime library only deals with uintptr types.
1589 // If it does not fit the uintptr size, we need to pass the data by reference
1590 // instead.
1591 if (!IsByRef &&
1592 (Ctx.getTypeSizeInChars(Ty) >
1593 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001594 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001595 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001596 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001597
1598 return IsByRef;
1599}
1600
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001601unsigned Sema::getOpenMPNestingLevel() const {
1602 assert(getLangOpts().OpenMP);
1603 return DSAStack->getNestingLevel();
1604}
1605
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001606bool Sema::isInOpenMPTargetExecutionDirective() const {
1607 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1608 !DSAStack->isClauseParsingMode()) ||
1609 DSAStack->hasDirective(
1610 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1611 SourceLocation) -> bool {
1612 return isOpenMPTargetExecutionDirective(K);
1613 },
1614 false);
1615}
1616
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001617VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001618 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001619 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001620
1621 // If we are attempting to capture a global variable in a directive with
1622 // 'target' we return true so that this global is also mapped to the device.
1623 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001624 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001625 if (VD && !VD->hasLocalStorage()) {
1626 if (isInOpenMPDeclareTargetContext() &&
1627 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1628 // Try to mark variable as declare target if it is used in capturing
1629 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001630 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001631 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001632 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001633 } else if (isInOpenMPTargetExecutionDirective()) {
1634 // If the declaration is enclosed in a 'declare target' directive,
1635 // then it should not be captured.
1636 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001637 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001638 return nullptr;
1639 return VD;
1640 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001641 }
Alexey Bataev60705422018-10-30 15:50:12 +00001642 // Capture variables captured by reference in lambdas for target-based
1643 // directives.
1644 if (VD && !DSAStack->isClauseParsingMode()) {
1645 if (const auto *RD = VD->getType()
1646 .getCanonicalType()
1647 .getNonReferenceType()
1648 ->getAsCXXRecordDecl()) {
1649 bool SavedForceCaptureByReferenceInTargetExecutable =
1650 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1651 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Alexey Bataevd1840e52018-11-16 21:13:33 +00001652 if (RD->isLambda()) {
1653 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1654 FieldDecl *ThisCapture;
1655 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001656 for (const LambdaCapture &LC : RD->captures()) {
1657 if (LC.getCaptureKind() == LCK_ByRef) {
1658 VarDecl *VD = LC.getCapturedVar();
1659 DeclContext *VDC = VD->getDeclContext();
1660 if (!VDC->Encloses(CurContext))
1661 continue;
1662 DSAStackTy::DSAVarData DVarPrivate =
1663 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1664 // Do not capture already captured variables.
1665 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1666 DVarPrivate.CKind == OMPC_unknown &&
1667 !DSAStack->checkMappableExprComponentListsForDecl(
1668 D, /*CurrentRegionOnly=*/true,
1669 [](OMPClauseMappableExprCommon::
1670 MappableExprComponentListRef,
1671 OpenMPClauseKind) { return true; }))
1672 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1673 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001674 QualType ThisTy = getCurrentThisType();
1675 if (!ThisTy.isNull() &&
1676 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1677 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001678 }
1679 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001680 }
Alexey Bataev60705422018-10-30 15:50:12 +00001681 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1682 SavedForceCaptureByReferenceInTargetExecutable);
1683 }
1684 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001685
Alexey Bataev48977c32015-08-04 08:10:48 +00001686 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1687 (!DSAStack->isClauseParsingMode() ||
1688 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001689 auto &&Info = DSAStack->isLoopControlVariable(D);
1690 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001691 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001692 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001693 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001694 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001695 DSAStackTy::DSAVarData DVarPrivate =
1696 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001697 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001698 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001699 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1700 [](OpenMPDirectiveKind) { return true; },
1701 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001702 if (DVarPrivate.CKind != OMPC_unknown)
1703 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001704 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001705 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001706}
1707
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001708void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1709 unsigned Level) const {
1710 SmallVector<OpenMPDirectiveKind, 4> Regions;
1711 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1712 FunctionScopesIndex -= Regions.size();
1713}
1714
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001715void Sema::startOpenMPLoop() {
1716 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1717 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1718 DSAStack->loopInit();
1719}
1720
Alexey Bataeve3727102018-04-18 15:57:46 +00001721bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001722 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001723 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1724 if (DSAStack->getAssociatedLoops() > 0 &&
1725 !DSAStack->isLoopStarted()) {
1726 DSAStack->resetPossibleLoopCounter(D);
1727 DSAStack->loopStart();
1728 return true;
1729 }
1730 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1731 DSAStack->isLoopControlVariable(D).first) &&
1732 !DSAStack->hasExplicitDSA(
1733 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1734 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1735 return true;
1736 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001737 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001738 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001739 (DSAStack->isClauseParsingMode() &&
1740 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001741 // Consider taskgroup reduction descriptor variable a private to avoid
1742 // possible capture in the region.
1743 (DSAStack->hasExplicitDirective(
1744 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1745 Level) &&
1746 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001747}
1748
Alexey Bataeve3727102018-04-18 15:57:46 +00001749void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1750 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001751 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1752 D = getCanonicalDecl(D);
1753 OpenMPClauseKind OMPC = OMPC_unknown;
1754 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1755 const unsigned NewLevel = I - 1;
1756 if (DSAStack->hasExplicitDSA(D,
1757 [&OMPC](const OpenMPClauseKind K) {
1758 if (isOpenMPPrivate(K)) {
1759 OMPC = K;
1760 return true;
1761 }
1762 return false;
1763 },
1764 NewLevel))
1765 break;
1766 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1767 D, NewLevel,
1768 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1769 OpenMPClauseKind) { return true; })) {
1770 OMPC = OMPC_map;
1771 break;
1772 }
1773 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1774 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001775 OMPC = OMPC_map;
1776 if (D->getType()->isScalarType() &&
1777 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1778 DefaultMapAttributes::DMA_tofrom_scalar)
1779 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001780 break;
1781 }
1782 }
1783 if (OMPC != OMPC_unknown)
1784 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1785}
1786
Alexey Bataeve3727102018-04-18 15:57:46 +00001787bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1788 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001789 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1790 // Return true if the current level is no longer enclosed in a target region.
1791
Alexey Bataeve3727102018-04-18 15:57:46 +00001792 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001793 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001794 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1795 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001796}
1797
Alexey Bataeved09d242014-05-28 05:53:51 +00001798void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001799
1800void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1801 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001802 Scope *CurScope, SourceLocation Loc) {
1803 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001804 PushExpressionEvaluationContext(
1805 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001806}
1807
Alexey Bataevaac108a2015-06-23 04:51:00 +00001808void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1809 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001810}
1811
Alexey Bataevaac108a2015-06-23 04:51:00 +00001812void Sema::EndOpenMPClause() {
1813 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001814}
1815
Alexey Bataev758e55e2013-09-06 18:03:48 +00001816void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001817 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1818 // A variable of class type (or array thereof) that appears in a lastprivate
1819 // clause requires an accessible, unambiguous default constructor for the
1820 // class type, unless the list item is also specified in a firstprivate
1821 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001822 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1823 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001824 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1825 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001826 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001827 if (DE->isValueDependent() || DE->isTypeDependent()) {
1828 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001829 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001830 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001831 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001832 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001833 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001834 const DSAStackTy::DSAVarData DVar =
1835 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001836 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001837 // Generate helper private variable and initialize it with the
1838 // default value. The address of the original variable is replaced
1839 // by the address of the new private variable in CodeGen. This new
1840 // variable is not added to IdResolver, so the code in the OpenMP
1841 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00001842 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001843 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001844 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001845 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001846 if (VDPrivate->isInvalidDecl())
1847 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001848 PrivateCopies.push_back(buildDeclRefExpr(
1849 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001850 } else {
1851 // The variable is also a firstprivate, so initialization sequence
1852 // for private copy is generated already.
1853 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001854 }
1855 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001856 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001857 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001858 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001859 }
1860 }
1861 }
1862
Alexey Bataev758e55e2013-09-06 18:03:48 +00001863 DSAStack->pop();
1864 DiscardCleanupsInEvaluationContext();
1865 PopExpressionEvaluationContext();
1866}
1867
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001868static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1869 Expr *NumIterations, Sema &SemaRef,
1870 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001871
Alexey Bataeva769e072013-03-22 06:34:35 +00001872namespace {
1873
Alexey Bataeve3727102018-04-18 15:57:46 +00001874class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001875private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001876 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001877
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001878public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001879 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001880 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001881 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00001882 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001883 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001884 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1885 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001886 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001887 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001888 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001889};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001890
Alexey Bataeve3727102018-04-18 15:57:46 +00001891class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001892private:
1893 Sema &SemaRef;
1894
1895public:
1896 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1897 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1898 NamedDecl *ND = Candidate.getCorrectionDecl();
Kelvin Li59e3d192017-11-30 18:52:06 +00001899 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001900 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1901 SemaRef.getCurScope());
1902 }
1903 return false;
1904 }
1905};
1906
Alexey Bataeved09d242014-05-28 05:53:51 +00001907} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001908
1909ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1910 CXXScopeSpec &ScopeSpec,
1911 const DeclarationNameInfo &Id) {
1912 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1913 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1914
1915 if (Lookup.isAmbiguous())
1916 return ExprError();
1917
1918 VarDecl *VD;
1919 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001920 if (TypoCorrection Corrected = CorrectTypo(
1921 Id, LookupOrdinaryName, CurScope, nullptr,
1922 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001923 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001924 PDiag(Lookup.empty()
1925 ? diag::err_undeclared_var_use_suggest
1926 : diag::err_omp_expected_var_arg_suggest)
1927 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001928 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001929 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001930 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1931 : diag::err_omp_expected_var_arg)
1932 << Id.getName();
1933 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001934 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001935 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1936 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1937 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1938 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001939 }
1940 Lookup.suppressDiagnostics();
1941
1942 // OpenMP [2.9.2, Syntax, C/C++]
1943 // Variables must be file-scope, namespace-scope, or static block-scope.
1944 if (!VD->hasGlobalStorage()) {
1945 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001946 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1947 bool IsDecl =
1948 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001949 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001950 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1951 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001952 return ExprError();
1953 }
1954
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001955 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001956 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001957 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1958 // A threadprivate directive for file-scope variables must appear outside
1959 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001960 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1961 !getCurLexicalContext()->isTranslationUnit()) {
1962 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001963 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1964 bool IsDecl =
1965 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1966 Diag(VD->getLocation(),
1967 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1968 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001969 return ExprError();
1970 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001971 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1972 // A threadprivate directive for static class member variables must appear
1973 // in the class definition, in the same scope in which the member
1974 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001975 if (CanonicalVD->isStaticDataMember() &&
1976 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1977 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001978 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1979 bool IsDecl =
1980 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1981 Diag(VD->getLocation(),
1982 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1983 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001984 return ExprError();
1985 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001986 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1987 // A threadprivate directive for namespace-scope variables must appear
1988 // outside any definition or declaration other than the namespace
1989 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001990 if (CanonicalVD->getDeclContext()->isNamespace() &&
1991 (!getCurLexicalContext()->isFileContext() ||
1992 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1993 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001994 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1995 bool IsDecl =
1996 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1997 Diag(VD->getLocation(),
1998 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1999 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002000 return ExprError();
2001 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002002 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2003 // A threadprivate directive for static block-scope variables must appear
2004 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002005 if (CanonicalVD->isStaticLocal() && CurScope &&
2006 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002007 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00002008 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
2009 bool IsDecl =
2010 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2011 Diag(VD->getLocation(),
2012 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2013 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002014 return ExprError();
2015 }
2016
2017 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2018 // A threadprivate directive must lexically precede all references to any
2019 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00002020 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002021 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00002022 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002023 return ExprError();
2024 }
2025
2026 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002027 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2028 SourceLocation(), VD,
2029 /*RefersToEnclosingVariableOrCapture=*/false,
2030 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002031}
2032
Alexey Bataeved09d242014-05-28 05:53:51 +00002033Sema::DeclGroupPtrTy
2034Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2035 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002036 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002037 CurContext->addDecl(D);
2038 return DeclGroupPtrTy::make(DeclGroupRef(D));
2039 }
David Blaikie0403cb12016-01-15 23:43:25 +00002040 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002041}
2042
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002043namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002044class LocalVarRefChecker final
2045 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002046 Sema &SemaRef;
2047
2048public:
2049 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002050 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002051 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002052 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002053 diag::err_omp_local_var_in_threadprivate_init)
2054 << E->getSourceRange();
2055 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2056 << VD << VD->getSourceRange();
2057 return true;
2058 }
2059 }
2060 return false;
2061 }
2062 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002063 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002064 if (Child && Visit(Child))
2065 return true;
2066 }
2067 return false;
2068 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002069 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002070};
2071} // namespace
2072
Alexey Bataeved09d242014-05-28 05:53:51 +00002073OMPThreadPrivateDecl *
2074Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002075 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002076 for (Expr *RefExpr : VarList) {
2077 auto *DE = cast<DeclRefExpr>(RefExpr);
2078 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002079 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002080
Alexey Bataev376b4a42016-02-09 09:41:09 +00002081 // Mark variable as used.
2082 VD->setReferenced();
2083 VD->markUsed(Context);
2084
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002085 QualType QType = VD->getType();
2086 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2087 // It will be analyzed later.
2088 Vars.push_back(DE);
2089 continue;
2090 }
2091
Alexey Bataeva769e072013-03-22 06:34:35 +00002092 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2093 // A threadprivate variable must not have an incomplete type.
2094 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002095 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002096 continue;
2097 }
2098
2099 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2100 // A threadprivate variable must not have a reference type.
2101 if (VD->getType()->isReferenceType()) {
2102 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002103 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2104 bool IsDecl =
2105 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2106 Diag(VD->getLocation(),
2107 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2108 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002109 continue;
2110 }
2111
Samuel Antaof8b50122015-07-13 22:54:53 +00002112 // Check if this is a TLS variable. If TLS is not being supported, produce
2113 // the corresponding diagnostic.
2114 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2115 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2116 getLangOpts().OpenMPUseTLS &&
2117 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002118 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2119 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002120 Diag(ILoc, diag::err_omp_var_thread_local)
2121 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002122 bool IsDecl =
2123 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2124 Diag(VD->getLocation(),
2125 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2126 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002127 continue;
2128 }
2129
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002130 // Check if initial value of threadprivate variable reference variable with
2131 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002132 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002133 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002134 if (Checker.Visit(Init))
2135 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002136 }
2137
Alexey Bataeved09d242014-05-28 05:53:51 +00002138 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002139 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002140 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2141 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002142 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002143 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002144 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002145 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002146 if (!Vars.empty()) {
2147 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2148 Vars);
2149 D->setAccess(AS_public);
2150 }
2151 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002152}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002153
Kelvin Li1408f912018-09-26 04:28:39 +00002154Sema::DeclGroupPtrTy
2155Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2156 ArrayRef<OMPClause *> ClauseList) {
2157 OMPRequiresDecl *D = nullptr;
2158 if (!CurContext->isFileContext()) {
2159 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2160 } else {
2161 D = CheckOMPRequiresDecl(Loc, ClauseList);
2162 if (D) {
2163 CurContext->addDecl(D);
2164 DSAStack->addRequiresDecl(D);
2165 }
2166 }
2167 return DeclGroupPtrTy::make(DeclGroupRef(D));
2168}
2169
2170OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2171 ArrayRef<OMPClause *> ClauseList) {
2172 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2173 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2174 ClauseList);
2175 return nullptr;
2176}
2177
Alexey Bataeve3727102018-04-18 15:57:46 +00002178static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2179 const ValueDecl *D,
2180 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002181 bool IsLoopIterVar = false) {
2182 if (DVar.RefExpr) {
2183 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2184 << getOpenMPClauseName(DVar.CKind);
2185 return;
2186 }
2187 enum {
2188 PDSA_StaticMemberShared,
2189 PDSA_StaticLocalVarShared,
2190 PDSA_LoopIterVarPrivate,
2191 PDSA_LoopIterVarLinear,
2192 PDSA_LoopIterVarLastprivate,
2193 PDSA_ConstVarShared,
2194 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002195 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002196 PDSA_LocalVarPrivate,
2197 PDSA_Implicit
2198 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002199 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002200 auto ReportLoc = D->getLocation();
2201 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002202 if (IsLoopIterVar) {
2203 if (DVar.CKind == OMPC_private)
2204 Reason = PDSA_LoopIterVarPrivate;
2205 else if (DVar.CKind == OMPC_lastprivate)
2206 Reason = PDSA_LoopIterVarLastprivate;
2207 else
2208 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002209 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2210 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002211 Reason = PDSA_TaskVarFirstprivate;
2212 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002213 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002214 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002215 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002216 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002217 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002218 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002219 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002220 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002221 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002222 ReportHint = true;
2223 Reason = PDSA_LocalVarPrivate;
2224 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002225 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002226 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002227 << Reason << ReportHint
2228 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2229 } else if (DVar.ImplicitDSALoc.isValid()) {
2230 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2231 << getOpenMPClauseName(DVar.CKind);
2232 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002233}
2234
Alexey Bataev758e55e2013-09-06 18:03:48 +00002235namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002236class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002237 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002238 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002239 bool ErrorFound = false;
2240 CapturedStmt *CS = nullptr;
2241 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2242 llvm::SmallVector<Expr *, 4> ImplicitMap;
2243 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2244 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002245
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002246 void VisitSubCaptures(OMPExecutableDirective *S) {
2247 // Check implicitly captured variables.
2248 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2249 return;
2250 for (const CapturedStmt::Capture &Cap :
2251 S->getInnermostCapturedStmt()->captures()) {
2252 if (!Cap.capturesVariable())
2253 continue;
2254 VarDecl *VD = Cap.getCapturedVar();
2255 // Do not try to map the variable if it or its sub-component was mapped
2256 // already.
2257 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2258 Stack->checkMappableExprComponentListsForDecl(
2259 VD, /*CurrentRegionOnly=*/true,
2260 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2261 OpenMPClauseKind) { return true; }))
2262 continue;
2263 DeclRefExpr *DRE = buildDeclRefExpr(
2264 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2265 Cap.getLocation(), /*RefersToCapture=*/true);
2266 Visit(DRE);
2267 }
2268 }
2269
Alexey Bataev758e55e2013-09-06 18:03:48 +00002270public:
2271 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002272 if (E->isTypeDependent() || E->isValueDependent() ||
2273 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2274 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002275 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002276 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002277 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002278 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002279 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002280
Alexey Bataeve3727102018-04-18 15:57:46 +00002281 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002282 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002283 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002284 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002285
Alexey Bataevafe50572017-10-06 17:00:28 +00002286 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002287 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002288 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002289 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2290 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002291 return;
2292
Alexey Bataeve3727102018-04-18 15:57:46 +00002293 SourceLocation ELoc = E->getExprLoc();
2294 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002295 // The default(none) clause requires that each variable that is referenced
2296 // in the construct, and does not have a predetermined data-sharing
2297 // attribute, must have its data-sharing attribute explicitly determined
2298 // by being listed in a data-sharing attribute clause.
2299 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002300 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002301 VarsWithInheritedDSA.count(VD) == 0) {
2302 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002303 return;
2304 }
2305
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002306 if (isOpenMPTargetExecutionDirective(DKind) &&
2307 !Stack->isLoopControlVariable(VD).first) {
2308 if (!Stack->checkMappableExprComponentListsForDecl(
2309 VD, /*CurrentRegionOnly=*/true,
2310 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2311 StackComponents,
2312 OpenMPClauseKind) {
2313 // Variable is used if it has been marked as an array, array
2314 // section or the variable iself.
2315 return StackComponents.size() == 1 ||
2316 std::all_of(
2317 std::next(StackComponents.rbegin()),
2318 StackComponents.rend(),
2319 [](const OMPClauseMappableExprCommon::
2320 MappableComponent &MC) {
2321 return MC.getAssociatedDeclaration() ==
2322 nullptr &&
2323 (isa<OMPArraySectionExpr>(
2324 MC.getAssociatedExpression()) ||
2325 isa<ArraySubscriptExpr>(
2326 MC.getAssociatedExpression()));
2327 });
2328 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002329 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002330 // By default lambdas are captured as firstprivates.
2331 if (const auto *RD =
2332 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002333 IsFirstprivate = RD->isLambda();
2334 IsFirstprivate =
2335 IsFirstprivate ||
2336 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002337 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002338 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002339 ImplicitFirstprivate.emplace_back(E);
2340 else
2341 ImplicitMap.emplace_back(E);
2342 return;
2343 }
2344 }
2345
Alexey Bataev758e55e2013-09-06 18:03:48 +00002346 // OpenMP [2.9.3.6, Restrictions, p.2]
2347 // A list item that appears in a reduction clause of the innermost
2348 // enclosing worksharing or parallel construct may not be accessed in an
2349 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002350 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002351 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2352 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002353 return isOpenMPParallelDirective(K) ||
2354 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2355 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002356 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002357 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002358 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002359 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002360 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002361 return;
2362 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002363
2364 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002365 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002366 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2367 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002368 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002369 }
2370 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002371 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002372 if (E->isTypeDependent() || E->isValueDependent() ||
2373 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2374 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002375 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002376 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002377 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002378 if (!FD)
2379 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002380 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002381 // Check if the variable has explicit DSA set and stop analysis if it
2382 // so.
2383 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2384 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002385
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002386 if (isOpenMPTargetExecutionDirective(DKind) &&
2387 !Stack->isLoopControlVariable(FD).first &&
2388 !Stack->checkMappableExprComponentListsForDecl(
2389 FD, /*CurrentRegionOnly=*/true,
2390 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2391 StackComponents,
2392 OpenMPClauseKind) {
2393 return isa<CXXThisExpr>(
2394 cast<MemberExpr>(
2395 StackComponents.back().getAssociatedExpression())
2396 ->getBase()
2397 ->IgnoreParens());
2398 })) {
2399 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2400 // A bit-field cannot appear in a map clause.
2401 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002402 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002403 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002404
2405 // Check to see if the member expression is referencing a class that
2406 // has already been explicitly mapped
2407 if (Stack->isClassPreviouslyMapped(TE->getType()))
2408 return;
2409
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002410 ImplicitMap.emplace_back(E);
2411 return;
2412 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002413
Alexey Bataeve3727102018-04-18 15:57:46 +00002414 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002415 // OpenMP [2.9.3.6, Restrictions, p.2]
2416 // A list item that appears in a reduction clause of the innermost
2417 // enclosing worksharing or parallel construct may not be accessed in
2418 // an explicit task.
2419 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002420 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2421 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002422 return isOpenMPParallelDirective(K) ||
2423 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2424 },
2425 /*FromParent=*/true);
2426 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2427 ErrorFound = true;
2428 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002429 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002430 return;
2431 }
2432
2433 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002434 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002435 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002436 !Stack->isLoopControlVariable(FD).first) {
2437 // Check if there is a captured expression for the current field in the
2438 // region. Do not mark it as firstprivate unless there is no captured
2439 // expression.
2440 // TODO: try to make it firstprivate.
2441 if (DVar.CKind != OMPC_unknown)
2442 ImplicitFirstprivate.push_back(E);
2443 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002444 return;
2445 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002446 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002447 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002448 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002449 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002450 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002451 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002452 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2453 if (!Stack->checkMappableExprComponentListsForDecl(
2454 VD, /*CurrentRegionOnly=*/true,
2455 [&CurComponents](
2456 OMPClauseMappableExprCommon::MappableExprComponentListRef
2457 StackComponents,
2458 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002459 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002460 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002461 for (const auto &SC : llvm::reverse(StackComponents)) {
2462 // Do both expressions have the same kind?
2463 if (CCI->getAssociatedExpression()->getStmtClass() !=
2464 SC.getAssociatedExpression()->getStmtClass())
2465 if (!(isa<OMPArraySectionExpr>(
2466 SC.getAssociatedExpression()) &&
2467 isa<ArraySubscriptExpr>(
2468 CCI->getAssociatedExpression())))
2469 return false;
2470
Alexey Bataeve3727102018-04-18 15:57:46 +00002471 const Decl *CCD = CCI->getAssociatedDeclaration();
2472 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002473 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2474 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2475 if (SCD != CCD)
2476 return false;
2477 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002478 if (CCI == CCE)
2479 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002480 }
2481 return true;
2482 })) {
2483 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002484 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002485 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002486 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002487 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002488 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002489 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002490 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002491 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002492 // for task|target directives.
2493 // Skip analysis of arguments of implicitly defined map clause for target
2494 // directives.
2495 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2496 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002497 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002498 if (CC)
2499 Visit(CC);
2500 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002501 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002502 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002503 // Check implicitly captured variables.
2504 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002505 }
2506 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002507 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002508 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002509 // Check implicitly captured variables in the task-based directives to
2510 // check if they must be firstprivatized.
2511 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002512 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002513 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002514 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002515
Alexey Bataeve3727102018-04-18 15:57:46 +00002516 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002517 ArrayRef<Expr *> getImplicitFirstprivate() const {
2518 return ImplicitFirstprivate;
2519 }
2520 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002521 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002522 return VarsWithInheritedDSA;
2523 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002524
Alexey Bataev7ff55242014-06-19 09:13:45 +00002525 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2526 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002527};
Alexey Bataeved09d242014-05-28 05:53:51 +00002528} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002529
Alexey Bataevbae9a792014-06-27 10:37:06 +00002530void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002531 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002532 case OMPD_parallel:
2533 case OMPD_parallel_for:
2534 case OMPD_parallel_for_simd:
2535 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002536 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002537 case OMPD_teams_distribute:
2538 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002539 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002540 QualType KmpInt32PtrTy =
2541 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002542 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002543 std::make_pair(".global_tid.", KmpInt32PtrTy),
2544 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2545 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002546 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002547 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2548 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002549 break;
2550 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002551 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002552 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002553 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002554 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002555 case OMPD_target_teams_distribute:
2556 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002557 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2558 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2559 QualType KmpInt32PtrTy =
2560 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2561 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002562 FunctionProtoType::ExtProtoInfo EPI;
2563 EPI.Variadic = true;
2564 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2565 Sema::CapturedParamNameType Params[] = {
2566 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002567 std::make_pair(".part_id.", KmpInt32PtrTy),
2568 std::make_pair(".privates.", VoidPtrTy),
2569 std::make_pair(
2570 ".copy_fn.",
2571 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002572 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2573 std::make_pair(StringRef(), QualType()) // __context with shared vars
2574 };
2575 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2576 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002577 // Mark this captured region as inlined, because we don't use outlined
2578 // function directly.
2579 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2580 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002581 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002582 Sema::CapturedParamNameType ParamsTarget[] = {
2583 std::make_pair(StringRef(), QualType()) // __context with shared vars
2584 };
2585 // Start a captured region for 'target' with no implicit parameters.
2586 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2587 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002588 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002589 std::make_pair(".global_tid.", KmpInt32PtrTy),
2590 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2591 std::make_pair(StringRef(), QualType()) // __context with shared vars
2592 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002593 // Start a captured region for 'teams' or 'parallel'. Both regions have
2594 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002595 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002596 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002597 break;
2598 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002599 case OMPD_target:
2600 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002601 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2602 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2603 QualType KmpInt32PtrTy =
2604 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2605 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002606 FunctionProtoType::ExtProtoInfo EPI;
2607 EPI.Variadic = true;
2608 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2609 Sema::CapturedParamNameType Params[] = {
2610 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002611 std::make_pair(".part_id.", KmpInt32PtrTy),
2612 std::make_pair(".privates.", VoidPtrTy),
2613 std::make_pair(
2614 ".copy_fn.",
2615 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002616 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2617 std::make_pair(StringRef(), QualType()) // __context with shared vars
2618 };
2619 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2620 Params);
2621 // Mark this captured region as inlined, because we don't use outlined
2622 // function directly.
2623 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2624 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002625 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002626 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2627 std::make_pair(StringRef(), QualType()));
2628 break;
2629 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002630 case OMPD_simd:
2631 case OMPD_for:
2632 case OMPD_for_simd:
2633 case OMPD_sections:
2634 case OMPD_section:
2635 case OMPD_single:
2636 case OMPD_master:
2637 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002638 case OMPD_taskgroup:
2639 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002640 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002641 case OMPD_ordered:
2642 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002643 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002644 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002645 std::make_pair(StringRef(), QualType()) // __context with shared vars
2646 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002647 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2648 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002649 break;
2650 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002651 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002652 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2653 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2654 QualType KmpInt32PtrTy =
2655 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2656 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002657 FunctionProtoType::ExtProtoInfo EPI;
2658 EPI.Variadic = true;
2659 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002660 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002661 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002662 std::make_pair(".part_id.", KmpInt32PtrTy),
2663 std::make_pair(".privates.", VoidPtrTy),
2664 std::make_pair(
2665 ".copy_fn.",
2666 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002667 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002668 std::make_pair(StringRef(), QualType()) // __context with shared vars
2669 };
2670 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2671 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002672 // Mark this captured region as inlined, because we don't use outlined
2673 // function directly.
2674 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2675 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002676 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002677 break;
2678 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002679 case OMPD_taskloop:
2680 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002681 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002682 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2683 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002684 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002685 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2686 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002687 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002688 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2689 .withConst();
2690 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2691 QualType KmpInt32PtrTy =
2692 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2693 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002694 FunctionProtoType::ExtProtoInfo EPI;
2695 EPI.Variadic = true;
2696 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002697 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002698 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002699 std::make_pair(".part_id.", KmpInt32PtrTy),
2700 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002701 std::make_pair(
2702 ".copy_fn.",
2703 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2704 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2705 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002706 std::make_pair(".ub.", KmpUInt64Ty),
2707 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002708 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002709 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002710 std::make_pair(StringRef(), QualType()) // __context with shared vars
2711 };
2712 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2713 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002714 // Mark this captured region as inlined, because we don't use outlined
2715 // function directly.
2716 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2717 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002718 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002719 break;
2720 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002721 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002722 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002723 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002724 QualType KmpInt32PtrTy =
2725 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2726 Sema::CapturedParamNameType Params[] = {
2727 std::make_pair(".global_tid.", KmpInt32PtrTy),
2728 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002729 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2730 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002731 std::make_pair(StringRef(), QualType()) // __context with shared vars
2732 };
2733 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2734 Params);
2735 break;
2736 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002737 case OMPD_target_teams_distribute_parallel_for:
2738 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002739 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002740 QualType KmpInt32PtrTy =
2741 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002742 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002743
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002744 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002745 FunctionProtoType::ExtProtoInfo EPI;
2746 EPI.Variadic = true;
2747 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2748 Sema::CapturedParamNameType Params[] = {
2749 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002750 std::make_pair(".part_id.", KmpInt32PtrTy),
2751 std::make_pair(".privates.", VoidPtrTy),
2752 std::make_pair(
2753 ".copy_fn.",
2754 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002755 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2756 std::make_pair(StringRef(), QualType()) // __context with shared vars
2757 };
2758 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2759 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002760 // Mark this captured region as inlined, because we don't use outlined
2761 // function directly.
2762 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2763 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002764 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002765 Sema::CapturedParamNameType ParamsTarget[] = {
2766 std::make_pair(StringRef(), QualType()) // __context with shared vars
2767 };
2768 // Start a captured region for 'target' with no implicit parameters.
2769 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2770 ParamsTarget);
2771
2772 Sema::CapturedParamNameType ParamsTeams[] = {
2773 std::make_pair(".global_tid.", KmpInt32PtrTy),
2774 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2775 std::make_pair(StringRef(), QualType()) // __context with shared vars
2776 };
2777 // Start a captured region for 'target' with no implicit parameters.
2778 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2779 ParamsTeams);
2780
2781 Sema::CapturedParamNameType ParamsParallel[] = {
2782 std::make_pair(".global_tid.", KmpInt32PtrTy),
2783 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002784 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2785 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00002786 std::make_pair(StringRef(), QualType()) // __context with shared vars
2787 };
2788 // Start a captured region for 'teams' or 'parallel'. Both regions have
2789 // the same implicit parameters.
2790 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2791 ParamsParallel);
2792 break;
2793 }
2794
Alexey Bataev46506272017-12-05 17:41:34 +00002795 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002796 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002797 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00002798 QualType KmpInt32PtrTy =
2799 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2800
2801 Sema::CapturedParamNameType ParamsTeams[] = {
2802 std::make_pair(".global_tid.", KmpInt32PtrTy),
2803 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2804 std::make_pair(StringRef(), QualType()) // __context with shared vars
2805 };
2806 // Start a captured region for 'target' with no implicit parameters.
2807 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2808 ParamsTeams);
2809
2810 Sema::CapturedParamNameType ParamsParallel[] = {
2811 std::make_pair(".global_tid.", KmpInt32PtrTy),
2812 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002813 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2814 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00002815 std::make_pair(StringRef(), QualType()) // __context with shared vars
2816 };
2817 // Start a captured region for 'teams' or 'parallel'. Both regions have
2818 // the same implicit parameters.
2819 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2820 ParamsParallel);
2821 break;
2822 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002823 case OMPD_target_update:
2824 case OMPD_target_enter_data:
2825 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002826 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2827 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2828 QualType KmpInt32PtrTy =
2829 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2830 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00002831 FunctionProtoType::ExtProtoInfo EPI;
2832 EPI.Variadic = true;
2833 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2834 Sema::CapturedParamNameType Params[] = {
2835 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002836 std::make_pair(".part_id.", KmpInt32PtrTy),
2837 std::make_pair(".privates.", VoidPtrTy),
2838 std::make_pair(
2839 ".copy_fn.",
2840 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00002841 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2842 std::make_pair(StringRef(), QualType()) // __context with shared vars
2843 };
2844 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2845 Params);
2846 // Mark this captured region as inlined, because we don't use outlined
2847 // function directly.
2848 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2849 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002850 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00002851 break;
2852 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002853 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002854 case OMPD_taskyield:
2855 case OMPD_barrier:
2856 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002857 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002858 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002859 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002860 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00002861 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002862 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002863 case OMPD_declare_target:
2864 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00002865 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00002866 llvm_unreachable("OpenMP Directive is not allowed");
2867 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002868 llvm_unreachable("Unknown OpenMP directive");
2869 }
2870}
2871
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002872int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2873 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2874 getOpenMPCaptureRegions(CaptureRegions, DKind);
2875 return CaptureRegions.size();
2876}
2877
Alexey Bataev3392d762016-02-16 11:18:12 +00002878static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002879 Expr *CaptureExpr, bool WithInit,
2880 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002881 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002882 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002883 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002884 QualType Ty = Init->getType();
2885 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002886 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002887 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002888 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002889 Ty = C.getPointerType(Ty);
2890 ExprResult Res =
2891 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2892 if (!Res.isUsable())
2893 return nullptr;
2894 Init = Res.get();
2895 }
Alexey Bataev61205072016-03-02 04:57:40 +00002896 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002897 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002898 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002899 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002900 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00002901 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00002902 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002903 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002904 return CED;
2905}
2906
Alexey Bataev61205072016-03-02 04:57:40 +00002907static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2908 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002909 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00002910 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002911 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00002912 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002913 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2914 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002915 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002916 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002917}
2918
Alexey Bataev5a3af132016-03-29 08:58:54 +00002919static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002920 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002921 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002922 OMPCapturedExprDecl *CD = buildCaptureDecl(
2923 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2924 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002925 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2926 CaptureExpr->getExprLoc());
2927 }
2928 ExprResult Res = Ref;
2929 if (!S.getLangOpts().CPlusPlus &&
2930 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002931 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002932 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002933 if (!Res.isUsable())
2934 return ExprError();
2935 }
2936 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002937}
2938
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002939namespace {
2940// OpenMP directives parsed in this section are represented as a
2941// CapturedStatement with an associated statement. If a syntax error
2942// is detected during the parsing of the associated statement, the
2943// compiler must abort processing and close the CapturedStatement.
2944//
2945// Combined directives such as 'target parallel' have more than one
2946// nested CapturedStatements. This RAII ensures that we unwind out
2947// of all the nested CapturedStatements when an error is found.
2948class CaptureRegionUnwinderRAII {
2949private:
2950 Sema &S;
2951 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00002952 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002953
2954public:
2955 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2956 OpenMPDirectiveKind DKind)
2957 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2958 ~CaptureRegionUnwinderRAII() {
2959 if (ErrorFound) {
2960 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2961 while (--ThisCaptureLevel >= 0)
2962 S.ActOnCapturedRegionError();
2963 }
2964 }
2965};
2966} // namespace
2967
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002968StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2969 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002970 bool ErrorFound = false;
2971 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2972 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002973 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002974 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002975 return StmtError();
2976 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002977
Alexey Bataev2ba67042017-11-28 21:11:44 +00002978 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2979 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002980 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002981 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00002982 SmallVector<const OMPLinearClause *, 4> LCs;
2983 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002984 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00002985 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002986 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2987 Clause->getClauseKind() == OMPC_in_reduction) {
2988 // Capture taskgroup task_reduction descriptors inside the tasking regions
2989 // with the corresponding in_reduction items.
2990 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00002991 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00002992 if (E)
2993 MarkDeclarationsReferencedInExpr(E);
2994 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002995 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002996 Clause->getClauseKind() == OMPC_copyprivate ||
2997 (getLangOpts().OpenMPUseTLS &&
2998 getASTContext().getTargetInfo().isTLSSupported() &&
2999 Clause->getClauseKind() == OMPC_copyin)) {
3000 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003001 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003002 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003003 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003004 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003005 }
3006 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003007 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003008 } else if (CaptureRegions.size() > 1 ||
3009 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003010 if (auto *C = OMPClauseWithPreInit::get(Clause))
3011 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003012 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003013 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003014 MarkDeclarationsReferencedInExpr(E);
3015 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003016 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003017 if (Clause->getClauseKind() == OMPC_schedule)
3018 SC = cast<OMPScheduleClause>(Clause);
3019 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003020 OC = cast<OMPOrderedClause>(Clause);
3021 else if (Clause->getClauseKind() == OMPC_linear)
3022 LCs.push_back(cast<OMPLinearClause>(Clause));
3023 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003024 // OpenMP, 2.7.1 Loop Construct, Restrictions
3025 // The nonmonotonic modifier cannot be specified if an ordered clause is
3026 // specified.
3027 if (SC &&
3028 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3029 SC->getSecondScheduleModifier() ==
3030 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3031 OC) {
3032 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3033 ? SC->getFirstScheduleModifierLoc()
3034 : SC->getSecondScheduleModifierLoc(),
3035 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003036 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003037 ErrorFound = true;
3038 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003039 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003040 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003041 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003042 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003043 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003044 ErrorFound = true;
3045 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003046 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3047 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3048 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003049 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003050 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3051 ErrorFound = true;
3052 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003053 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003054 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003055 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003056 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003057 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003058 // Mark all variables in private list clauses as used in inner region.
3059 // Required for proper codegen of combined directives.
3060 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003061 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003062 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003063 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3064 // Find the particular capture region for the clause if the
3065 // directive is a combined one with multiple capture regions.
3066 // If the directive is not a combined one, the capture region
3067 // associated with the clause is OMPD_unknown and is generated
3068 // only once.
3069 if (CaptureRegion == ThisCaptureRegion ||
3070 CaptureRegion == OMPD_unknown) {
3071 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003072 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003073 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3074 }
3075 }
3076 }
3077 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003078 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003079 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003080 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003081}
3082
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003083static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3084 OpenMPDirectiveKind CancelRegion,
3085 SourceLocation StartLoc) {
3086 // CancelRegion is only needed for cancel and cancellation_point.
3087 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3088 return false;
3089
3090 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3091 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3092 return false;
3093
3094 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3095 << getOpenMPDirectiveName(CancelRegion);
3096 return true;
3097}
3098
Alexey Bataeve3727102018-04-18 15:57:46 +00003099static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003100 OpenMPDirectiveKind CurrentRegion,
3101 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003102 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003103 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003104 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003105 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3106 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003107 bool NestingProhibited = false;
3108 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003109 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003110 enum {
3111 NoRecommend,
3112 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003113 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003114 ShouldBeInTargetRegion,
3115 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003116 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003117 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003118 // OpenMP [2.16, Nesting of Regions]
3119 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003120 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003121 // An ordered construct with the simd clause is the only OpenMP
3122 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003123 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003124 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3125 // message.
3126 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3127 ? diag::err_omp_prohibited_region_simd
3128 : diag::warn_omp_nesting_simd);
3129 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003130 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003131 if (ParentRegion == OMPD_atomic) {
3132 // OpenMP [2.16, Nesting of Regions]
3133 // OpenMP constructs may not be nested inside an atomic region.
3134 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3135 return true;
3136 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003137 if (CurrentRegion == OMPD_section) {
3138 // OpenMP [2.7.2, sections Construct, Restrictions]
3139 // Orphaned section directives are prohibited. That is, the section
3140 // directives must appear within the sections construct and must not be
3141 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003142 if (ParentRegion != OMPD_sections &&
3143 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003144 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3145 << (ParentRegion != OMPD_unknown)
3146 << getOpenMPDirectiveName(ParentRegion);
3147 return true;
3148 }
3149 return false;
3150 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003151 // Allow some constructs (except teams and cancellation constructs) to be
3152 // orphaned (they could be used in functions, called from OpenMP regions
3153 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003154 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003155 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3156 CurrentRegion != OMPD_cancellation_point &&
3157 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003158 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003159 if (CurrentRegion == OMPD_cancellation_point ||
3160 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003161 // OpenMP [2.16, Nesting of Regions]
3162 // A cancellation point construct for which construct-type-clause is
3163 // taskgroup must be nested inside a task construct. A cancellation
3164 // point construct for which construct-type-clause is not taskgroup must
3165 // be closely nested inside an OpenMP construct that matches the type
3166 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003167 // A cancel construct for which construct-type-clause is taskgroup must be
3168 // nested inside a task construct. A cancel construct for which
3169 // construct-type-clause is not taskgroup must be closely nested inside an
3170 // OpenMP construct that matches the type specified in
3171 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003172 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003173 !((CancelRegion == OMPD_parallel &&
3174 (ParentRegion == OMPD_parallel ||
3175 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003176 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003177 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003178 ParentRegion == OMPD_target_parallel_for ||
3179 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003180 ParentRegion == OMPD_teams_distribute_parallel_for ||
3181 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003182 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3183 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003184 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3185 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003186 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003187 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003188 // OpenMP [2.16, Nesting of Regions]
3189 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003190 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003191 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003192 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003193 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3194 // OpenMP [2.16, Nesting of Regions]
3195 // A critical region may not be nested (closely or otherwise) inside a
3196 // critical region with the same name. Note that this restriction is not
3197 // sufficient to prevent deadlock.
3198 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003199 bool DeadLock = Stack->hasDirective(
3200 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3201 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003202 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003203 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3204 PreviousCriticalLoc = Loc;
3205 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003206 }
3207 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003208 },
3209 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003210 if (DeadLock) {
3211 SemaRef.Diag(StartLoc,
3212 diag::err_omp_prohibited_region_critical_same_name)
3213 << CurrentName.getName();
3214 if (PreviousCriticalLoc.isValid())
3215 SemaRef.Diag(PreviousCriticalLoc,
3216 diag::note_omp_previous_critical_region);
3217 return true;
3218 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003219 } else if (CurrentRegion == OMPD_barrier) {
3220 // OpenMP [2.16, Nesting of Regions]
3221 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003222 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003223 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3224 isOpenMPTaskingDirective(ParentRegion) ||
3225 ParentRegion == OMPD_master ||
3226 ParentRegion == OMPD_critical ||
3227 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003228 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003229 !isOpenMPParallelDirective(CurrentRegion) &&
3230 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003231 // OpenMP [2.16, Nesting of Regions]
3232 // A worksharing region may not be closely nested inside a worksharing,
3233 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003234 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3235 isOpenMPTaskingDirective(ParentRegion) ||
3236 ParentRegion == OMPD_master ||
3237 ParentRegion == OMPD_critical ||
3238 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003239 Recommend = ShouldBeInParallelRegion;
3240 } else if (CurrentRegion == OMPD_ordered) {
3241 // OpenMP [2.16, Nesting of Regions]
3242 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003243 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003244 // An ordered region must be closely nested inside a loop region (or
3245 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003246 // OpenMP [2.8.1,simd Construct, Restrictions]
3247 // An ordered construct with the simd clause is the only OpenMP construct
3248 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003249 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003250 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003251 !(isOpenMPSimdDirective(ParentRegion) ||
3252 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003253 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003254 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003255 // OpenMP [2.16, Nesting of Regions]
3256 // If specified, a teams construct must be contained within a target
3257 // construct.
3258 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003259 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003260 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003261 }
Kelvin Libf594a52016-12-17 05:48:59 +00003262 if (!NestingProhibited &&
3263 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3264 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3265 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003266 // OpenMP [2.16, Nesting of Regions]
3267 // distribute, parallel, parallel sections, parallel workshare, and the
3268 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3269 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003270 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3271 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003272 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003273 }
David Majnemer9d168222016-08-05 17:44:54 +00003274 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003275 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003276 // OpenMP 4.5 [2.17 Nesting of Regions]
3277 // The region associated with the distribute construct must be strictly
3278 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003279 NestingProhibited =
3280 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003281 Recommend = ShouldBeInTeamsRegion;
3282 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003283 if (!NestingProhibited &&
3284 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3285 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3286 // OpenMP 4.5 [2.17 Nesting of Regions]
3287 // If a target, target update, target data, target enter data, or
3288 // target exit data construct is encountered during execution of a
3289 // target region, the behavior is unspecified.
3290 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003291 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003292 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003293 if (isOpenMPTargetExecutionDirective(K)) {
3294 OffendingRegion = K;
3295 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003296 }
3297 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003298 },
3299 false /* don't skip top directive */);
3300 CloseNesting = false;
3301 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003302 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003303 if (OrphanSeen) {
3304 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3305 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3306 } else {
3307 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3308 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3309 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3310 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003311 return true;
3312 }
3313 }
3314 return false;
3315}
3316
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003317static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3318 ArrayRef<OMPClause *> Clauses,
3319 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3320 bool ErrorFound = false;
3321 unsigned NamedModifiersNumber = 0;
3322 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3323 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003324 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003325 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003326 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3327 // At most one if clause without a directive-name-modifier can appear on
3328 // the directive.
3329 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3330 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003331 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003332 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3333 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3334 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003335 } else if (CurNM != OMPD_unknown) {
3336 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003337 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003338 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003339 FoundNameModifiers[CurNM] = IC;
3340 if (CurNM == OMPD_unknown)
3341 continue;
3342 // Check if the specified name modifier is allowed for the current
3343 // directive.
3344 // At most one if clause with the particular directive-name-modifier can
3345 // appear on the directive.
3346 bool MatchFound = false;
3347 for (auto NM : AllowedNameModifiers) {
3348 if (CurNM == NM) {
3349 MatchFound = true;
3350 break;
3351 }
3352 }
3353 if (!MatchFound) {
3354 S.Diag(IC->getNameModifierLoc(),
3355 diag::err_omp_wrong_if_directive_name_modifier)
3356 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3357 ErrorFound = true;
3358 }
3359 }
3360 }
3361 // If any if clause on the directive includes a directive-name-modifier then
3362 // all if clauses on the directive must include a directive-name-modifier.
3363 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3364 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003365 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003366 diag::err_omp_no_more_if_clause);
3367 } else {
3368 std::string Values;
3369 std::string Sep(", ");
3370 unsigned AllowedCnt = 0;
3371 unsigned TotalAllowedNum =
3372 AllowedNameModifiers.size() - NamedModifiersNumber;
3373 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3374 ++Cnt) {
3375 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3376 if (!FoundNameModifiers[NM]) {
3377 Values += "'";
3378 Values += getOpenMPDirectiveName(NM);
3379 Values += "'";
3380 if (AllowedCnt + 2 == TotalAllowedNum)
3381 Values += " or ";
3382 else if (AllowedCnt + 1 != TotalAllowedNum)
3383 Values += Sep;
3384 ++AllowedCnt;
3385 }
3386 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003387 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003388 diag::err_omp_unnamed_if_clause)
3389 << (TotalAllowedNum > 1) << Values;
3390 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003391 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003392 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3393 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003394 ErrorFound = true;
3395 }
3396 return ErrorFound;
3397}
3398
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003399StmtResult Sema::ActOnOpenMPExecutableDirective(
3400 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3401 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3402 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003403 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003404 // First check CancelRegion which is then used in checkNestingOfRegions.
3405 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3406 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003407 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003408 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003409
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003410 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003411 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003412 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003413 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003414 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003415 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3416
3417 // Check default data sharing attributes for referenced variables.
3418 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003419 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3420 Stmt *S = AStmt;
3421 while (--ThisCaptureLevel >= 0)
3422 S = cast<CapturedStmt>(S)->getCapturedStmt();
3423 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003424 if (DSAChecker.isErrorFound())
3425 return StmtError();
3426 // Generate list of implicitly defined firstprivate variables.
3427 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003428
Alexey Bataev88202be2017-07-27 13:20:36 +00003429 SmallVector<Expr *, 4> ImplicitFirstprivates(
3430 DSAChecker.getImplicitFirstprivate().begin(),
3431 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003432 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3433 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003434 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003435 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003436 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003437 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003438 if (E)
3439 ImplicitFirstprivates.emplace_back(E);
3440 }
3441 }
3442 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003443 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003444 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3445 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003446 ClausesWithImplicit.push_back(Implicit);
3447 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003448 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003449 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003450 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003451 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003452 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003453 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003454 CXXScopeSpec MapperIdScopeSpec;
3455 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003456 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003457 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3458 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3459 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003460 ClausesWithImplicit.emplace_back(Implicit);
3461 ErrorFound |=
3462 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003463 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003464 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003465 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003466 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003467 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003468
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003469 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003470 switch (Kind) {
3471 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003472 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3473 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003474 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003475 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003476 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003477 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3478 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003479 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003480 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003481 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3482 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003483 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003484 case OMPD_for_simd:
3485 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3486 EndLoc, VarsWithInheritedDSA);
3487 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003488 case OMPD_sections:
3489 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3490 EndLoc);
3491 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003492 case OMPD_section:
3493 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003494 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003495 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3496 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003497 case OMPD_single:
3498 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3499 EndLoc);
3500 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003501 case OMPD_master:
3502 assert(ClausesWithImplicit.empty() &&
3503 "No clauses are allowed for 'omp master' directive");
3504 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3505 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003506 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003507 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3508 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003509 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003510 case OMPD_parallel_for:
3511 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3512 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003513 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003514 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003515 case OMPD_parallel_for_simd:
3516 Res = ActOnOpenMPParallelForSimdDirective(
3517 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003518 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003519 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003520 case OMPD_parallel_sections:
3521 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3522 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003523 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003524 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003525 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003526 Res =
3527 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003528 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003529 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003530 case OMPD_taskyield:
3531 assert(ClausesWithImplicit.empty() &&
3532 "No clauses are allowed for 'omp taskyield' directive");
3533 assert(AStmt == nullptr &&
3534 "No associated statement allowed for 'omp taskyield' directive");
3535 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3536 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003537 case OMPD_barrier:
3538 assert(ClausesWithImplicit.empty() &&
3539 "No clauses are allowed for 'omp barrier' directive");
3540 assert(AStmt == nullptr &&
3541 "No associated statement allowed for 'omp barrier' directive");
3542 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3543 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003544 case OMPD_taskwait:
3545 assert(ClausesWithImplicit.empty() &&
3546 "No clauses are allowed for 'omp taskwait' directive");
3547 assert(AStmt == nullptr &&
3548 "No associated statement allowed for 'omp taskwait' directive");
3549 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3550 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003551 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003552 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3553 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003554 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003555 case OMPD_flush:
3556 assert(AStmt == nullptr &&
3557 "No associated statement allowed for 'omp flush' directive");
3558 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3559 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003560 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003561 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3562 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003563 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003564 case OMPD_atomic:
3565 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3566 EndLoc);
3567 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003568 case OMPD_teams:
3569 Res =
3570 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3571 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003572 case OMPD_target:
3573 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3574 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003575 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003576 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003577 case OMPD_target_parallel:
3578 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3579 StartLoc, EndLoc);
3580 AllowedNameModifiers.push_back(OMPD_target);
3581 AllowedNameModifiers.push_back(OMPD_parallel);
3582 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003583 case OMPD_target_parallel_for:
3584 Res = ActOnOpenMPTargetParallelForDirective(
3585 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3586 AllowedNameModifiers.push_back(OMPD_target);
3587 AllowedNameModifiers.push_back(OMPD_parallel);
3588 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003589 case OMPD_cancellation_point:
3590 assert(ClausesWithImplicit.empty() &&
3591 "No clauses are allowed for 'omp cancellation point' directive");
3592 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3593 "cancellation point' directive");
3594 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3595 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003596 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003597 assert(AStmt == nullptr &&
3598 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003599 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3600 CancelRegion);
3601 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003602 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003603 case OMPD_target_data:
3604 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3605 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003606 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003607 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003608 case OMPD_target_enter_data:
3609 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003610 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003611 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3612 break;
Samuel Antao72590762016-01-19 20:04:50 +00003613 case OMPD_target_exit_data:
3614 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003615 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003616 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3617 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003618 case OMPD_taskloop:
3619 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3620 EndLoc, VarsWithInheritedDSA);
3621 AllowedNameModifiers.push_back(OMPD_taskloop);
3622 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003623 case OMPD_taskloop_simd:
3624 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3625 EndLoc, VarsWithInheritedDSA);
3626 AllowedNameModifiers.push_back(OMPD_taskloop);
3627 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003628 case OMPD_distribute:
3629 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3630 EndLoc, VarsWithInheritedDSA);
3631 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003632 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003633 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3634 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003635 AllowedNameModifiers.push_back(OMPD_target_update);
3636 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003637 case OMPD_distribute_parallel_for:
3638 Res = ActOnOpenMPDistributeParallelForDirective(
3639 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3640 AllowedNameModifiers.push_back(OMPD_parallel);
3641 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003642 case OMPD_distribute_parallel_for_simd:
3643 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3644 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3645 AllowedNameModifiers.push_back(OMPD_parallel);
3646 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003647 case OMPD_distribute_simd:
3648 Res = ActOnOpenMPDistributeSimdDirective(
3649 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3650 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003651 case OMPD_target_parallel_for_simd:
3652 Res = ActOnOpenMPTargetParallelForSimdDirective(
3653 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3654 AllowedNameModifiers.push_back(OMPD_target);
3655 AllowedNameModifiers.push_back(OMPD_parallel);
3656 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003657 case OMPD_target_simd:
3658 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3659 EndLoc, VarsWithInheritedDSA);
3660 AllowedNameModifiers.push_back(OMPD_target);
3661 break;
Kelvin Li02532872016-08-05 14:37:37 +00003662 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003663 Res = ActOnOpenMPTeamsDistributeDirective(
3664 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003665 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003666 case OMPD_teams_distribute_simd:
3667 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3668 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3669 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003670 case OMPD_teams_distribute_parallel_for_simd:
3671 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3672 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3673 AllowedNameModifiers.push_back(OMPD_parallel);
3674 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003675 case OMPD_teams_distribute_parallel_for:
3676 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3677 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3678 AllowedNameModifiers.push_back(OMPD_parallel);
3679 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003680 case OMPD_target_teams:
3681 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3682 EndLoc);
3683 AllowedNameModifiers.push_back(OMPD_target);
3684 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003685 case OMPD_target_teams_distribute:
3686 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3687 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3688 AllowedNameModifiers.push_back(OMPD_target);
3689 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003690 case OMPD_target_teams_distribute_parallel_for:
3691 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3692 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3693 AllowedNameModifiers.push_back(OMPD_target);
3694 AllowedNameModifiers.push_back(OMPD_parallel);
3695 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003696 case OMPD_target_teams_distribute_parallel_for_simd:
3697 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3698 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3699 AllowedNameModifiers.push_back(OMPD_target);
3700 AllowedNameModifiers.push_back(OMPD_parallel);
3701 break;
Kelvin Lida681182017-01-10 18:08:18 +00003702 case OMPD_target_teams_distribute_simd:
3703 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3704 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3705 AllowedNameModifiers.push_back(OMPD_target);
3706 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003707 case OMPD_declare_target:
3708 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003709 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003710 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003711 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003712 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003713 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003714 llvm_unreachable("OpenMP Directive is not allowed");
3715 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003716 llvm_unreachable("Unknown OpenMP directive");
3717 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003718
Alexey Bataeve3727102018-04-18 15:57:46 +00003719 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003720 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3721 << P.first << P.second->getSourceRange();
3722 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003723 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3724
3725 if (!AllowedNameModifiers.empty())
3726 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3727 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003728
Alexey Bataeved09d242014-05-28 05:53:51 +00003729 if (ErrorFound)
3730 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003731 return Res;
3732}
3733
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003734Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3735 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003736 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003737 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3738 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003739 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003740 assert(Linears.size() == LinModifiers.size());
3741 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003742 if (!DG || DG.get().isNull())
3743 return DeclGroupPtrTy();
3744
3745 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003746 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003747 return DG;
3748 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003749 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003750 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3751 ADecl = FTD->getTemplatedDecl();
3752
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003753 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3754 if (!FD) {
3755 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003756 return DeclGroupPtrTy();
3757 }
3758
Alexey Bataev2af33e32016-04-07 12:45:37 +00003759 // OpenMP [2.8.2, declare simd construct, Description]
3760 // The parameter of the simdlen clause must be a constant positive integer
3761 // expression.
3762 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003763 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003764 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003765 // OpenMP [2.8.2, declare simd construct, Description]
3766 // The special this pointer can be used as if was one of the arguments to the
3767 // function in any of the linear, aligned, or uniform clauses.
3768 // The uniform clause declares one or more arguments to have an invariant
3769 // value for all concurrent invocations of the function in the execution of a
3770 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00003771 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3772 const Expr *UniformedLinearThis = nullptr;
3773 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003774 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003775 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3776 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003777 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3778 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003779 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00003780 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003781 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003782 }
3783 if (isa<CXXThisExpr>(E)) {
3784 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003785 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003786 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003787 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3788 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003789 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003790 // OpenMP [2.8.2, declare simd construct, Description]
3791 // The aligned clause declares that the object to which each list item points
3792 // is aligned to the number of bytes expressed in the optional parameter of
3793 // the aligned clause.
3794 // The special this pointer can be used as if was one of the arguments to the
3795 // function in any of the linear, aligned, or uniform clauses.
3796 // The type of list items appearing in the aligned clause must be array,
3797 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00003798 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3799 const Expr *AlignedThis = nullptr;
3800 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003801 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003802 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3803 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3804 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00003805 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3806 FD->getParamDecl(PVD->getFunctionScopeIndex())
3807 ->getCanonicalDecl() == CanonPVD) {
3808 // OpenMP [2.8.1, simd construct, Restrictions]
3809 // A list-item cannot appear in more than one aligned clause.
3810 if (AlignedArgs.count(CanonPVD) > 0) {
3811 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3812 << 1 << E->getSourceRange();
3813 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3814 diag::note_omp_explicit_dsa)
3815 << getOpenMPClauseName(OMPC_aligned);
3816 continue;
3817 }
3818 AlignedArgs[CanonPVD] = E;
3819 QualType QTy = PVD->getType()
3820 .getNonReferenceType()
3821 .getUnqualifiedType()
3822 .getCanonicalType();
3823 const Type *Ty = QTy.getTypePtrOrNull();
3824 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3825 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3826 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3827 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3828 }
3829 continue;
3830 }
3831 }
3832 if (isa<CXXThisExpr>(E)) {
3833 if (AlignedThis) {
3834 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3835 << 2 << E->getSourceRange();
3836 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3837 << getOpenMPClauseName(OMPC_aligned);
3838 }
3839 AlignedThis = E;
3840 continue;
3841 }
3842 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3843 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3844 }
3845 // The optional parameter of the aligned clause, alignment, must be a constant
3846 // positive integer expression. If no optional parameter is specified,
3847 // implementation-defined default alignments for SIMD instructions on the
3848 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00003849 SmallVector<const Expr *, 4> NewAligns;
3850 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003851 ExprResult Align;
3852 if (E)
3853 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3854 NewAligns.push_back(Align.get());
3855 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003856 // OpenMP [2.8.2, declare simd construct, Description]
3857 // The linear clause declares one or more list items to be private to a SIMD
3858 // lane and to have a linear relationship with respect to the iteration space
3859 // of a loop.
3860 // The special this pointer can be used as if was one of the arguments to the
3861 // function in any of the linear, aligned, or uniform clauses.
3862 // When a linear-step expression is specified in a linear clause it must be
3863 // either a constant integer expression or an integer-typed parameter that is
3864 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00003865 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003866 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3867 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00003868 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003869 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3870 ++MI;
3871 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003872 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3873 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3874 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003875 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3876 FD->getParamDecl(PVD->getFunctionScopeIndex())
3877 ->getCanonicalDecl() == CanonPVD) {
3878 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3879 // A list-item cannot appear in more than one linear clause.
3880 if (LinearArgs.count(CanonPVD) > 0) {
3881 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3882 << getOpenMPClauseName(OMPC_linear)
3883 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3884 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3885 diag::note_omp_explicit_dsa)
3886 << getOpenMPClauseName(OMPC_linear);
3887 continue;
3888 }
3889 // Each argument can appear in at most one uniform or linear clause.
3890 if (UniformedArgs.count(CanonPVD) > 0) {
3891 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3892 << getOpenMPClauseName(OMPC_linear)
3893 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3894 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3895 diag::note_omp_explicit_dsa)
3896 << getOpenMPClauseName(OMPC_uniform);
3897 continue;
3898 }
3899 LinearArgs[CanonPVD] = E;
3900 if (E->isValueDependent() || E->isTypeDependent() ||
3901 E->isInstantiationDependent() ||
3902 E->containsUnexpandedParameterPack())
3903 continue;
3904 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3905 PVD->getOriginalType());
3906 continue;
3907 }
3908 }
3909 if (isa<CXXThisExpr>(E)) {
3910 if (UniformedLinearThis) {
3911 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3912 << getOpenMPClauseName(OMPC_linear)
3913 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3914 << E->getSourceRange();
3915 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3916 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3917 : OMPC_linear);
3918 continue;
3919 }
3920 UniformedLinearThis = E;
3921 if (E->isValueDependent() || E->isTypeDependent() ||
3922 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3923 continue;
3924 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3925 E->getType());
3926 continue;
3927 }
3928 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3929 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3930 }
3931 Expr *Step = nullptr;
3932 Expr *NewStep = nullptr;
3933 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00003934 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003935 // Skip the same step expression, it was checked already.
3936 if (Step == E || !E) {
3937 NewSteps.push_back(E ? NewStep : nullptr);
3938 continue;
3939 }
3940 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00003941 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
3942 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3943 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003944 if (UniformedArgs.count(CanonPVD) == 0) {
3945 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3946 << Step->getSourceRange();
3947 } else if (E->isValueDependent() || E->isTypeDependent() ||
3948 E->isInstantiationDependent() ||
3949 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00003950 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003951 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00003952 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003953 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3954 << Step->getSourceRange();
3955 }
3956 continue;
3957 }
3958 NewStep = Step;
3959 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3960 !Step->isInstantiationDependent() &&
3961 !Step->containsUnexpandedParameterPack()) {
3962 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3963 .get();
3964 if (NewStep)
3965 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3966 }
3967 NewSteps.push_back(NewStep);
3968 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003969 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3970 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003971 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003972 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3973 const_cast<Expr **>(Linears.data()), Linears.size(),
3974 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3975 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003976 ADecl->addAttr(NewAttr);
3977 return ConvertDeclToDeclGroup(ADecl);
3978}
3979
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003980StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3981 Stmt *AStmt,
3982 SourceLocation StartLoc,
3983 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003984 if (!AStmt)
3985 return StmtError();
3986
Alexey Bataeve3727102018-04-18 15:57:46 +00003987 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00003988 // 1.2.2 OpenMP Language Terminology
3989 // Structured block - An executable statement with a single entry at the
3990 // top and a single exit at the bottom.
3991 // The point of exit cannot be a branch out of the structured block.
3992 // longjmp() and throw() must not violate the entry/exit criteria.
3993 CS->getCapturedDecl()->setNothrow();
3994
Reid Kleckner87a31802018-03-12 21:43:02 +00003995 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003996
Alexey Bataev25e5b442015-09-15 12:52:43 +00003997 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3998 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003999}
4000
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004001namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004002/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004003/// extracting iteration space of each loop in the loop nest, that will be used
4004/// for IR generation.
4005class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004006 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004007 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004008 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004009 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004010 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004011 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004012 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004013 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004014 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004015 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004016 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004017 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004018 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004019 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004020 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004021 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004022 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004023 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004024 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004025 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004026 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004027 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004028 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004029 /// Var < UB
4030 /// Var <= UB
4031 /// UB > Var
4032 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004033 /// This will have no value when the condition is !=
4034 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004035 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004036 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004037 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004038 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004039
4040public:
4041 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004042 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004043 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004044 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004045 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004046 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004047 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004048 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004049 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004050 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004051 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004052 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004053 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004054 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004055 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004056 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004057 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004058 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004059 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004060 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004061 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004062 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004063 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004064 /// True, if the compare operator is strict (<, > or !=).
4065 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004066 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004067 Expr *buildNumIterations(
4068 Scope *S, const bool LimitedType,
4069 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004070 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004071 Expr *
4072 buildPreCond(Scope *S, Expr *Cond,
4073 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004074 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004075 DeclRefExpr *
4076 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4077 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004078 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004079 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004080 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004081 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004082 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004083 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004084 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004085 /// Build loop data with counter value for depend clauses in ordered
4086 /// directives.
4087 Expr *
4088 buildOrderedLoopData(Scope *S, Expr *Counter,
4089 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4090 SourceLocation Loc, Expr *Inc = nullptr,
4091 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004092 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004093 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004094
4095private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004096 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004097 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004098 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004099 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004100 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004101 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004102 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4103 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004104 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004105 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004106};
4107
Alexey Bataeve3727102018-04-18 15:57:46 +00004108bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004109 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004110 assert(!LB && !UB && !Step);
4111 return false;
4112 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004113 return LCDecl->getType()->isDependentType() ||
4114 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4115 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004116}
4117
Alexey Bataeve3727102018-04-18 15:57:46 +00004118bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004119 Expr *NewLCRefExpr,
4120 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004121 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004122 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004123 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004124 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004125 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004126 LCDecl = getCanonicalDecl(NewLCDecl);
4127 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004128 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4129 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004130 if ((Ctor->isCopyOrMoveConstructor() ||
4131 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4132 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004133 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004134 LB = NewLB;
4135 return false;
4136}
4137
Alexey Bataev316ccf62019-01-29 18:51:58 +00004138bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4139 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004140 bool StrictOp, SourceRange SR,
4141 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004142 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004143 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4144 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004145 if (!NewUB)
4146 return true;
4147 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004148 if (LessOp)
4149 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004150 TestIsStrictOp = StrictOp;
4151 ConditionSrcRange = SR;
4152 ConditionLoc = SL;
4153 return false;
4154}
4155
Alexey Bataeve3727102018-04-18 15:57:46 +00004156bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004157 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004158 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004159 if (!NewStep)
4160 return true;
4161 if (!NewStep->isValueDependent()) {
4162 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004163 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004164 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4165 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004166 if (Val.isInvalid())
4167 return true;
4168 NewStep = Val.get();
4169
4170 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4171 // If test-expr is of form var relational-op b and relational-op is < or
4172 // <= then incr-expr must cause var to increase on each iteration of the
4173 // loop. If test-expr is of form var relational-op b and relational-op is
4174 // > or >= then incr-expr must cause var to decrease on each iteration of
4175 // the loop.
4176 // If test-expr is of form b relational-op var and relational-op is < or
4177 // <= then incr-expr must cause var to decrease on each iteration of the
4178 // loop. If test-expr is of form b relational-op var and relational-op is
4179 // > or >= then incr-expr must cause var to increase on each iteration of
4180 // the loop.
4181 llvm::APSInt Result;
4182 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4183 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4184 bool IsConstNeg =
4185 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004186 bool IsConstPos =
4187 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004188 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004189
4190 // != with increment is treated as <; != with decrement is treated as >
4191 if (!TestIsLessOp.hasValue())
4192 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004193 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004194 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004195 (IsConstNeg || (IsUnsigned && Subtract)) :
4196 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004197 SemaRef.Diag(NewStep->getExprLoc(),
4198 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004199 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004200 SemaRef.Diag(ConditionLoc,
4201 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004202 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004203 return true;
4204 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004205 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004206 NewStep =
4207 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4208 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004209 Subtract = !Subtract;
4210 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004211 }
4212
4213 Step = NewStep;
4214 SubtractStep = Subtract;
4215 return false;
4216}
4217
Alexey Bataeve3727102018-04-18 15:57:46 +00004218bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004219 // Check init-expr for canonical loop form and save loop counter
4220 // variable - #Var and its initialization value - #LB.
4221 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4222 // var = lb
4223 // integer-type var = lb
4224 // random-access-iterator-type var = lb
4225 // pointer-type var = lb
4226 //
4227 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004228 if (EmitDiags) {
4229 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4230 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004231 return true;
4232 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004233 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4234 if (!ExprTemp->cleanupsHaveSideEffects())
4235 S = ExprTemp->getSubExpr();
4236
Alexander Musmana5f070a2014-10-01 06:03:56 +00004237 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004238 if (Expr *E = dyn_cast<Expr>(S))
4239 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004240 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004241 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004242 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004243 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4244 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4245 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004246 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4247 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004248 }
4249 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4250 if (ME->isArrow() &&
4251 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004252 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004253 }
4254 }
David Majnemer9d168222016-08-05 17:44:54 +00004255 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004256 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004257 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004258 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004259 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004260 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004261 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004262 diag::ext_omp_loop_not_canonical_init)
4263 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004264 return setLCDeclAndLB(
4265 Var,
4266 buildDeclRefExpr(SemaRef, Var,
4267 Var->getType().getNonReferenceType(),
4268 DS->getBeginLoc()),
4269 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004270 }
4271 }
4272 }
David Majnemer9d168222016-08-05 17:44:54 +00004273 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004274 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004275 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004276 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004277 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4278 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004279 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4280 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004281 }
4282 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4283 if (ME->isArrow() &&
4284 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004285 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004286 }
4287 }
4288 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004289
Alexey Bataeve3727102018-04-18 15:57:46 +00004290 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004291 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004292 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004293 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004294 << S->getSourceRange();
4295 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004296 return true;
4297}
4298
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004299/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004300/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004301static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004302 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004303 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004304 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004305 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004306 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004307 if ((Ctor->isCopyOrMoveConstructor() ||
4308 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4309 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004310 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004311 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4312 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004313 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004314 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004315 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004316 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4317 return getCanonicalDecl(ME->getMemberDecl());
4318 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004319}
4320
Alexey Bataeve3727102018-04-18 15:57:46 +00004321bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004322 // Check test-expr for canonical form, save upper-bound UB, flags for
4323 // less/greater and for strict/non-strict comparison.
4324 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4325 // var relational-op b
4326 // b relational-op var
4327 //
4328 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004329 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004330 return true;
4331 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004332 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004333 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004334 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004335 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004336 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4337 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004338 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4339 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4340 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004341 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4342 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004343 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4344 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4345 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004346 } else if (BO->getOpcode() == BO_NE)
4347 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4348 BO->getRHS() : BO->getLHS(),
4349 /*LessOp=*/llvm::None,
4350 /*StrictOp=*/true,
4351 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004352 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004353 if (CE->getNumArgs() == 2) {
4354 auto Op = CE->getOperator();
4355 switch (Op) {
4356 case OO_Greater:
4357 case OO_GreaterEqual:
4358 case OO_Less:
4359 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004360 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4361 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004362 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4363 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004364 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4365 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004366 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4367 CE->getOperatorLoc());
4368 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004369 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004370 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4371 CE->getArg(1) : CE->getArg(0),
4372 /*LessOp=*/llvm::None,
4373 /*StrictOp=*/true,
4374 CE->getSourceRange(),
4375 CE->getOperatorLoc());
4376 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004377 default:
4378 break;
4379 }
4380 }
4381 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004382 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004383 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004384 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004385 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004386 return true;
4387}
4388
Alexey Bataeve3727102018-04-18 15:57:46 +00004389bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004390 // RHS of canonical loop form increment can be:
4391 // var + incr
4392 // incr + var
4393 // var - incr
4394 //
4395 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004396 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004397 if (BO->isAdditiveOp()) {
4398 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004399 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4400 return setStep(BO->getRHS(), !IsAdd);
4401 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4402 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004403 }
David Majnemer9d168222016-08-05 17:44:54 +00004404 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004405 bool IsAdd = CE->getOperator() == OO_Plus;
4406 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004407 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4408 return setStep(CE->getArg(1), !IsAdd);
4409 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4410 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004411 }
4412 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004413 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004414 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004415 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004416 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004417 return true;
4418}
4419
Alexey Bataeve3727102018-04-18 15:57:46 +00004420bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004421 // Check incr-expr for canonical loop form and return true if it
4422 // does not conform.
4423 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4424 // ++var
4425 // var++
4426 // --var
4427 // var--
4428 // var += incr
4429 // var -= incr
4430 // var = var + incr
4431 // var = incr + var
4432 // var = var - incr
4433 //
4434 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004435 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004436 return true;
4437 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004438 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4439 if (!ExprTemp->cleanupsHaveSideEffects())
4440 S = ExprTemp->getSubExpr();
4441
Alexander Musmana5f070a2014-10-01 06:03:56 +00004442 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004443 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004444 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004445 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004446 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4447 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004448 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004449 (UO->isDecrementOp() ? -1 : 1))
4450 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004451 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004452 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004453 switch (BO->getOpcode()) {
4454 case BO_AddAssign:
4455 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004456 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4457 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004458 break;
4459 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004460 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4461 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004462 break;
4463 default:
4464 break;
4465 }
David Majnemer9d168222016-08-05 17:44:54 +00004466 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004467 switch (CE->getOperator()) {
4468 case OO_PlusPlus:
4469 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004470 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4471 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004472 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004473 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004474 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4475 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004476 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004477 break;
4478 case OO_PlusEqual:
4479 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004480 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4481 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004482 break;
4483 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004484 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4485 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004486 break;
4487 default:
4488 break;
4489 }
4490 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004491 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004492 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004493 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004494 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004495 return true;
4496}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004497
Alexey Bataev5a3af132016-03-29 08:58:54 +00004498static ExprResult
4499tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004500 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004501 if (SemaRef.CurContext->isDependentContext())
4502 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004503 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4504 return SemaRef.PerformImplicitConversion(
4505 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4506 /*AllowExplicit=*/true);
4507 auto I = Captures.find(Capture);
4508 if (I != Captures.end())
4509 return buildCapture(SemaRef, Capture, I->second);
4510 DeclRefExpr *Ref = nullptr;
4511 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4512 Captures[Capture] = Ref;
4513 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004514}
4515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004516/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004517Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004518 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004519 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004520 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004521 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004522 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004523 SemaRef.getLangOpts().CPlusPlus) {
4524 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004525 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4526 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004527 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4528 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004529 if (!Upper || !Lower)
4530 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004531
4532 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4533
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004534 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004535 // BuildBinOp already emitted error, this one is to point user to upper
4536 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004537 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004538 << Upper->getSourceRange() << Lower->getSourceRange();
4539 return nullptr;
4540 }
4541 }
4542
4543 if (!Diff.isUsable())
4544 return nullptr;
4545
4546 // Upper - Lower [- 1]
4547 if (TestIsStrictOp)
4548 Diff = SemaRef.BuildBinOp(
4549 S, DefaultLoc, BO_Sub, Diff.get(),
4550 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4551 if (!Diff.isUsable())
4552 return nullptr;
4553
4554 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004555 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004556 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004557 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004558 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004559 if (!Diff.isUsable())
4560 return nullptr;
4561
4562 // Parentheses (for dumping/debugging purposes only).
4563 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4564 if (!Diff.isUsable())
4565 return nullptr;
4566
4567 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004568 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004569 if (!Diff.isUsable())
4570 return nullptr;
4571
Alexander Musman174b3ca2014-10-06 11:16:29 +00004572 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004573 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004574 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004575 bool UseVarType = VarType->hasIntegerRepresentation() &&
4576 C.getTypeSize(Type) > C.getTypeSize(VarType);
4577 if (!Type->isIntegerType() || UseVarType) {
4578 unsigned NewSize =
4579 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4580 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4581 : Type->hasSignedIntegerRepresentation();
4582 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004583 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4584 Diff = SemaRef.PerformImplicitConversion(
4585 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4586 if (!Diff.isUsable())
4587 return nullptr;
4588 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004589 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004590 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004591 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4592 if (NewSize != C.getTypeSize(Type)) {
4593 if (NewSize < C.getTypeSize(Type)) {
4594 assert(NewSize == 64 && "incorrect loop var size");
4595 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4596 << InitSrcRange << ConditionSrcRange;
4597 }
4598 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004599 NewSize, Type->hasSignedIntegerRepresentation() ||
4600 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004601 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4602 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4603 Sema::AA_Converting, true);
4604 if (!Diff.isUsable())
4605 return nullptr;
4606 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004607 }
4608 }
4609
Alexander Musmana5f070a2014-10-01 06:03:56 +00004610 return Diff.get();
4611}
4612
Alexey Bataeve3727102018-04-18 15:57:46 +00004613Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004614 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004615 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004616 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4617 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4618 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004619
Alexey Bataeve3727102018-04-18 15:57:46 +00004620 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4621 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004622 if (!NewLB.isUsable() || !NewUB.isUsable())
4623 return nullptr;
4624
Alexey Bataeve3727102018-04-18 15:57:46 +00004625 ExprResult CondExpr =
4626 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004627 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004628 (TestIsStrictOp ? BO_LT : BO_LE) :
4629 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004630 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004631 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004632 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4633 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004634 CondExpr = SemaRef.PerformImplicitConversion(
4635 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4636 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004637 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004638 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00004639 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004640 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4641}
4642
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004643/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004644DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004645 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4646 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004647 auto *VD = dyn_cast<VarDecl>(LCDecl);
4648 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004649 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4650 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004651 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004652 const DSAStackTy::DSAVarData Data =
4653 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004654 // If the loop control decl is explicitly marked as private, do not mark it
4655 // as captured again.
4656 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4657 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004658 return Ref;
4659 }
4660 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004661 DefaultLoc);
4662}
4663
Alexey Bataeve3727102018-04-18 15:57:46 +00004664Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004665 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004666 QualType Type = LCDecl->getType().getNonReferenceType();
4667 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004668 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4669 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4670 isa<VarDecl>(LCDecl)
4671 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4672 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004673 if (PrivateVar->isInvalidDecl())
4674 return nullptr;
4675 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4676 }
4677 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004678}
4679
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004680/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004681Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004682
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004683/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004684Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004685
Alexey Bataevf138fda2018-08-13 19:04:24 +00004686Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4687 Scope *S, Expr *Counter,
4688 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4689 Expr *Inc, OverloadedOperatorKind OOK) {
4690 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4691 if (!Cnt)
4692 return nullptr;
4693 if (Inc) {
4694 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4695 "Expected only + or - operations for depend clauses.");
4696 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4697 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4698 if (!Cnt)
4699 return nullptr;
4700 }
4701 ExprResult Diff;
4702 QualType VarType = LCDecl->getType().getNonReferenceType();
4703 if (VarType->isIntegerType() || VarType->isPointerType() ||
4704 SemaRef.getLangOpts().CPlusPlus) {
4705 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00004706 Expr *Upper = TestIsLessOp.getValue()
4707 ? Cnt
4708 : tryBuildCapture(SemaRef, UB, Captures).get();
4709 Expr *Lower = TestIsLessOp.getValue()
4710 ? tryBuildCapture(SemaRef, LB, Captures).get()
4711 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004712 if (!Upper || !Lower)
4713 return nullptr;
4714
4715 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4716
4717 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4718 // BuildBinOp already emitted error, this one is to point user to upper
4719 // and lower bound, and to tell what is passed to 'operator-'.
4720 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4721 << Upper->getSourceRange() << Lower->getSourceRange();
4722 return nullptr;
4723 }
4724 }
4725
4726 if (!Diff.isUsable())
4727 return nullptr;
4728
4729 // Parentheses (for dumping/debugging purposes only).
4730 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4731 if (!Diff.isUsable())
4732 return nullptr;
4733
4734 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4735 if (!NewStep.isUsable())
4736 return nullptr;
4737 // (Upper - Lower) / Step
4738 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4739 if (!Diff.isUsable())
4740 return nullptr;
4741
4742 return Diff.get();
4743}
4744
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004745/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004746struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00004747 /// True if the condition operator is the strict compare operator (<, > or
4748 /// !=).
4749 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004750 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004751 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004752 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004753 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004754 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004755 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004756 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004757 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004758 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004759 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004760 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004761 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00004762 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004763 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004764 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004765 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004766 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004767 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004768 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004769 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004770 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004771 SourceRange IncSrcRange;
4772};
4773
Alexey Bataev23b69422014-06-18 07:08:49 +00004774} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004775
Alexey Bataev9c821032015-04-30 04:23:23 +00004776void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4777 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4778 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004779 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4780 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004781 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00004782 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00004783 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004784 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4785 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004786 auto *VD = dyn_cast<VarDecl>(D);
4787 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004788 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004789 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00004790 } else {
4791 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4792 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004793 VD = cast<VarDecl>(Ref->getDecl());
4794 }
4795 }
4796 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00004797 const Decl *LD = DSAStack->getPossiblyLoopCunter();
4798 if (LD != D->getCanonicalDecl()) {
4799 DSAStack->resetPossibleLoopCounter();
4800 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
4801 MarkDeclarationsReferencedInExpr(
4802 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
4803 Var->getType().getNonLValueExprType(Context),
4804 ForLoc, /*RefersToCapture=*/true));
4805 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004806 }
4807 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004808 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004809 }
4810}
4811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004812/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004813/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00004814static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00004815 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4816 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00004817 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
4818 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00004819 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004820 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00004821 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004822 // OpenMP [2.6, Canonical Loop Form]
4823 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004824 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004825 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004826 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004827 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00004828 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00004829 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004830 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00004831 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4832 SemaRef.Diag(DSA.getConstructLoc(),
4833 diag::note_omp_collapse_ordered_expr)
4834 << 2 << CollapseLoopCountExpr->getSourceRange()
4835 << OrderedLoopCountExpr->getSourceRange();
4836 else if (CollapseLoopCountExpr)
4837 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4838 diag::note_omp_collapse_ordered_expr)
4839 << 0 << CollapseLoopCountExpr->getSourceRange();
4840 else
4841 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4842 diag::note_omp_collapse_ordered_expr)
4843 << 1 << OrderedLoopCountExpr->getSourceRange();
4844 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004845 return true;
4846 }
4847 assert(For->getBody());
4848
4849 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4850
4851 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004852 Stmt *Init = For->getInit();
4853 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004854 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004855
4856 bool HasErrors = false;
4857
4858 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004859 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4860 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004861
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004862 // OpenMP [2.6, Canonical Loop Form]
4863 // Var is one of the following:
4864 // A variable of signed or unsigned integer type.
4865 // For C++, a variable of a random access iterator type.
4866 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004867 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004868 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4869 !VarType->isPointerType() &&
4870 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004871 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004872 << SemaRef.getLangOpts().CPlusPlus;
4873 HasErrors = true;
4874 }
4875
4876 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4877 // a Construct
4878 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4879 // parallel for construct is (are) private.
4880 // The loop iteration variable in the associated for-loop of a simd
4881 // construct with just one associated for-loop is linear with a
4882 // constant-linear-step that is the increment of the associated for-loop.
4883 // Exclude loop var from the list of variables with implicitly defined data
4884 // sharing attributes.
4885 VarsWithImplicitDSA.erase(LCDecl);
4886
4887 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4888 // in a Construct, C/C++].
4889 // The loop iteration variable in the associated for-loop of a simd
4890 // construct with just one associated for-loop may be listed in a linear
4891 // clause with a constant-linear-step that is the increment of the
4892 // associated for-loop.
4893 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4894 // parallel for construct may be listed in a private or lastprivate clause.
4895 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4896 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4897 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00004898 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004899 isOpenMPSimdDirective(DKind)
4900 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4901 : OMPC_private;
4902 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4903 DVar.CKind != PredeterminedCKind) ||
4904 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4905 isOpenMPDistributeDirective(DKind)) &&
4906 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4907 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4908 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004909 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004910 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4911 << getOpenMPClauseName(PredeterminedCKind);
4912 if (DVar.RefExpr == nullptr)
4913 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00004914 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004915 HasErrors = true;
4916 } else if (LoopDeclRefExpr != nullptr) {
4917 // Make the loop iteration variable private (for worksharing constructs),
4918 // linear (for simd directives with the only one associated loop) or
4919 // lastprivate (for simd directives with several collapsed or ordered
4920 // loops).
4921 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00004922 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004923 }
4924
4925 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4926
4927 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00004928 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004929
4930 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00004931 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004932 }
4933
Alexey Bataeve3727102018-04-18 15:57:46 +00004934 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004935 return HasErrors;
4936
Alexander Musmana5f070a2014-10-01 06:03:56 +00004937 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004938 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00004939 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4940 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004941 DSA.getCurScope(),
4942 (isOpenMPWorksharingDirective(DKind) ||
4943 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4944 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00004945 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
4946 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
4947 ResultIterSpace.CounterInit = ISC.buildCounterInit();
4948 ResultIterSpace.CounterStep = ISC.buildCounterStep();
4949 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
4950 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
4951 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
4952 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00004953 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004954
Alexey Bataev62dbb972015-04-22 11:59:37 +00004955 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4956 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004957 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004958 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004959 ResultIterSpace.CounterInit == nullptr ||
4960 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00004961 if (!HasErrors && DSA.isOrderedRegion()) {
4962 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
4963 if (CurrentNestedLoopCount <
4964 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
4965 DSA.getOrderedRegionParam().second->setLoopNumIterations(
4966 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
4967 DSA.getOrderedRegionParam().second->setLoopCounter(
4968 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
4969 }
4970 }
4971 for (auto &Pair : DSA.getDoacrossDependClauses()) {
4972 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
4973 // Erroneous case - clause has some problems.
4974 continue;
4975 }
4976 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
4977 Pair.second.size() <= CurrentNestedLoopCount) {
4978 // Erroneous case - clause has some problems.
4979 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
4980 continue;
4981 }
4982 Expr *CntValue;
4983 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4984 CntValue = ISC.buildOrderedLoopData(
4985 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4986 Pair.first->getDependencyLoc());
4987 else
4988 CntValue = ISC.buildOrderedLoopData(
4989 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4990 Pair.first->getDependencyLoc(),
4991 Pair.second[CurrentNestedLoopCount].first,
4992 Pair.second[CurrentNestedLoopCount].second);
4993 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
4994 }
4995 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004996
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004997 return HasErrors;
4998}
4999
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005000/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005001static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005002buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005003 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005004 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005005 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005006 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005007 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005008 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005009 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005010 VarRef.get()->getType())) {
5011 NewStart = SemaRef.PerformImplicitConversion(
5012 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5013 /*AllowExplicit=*/true);
5014 if (!NewStart.isUsable())
5015 return ExprError();
5016 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005017
Alexey Bataeve3727102018-04-18 15:57:46 +00005018 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005019 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5020 return Init;
5021}
5022
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005023/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005024static ExprResult buildCounterUpdate(
5025 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5026 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5027 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005028 // Add parentheses (for debugging purposes only).
5029 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5030 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5031 !Step.isUsable())
5032 return ExprError();
5033
Alexey Bataev5a3af132016-03-29 08:58:54 +00005034 ExprResult NewStep = Step;
5035 if (Captures)
5036 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005037 if (NewStep.isInvalid())
5038 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005039 ExprResult Update =
5040 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005041 if (!Update.isUsable())
5042 return ExprError();
5043
Alexey Bataevc0214e02016-02-16 12:13:49 +00005044 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5045 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005046 ExprResult NewStart = Start;
5047 if (Captures)
5048 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005049 if (NewStart.isInvalid())
5050 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005051
Alexey Bataevc0214e02016-02-16 12:13:49 +00005052 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5053 ExprResult SavedUpdate = Update;
5054 ExprResult UpdateVal;
5055 if (VarRef.get()->getType()->isOverloadableType() ||
5056 NewStart.get()->getType()->isOverloadableType() ||
5057 Update.get()->getType()->isOverloadableType()) {
5058 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5059 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5060 Update =
5061 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5062 if (Update.isUsable()) {
5063 UpdateVal =
5064 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5065 VarRef.get(), SavedUpdate.get());
5066 if (UpdateVal.isUsable()) {
5067 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5068 UpdateVal.get());
5069 }
5070 }
5071 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5072 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005073
Alexey Bataevc0214e02016-02-16 12:13:49 +00005074 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5075 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5076 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5077 NewStart.get(), SavedUpdate.get());
5078 if (!Update.isUsable())
5079 return ExprError();
5080
Alexey Bataev11481f52016-02-17 10:29:05 +00005081 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5082 VarRef.get()->getType())) {
5083 Update = SemaRef.PerformImplicitConversion(
5084 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5085 if (!Update.isUsable())
5086 return ExprError();
5087 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005088
5089 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5090 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005091 return Update;
5092}
5093
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005094/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005095/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005096static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005097 if (E == nullptr)
5098 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005099 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005100 QualType OldType = E->getType();
5101 unsigned HasBits = C.getTypeSize(OldType);
5102 if (HasBits >= Bits)
5103 return ExprResult(E);
5104 // OK to convert to signed, because new type has more bits than old.
5105 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5106 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5107 true);
5108}
5109
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005110/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005111/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005112static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005113 if (E == nullptr)
5114 return false;
5115 llvm::APSInt Result;
5116 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5117 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5118 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005119}
5120
Alexey Bataev5a3af132016-03-29 08:58:54 +00005121/// Build preinits statement for the given declarations.
5122static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005123 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005124 if (!PreInits.empty()) {
5125 return new (Context) DeclStmt(
5126 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5127 SourceLocation(), SourceLocation());
5128 }
5129 return nullptr;
5130}
5131
5132/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005133static Stmt *
5134buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005135 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005136 if (!Captures.empty()) {
5137 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005138 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005139 PreInits.push_back(Pair.second->getDecl());
5140 return buildPreInits(Context, PreInits);
5141 }
5142 return nullptr;
5143}
5144
5145/// Build postupdate expression for the given list of postupdates expressions.
5146static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5147 Expr *PostUpdate = nullptr;
5148 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005149 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005150 Expr *ConvE = S.BuildCStyleCastExpr(
5151 E->getExprLoc(),
5152 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5153 E->getExprLoc(), E)
5154 .get();
5155 PostUpdate = PostUpdate
5156 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5157 PostUpdate, ConvE)
5158 .get()
5159 : ConvE;
5160 }
5161 }
5162 return PostUpdate;
5163}
5164
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005165/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005166/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5167/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005168static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005169checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005170 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5171 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005172 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005173 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005174 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005175 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005176 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005177 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005178 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005179 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005180 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005181 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005182 if (OrderedLoopCountExpr) {
5183 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005184 Expr::EvalResult EVResult;
5185 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5186 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005187 if (Result.getLimitedValue() < NestedLoopCount) {
5188 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5189 diag::err_omp_wrong_ordered_loop_count)
5190 << OrderedLoopCountExpr->getSourceRange();
5191 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5192 diag::note_collapse_loop_count)
5193 << CollapseLoopCountExpr->getSourceRange();
5194 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005195 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005196 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005197 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005198 // This is helper routine for loop directives (e.g., 'for', 'simd',
5199 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005200 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005201 SmallVector<LoopIterationSpace, 4> IterSpaces(
5202 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005203 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005204 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005205 if (checkOpenMPIterationSpace(
5206 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5207 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5208 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5209 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005210 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005211 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005212 // OpenMP [2.8.1, simd construct, Restrictions]
5213 // All loops associated with the construct must be perfectly nested; that
5214 // is, there must be no intervening code nor any OpenMP directive between
5215 // any two loops.
5216 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005217 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005218 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5219 if (checkOpenMPIterationSpace(
5220 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5221 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5222 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5223 Captures))
5224 return 0;
5225 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5226 // Handle initialization of captured loop iterator variables.
5227 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5228 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5229 Captures[DRE] = DRE;
5230 }
5231 }
5232 // Move on to the next nested for loop, or to the loop body.
5233 // OpenMP [2.8.1, simd construct, Restrictions]
5234 // All loops associated with the construct must be perfectly nested; that
5235 // is, there must be no intervening code nor any OpenMP directive between
5236 // any two loops.
5237 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5238 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005239
Alexander Musmana5f070a2014-10-01 06:03:56 +00005240 Built.clear(/* size */ NestedLoopCount);
5241
5242 if (SemaRef.CurContext->isDependentContext())
5243 return NestedLoopCount;
5244
5245 // An example of what is generated for the following code:
5246 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005247 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005248 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005249 // for (k = 0; k < NK; ++k)
5250 // for (j = J0; j < NJ; j+=2) {
5251 // <loop body>
5252 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005253 //
5254 // We generate the code below.
5255 // Note: the loop body may be outlined in CodeGen.
5256 // Note: some counters may be C++ classes, operator- is used to find number of
5257 // iterations and operator+= to calculate counter value.
5258 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5259 // or i64 is currently supported).
5260 //
5261 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5262 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5263 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5264 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5265 // // similar updates for vars in clauses (e.g. 'linear')
5266 // <loop body (using local i and j)>
5267 // }
5268 // i = NI; // assign final values of counters
5269 // j = NJ;
5270 //
5271
5272 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5273 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005274 // Precondition tests if there is at least one iteration (all conditions are
5275 // true).
5276 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005277 Expr *N0 = IterSpaces[0].NumIterations;
5278 ExprResult LastIteration32 =
5279 widenIterationCount(/*Bits=*/32,
5280 SemaRef
5281 .PerformImplicitConversion(
5282 N0->IgnoreImpCasts(), N0->getType(),
5283 Sema::AA_Converting, /*AllowExplicit=*/true)
5284 .get(),
5285 SemaRef);
5286 ExprResult LastIteration64 = widenIterationCount(
5287 /*Bits=*/64,
5288 SemaRef
5289 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5290 Sema::AA_Converting,
5291 /*AllowExplicit=*/true)
5292 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005293 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005294
5295 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5296 return NestedLoopCount;
5297
Alexey Bataeve3727102018-04-18 15:57:46 +00005298 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005299 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5300
5301 Scope *CurScope = DSA.getCurScope();
5302 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005303 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005304 PreCond =
5305 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5306 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005307 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005308 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005309 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005310 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5311 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005312 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005313 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005314 SemaRef
5315 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5316 Sema::AA_Converting,
5317 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005318 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005319 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005320 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005321 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005322 SemaRef
5323 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5324 Sema::AA_Converting,
5325 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005326 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005327 }
5328
5329 // Choose either the 32-bit or 64-bit version.
5330 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005331 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5332 (LastIteration32.isUsable() &&
5333 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5334 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5335 fitsInto(
5336 /*Bits=*/32,
5337 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5338 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005339 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005340 QualType VType = LastIteration.get()->getType();
5341 QualType RealVType = VType;
5342 QualType StrideVType = VType;
5343 if (isOpenMPTaskLoopDirective(DKind)) {
5344 VType =
5345 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5346 StrideVType =
5347 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5348 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005349
5350 if (!LastIteration.isUsable())
5351 return 0;
5352
5353 // Save the number of iterations.
5354 ExprResult NumIterations = LastIteration;
5355 {
5356 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005357 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5358 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005359 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5360 if (!LastIteration.isUsable())
5361 return 0;
5362 }
5363
5364 // Calculate the last iteration number beforehand instead of doing this on
5365 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5366 llvm::APSInt Result;
5367 bool IsConstant =
5368 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5369 ExprResult CalcLastIteration;
5370 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005371 ExprResult SaveRef =
5372 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005373 LastIteration = SaveRef;
5374
5375 // Prepare SaveRef + 1.
5376 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005377 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005378 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5379 if (!NumIterations.isUsable())
5380 return 0;
5381 }
5382
5383 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5384
David Majnemer9d168222016-08-05 17:44:54 +00005385 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005386 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005387 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5388 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005389 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005390 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5391 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005392 SemaRef.AddInitializerToDecl(LBDecl,
5393 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5394 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005395
5396 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005397 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5398 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005399 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005400 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005401
5402 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5403 // This will be used to implement clause 'lastprivate'.
5404 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005405 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5406 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005407 SemaRef.AddInitializerToDecl(ILDecl,
5408 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5409 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005410
5411 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005412 VarDecl *STDecl =
5413 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5414 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005415 SemaRef.AddInitializerToDecl(STDecl,
5416 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5417 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005418
5419 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005420 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005421 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5422 UB.get(), LastIteration.get());
5423 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005424 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5425 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005426 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5427 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005428 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005429
5430 // If we have a combined directive that combines 'distribute', 'for' or
5431 // 'simd' we need to be able to access the bounds of the schedule of the
5432 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5433 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5434 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005435 // Lower bound variable, initialized with zero.
5436 VarDecl *CombLBDecl =
5437 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5438 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5439 SemaRef.AddInitializerToDecl(
5440 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5441 /*DirectInit*/ false);
5442
5443 // Upper bound variable, initialized with last iteration number.
5444 VarDecl *CombUBDecl =
5445 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5446 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5447 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5448 /*DirectInit*/ false);
5449
5450 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5451 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5452 ExprResult CombCondOp =
5453 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5454 LastIteration.get(), CombUB.get());
5455 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5456 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005457 CombEUB =
5458 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005459
Alexey Bataeve3727102018-04-18 15:57:46 +00005460 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005461 // We expect to have at least 2 more parameters than the 'parallel'
5462 // directive does - the lower and upper bounds of the previous schedule.
5463 assert(CD->getNumParams() >= 4 &&
5464 "Unexpected number of parameters in loop combined directive");
5465
5466 // Set the proper type for the bounds given what we learned from the
5467 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005468 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5469 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005470
5471 // Previous lower and upper bounds are obtained from the region
5472 // parameters.
5473 PrevLB =
5474 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5475 PrevUB =
5476 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5477 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005478 }
5479
5480 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005481 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005482 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005483 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005484 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5485 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005486 Expr *RHS =
5487 (isOpenMPWorksharingDirective(DKind) ||
5488 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5489 ? LB.get()
5490 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005491 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005492 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005493
5494 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5495 Expr *CombRHS =
5496 (isOpenMPWorksharingDirective(DKind) ||
5497 isOpenMPTaskLoopDirective(DKind) ||
5498 isOpenMPDistributeDirective(DKind))
5499 ? CombLB.get()
5500 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5501 CombInit =
5502 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005503 CombInit =
5504 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005505 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005506 }
5507
Alexey Bataev316ccf62019-01-29 18:51:58 +00005508 bool UseStrictCompare =
5509 RealVType->hasUnsignedIntegerRepresentation() &&
5510 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5511 return LIS.IsStrictCompare;
5512 });
5513 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5514 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005515 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005516 Expr *BoundUB = UB.get();
5517 if (UseStrictCompare) {
5518 BoundUB =
5519 SemaRef
5520 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5521 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5522 .get();
5523 BoundUB =
5524 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5525 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005526 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005527 (isOpenMPWorksharingDirective(DKind) ||
5528 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00005529 ? SemaRef.BuildBinOp(CurScope, CondLoc,
5530 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5531 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00005532 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5533 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005534 ExprResult CombDistCond;
5535 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005536 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5537 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005538 }
5539
Carlo Bertolliffafe102017-04-20 00:39:39 +00005540 ExprResult CombCond;
5541 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005542 Expr *BoundCombUB = CombUB.get();
5543 if (UseStrictCompare) {
5544 BoundCombUB =
5545 SemaRef
5546 .BuildBinOp(
5547 CurScope, CondLoc, BO_Add, BoundCombUB,
5548 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5549 .get();
5550 BoundCombUB =
5551 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5552 .get();
5553 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00005554 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005555 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5556 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005557 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005558 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005559 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005560 ExprResult Inc =
5561 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5562 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5563 if (!Inc.isUsable())
5564 return 0;
5565 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005566 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005567 if (!Inc.isUsable())
5568 return 0;
5569
5570 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5571 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005572 // In combined construct, add combined version that use CombLB and CombUB
5573 // base variables for the update
5574 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005575 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5576 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005577 // LB + ST
5578 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5579 if (!NextLB.isUsable())
5580 return 0;
5581 // LB = LB + ST
5582 NextLB =
5583 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005584 NextLB =
5585 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005586 if (!NextLB.isUsable())
5587 return 0;
5588 // UB + ST
5589 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5590 if (!NextUB.isUsable())
5591 return 0;
5592 // UB = UB + ST
5593 NextUB =
5594 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005595 NextUB =
5596 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005597 if (!NextUB.isUsable())
5598 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005599 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5600 CombNextLB =
5601 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5602 if (!NextLB.isUsable())
5603 return 0;
5604 // LB = LB + ST
5605 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5606 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005607 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5608 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005609 if (!CombNextLB.isUsable())
5610 return 0;
5611 // UB + ST
5612 CombNextUB =
5613 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5614 if (!CombNextUB.isUsable())
5615 return 0;
5616 // UB = UB + ST
5617 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5618 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005619 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5620 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005621 if (!CombNextUB.isUsable())
5622 return 0;
5623 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005624 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005625
Carlo Bertolliffafe102017-04-20 00:39:39 +00005626 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005627 // directive with for as IV = IV + ST; ensure upper bound expression based
5628 // on PrevUB instead of NumIterations - used to implement 'for' when found
5629 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005630 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005631 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005632 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005633 DistCond = SemaRef.BuildBinOp(
5634 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005635 assert(DistCond.isUsable() && "distribute cond expr was not built");
5636
5637 DistInc =
5638 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5639 assert(DistInc.isUsable() && "distribute inc expr was not built");
5640 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5641 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005642 DistInc =
5643 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005644 assert(DistInc.isUsable() && "distribute inc expr was not built");
5645
5646 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5647 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005648 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005649 ExprResult IsUBGreater =
5650 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5651 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5652 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5653 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5654 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005655 PrevEUB =
5656 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005657
Alexey Bataev316ccf62019-01-29 18:51:58 +00005658 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5659 // parallel for is in combination with a distribute directive with
5660 // schedule(static, 1)
5661 Expr *BoundPrevUB = PrevUB.get();
5662 if (UseStrictCompare) {
5663 BoundPrevUB =
5664 SemaRef
5665 .BuildBinOp(
5666 CurScope, CondLoc, BO_Add, BoundPrevUB,
5667 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5668 .get();
5669 BoundPrevUB =
5670 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5671 .get();
5672 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005673 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005674 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5675 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005676 }
5677
Alexander Musmana5f070a2014-10-01 06:03:56 +00005678 // Build updates and final values of the loop counters.
5679 bool HasErrors = false;
5680 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005681 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005682 Built.Updates.resize(NestedLoopCount);
5683 Built.Finals.resize(NestedLoopCount);
5684 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005685 // We implement the following algorithm for obtaining the
5686 // original loop iteration variable values based on the
5687 // value of the collapsed loop iteration variable IV.
5688 //
5689 // Let n+1 be the number of collapsed loops in the nest.
5690 // Iteration variables (I0, I1, .... In)
5691 // Iteration counts (N0, N1, ... Nn)
5692 //
5693 // Acc = IV;
5694 //
5695 // To compute Ik for loop k, 0 <= k <= n, generate:
5696 // Prod = N(k+1) * N(k+2) * ... * Nn;
5697 // Ik = Acc / Prod;
5698 // Acc -= Ik * Prod;
5699 //
5700 ExprResult Acc = IV;
5701 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005702 LoopIterationSpace &IS = IterSpaces[Cnt];
5703 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005704 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005705
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005706 // Compute prod
5707 ExprResult Prod =
5708 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5709 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5710 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5711 IterSpaces[K].NumIterations);
5712
5713 // Iter = Acc / Prod
5714 // If there is at least one more inner loop to avoid
5715 // multiplication by 1.
5716 if (Cnt + 1 < NestedLoopCount)
5717 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5718 Acc.get(), Prod.get());
5719 else
5720 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005721 if (!Iter.isUsable()) {
5722 HasErrors = true;
5723 break;
5724 }
5725
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005726 // Update Acc:
5727 // Acc -= Iter * Prod
5728 // Check if there is at least one more inner loop to avoid
5729 // multiplication by 1.
5730 if (Cnt + 1 < NestedLoopCount)
5731 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5732 Iter.get(), Prod.get());
5733 else
5734 Prod = Iter;
5735 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5736 Acc.get(), Prod.get());
5737
Alexey Bataev39f915b82015-05-08 10:41:21 +00005738 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005739 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005740 DeclRefExpr *CounterVar = buildDeclRefExpr(
5741 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5742 /*RefersToCapture=*/true);
5743 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005744 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005745 if (!Init.isUsable()) {
5746 HasErrors = true;
5747 break;
5748 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005749 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005750 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5751 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005752 if (!Update.isUsable()) {
5753 HasErrors = true;
5754 break;
5755 }
5756
5757 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005758 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005759 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005760 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005761 if (!Final.isUsable()) {
5762 HasErrors = true;
5763 break;
5764 }
5765
Alexander Musmana5f070a2014-10-01 06:03:56 +00005766 if (!Update.isUsable() || !Final.isUsable()) {
5767 HasErrors = true;
5768 break;
5769 }
5770 // Save results
5771 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005772 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005773 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005774 Built.Updates[Cnt] = Update.get();
5775 Built.Finals[Cnt] = Final.get();
5776 }
5777 }
5778
5779 if (HasErrors)
5780 return 0;
5781
5782 // Save results
5783 Built.IterationVarRef = IV.get();
5784 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005785 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005786 Built.CalcLastIteration = SemaRef
5787 .ActOnFinishFullExpr(CalcLastIteration.get(),
5788 /*DiscardedValue*/ false)
5789 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005790 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005791 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005792 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005793 Built.Init = Init.get();
5794 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005795 Built.LB = LB.get();
5796 Built.UB = UB.get();
5797 Built.IL = IL.get();
5798 Built.ST = ST.get();
5799 Built.EUB = EUB.get();
5800 Built.NLB = NextLB.get();
5801 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005802 Built.PrevLB = PrevLB.get();
5803 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005804 Built.DistInc = DistInc.get();
5805 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005806 Built.DistCombinedFields.LB = CombLB.get();
5807 Built.DistCombinedFields.UB = CombUB.get();
5808 Built.DistCombinedFields.EUB = CombEUB.get();
5809 Built.DistCombinedFields.Init = CombInit.get();
5810 Built.DistCombinedFields.Cond = CombCond.get();
5811 Built.DistCombinedFields.NLB = CombNextLB.get();
5812 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005813 Built.DistCombinedFields.DistCond = CombDistCond.get();
5814 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005815
Alexey Bataevabfc0692014-06-25 06:52:00 +00005816 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005817}
5818
Alexey Bataev10e775f2015-07-30 11:36:16 +00005819static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005820 auto CollapseClauses =
5821 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5822 if (CollapseClauses.begin() != CollapseClauses.end())
5823 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005824 return nullptr;
5825}
5826
Alexey Bataev10e775f2015-07-30 11:36:16 +00005827static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005828 auto OrderedClauses =
5829 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5830 if (OrderedClauses.begin() != OrderedClauses.end())
5831 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005832 return nullptr;
5833}
5834
Kelvin Lic5609492016-07-15 04:39:07 +00005835static bool checkSimdlenSafelenSpecified(Sema &S,
5836 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005837 const OMPSafelenClause *Safelen = nullptr;
5838 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00005839
Alexey Bataeve3727102018-04-18 15:57:46 +00005840 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00005841 if (Clause->getClauseKind() == OMPC_safelen)
5842 Safelen = cast<OMPSafelenClause>(Clause);
5843 else if (Clause->getClauseKind() == OMPC_simdlen)
5844 Simdlen = cast<OMPSimdlenClause>(Clause);
5845 if (Safelen && Simdlen)
5846 break;
5847 }
5848
5849 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005850 const Expr *SimdlenLength = Simdlen->getSimdlen();
5851 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00005852 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5853 SimdlenLength->isInstantiationDependent() ||
5854 SimdlenLength->containsUnexpandedParameterPack())
5855 return false;
5856 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5857 SafelenLength->isInstantiationDependent() ||
5858 SafelenLength->containsUnexpandedParameterPack())
5859 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005860 Expr::EvalResult SimdlenResult, SafelenResult;
5861 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
5862 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
5863 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
5864 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00005865 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5866 // If both simdlen and safelen clauses are specified, the value of the
5867 // simdlen parameter must be less than or equal to the value of the safelen
5868 // parameter.
5869 if (SimdlenRes > SafelenRes) {
5870 S.Diag(SimdlenLength->getExprLoc(),
5871 diag::err_omp_wrong_simdlen_safelen_values)
5872 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5873 return true;
5874 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005875 }
5876 return false;
5877}
5878
Alexey Bataeve3727102018-04-18 15:57:46 +00005879StmtResult
5880Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5881 SourceLocation StartLoc, SourceLocation EndLoc,
5882 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005883 if (!AStmt)
5884 return StmtError();
5885
5886 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005887 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005888 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5889 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005890 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005891 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5892 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005893 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005894 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005895
Alexander Musmana5f070a2014-10-01 06:03:56 +00005896 assert((CurContext->isDependentContext() || B.builtAll()) &&
5897 "omp simd loop exprs were not built");
5898
Alexander Musman3276a272015-03-21 10:12:56 +00005899 if (!CurContext->isDependentContext()) {
5900 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005901 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005902 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005903 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005904 B.NumIterations, *this, CurScope,
5905 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005906 return StmtError();
5907 }
5908 }
5909
Kelvin Lic5609492016-07-15 04:39:07 +00005910 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005911 return StmtError();
5912
Reid Kleckner87a31802018-03-12 21:43:02 +00005913 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005914 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5915 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005916}
5917
Alexey Bataeve3727102018-04-18 15:57:46 +00005918StmtResult
5919Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5920 SourceLocation StartLoc, SourceLocation EndLoc,
5921 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005922 if (!AStmt)
5923 return StmtError();
5924
5925 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005926 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005927 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5928 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005929 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005930 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5931 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005932 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005933 return StmtError();
5934
Alexander Musmana5f070a2014-10-01 06:03:56 +00005935 assert((CurContext->isDependentContext() || B.builtAll()) &&
5936 "omp for loop exprs were not built");
5937
Alexey Bataev54acd402015-08-04 11:18:19 +00005938 if (!CurContext->isDependentContext()) {
5939 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005940 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005941 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005942 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005943 B.NumIterations, *this, CurScope,
5944 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005945 return StmtError();
5946 }
5947 }
5948
Reid Kleckner87a31802018-03-12 21:43:02 +00005949 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005950 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005951 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005952}
5953
Alexander Musmanf82886e2014-09-18 05:12:34 +00005954StmtResult Sema::ActOnOpenMPForSimdDirective(
5955 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00005956 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005957 if (!AStmt)
5958 return StmtError();
5959
5960 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005961 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005962 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5963 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005964 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00005965 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00005966 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5967 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005968 if (NestedLoopCount == 0)
5969 return StmtError();
5970
Alexander Musmanc6388682014-12-15 07:07:06 +00005971 assert((CurContext->isDependentContext() || B.builtAll()) &&
5972 "omp for simd loop exprs were not built");
5973
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005974 if (!CurContext->isDependentContext()) {
5975 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005976 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005977 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005978 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005979 B.NumIterations, *this, CurScope,
5980 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005981 return StmtError();
5982 }
5983 }
5984
Kelvin Lic5609492016-07-15 04:39:07 +00005985 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005986 return StmtError();
5987
Reid Kleckner87a31802018-03-12 21:43:02 +00005988 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005989 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5990 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005991}
5992
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005993StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5994 Stmt *AStmt,
5995 SourceLocation StartLoc,
5996 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005997 if (!AStmt)
5998 return StmtError();
5999
6000 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006001 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006002 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006003 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006004 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006005 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006006 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006007 return StmtError();
6008 // All associated statements must be '#pragma omp section' except for
6009 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006010 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006011 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6012 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006013 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006014 diag::err_omp_sections_substmt_not_section);
6015 return StmtError();
6016 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006017 cast<OMPSectionDirective>(SectionStmt)
6018 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006019 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006020 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006021 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006022 return StmtError();
6023 }
6024
Reid Kleckner87a31802018-03-12 21:43:02 +00006025 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006026
Alexey Bataev25e5b442015-09-15 12:52:43 +00006027 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6028 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006029}
6030
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006031StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6032 SourceLocation StartLoc,
6033 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006034 if (!AStmt)
6035 return StmtError();
6036
6037 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006038
Reid Kleckner87a31802018-03-12 21:43:02 +00006039 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006040 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006041
Alexey Bataev25e5b442015-09-15 12:52:43 +00006042 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6043 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006044}
6045
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006046StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6047 Stmt *AStmt,
6048 SourceLocation StartLoc,
6049 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006050 if (!AStmt)
6051 return StmtError();
6052
6053 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006054
Reid Kleckner87a31802018-03-12 21:43:02 +00006055 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006056
Alexey Bataev3255bf32015-01-19 05:20:46 +00006057 // OpenMP [2.7.3, single Construct, Restrictions]
6058 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006059 const OMPClause *Nowait = nullptr;
6060 const OMPClause *Copyprivate = nullptr;
6061 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006062 if (Clause->getClauseKind() == OMPC_nowait)
6063 Nowait = Clause;
6064 else if (Clause->getClauseKind() == OMPC_copyprivate)
6065 Copyprivate = Clause;
6066 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006067 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006068 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006069 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006070 return StmtError();
6071 }
6072 }
6073
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006074 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6075}
6076
Alexander Musman80c22892014-07-17 08:54:58 +00006077StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6078 SourceLocation StartLoc,
6079 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006080 if (!AStmt)
6081 return StmtError();
6082
6083 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006084
Reid Kleckner87a31802018-03-12 21:43:02 +00006085 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006086
6087 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6088}
6089
Alexey Bataev28c75412015-12-15 08:19:24 +00006090StmtResult Sema::ActOnOpenMPCriticalDirective(
6091 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6092 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006093 if (!AStmt)
6094 return StmtError();
6095
6096 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006097
Alexey Bataev28c75412015-12-15 08:19:24 +00006098 bool ErrorFound = false;
6099 llvm::APSInt Hint;
6100 SourceLocation HintLoc;
6101 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006102 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006103 if (C->getClauseKind() == OMPC_hint) {
6104 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006105 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006106 ErrorFound = true;
6107 }
6108 Expr *E = cast<OMPHintClause>(C)->getHint();
6109 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006110 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006111 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006112 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006113 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006114 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006115 }
6116 }
6117 }
6118 if (ErrorFound)
6119 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006120 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006121 if (Pair.first && DirName.getName() && !DependentHint) {
6122 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6123 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006124 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006125 Diag(HintLoc, diag::note_omp_critical_hint_here)
6126 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006127 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006128 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006129 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006130 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006131 << 1
6132 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6133 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006134 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006135 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006136 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006137 }
6138 }
6139
Reid Kleckner87a31802018-03-12 21:43:02 +00006140 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006141
Alexey Bataev28c75412015-12-15 08:19:24 +00006142 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6143 Clauses, AStmt);
6144 if (!Pair.first && DirName.getName() && !DependentHint)
6145 DSAStack->addCriticalWithHint(Dir, Hint);
6146 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006147}
6148
Alexey Bataev4acb8592014-07-07 13:01:15 +00006149StmtResult Sema::ActOnOpenMPParallelForDirective(
6150 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006151 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006152 if (!AStmt)
6153 return StmtError();
6154
Alexey Bataeve3727102018-04-18 15:57:46 +00006155 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006156 // 1.2.2 OpenMP Language Terminology
6157 // Structured block - An executable statement with a single entry at the
6158 // top and a single exit at the bottom.
6159 // The point of exit cannot be a branch out of the structured block.
6160 // longjmp() and throw() must not violate the entry/exit criteria.
6161 CS->getCapturedDecl()->setNothrow();
6162
Alexander Musmanc6388682014-12-15 07:07:06 +00006163 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006164 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6165 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006166 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006167 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006168 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6169 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006170 if (NestedLoopCount == 0)
6171 return StmtError();
6172
Alexander Musmana5f070a2014-10-01 06:03:56 +00006173 assert((CurContext->isDependentContext() || B.builtAll()) &&
6174 "omp parallel for loop exprs were not built");
6175
Alexey Bataev54acd402015-08-04 11:18:19 +00006176 if (!CurContext->isDependentContext()) {
6177 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006178 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006179 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006180 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006181 B.NumIterations, *this, CurScope,
6182 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006183 return StmtError();
6184 }
6185 }
6186
Reid Kleckner87a31802018-03-12 21:43:02 +00006187 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006188 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006189 NestedLoopCount, Clauses, AStmt, B,
6190 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006191}
6192
Alexander Musmane4e893b2014-09-23 09:33:00 +00006193StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006195 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006196 if (!AStmt)
6197 return StmtError();
6198
Alexey Bataeve3727102018-04-18 15:57:46 +00006199 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006200 // 1.2.2 OpenMP Language Terminology
6201 // Structured block - An executable statement with a single entry at the
6202 // top and a single exit at the bottom.
6203 // The point of exit cannot be a branch out of the structured block.
6204 // longjmp() and throw() must not violate the entry/exit criteria.
6205 CS->getCapturedDecl()->setNothrow();
6206
Alexander Musmanc6388682014-12-15 07:07:06 +00006207 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006208 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6209 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006210 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006211 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006212 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6213 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006214 if (NestedLoopCount == 0)
6215 return StmtError();
6216
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006217 if (!CurContext->isDependentContext()) {
6218 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006219 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006220 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006221 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006222 B.NumIterations, *this, CurScope,
6223 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006224 return StmtError();
6225 }
6226 }
6227
Kelvin Lic5609492016-07-15 04:39:07 +00006228 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006229 return StmtError();
6230
Reid Kleckner87a31802018-03-12 21:43:02 +00006231 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006232 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006233 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006234}
6235
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006236StmtResult
6237Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6238 Stmt *AStmt, SourceLocation StartLoc,
6239 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006240 if (!AStmt)
6241 return StmtError();
6242
6243 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006244 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006245 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006246 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006247 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006248 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006249 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006250 return StmtError();
6251 // All associated statements must be '#pragma omp section' except for
6252 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006253 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006254 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6255 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006256 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006257 diag::err_omp_parallel_sections_substmt_not_section);
6258 return StmtError();
6259 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006260 cast<OMPSectionDirective>(SectionStmt)
6261 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006262 }
6263 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006264 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006265 diag::err_omp_parallel_sections_not_compound_stmt);
6266 return StmtError();
6267 }
6268
Reid Kleckner87a31802018-03-12 21:43:02 +00006269 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006270
Alexey Bataev25e5b442015-09-15 12:52:43 +00006271 return OMPParallelSectionsDirective::Create(
6272 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006273}
6274
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006275StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6276 Stmt *AStmt, SourceLocation StartLoc,
6277 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006278 if (!AStmt)
6279 return StmtError();
6280
David Majnemer9d168222016-08-05 17:44:54 +00006281 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006282 // 1.2.2 OpenMP Language Terminology
6283 // Structured block - An executable statement with a single entry at the
6284 // top and a single exit at the bottom.
6285 // The point of exit cannot be a branch out of the structured block.
6286 // longjmp() and throw() must not violate the entry/exit criteria.
6287 CS->getCapturedDecl()->setNothrow();
6288
Reid Kleckner87a31802018-03-12 21:43:02 +00006289 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006290
Alexey Bataev25e5b442015-09-15 12:52:43 +00006291 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6292 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006293}
6294
Alexey Bataev68446b72014-07-18 07:47:19 +00006295StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6296 SourceLocation EndLoc) {
6297 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6298}
6299
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006300StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6301 SourceLocation EndLoc) {
6302 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6303}
6304
Alexey Bataev2df347a2014-07-18 10:17:07 +00006305StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6306 SourceLocation EndLoc) {
6307 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6308}
6309
Alexey Bataev169d96a2017-07-18 20:17:46 +00006310StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6311 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006312 SourceLocation StartLoc,
6313 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006314 if (!AStmt)
6315 return StmtError();
6316
6317 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006318
Reid Kleckner87a31802018-03-12 21:43:02 +00006319 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006320
Alexey Bataev169d96a2017-07-18 20:17:46 +00006321 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006322 AStmt,
6323 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006324}
6325
Alexey Bataev6125da92014-07-21 11:26:11 +00006326StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6327 SourceLocation StartLoc,
6328 SourceLocation EndLoc) {
6329 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6330 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6331}
6332
Alexey Bataev346265e2015-09-25 10:37:12 +00006333StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6334 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006335 SourceLocation StartLoc,
6336 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006337 const OMPClause *DependFound = nullptr;
6338 const OMPClause *DependSourceClause = nullptr;
6339 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006340 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006341 const OMPThreadsClause *TC = nullptr;
6342 const OMPSIMDClause *SC = nullptr;
6343 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006344 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6345 DependFound = C;
6346 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6347 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006348 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006349 << getOpenMPDirectiveName(OMPD_ordered)
6350 << getOpenMPClauseName(OMPC_depend) << 2;
6351 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006352 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006353 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006354 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006355 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006356 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006357 << 0;
6358 ErrorFound = true;
6359 }
6360 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6361 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006362 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006363 << 1;
6364 ErrorFound = true;
6365 }
6366 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006367 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006368 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006369 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006370 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006371 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006372 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006373 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006374 if (!ErrorFound && !SC &&
6375 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006376 // OpenMP [2.8.1,simd Construct, Restrictions]
6377 // An ordered construct with the simd clause is the only OpenMP construct
6378 // that can appear in the simd region.
6379 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006380 ErrorFound = true;
6381 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006382 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006383 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6384 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006385 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006386 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006387 diag::err_omp_ordered_directive_without_param);
6388 ErrorFound = true;
6389 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006390 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006391 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006392 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6393 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006394 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006395 ErrorFound = true;
6396 }
6397 }
6398 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006399 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006400
6401 if (AStmt) {
6402 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6403
Reid Kleckner87a31802018-03-12 21:43:02 +00006404 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006405 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006406
6407 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006408}
6409
Alexey Bataev1d160b12015-03-13 12:27:31 +00006410namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006411/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006412/// construct.
6413class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006414 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006415 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006416 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006417 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006418 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006419 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006420 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006421 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006422 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006423 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006424 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006425 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006426 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006427 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006428 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006429 /// expression.
6430 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006431 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006432 /// part.
6433 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006434 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006435 NoError
6436 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006437 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006438 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006439 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006440 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006441 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006442 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006443 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006444 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006445 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006446 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6447 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6448 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006449 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006450 /// important for non-associative operations.
6451 bool IsXLHSInRHSPart;
6452 BinaryOperatorKind Op;
6453 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006454 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006455 /// if it is a prefix unary operation.
6456 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006457
6458public:
6459 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006460 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006461 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006462 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006463 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006464 /// expression. If DiagId and NoteId == 0, then only check is performed
6465 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006466 /// \param DiagId Diagnostic which should be emitted if error is found.
6467 /// \param NoteId Diagnostic note for the main error message.
6468 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006469 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006470 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006471 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006472 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006473 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006474 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006475 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6476 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6477 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006478 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006479 /// false otherwise.
6480 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6481
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006482 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006483 /// if it is a prefix unary operation.
6484 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6485
Alexey Bataev1d160b12015-03-13 12:27:31 +00006486private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006487 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6488 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006489};
6490} // namespace
6491
6492bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6493 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6494 ExprAnalysisErrorCode ErrorFound = NoError;
6495 SourceLocation ErrorLoc, NoteLoc;
6496 SourceRange ErrorRange, NoteRange;
6497 // Allowed constructs are:
6498 // x = x binop expr;
6499 // x = expr binop x;
6500 if (AtomicBinOp->getOpcode() == BO_Assign) {
6501 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006502 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006503 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6504 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6505 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6506 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006507 Op = AtomicInnerBinOp->getOpcode();
6508 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006509 Expr *LHS = AtomicInnerBinOp->getLHS();
6510 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006511 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6512 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6513 /*Canonical=*/true);
6514 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6515 /*Canonical=*/true);
6516 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6517 /*Canonical=*/true);
6518 if (XId == LHSId) {
6519 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006520 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006521 } else if (XId == RHSId) {
6522 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006523 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006524 } else {
6525 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6526 ErrorRange = AtomicInnerBinOp->getSourceRange();
6527 NoteLoc = X->getExprLoc();
6528 NoteRange = X->getSourceRange();
6529 ErrorFound = NotAnUpdateExpression;
6530 }
6531 } else {
6532 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6533 ErrorRange = AtomicInnerBinOp->getSourceRange();
6534 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6535 NoteRange = SourceRange(NoteLoc, NoteLoc);
6536 ErrorFound = NotABinaryOperator;
6537 }
6538 } else {
6539 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6540 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6541 ErrorFound = NotABinaryExpression;
6542 }
6543 } else {
6544 ErrorLoc = AtomicBinOp->getExprLoc();
6545 ErrorRange = AtomicBinOp->getSourceRange();
6546 NoteLoc = AtomicBinOp->getOperatorLoc();
6547 NoteRange = SourceRange(NoteLoc, NoteLoc);
6548 ErrorFound = NotAnAssignmentOp;
6549 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006550 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006551 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6552 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6553 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006554 }
6555 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006556 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006557 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006558}
6559
6560bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6561 unsigned NoteId) {
6562 ExprAnalysisErrorCode ErrorFound = NoError;
6563 SourceLocation ErrorLoc, NoteLoc;
6564 SourceRange ErrorRange, NoteRange;
6565 // Allowed constructs are:
6566 // x++;
6567 // x--;
6568 // ++x;
6569 // --x;
6570 // x binop= expr;
6571 // x = x binop expr;
6572 // x = expr binop x;
6573 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6574 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6575 if (AtomicBody->getType()->isScalarType() ||
6576 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006577 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006578 AtomicBody->IgnoreParenImpCasts())) {
6579 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006580 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006581 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006582 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006583 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006584 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006585 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006586 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6587 AtomicBody->IgnoreParenImpCasts())) {
6588 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006589 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006590 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006591 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006592 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006593 // Check for Unary Operation
6594 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006595 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006596 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6597 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006598 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006599 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6600 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006601 } else {
6602 ErrorFound = NotAnUnaryIncDecExpression;
6603 ErrorLoc = AtomicUnaryOp->getExprLoc();
6604 ErrorRange = AtomicUnaryOp->getSourceRange();
6605 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6606 NoteRange = SourceRange(NoteLoc, NoteLoc);
6607 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006608 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006609 ErrorFound = NotABinaryOrUnaryExpression;
6610 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6611 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6612 }
6613 } else {
6614 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006615 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006616 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6617 }
6618 } else {
6619 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006620 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006621 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6622 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006623 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006624 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6625 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6626 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006627 }
6628 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006629 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006630 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006631 // Build an update expression of form 'OpaqueValueExpr(x) binop
6632 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6633 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6634 auto *OVEX = new (SemaRef.getASTContext())
6635 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6636 auto *OVEExpr = new (SemaRef.getASTContext())
6637 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006638 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006639 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6640 IsXLHSInRHSPart ? OVEExpr : OVEX);
6641 if (Update.isInvalid())
6642 return true;
6643 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6644 Sema::AA_Casting);
6645 if (Update.isInvalid())
6646 return true;
6647 UpdateExpr = Update.get();
6648 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006649 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006650}
6651
Alexey Bataev0162e452014-07-22 10:10:35 +00006652StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6653 Stmt *AStmt,
6654 SourceLocation StartLoc,
6655 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006656 if (!AStmt)
6657 return StmtError();
6658
David Majnemer9d168222016-08-05 17:44:54 +00006659 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006660 // 1.2.2 OpenMP Language Terminology
6661 // Structured block - An executable statement with a single entry at the
6662 // top and a single exit at the bottom.
6663 // The point of exit cannot be a branch out of the structured block.
6664 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006665 OpenMPClauseKind AtomicKind = OMPC_unknown;
6666 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006667 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006668 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006669 C->getClauseKind() == OMPC_update ||
6670 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006671 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006672 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006673 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006674 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6675 << getOpenMPClauseName(AtomicKind);
6676 } else {
6677 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006678 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006679 }
6680 }
6681 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006682
Alexey Bataeve3727102018-04-18 15:57:46 +00006683 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006684 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6685 Body = EWC->getSubExpr();
6686
Alexey Bataev62cec442014-11-18 10:14:22 +00006687 Expr *X = nullptr;
6688 Expr *V = nullptr;
6689 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006690 Expr *UE = nullptr;
6691 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006692 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006693 // OpenMP [2.12.6, atomic Construct]
6694 // In the next expressions:
6695 // * x and v (as applicable) are both l-value expressions with scalar type.
6696 // * During the execution of an atomic region, multiple syntactic
6697 // occurrences of x must designate the same storage location.
6698 // * Neither of v and expr (as applicable) may access the storage location
6699 // designated by x.
6700 // * Neither of x and expr (as applicable) may access the storage location
6701 // designated by v.
6702 // * expr is an expression with scalar type.
6703 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6704 // * binop, binop=, ++, and -- are not overloaded operators.
6705 // * The expression x binop expr must be numerically equivalent to x binop
6706 // (expr). This requirement is satisfied if the operators in expr have
6707 // precedence greater than binop, or by using parentheses around expr or
6708 // subexpressions of expr.
6709 // * The expression expr binop x must be numerically equivalent to (expr)
6710 // binop x. This requirement is satisfied if the operators in expr have
6711 // precedence equal to or greater than binop, or by using parentheses around
6712 // expr or subexpressions of expr.
6713 // * For forms that allow multiple occurrences of x, the number of times
6714 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006715 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006716 enum {
6717 NotAnExpression,
6718 NotAnAssignmentOp,
6719 NotAScalarType,
6720 NotAnLValue,
6721 NoError
6722 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006723 SourceLocation ErrorLoc, NoteLoc;
6724 SourceRange ErrorRange, NoteRange;
6725 // If clause is read:
6726 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006727 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6728 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006729 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6730 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6731 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6732 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6733 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6734 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6735 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006736 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006737 ErrorFound = NotAnLValue;
6738 ErrorLoc = AtomicBinOp->getExprLoc();
6739 ErrorRange = AtomicBinOp->getSourceRange();
6740 NoteLoc = NotLValueExpr->getExprLoc();
6741 NoteRange = NotLValueExpr->getSourceRange();
6742 }
6743 } else if (!X->isInstantiationDependent() ||
6744 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006745 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006746 (X->isInstantiationDependent() || X->getType()->isScalarType())
6747 ? V
6748 : X;
6749 ErrorFound = NotAScalarType;
6750 ErrorLoc = AtomicBinOp->getExprLoc();
6751 ErrorRange = AtomicBinOp->getSourceRange();
6752 NoteLoc = NotScalarExpr->getExprLoc();
6753 NoteRange = NotScalarExpr->getSourceRange();
6754 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006755 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006756 ErrorFound = NotAnAssignmentOp;
6757 ErrorLoc = AtomicBody->getExprLoc();
6758 ErrorRange = AtomicBody->getSourceRange();
6759 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6760 : AtomicBody->getExprLoc();
6761 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6762 : AtomicBody->getSourceRange();
6763 }
6764 } else {
6765 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006766 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00006767 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006768 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006769 if (ErrorFound != NoError) {
6770 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6771 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006772 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6773 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006774 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006775 }
6776 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00006777 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006778 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006779 enum {
6780 NotAnExpression,
6781 NotAnAssignmentOp,
6782 NotAScalarType,
6783 NotAnLValue,
6784 NoError
6785 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006786 SourceLocation ErrorLoc, NoteLoc;
6787 SourceRange ErrorRange, NoteRange;
6788 // If clause is write:
6789 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00006790 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6791 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006792 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6793 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006794 X = AtomicBinOp->getLHS();
6795 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006796 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6797 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6798 if (!X->isLValue()) {
6799 ErrorFound = NotAnLValue;
6800 ErrorLoc = AtomicBinOp->getExprLoc();
6801 ErrorRange = AtomicBinOp->getSourceRange();
6802 NoteLoc = X->getExprLoc();
6803 NoteRange = X->getSourceRange();
6804 }
6805 } else if (!X->isInstantiationDependent() ||
6806 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006807 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006808 (X->isInstantiationDependent() || X->getType()->isScalarType())
6809 ? E
6810 : X;
6811 ErrorFound = NotAScalarType;
6812 ErrorLoc = AtomicBinOp->getExprLoc();
6813 ErrorRange = AtomicBinOp->getSourceRange();
6814 NoteLoc = NotScalarExpr->getExprLoc();
6815 NoteRange = NotScalarExpr->getSourceRange();
6816 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006817 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006818 ErrorFound = NotAnAssignmentOp;
6819 ErrorLoc = AtomicBody->getExprLoc();
6820 ErrorRange = AtomicBody->getSourceRange();
6821 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6822 : AtomicBody->getExprLoc();
6823 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6824 : AtomicBody->getSourceRange();
6825 }
6826 } else {
6827 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006828 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006829 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006830 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006831 if (ErrorFound != NoError) {
6832 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6833 << ErrorRange;
6834 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6835 << NoteRange;
6836 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006837 }
6838 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00006839 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006840 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006841 // If clause is update:
6842 // x++;
6843 // x--;
6844 // ++x;
6845 // --x;
6846 // x binop= expr;
6847 // x = x binop expr;
6848 // x = expr binop x;
6849 OpenMPAtomicUpdateChecker Checker(*this);
6850 if (Checker.checkStatement(
6851 Body, (AtomicKind == OMPC_update)
6852 ? diag::err_omp_atomic_update_not_expression_statement
6853 : diag::err_omp_atomic_not_expression_statement,
6854 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006855 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006856 if (!CurContext->isDependentContext()) {
6857 E = Checker.getExpr();
6858 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006859 UE = Checker.getUpdateExpr();
6860 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006861 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006862 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006863 enum {
6864 NotAnAssignmentOp,
6865 NotACompoundStatement,
6866 NotTwoSubstatements,
6867 NotASpecificExpression,
6868 NoError
6869 } ErrorFound = NoError;
6870 SourceLocation ErrorLoc, NoteLoc;
6871 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00006872 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006873 // If clause is a capture:
6874 // v = x++;
6875 // v = x--;
6876 // v = ++x;
6877 // v = --x;
6878 // v = x binop= expr;
6879 // v = x = x binop expr;
6880 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006881 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00006882 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6883 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6884 V = AtomicBinOp->getLHS();
6885 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6886 OpenMPAtomicUpdateChecker Checker(*this);
6887 if (Checker.checkStatement(
6888 Body, diag::err_omp_atomic_capture_not_expression_statement,
6889 diag::note_omp_atomic_update))
6890 return StmtError();
6891 E = Checker.getExpr();
6892 X = Checker.getX();
6893 UE = Checker.getUpdateExpr();
6894 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6895 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006896 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006897 ErrorLoc = AtomicBody->getExprLoc();
6898 ErrorRange = AtomicBody->getSourceRange();
6899 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6900 : AtomicBody->getExprLoc();
6901 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6902 : AtomicBody->getSourceRange();
6903 ErrorFound = NotAnAssignmentOp;
6904 }
6905 if (ErrorFound != NoError) {
6906 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6907 << ErrorRange;
6908 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6909 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006910 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006911 if (CurContext->isDependentContext())
6912 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006913 } else {
6914 // If clause is a capture:
6915 // { v = x; x = expr; }
6916 // { v = x; x++; }
6917 // { v = x; x--; }
6918 // { v = x; ++x; }
6919 // { v = x; --x; }
6920 // { v = x; x binop= expr; }
6921 // { v = x; x = x binop expr; }
6922 // { v = x; x = expr binop x; }
6923 // { x++; v = x; }
6924 // { x--; v = x; }
6925 // { ++x; v = x; }
6926 // { --x; v = x; }
6927 // { x binop= expr; v = x; }
6928 // { x = x binop expr; v = x; }
6929 // { x = expr binop x; v = x; }
6930 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6931 // Check that this is { expr1; expr2; }
6932 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006933 Stmt *First = CS->body_front();
6934 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006935 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6936 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6937 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6938 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6939 // Need to find what subexpression is 'v' and what is 'x'.
6940 OpenMPAtomicUpdateChecker Checker(*this);
6941 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6942 BinaryOperator *BinOp = nullptr;
6943 if (IsUpdateExprFound) {
6944 BinOp = dyn_cast<BinaryOperator>(First);
6945 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6946 }
6947 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6948 // { v = x; x++; }
6949 // { v = x; x--; }
6950 // { v = x; ++x; }
6951 // { v = x; --x; }
6952 // { v = x; x binop= expr; }
6953 // { v = x; x = x binop expr; }
6954 // { v = x; x = expr binop x; }
6955 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00006956 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006957 llvm::FoldingSetNodeID XId, PossibleXId;
6958 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6959 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6960 IsUpdateExprFound = XId == PossibleXId;
6961 if (IsUpdateExprFound) {
6962 V = BinOp->getLHS();
6963 X = Checker.getX();
6964 E = Checker.getExpr();
6965 UE = Checker.getUpdateExpr();
6966 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006967 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006968 }
6969 }
6970 if (!IsUpdateExprFound) {
6971 IsUpdateExprFound = !Checker.checkStatement(First);
6972 BinOp = nullptr;
6973 if (IsUpdateExprFound) {
6974 BinOp = dyn_cast<BinaryOperator>(Second);
6975 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6976 }
6977 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6978 // { x++; v = x; }
6979 // { x--; v = x; }
6980 // { ++x; v = x; }
6981 // { --x; v = x; }
6982 // { x binop= expr; v = x; }
6983 // { x = x binop expr; v = x; }
6984 // { x = expr binop x; v = x; }
6985 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00006986 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006987 llvm::FoldingSetNodeID XId, PossibleXId;
6988 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6989 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6990 IsUpdateExprFound = XId == PossibleXId;
6991 if (IsUpdateExprFound) {
6992 V = BinOp->getLHS();
6993 X = Checker.getX();
6994 E = Checker.getExpr();
6995 UE = Checker.getUpdateExpr();
6996 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006997 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006998 }
6999 }
7000 }
7001 if (!IsUpdateExprFound) {
7002 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007003 auto *FirstExpr = dyn_cast<Expr>(First);
7004 auto *SecondExpr = dyn_cast<Expr>(Second);
7005 if (!FirstExpr || !SecondExpr ||
7006 !(FirstExpr->isInstantiationDependent() ||
7007 SecondExpr->isInstantiationDependent())) {
7008 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7009 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007010 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007011 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007012 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007013 NoteRange = ErrorRange = FirstBinOp
7014 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007015 : SourceRange(ErrorLoc, ErrorLoc);
7016 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007017 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7018 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7019 ErrorFound = NotAnAssignmentOp;
7020 NoteLoc = ErrorLoc = SecondBinOp
7021 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007022 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007023 NoteRange = ErrorRange =
7024 SecondBinOp ? SecondBinOp->getSourceRange()
7025 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007026 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007027 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007028 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007029 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007030 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7031 llvm::FoldingSetNodeID X1Id, X2Id;
7032 PossibleXRHSInFirst->Profile(X1Id, Context,
7033 /*Canonical=*/true);
7034 PossibleXLHSInSecond->Profile(X2Id, Context,
7035 /*Canonical=*/true);
7036 IsUpdateExprFound = X1Id == X2Id;
7037 if (IsUpdateExprFound) {
7038 V = FirstBinOp->getLHS();
7039 X = SecondBinOp->getLHS();
7040 E = SecondBinOp->getRHS();
7041 UE = nullptr;
7042 IsXLHSInRHSPart = false;
7043 IsPostfixUpdate = true;
7044 } else {
7045 ErrorFound = NotASpecificExpression;
7046 ErrorLoc = FirstBinOp->getExprLoc();
7047 ErrorRange = FirstBinOp->getSourceRange();
7048 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7049 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7050 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007051 }
7052 }
7053 }
7054 }
7055 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007056 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007057 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007058 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007059 ErrorFound = NotTwoSubstatements;
7060 }
7061 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007062 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007063 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007064 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007065 ErrorFound = NotACompoundStatement;
7066 }
7067 if (ErrorFound != NoError) {
7068 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7069 << ErrorRange;
7070 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7071 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007072 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007073 if (CurContext->isDependentContext())
7074 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007075 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007076 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007077
Reid Kleckner87a31802018-03-12 21:43:02 +00007078 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007079
Alexey Bataev62cec442014-11-18 10:14:22 +00007080 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007081 X, V, E, UE, IsXLHSInRHSPart,
7082 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007083}
7084
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007085StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7086 Stmt *AStmt,
7087 SourceLocation StartLoc,
7088 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007089 if (!AStmt)
7090 return StmtError();
7091
Alexey Bataeve3727102018-04-18 15:57:46 +00007092 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007093 // 1.2.2 OpenMP Language Terminology
7094 // Structured block - An executable statement with a single entry at the
7095 // top and a single exit at the bottom.
7096 // The point of exit cannot be a branch out of the structured block.
7097 // longjmp() and throw() must not violate the entry/exit criteria.
7098 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007099 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7100 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7101 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7102 // 1.2.2 OpenMP Language Terminology
7103 // Structured block - An executable statement with a single entry at the
7104 // top and a single exit at the bottom.
7105 // The point of exit cannot be a branch out of the structured block.
7106 // longjmp() and throw() must not violate the entry/exit criteria.
7107 CS->getCapturedDecl()->setNothrow();
7108 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007109
Alexey Bataev13314bf2014-10-09 04:18:56 +00007110 // OpenMP [2.16, Nesting of Regions]
7111 // If specified, a teams construct must be contained within a target
7112 // construct. That target construct must contain no statements or directives
7113 // outside of the teams construct.
7114 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007115 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007116 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007117 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007118 auto I = CS->body_begin();
7119 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007120 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007121 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7122 OMPTeamsFound) {
7123
Alexey Bataev13314bf2014-10-09 04:18:56 +00007124 OMPTeamsFound = false;
7125 break;
7126 }
7127 ++I;
7128 }
7129 assert(I != CS->body_end() && "Not found statement");
7130 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007131 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007132 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007133 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007134 }
7135 if (!OMPTeamsFound) {
7136 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7137 Diag(DSAStack->getInnerTeamsRegionLoc(),
7138 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007139 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007140 << isa<OMPExecutableDirective>(S);
7141 return StmtError();
7142 }
7143 }
7144
Reid Kleckner87a31802018-03-12 21:43:02 +00007145 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007146
7147 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7148}
7149
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007150StmtResult
7151Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7152 Stmt *AStmt, SourceLocation StartLoc,
7153 SourceLocation EndLoc) {
7154 if (!AStmt)
7155 return StmtError();
7156
Alexey Bataeve3727102018-04-18 15:57:46 +00007157 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007158 // 1.2.2 OpenMP Language Terminology
7159 // Structured block - An executable statement with a single entry at the
7160 // top and a single exit at the bottom.
7161 // The point of exit cannot be a branch out of the structured block.
7162 // longjmp() and throw() must not violate the entry/exit criteria.
7163 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007164 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7165 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7166 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7167 // 1.2.2 OpenMP Language Terminology
7168 // Structured block - An executable statement with a single entry at the
7169 // top and a single exit at the bottom.
7170 // The point of exit cannot be a branch out of the structured block.
7171 // longjmp() and throw() must not violate the entry/exit criteria.
7172 CS->getCapturedDecl()->setNothrow();
7173 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007174
Reid Kleckner87a31802018-03-12 21:43:02 +00007175 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007176
7177 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7178 AStmt);
7179}
7180
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007181StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7182 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007183 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007184 if (!AStmt)
7185 return StmtError();
7186
Alexey Bataeve3727102018-04-18 15:57:46 +00007187 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007188 // 1.2.2 OpenMP Language Terminology
7189 // Structured block - An executable statement with a single entry at the
7190 // top and a single exit at the bottom.
7191 // The point of exit cannot be a branch out of the structured block.
7192 // longjmp() and throw() must not violate the entry/exit criteria.
7193 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007194 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7195 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7196 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7197 // 1.2.2 OpenMP Language Terminology
7198 // Structured block - An executable statement with a single entry at the
7199 // top and a single exit at the bottom.
7200 // The point of exit cannot be a branch out of the structured block.
7201 // longjmp() and throw() must not violate the entry/exit criteria.
7202 CS->getCapturedDecl()->setNothrow();
7203 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007204
7205 OMPLoopDirective::HelperExprs B;
7206 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7207 // define the nested loops number.
7208 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007209 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007210 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007211 VarsWithImplicitDSA, B);
7212 if (NestedLoopCount == 0)
7213 return StmtError();
7214
7215 assert((CurContext->isDependentContext() || B.builtAll()) &&
7216 "omp target parallel for loop exprs were not built");
7217
7218 if (!CurContext->isDependentContext()) {
7219 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007220 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007221 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007222 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007223 B.NumIterations, *this, CurScope,
7224 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007225 return StmtError();
7226 }
7227 }
7228
Reid Kleckner87a31802018-03-12 21:43:02 +00007229 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007230 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7231 NestedLoopCount, Clauses, AStmt,
7232 B, DSAStack->isCancelRegion());
7233}
7234
Alexey Bataev95b64a92017-05-30 16:00:04 +00007235/// Check for existence of a map clause in the list of clauses.
7236static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7237 const OpenMPClauseKind K) {
7238 return llvm::any_of(
7239 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7240}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007241
Alexey Bataev95b64a92017-05-30 16:00:04 +00007242template <typename... Params>
7243static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7244 const Params... ClauseTypes) {
7245 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007246}
7247
Michael Wong65f367f2015-07-21 13:44:28 +00007248StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7249 Stmt *AStmt,
7250 SourceLocation StartLoc,
7251 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007252 if (!AStmt)
7253 return StmtError();
7254
7255 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7256
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007257 // OpenMP [2.10.1, Restrictions, p. 97]
7258 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007259 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7260 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7261 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007262 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007263 return StmtError();
7264 }
7265
Reid Kleckner87a31802018-03-12 21:43:02 +00007266 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007267
7268 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7269 AStmt);
7270}
7271
Samuel Antaodf67fc42016-01-19 19:15:56 +00007272StmtResult
7273Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7274 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007275 SourceLocation EndLoc, Stmt *AStmt) {
7276 if (!AStmt)
7277 return StmtError();
7278
Alexey Bataeve3727102018-04-18 15:57:46 +00007279 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007280 // 1.2.2 OpenMP Language Terminology
7281 // Structured block - An executable statement with a single entry at the
7282 // top and a single exit at the bottom.
7283 // The point of exit cannot be a branch out of the structured block.
7284 // longjmp() and throw() must not violate the entry/exit criteria.
7285 CS->getCapturedDecl()->setNothrow();
7286 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7287 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7288 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7289 // 1.2.2 OpenMP Language Terminology
7290 // Structured block - An executable statement with a single entry at the
7291 // top and a single exit at the bottom.
7292 // The point of exit cannot be a branch out of the structured block.
7293 // longjmp() and throw() must not violate the entry/exit criteria.
7294 CS->getCapturedDecl()->setNothrow();
7295 }
7296
Samuel Antaodf67fc42016-01-19 19:15:56 +00007297 // OpenMP [2.10.2, Restrictions, p. 99]
7298 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007299 if (!hasClauses(Clauses, OMPC_map)) {
7300 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7301 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007302 return StmtError();
7303 }
7304
Alexey Bataev7828b252017-11-21 17:08:48 +00007305 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7306 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007307}
7308
Samuel Antao72590762016-01-19 20:04:50 +00007309StmtResult
7310Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7311 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007312 SourceLocation EndLoc, Stmt *AStmt) {
7313 if (!AStmt)
7314 return StmtError();
7315
Alexey Bataeve3727102018-04-18 15:57:46 +00007316 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007317 // 1.2.2 OpenMP Language Terminology
7318 // Structured block - An executable statement with a single entry at the
7319 // top and a single exit at the bottom.
7320 // The point of exit cannot be a branch out of the structured block.
7321 // longjmp() and throw() must not violate the entry/exit criteria.
7322 CS->getCapturedDecl()->setNothrow();
7323 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7324 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7325 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7326 // 1.2.2 OpenMP Language Terminology
7327 // Structured block - An executable statement with a single entry at the
7328 // top and a single exit at the bottom.
7329 // The point of exit cannot be a branch out of the structured block.
7330 // longjmp() and throw() must not violate the entry/exit criteria.
7331 CS->getCapturedDecl()->setNothrow();
7332 }
7333
Samuel Antao72590762016-01-19 20:04:50 +00007334 // OpenMP [2.10.3, Restrictions, p. 102]
7335 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007336 if (!hasClauses(Clauses, OMPC_map)) {
7337 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7338 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007339 return StmtError();
7340 }
7341
Alexey Bataev7828b252017-11-21 17:08:48 +00007342 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7343 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007344}
7345
Samuel Antao686c70c2016-05-26 17:30:50 +00007346StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7347 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007348 SourceLocation EndLoc,
7349 Stmt *AStmt) {
7350 if (!AStmt)
7351 return StmtError();
7352
Alexey Bataeve3727102018-04-18 15:57:46 +00007353 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007354 // 1.2.2 OpenMP Language Terminology
7355 // Structured block - An executable statement with a single entry at the
7356 // top and a single exit at the bottom.
7357 // The point of exit cannot be a branch out of the structured block.
7358 // longjmp() and throw() must not violate the entry/exit criteria.
7359 CS->getCapturedDecl()->setNothrow();
7360 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7361 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7362 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7363 // 1.2.2 OpenMP Language Terminology
7364 // Structured block - An executable statement with a single entry at the
7365 // top and a single exit at the bottom.
7366 // The point of exit cannot be a branch out of the structured block.
7367 // longjmp() and throw() must not violate the entry/exit criteria.
7368 CS->getCapturedDecl()->setNothrow();
7369 }
7370
Alexey Bataev95b64a92017-05-30 16:00:04 +00007371 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007372 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7373 return StmtError();
7374 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007375 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7376 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007377}
7378
Alexey Bataev13314bf2014-10-09 04:18:56 +00007379StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7380 Stmt *AStmt, SourceLocation StartLoc,
7381 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007382 if (!AStmt)
7383 return StmtError();
7384
Alexey Bataeve3727102018-04-18 15:57:46 +00007385 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007386 // 1.2.2 OpenMP Language Terminology
7387 // Structured block - An executable statement with a single entry at the
7388 // top and a single exit at the bottom.
7389 // The point of exit cannot be a branch out of the structured block.
7390 // longjmp() and throw() must not violate the entry/exit criteria.
7391 CS->getCapturedDecl()->setNothrow();
7392
Reid Kleckner87a31802018-03-12 21:43:02 +00007393 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007394
Alexey Bataevceabd412017-11-30 18:01:54 +00007395 DSAStack->setParentTeamsRegionLoc(StartLoc);
7396
Alexey Bataev13314bf2014-10-09 04:18:56 +00007397 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7398}
7399
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007400StmtResult
7401Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7402 SourceLocation EndLoc,
7403 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007404 if (DSAStack->isParentNowaitRegion()) {
7405 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7406 return StmtError();
7407 }
7408 if (DSAStack->isParentOrderedRegion()) {
7409 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7410 return StmtError();
7411 }
7412 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7413 CancelRegion);
7414}
7415
Alexey Bataev87933c72015-09-18 08:07:34 +00007416StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7417 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007418 SourceLocation EndLoc,
7419 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007420 if (DSAStack->isParentNowaitRegion()) {
7421 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7422 return StmtError();
7423 }
7424 if (DSAStack->isParentOrderedRegion()) {
7425 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7426 return StmtError();
7427 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007428 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007429 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7430 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007431}
7432
Alexey Bataev382967a2015-12-08 12:06:20 +00007433static bool checkGrainsizeNumTasksClauses(Sema &S,
7434 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007435 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007436 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007437 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007438 if (C->getClauseKind() == OMPC_grainsize ||
7439 C->getClauseKind() == OMPC_num_tasks) {
7440 if (!PrevClause)
7441 PrevClause = C;
7442 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007443 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007444 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7445 << getOpenMPClauseName(C->getClauseKind())
7446 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007447 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007448 diag::note_omp_previous_grainsize_num_tasks)
7449 << getOpenMPClauseName(PrevClause->getClauseKind());
7450 ErrorFound = true;
7451 }
7452 }
7453 }
7454 return ErrorFound;
7455}
7456
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007457static bool checkReductionClauseWithNogroup(Sema &S,
7458 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007459 const OMPClause *ReductionClause = nullptr;
7460 const OMPClause *NogroupClause = nullptr;
7461 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007462 if (C->getClauseKind() == OMPC_reduction) {
7463 ReductionClause = C;
7464 if (NogroupClause)
7465 break;
7466 continue;
7467 }
7468 if (C->getClauseKind() == OMPC_nogroup) {
7469 NogroupClause = C;
7470 if (ReductionClause)
7471 break;
7472 continue;
7473 }
7474 }
7475 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007476 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7477 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007478 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007479 return true;
7480 }
7481 return false;
7482}
7483
Alexey Bataev49f6e782015-12-01 04:18:41 +00007484StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007486 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007487 if (!AStmt)
7488 return StmtError();
7489
7490 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7491 OMPLoopDirective::HelperExprs B;
7492 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7493 // define the nested loops number.
7494 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007495 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007496 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007497 VarsWithImplicitDSA, B);
7498 if (NestedLoopCount == 0)
7499 return StmtError();
7500
7501 assert((CurContext->isDependentContext() || B.builtAll()) &&
7502 "omp for loop exprs were not built");
7503
Alexey Bataev382967a2015-12-08 12:06:20 +00007504 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7505 // The grainsize clause and num_tasks clause are mutually exclusive and may
7506 // not appear on the same taskloop directive.
7507 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7508 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007509 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7510 // If a reduction clause is present on the taskloop directive, the nogroup
7511 // clause must not be specified.
7512 if (checkReductionClauseWithNogroup(*this, Clauses))
7513 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007514
Reid Kleckner87a31802018-03-12 21:43:02 +00007515 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007516 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7517 NestedLoopCount, Clauses, AStmt, B);
7518}
7519
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007520StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007522 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007523 if (!AStmt)
7524 return StmtError();
7525
7526 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7527 OMPLoopDirective::HelperExprs B;
7528 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7529 // define the nested loops number.
7530 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007531 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007532 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7533 VarsWithImplicitDSA, B);
7534 if (NestedLoopCount == 0)
7535 return StmtError();
7536
7537 assert((CurContext->isDependentContext() || B.builtAll()) &&
7538 "omp for loop exprs were not built");
7539
Alexey Bataev5a3af132016-03-29 08:58:54 +00007540 if (!CurContext->isDependentContext()) {
7541 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007542 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007543 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007544 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007545 B.NumIterations, *this, CurScope,
7546 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007547 return StmtError();
7548 }
7549 }
7550
Alexey Bataev382967a2015-12-08 12:06:20 +00007551 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7552 // The grainsize clause and num_tasks clause are mutually exclusive and may
7553 // not appear on the same taskloop directive.
7554 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7555 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007556 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7557 // If a reduction clause is present on the taskloop directive, the nogroup
7558 // clause must not be specified.
7559 if (checkReductionClauseWithNogroup(*this, Clauses))
7560 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007561 if (checkSimdlenSafelenSpecified(*this, Clauses))
7562 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007563
Reid Kleckner87a31802018-03-12 21:43:02 +00007564 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007565 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7566 NestedLoopCount, Clauses, AStmt, B);
7567}
7568
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007569StmtResult Sema::ActOnOpenMPDistributeDirective(
7570 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007571 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007572 if (!AStmt)
7573 return StmtError();
7574
7575 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7576 OMPLoopDirective::HelperExprs B;
7577 // In presence of clause 'collapse' with number of loops, it will
7578 // define the nested loops number.
7579 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007580 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007581 nullptr /*ordered not a clause on distribute*/, AStmt,
7582 *this, *DSAStack, VarsWithImplicitDSA, B);
7583 if (NestedLoopCount == 0)
7584 return StmtError();
7585
7586 assert((CurContext->isDependentContext() || B.builtAll()) &&
7587 "omp for loop exprs were not built");
7588
Reid Kleckner87a31802018-03-12 21:43:02 +00007589 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007590 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7591 NestedLoopCount, Clauses, AStmt, B);
7592}
7593
Carlo Bertolli9925f152016-06-27 14:55:37 +00007594StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7595 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007596 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007597 if (!AStmt)
7598 return StmtError();
7599
Alexey Bataeve3727102018-04-18 15:57:46 +00007600 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007601 // 1.2.2 OpenMP Language Terminology
7602 // Structured block - An executable statement with a single entry at the
7603 // top and a single exit at the bottom.
7604 // The point of exit cannot be a branch out of the structured block.
7605 // longjmp() and throw() must not violate the entry/exit criteria.
7606 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007607 for (int ThisCaptureLevel =
7608 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7609 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7610 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7611 // 1.2.2 OpenMP Language Terminology
7612 // Structured block - An executable statement with a single entry at the
7613 // top and a single exit at the bottom.
7614 // The point of exit cannot be a branch out of the structured block.
7615 // longjmp() and throw() must not violate the entry/exit criteria.
7616 CS->getCapturedDecl()->setNothrow();
7617 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007618
7619 OMPLoopDirective::HelperExprs B;
7620 // In presence of clause 'collapse' with number of loops, it will
7621 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007622 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007623 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007624 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007625 VarsWithImplicitDSA, B);
7626 if (NestedLoopCount == 0)
7627 return StmtError();
7628
7629 assert((CurContext->isDependentContext() || B.builtAll()) &&
7630 "omp for loop exprs were not built");
7631
Reid Kleckner87a31802018-03-12 21:43:02 +00007632 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007633 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007634 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7635 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007636}
7637
Kelvin Li4a39add2016-07-05 05:00:15 +00007638StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7639 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007640 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007641 if (!AStmt)
7642 return StmtError();
7643
Alexey Bataeve3727102018-04-18 15:57:46 +00007644 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007645 // 1.2.2 OpenMP Language Terminology
7646 // Structured block - An executable statement with a single entry at the
7647 // top and a single exit at the bottom.
7648 // The point of exit cannot be a branch out of the structured block.
7649 // longjmp() and throw() must not violate the entry/exit criteria.
7650 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007651 for (int ThisCaptureLevel =
7652 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7653 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7654 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7655 // 1.2.2 OpenMP Language Terminology
7656 // Structured block - An executable statement with a single entry at the
7657 // top and a single exit at the bottom.
7658 // The point of exit cannot be a branch out of the structured block.
7659 // longjmp() and throw() must not violate the entry/exit criteria.
7660 CS->getCapturedDecl()->setNothrow();
7661 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007662
7663 OMPLoopDirective::HelperExprs B;
7664 // In presence of clause 'collapse' with number of loops, it will
7665 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007666 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007667 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007668 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007669 VarsWithImplicitDSA, B);
7670 if (NestedLoopCount == 0)
7671 return StmtError();
7672
7673 assert((CurContext->isDependentContext() || B.builtAll()) &&
7674 "omp for loop exprs were not built");
7675
Alexey Bataev438388c2017-11-22 18:34:02 +00007676 if (!CurContext->isDependentContext()) {
7677 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007678 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007679 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7680 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7681 B.NumIterations, *this, CurScope,
7682 DSAStack))
7683 return StmtError();
7684 }
7685 }
7686
Kelvin Lic5609492016-07-15 04:39:07 +00007687 if (checkSimdlenSafelenSpecified(*this, Clauses))
7688 return StmtError();
7689
Reid Kleckner87a31802018-03-12 21:43:02 +00007690 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007691 return OMPDistributeParallelForSimdDirective::Create(
7692 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7693}
7694
Kelvin Li787f3fc2016-07-06 04:45:38 +00007695StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7696 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007697 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007698 if (!AStmt)
7699 return StmtError();
7700
Alexey Bataeve3727102018-04-18 15:57:46 +00007701 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007702 // 1.2.2 OpenMP Language Terminology
7703 // Structured block - An executable statement with a single entry at the
7704 // top and a single exit at the bottom.
7705 // The point of exit cannot be a branch out of the structured block.
7706 // longjmp() and throw() must not violate the entry/exit criteria.
7707 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007708 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7709 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7710 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7711 // 1.2.2 OpenMP Language Terminology
7712 // Structured block - An executable statement with a single entry at the
7713 // top and a single exit at the bottom.
7714 // The point of exit cannot be a branch out of the structured block.
7715 // longjmp() and throw() must not violate the entry/exit criteria.
7716 CS->getCapturedDecl()->setNothrow();
7717 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007718
7719 OMPLoopDirective::HelperExprs B;
7720 // In presence of clause 'collapse' with number of loops, it will
7721 // define the nested loops number.
7722 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007723 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007724 nullptr /*ordered not a clause on distribute*/, CS, *this,
7725 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007726 if (NestedLoopCount == 0)
7727 return StmtError();
7728
7729 assert((CurContext->isDependentContext() || B.builtAll()) &&
7730 "omp for loop exprs were not built");
7731
Alexey Bataev438388c2017-11-22 18:34:02 +00007732 if (!CurContext->isDependentContext()) {
7733 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007734 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007735 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7736 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7737 B.NumIterations, *this, CurScope,
7738 DSAStack))
7739 return StmtError();
7740 }
7741 }
7742
Kelvin Lic5609492016-07-15 04:39:07 +00007743 if (checkSimdlenSafelenSpecified(*this, Clauses))
7744 return StmtError();
7745
Reid Kleckner87a31802018-03-12 21:43:02 +00007746 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007747 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7748 NestedLoopCount, Clauses, AStmt, B);
7749}
7750
Kelvin Lia579b912016-07-14 02:54:56 +00007751StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7752 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007753 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007754 if (!AStmt)
7755 return StmtError();
7756
Alexey Bataeve3727102018-04-18 15:57:46 +00007757 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00007758 // 1.2.2 OpenMP Language Terminology
7759 // Structured block - An executable statement with a single entry at the
7760 // top and a single exit at the bottom.
7761 // The point of exit cannot be a branch out of the structured block.
7762 // longjmp() and throw() must not violate the entry/exit criteria.
7763 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007764 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7765 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7766 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7767 // 1.2.2 OpenMP Language Terminology
7768 // Structured block - An executable statement with a single entry at the
7769 // top and a single exit at the bottom.
7770 // The point of exit cannot be a branch out of the structured block.
7771 // longjmp() and throw() must not violate the entry/exit criteria.
7772 CS->getCapturedDecl()->setNothrow();
7773 }
Kelvin Lia579b912016-07-14 02:54:56 +00007774
7775 OMPLoopDirective::HelperExprs B;
7776 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7777 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007778 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00007779 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007780 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007781 VarsWithImplicitDSA, B);
7782 if (NestedLoopCount == 0)
7783 return StmtError();
7784
7785 assert((CurContext->isDependentContext() || B.builtAll()) &&
7786 "omp target parallel for simd loop exprs were not built");
7787
7788 if (!CurContext->isDependentContext()) {
7789 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007790 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007791 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007792 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7793 B.NumIterations, *this, CurScope,
7794 DSAStack))
7795 return StmtError();
7796 }
7797 }
Kelvin Lic5609492016-07-15 04:39:07 +00007798 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007799 return StmtError();
7800
Reid Kleckner87a31802018-03-12 21:43:02 +00007801 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00007802 return OMPTargetParallelForSimdDirective::Create(
7803 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7804}
7805
Kelvin Li986330c2016-07-20 22:57:10 +00007806StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7807 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007808 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00007809 if (!AStmt)
7810 return StmtError();
7811
Alexey Bataeve3727102018-04-18 15:57:46 +00007812 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00007813 // 1.2.2 OpenMP Language Terminology
7814 // Structured block - An executable statement with a single entry at the
7815 // top and a single exit at the bottom.
7816 // The point of exit cannot be a branch out of the structured block.
7817 // longjmp() and throw() must not violate the entry/exit criteria.
7818 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007819 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7820 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7821 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7822 // 1.2.2 OpenMP Language Terminology
7823 // Structured block - An executable statement with a single entry at the
7824 // top and a single exit at the bottom.
7825 // The point of exit cannot be a branch out of the structured block.
7826 // longjmp() and throw() must not violate the entry/exit criteria.
7827 CS->getCapturedDecl()->setNothrow();
7828 }
7829
Kelvin Li986330c2016-07-20 22:57:10 +00007830 OMPLoopDirective::HelperExprs B;
7831 // In presence of clause 'collapse' with number of loops, it will define the
7832 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007833 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007834 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007835 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007836 VarsWithImplicitDSA, B);
7837 if (NestedLoopCount == 0)
7838 return StmtError();
7839
7840 assert((CurContext->isDependentContext() || B.builtAll()) &&
7841 "omp target simd loop exprs were not built");
7842
7843 if (!CurContext->isDependentContext()) {
7844 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007845 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007846 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007847 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7848 B.NumIterations, *this, CurScope,
7849 DSAStack))
7850 return StmtError();
7851 }
7852 }
7853
7854 if (checkSimdlenSafelenSpecified(*this, Clauses))
7855 return StmtError();
7856
Reid Kleckner87a31802018-03-12 21:43:02 +00007857 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00007858 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7859 NestedLoopCount, Clauses, AStmt, B);
7860}
7861
Kelvin Li02532872016-08-05 14:37:37 +00007862StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7863 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007864 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00007865 if (!AStmt)
7866 return StmtError();
7867
Alexey Bataeve3727102018-04-18 15:57:46 +00007868 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00007869 // 1.2.2 OpenMP Language Terminology
7870 // Structured block - An executable statement with a single entry at the
7871 // top and a single exit at the bottom.
7872 // The point of exit cannot be a branch out of the structured block.
7873 // longjmp() and throw() must not violate the entry/exit criteria.
7874 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007875 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7876 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7877 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7878 // 1.2.2 OpenMP Language Terminology
7879 // Structured block - An executable statement with a single entry at the
7880 // top and a single exit at the bottom.
7881 // The point of exit cannot be a branch out of the structured block.
7882 // longjmp() and throw() must not violate the entry/exit criteria.
7883 CS->getCapturedDecl()->setNothrow();
7884 }
Kelvin Li02532872016-08-05 14:37:37 +00007885
7886 OMPLoopDirective::HelperExprs B;
7887 // In presence of clause 'collapse' with number of loops, it will
7888 // define the nested loops number.
7889 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007890 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007891 nullptr /*ordered not a clause on distribute*/, CS, *this,
7892 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007893 if (NestedLoopCount == 0)
7894 return StmtError();
7895
7896 assert((CurContext->isDependentContext() || B.builtAll()) &&
7897 "omp teams distribute loop exprs were not built");
7898
Reid Kleckner87a31802018-03-12 21:43:02 +00007899 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007900
7901 DSAStack->setParentTeamsRegionLoc(StartLoc);
7902
David Majnemer9d168222016-08-05 17:44:54 +00007903 return OMPTeamsDistributeDirective::Create(
7904 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007905}
7906
Kelvin Li4e325f72016-10-25 12:50:55 +00007907StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7908 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007909 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00007910 if (!AStmt)
7911 return StmtError();
7912
Alexey Bataeve3727102018-04-18 15:57:46 +00007913 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00007914 // 1.2.2 OpenMP Language Terminology
7915 // Structured block - An executable statement with a single entry at the
7916 // top and a single exit at the bottom.
7917 // The point of exit cannot be a branch out of the structured block.
7918 // longjmp() and throw() must not violate the entry/exit criteria.
7919 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007920 for (int ThisCaptureLevel =
7921 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7922 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7923 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7924 // 1.2.2 OpenMP Language Terminology
7925 // Structured block - An executable statement with a single entry at the
7926 // top and a single exit at the bottom.
7927 // The point of exit cannot be a branch out of the structured block.
7928 // longjmp() and throw() must not violate the entry/exit criteria.
7929 CS->getCapturedDecl()->setNothrow();
7930 }
7931
Kelvin Li4e325f72016-10-25 12:50:55 +00007932
7933 OMPLoopDirective::HelperExprs B;
7934 // In presence of clause 'collapse' with number of loops, it will
7935 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007936 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00007937 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007938 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007939 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007940
7941 if (NestedLoopCount == 0)
7942 return StmtError();
7943
7944 assert((CurContext->isDependentContext() || B.builtAll()) &&
7945 "omp teams distribute simd loop exprs were not built");
7946
7947 if (!CurContext->isDependentContext()) {
7948 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007949 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00007950 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7951 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7952 B.NumIterations, *this, CurScope,
7953 DSAStack))
7954 return StmtError();
7955 }
7956 }
7957
7958 if (checkSimdlenSafelenSpecified(*this, Clauses))
7959 return StmtError();
7960
Reid Kleckner87a31802018-03-12 21:43:02 +00007961 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007962
7963 DSAStack->setParentTeamsRegionLoc(StartLoc);
7964
Kelvin Li4e325f72016-10-25 12:50:55 +00007965 return OMPTeamsDistributeSimdDirective::Create(
7966 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7967}
7968
Kelvin Li579e41c2016-11-30 23:51:03 +00007969StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7970 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007971 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00007972 if (!AStmt)
7973 return StmtError();
7974
Alexey Bataeve3727102018-04-18 15:57:46 +00007975 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00007976 // 1.2.2 OpenMP Language Terminology
7977 // Structured block - An executable statement with a single entry at the
7978 // top and a single exit at the bottom.
7979 // The point of exit cannot be a branch out of the structured block.
7980 // longjmp() and throw() must not violate the entry/exit criteria.
7981 CS->getCapturedDecl()->setNothrow();
7982
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007983 for (int ThisCaptureLevel =
7984 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7985 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7986 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7987 // 1.2.2 OpenMP Language Terminology
7988 // Structured block - An executable statement with a single entry at the
7989 // top and a single exit at the bottom.
7990 // The point of exit cannot be a branch out of the structured block.
7991 // longjmp() and throw() must not violate the entry/exit criteria.
7992 CS->getCapturedDecl()->setNothrow();
7993 }
7994
Kelvin Li579e41c2016-11-30 23:51:03 +00007995 OMPLoopDirective::HelperExprs B;
7996 // In presence of clause 'collapse' with number of loops, it will
7997 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007998 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00007999 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008000 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008001 VarsWithImplicitDSA, B);
8002
8003 if (NestedLoopCount == 0)
8004 return StmtError();
8005
8006 assert((CurContext->isDependentContext() || B.builtAll()) &&
8007 "omp for loop exprs were not built");
8008
8009 if (!CurContext->isDependentContext()) {
8010 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008011 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008012 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8013 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8014 B.NumIterations, *this, CurScope,
8015 DSAStack))
8016 return StmtError();
8017 }
8018 }
8019
8020 if (checkSimdlenSafelenSpecified(*this, Clauses))
8021 return StmtError();
8022
Reid Kleckner87a31802018-03-12 21:43:02 +00008023 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008024
8025 DSAStack->setParentTeamsRegionLoc(StartLoc);
8026
Kelvin Li579e41c2016-11-30 23:51:03 +00008027 return OMPTeamsDistributeParallelForSimdDirective::Create(
8028 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8029}
8030
Kelvin Li7ade93f2016-12-09 03:24:30 +00008031StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8032 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008033 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008034 if (!AStmt)
8035 return StmtError();
8036
Alexey Bataeve3727102018-04-18 15:57:46 +00008037 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008038 // 1.2.2 OpenMP Language Terminology
8039 // Structured block - An executable statement with a single entry at the
8040 // top and a single exit at the bottom.
8041 // The point of exit cannot be a branch out of the structured block.
8042 // longjmp() and throw() must not violate the entry/exit criteria.
8043 CS->getCapturedDecl()->setNothrow();
8044
Carlo Bertolli62fae152017-11-20 20:46:39 +00008045 for (int ThisCaptureLevel =
8046 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8047 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8048 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8049 // 1.2.2 OpenMP Language Terminology
8050 // Structured block - An executable statement with a single entry at the
8051 // top and a single exit at the bottom.
8052 // The point of exit cannot be a branch out of the structured block.
8053 // longjmp() and throw() must not violate the entry/exit criteria.
8054 CS->getCapturedDecl()->setNothrow();
8055 }
8056
Kelvin Li7ade93f2016-12-09 03:24:30 +00008057 OMPLoopDirective::HelperExprs B;
8058 // In presence of clause 'collapse' with number of loops, it will
8059 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008060 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008061 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008062 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008063 VarsWithImplicitDSA, B);
8064
8065 if (NestedLoopCount == 0)
8066 return StmtError();
8067
8068 assert((CurContext->isDependentContext() || B.builtAll()) &&
8069 "omp for loop exprs were not built");
8070
Reid Kleckner87a31802018-03-12 21:43:02 +00008071 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008072
8073 DSAStack->setParentTeamsRegionLoc(StartLoc);
8074
Kelvin Li7ade93f2016-12-09 03:24:30 +00008075 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008076 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8077 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008078}
8079
Kelvin Libf594a52016-12-17 05:48:59 +00008080StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8081 Stmt *AStmt,
8082 SourceLocation StartLoc,
8083 SourceLocation EndLoc) {
8084 if (!AStmt)
8085 return StmtError();
8086
Alexey Bataeve3727102018-04-18 15:57:46 +00008087 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008088 // 1.2.2 OpenMP Language Terminology
8089 // Structured block - An executable statement with a single entry at the
8090 // top and a single exit at the bottom.
8091 // The point of exit cannot be a branch out of the structured block.
8092 // longjmp() and throw() must not violate the entry/exit criteria.
8093 CS->getCapturedDecl()->setNothrow();
8094
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008095 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8096 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8097 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8098 // 1.2.2 OpenMP Language Terminology
8099 // Structured block - An executable statement with a single entry at the
8100 // top and a single exit at the bottom.
8101 // The point of exit cannot be a branch out of the structured block.
8102 // longjmp() and throw() must not violate the entry/exit criteria.
8103 CS->getCapturedDecl()->setNothrow();
8104 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008105 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008106
8107 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8108 AStmt);
8109}
8110
Kelvin Li83c451e2016-12-25 04:52:54 +00008111StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8112 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008113 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008114 if (!AStmt)
8115 return StmtError();
8116
Alexey Bataeve3727102018-04-18 15:57:46 +00008117 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008118 // 1.2.2 OpenMP Language Terminology
8119 // Structured block - An executable statement with a single entry at the
8120 // top and a single exit at the bottom.
8121 // The point of exit cannot be a branch out of the structured block.
8122 // longjmp() and throw() must not violate the entry/exit criteria.
8123 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008124 for (int ThisCaptureLevel =
8125 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8126 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8127 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8128 // 1.2.2 OpenMP Language Terminology
8129 // Structured block - An executable statement with a single entry at the
8130 // top and a single exit at the bottom.
8131 // The point of exit cannot be a branch out of the structured block.
8132 // longjmp() and throw() must not violate the entry/exit criteria.
8133 CS->getCapturedDecl()->setNothrow();
8134 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008135
8136 OMPLoopDirective::HelperExprs B;
8137 // In presence of clause 'collapse' with number of loops, it will
8138 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008139 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008140 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8141 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008142 VarsWithImplicitDSA, B);
8143 if (NestedLoopCount == 0)
8144 return StmtError();
8145
8146 assert((CurContext->isDependentContext() || B.builtAll()) &&
8147 "omp target teams distribute loop exprs were not built");
8148
Reid Kleckner87a31802018-03-12 21:43:02 +00008149 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008150 return OMPTargetTeamsDistributeDirective::Create(
8151 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8152}
8153
Kelvin Li80e8f562016-12-29 22:16:30 +00008154StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8155 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008156 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008157 if (!AStmt)
8158 return StmtError();
8159
Alexey Bataeve3727102018-04-18 15:57:46 +00008160 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008161 // 1.2.2 OpenMP Language Terminology
8162 // Structured block - An executable statement with a single entry at the
8163 // top and a single exit at the bottom.
8164 // The point of exit cannot be a branch out of the structured block.
8165 // longjmp() and throw() must not violate the entry/exit criteria.
8166 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008167 for (int ThisCaptureLevel =
8168 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8169 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8170 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8171 // 1.2.2 OpenMP Language Terminology
8172 // Structured block - An executable statement with a single entry at the
8173 // top and a single exit at the bottom.
8174 // The point of exit cannot be a branch out of the structured block.
8175 // longjmp() and throw() must not violate the entry/exit criteria.
8176 CS->getCapturedDecl()->setNothrow();
8177 }
8178
Kelvin Li80e8f562016-12-29 22:16:30 +00008179 OMPLoopDirective::HelperExprs B;
8180 // In presence of clause 'collapse' with number of loops, it will
8181 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008182 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008183 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8184 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008185 VarsWithImplicitDSA, B);
8186 if (NestedLoopCount == 0)
8187 return StmtError();
8188
8189 assert((CurContext->isDependentContext() || B.builtAll()) &&
8190 "omp target teams distribute parallel for loop exprs were not built");
8191
Alexey Bataev647dd842018-01-15 20:59:40 +00008192 if (!CurContext->isDependentContext()) {
8193 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008194 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008195 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8196 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8197 B.NumIterations, *this, CurScope,
8198 DSAStack))
8199 return StmtError();
8200 }
8201 }
8202
Reid Kleckner87a31802018-03-12 21:43:02 +00008203 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008204 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008205 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8206 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008207}
8208
Kelvin Li1851df52017-01-03 05:23:48 +00008209StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8210 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008211 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008212 if (!AStmt)
8213 return StmtError();
8214
Alexey Bataeve3727102018-04-18 15:57:46 +00008215 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008216 // 1.2.2 OpenMP Language Terminology
8217 // Structured block - An executable statement with a single entry at the
8218 // top and a single exit at the bottom.
8219 // The point of exit cannot be a branch out of the structured block.
8220 // longjmp() and throw() must not violate the entry/exit criteria.
8221 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008222 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8223 OMPD_target_teams_distribute_parallel_for_simd);
8224 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8225 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8226 // 1.2.2 OpenMP Language Terminology
8227 // Structured block - An executable statement with a single entry at the
8228 // top and a single exit at the bottom.
8229 // The point of exit cannot be a branch out of the structured block.
8230 // longjmp() and throw() must not violate the entry/exit criteria.
8231 CS->getCapturedDecl()->setNothrow();
8232 }
Kelvin Li1851df52017-01-03 05:23:48 +00008233
8234 OMPLoopDirective::HelperExprs B;
8235 // In presence of clause 'collapse' with number of loops, it will
8236 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008237 unsigned NestedLoopCount =
8238 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008239 getCollapseNumberExpr(Clauses),
8240 nullptr /*ordered not a clause on distribute*/, CS, *this,
8241 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008242 if (NestedLoopCount == 0)
8243 return StmtError();
8244
8245 assert((CurContext->isDependentContext() || B.builtAll()) &&
8246 "omp target teams distribute parallel for simd loop exprs were not "
8247 "built");
8248
8249 if (!CurContext->isDependentContext()) {
8250 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008251 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008252 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8253 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8254 B.NumIterations, *this, CurScope,
8255 DSAStack))
8256 return StmtError();
8257 }
8258 }
8259
Alexey Bataev438388c2017-11-22 18:34:02 +00008260 if (checkSimdlenSafelenSpecified(*this, Clauses))
8261 return StmtError();
8262
Reid Kleckner87a31802018-03-12 21:43:02 +00008263 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008264 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8265 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8266}
8267
Kelvin Lida681182017-01-10 18:08:18 +00008268StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8269 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008270 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008271 if (!AStmt)
8272 return StmtError();
8273
8274 auto *CS = cast<CapturedStmt>(AStmt);
8275 // 1.2.2 OpenMP Language Terminology
8276 // Structured block - An executable statement with a single entry at the
8277 // top and a single exit at the bottom.
8278 // The point of exit cannot be a branch out of the structured block.
8279 // longjmp() and throw() must not violate the entry/exit criteria.
8280 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008281 for (int ThisCaptureLevel =
8282 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8283 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8284 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8285 // 1.2.2 OpenMP Language Terminology
8286 // Structured block - An executable statement with a single entry at the
8287 // top and a single exit at the bottom.
8288 // The point of exit cannot be a branch out of the structured block.
8289 // longjmp() and throw() must not violate the entry/exit criteria.
8290 CS->getCapturedDecl()->setNothrow();
8291 }
Kelvin Lida681182017-01-10 18:08:18 +00008292
8293 OMPLoopDirective::HelperExprs B;
8294 // In presence of clause 'collapse' with number of loops, it will
8295 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008296 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008297 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008298 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008299 VarsWithImplicitDSA, B);
8300 if (NestedLoopCount == 0)
8301 return StmtError();
8302
8303 assert((CurContext->isDependentContext() || B.builtAll()) &&
8304 "omp target teams distribute simd loop exprs were not built");
8305
Alexey Bataev438388c2017-11-22 18:34:02 +00008306 if (!CurContext->isDependentContext()) {
8307 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008308 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008309 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8310 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8311 B.NumIterations, *this, CurScope,
8312 DSAStack))
8313 return StmtError();
8314 }
8315 }
8316
8317 if (checkSimdlenSafelenSpecified(*this, Clauses))
8318 return StmtError();
8319
Reid Kleckner87a31802018-03-12 21:43:02 +00008320 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008321 return OMPTargetTeamsDistributeSimdDirective::Create(
8322 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8323}
8324
Alexey Bataeved09d242014-05-28 05:53:51 +00008325OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008326 SourceLocation StartLoc,
8327 SourceLocation LParenLoc,
8328 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008329 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008330 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008331 case OMPC_final:
8332 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8333 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008334 case OMPC_num_threads:
8335 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8336 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008337 case OMPC_safelen:
8338 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8339 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008340 case OMPC_simdlen:
8341 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8342 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008343 case OMPC_collapse:
8344 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8345 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008346 case OMPC_ordered:
8347 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8348 break;
Michael Wonge710d542015-08-07 16:16:36 +00008349 case OMPC_device:
8350 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8351 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008352 case OMPC_num_teams:
8353 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8354 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008355 case OMPC_thread_limit:
8356 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8357 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008358 case OMPC_priority:
8359 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8360 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008361 case OMPC_grainsize:
8362 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8363 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008364 case OMPC_num_tasks:
8365 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8366 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008367 case OMPC_hint:
8368 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8369 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008370 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008371 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008372 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008373 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008374 case OMPC_private:
8375 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008376 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008377 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008378 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008379 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008380 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008381 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008382 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008383 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008384 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008385 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008386 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008387 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008388 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008389 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008390 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008391 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008392 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008393 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008394 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008395 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008396 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008397 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008398 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008399 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008400 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008401 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008402 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008403 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008404 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008405 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008406 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008407 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008408 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008409 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008410 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008411 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008412 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008413 llvm_unreachable("Clause is not allowed.");
8414 }
8415 return Res;
8416}
8417
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008418// An OpenMP directive such as 'target parallel' has two captured regions:
8419// for the 'target' and 'parallel' respectively. This function returns
8420// the region in which to capture expressions associated with a clause.
8421// A return value of OMPD_unknown signifies that the expression should not
8422// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008423static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8424 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8425 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008426 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008427 switch (CKind) {
8428 case OMPC_if:
8429 switch (DKind) {
8430 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008431 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008432 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008433 // If this clause applies to the nested 'parallel' region, capture within
8434 // the 'target' region, otherwise do not capture.
8435 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8436 CaptureRegion = OMPD_target;
8437 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008438 case OMPD_target_teams_distribute_parallel_for:
8439 case OMPD_target_teams_distribute_parallel_for_simd:
8440 // If this clause applies to the nested 'parallel' region, capture within
8441 // the 'teams' region, otherwise do not capture.
8442 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8443 CaptureRegion = OMPD_teams;
8444 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008445 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008446 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008447 CaptureRegion = OMPD_teams;
8448 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008449 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008450 case OMPD_target_enter_data:
8451 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008452 CaptureRegion = OMPD_task;
8453 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008454 case OMPD_cancel:
8455 case OMPD_parallel:
8456 case OMPD_parallel_sections:
8457 case OMPD_parallel_for:
8458 case OMPD_parallel_for_simd:
8459 case OMPD_target:
8460 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008461 case OMPD_target_teams:
8462 case OMPD_target_teams_distribute:
8463 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008464 case OMPD_distribute_parallel_for:
8465 case OMPD_distribute_parallel_for_simd:
8466 case OMPD_task:
8467 case OMPD_taskloop:
8468 case OMPD_taskloop_simd:
8469 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008470 // Do not capture if-clause expressions.
8471 break;
8472 case OMPD_threadprivate:
8473 case OMPD_taskyield:
8474 case OMPD_barrier:
8475 case OMPD_taskwait:
8476 case OMPD_cancellation_point:
8477 case OMPD_flush:
8478 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008479 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008480 case OMPD_declare_simd:
8481 case OMPD_declare_target:
8482 case OMPD_end_declare_target:
8483 case OMPD_teams:
8484 case OMPD_simd:
8485 case OMPD_for:
8486 case OMPD_for_simd:
8487 case OMPD_sections:
8488 case OMPD_section:
8489 case OMPD_single:
8490 case OMPD_master:
8491 case OMPD_critical:
8492 case OMPD_taskgroup:
8493 case OMPD_distribute:
8494 case OMPD_ordered:
8495 case OMPD_atomic:
8496 case OMPD_distribute_simd:
8497 case OMPD_teams_distribute:
8498 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008499 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008500 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8501 case OMPD_unknown:
8502 llvm_unreachable("Unknown OpenMP directive");
8503 }
8504 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008505 case OMPC_num_threads:
8506 switch (DKind) {
8507 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008508 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008509 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008510 CaptureRegion = OMPD_target;
8511 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008512 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008513 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008514 case OMPD_target_teams_distribute_parallel_for:
8515 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008516 CaptureRegion = OMPD_teams;
8517 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008518 case OMPD_parallel:
8519 case OMPD_parallel_sections:
8520 case OMPD_parallel_for:
8521 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008522 case OMPD_distribute_parallel_for:
8523 case OMPD_distribute_parallel_for_simd:
8524 // Do not capture num_threads-clause expressions.
8525 break;
8526 case OMPD_target_data:
8527 case OMPD_target_enter_data:
8528 case OMPD_target_exit_data:
8529 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008530 case OMPD_target:
8531 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008532 case OMPD_target_teams:
8533 case OMPD_target_teams_distribute:
8534 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008535 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008536 case OMPD_task:
8537 case OMPD_taskloop:
8538 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008539 case OMPD_threadprivate:
8540 case OMPD_taskyield:
8541 case OMPD_barrier:
8542 case OMPD_taskwait:
8543 case OMPD_cancellation_point:
8544 case OMPD_flush:
8545 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008546 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008547 case OMPD_declare_simd:
8548 case OMPD_declare_target:
8549 case OMPD_end_declare_target:
8550 case OMPD_teams:
8551 case OMPD_simd:
8552 case OMPD_for:
8553 case OMPD_for_simd:
8554 case OMPD_sections:
8555 case OMPD_section:
8556 case OMPD_single:
8557 case OMPD_master:
8558 case OMPD_critical:
8559 case OMPD_taskgroup:
8560 case OMPD_distribute:
8561 case OMPD_ordered:
8562 case OMPD_atomic:
8563 case OMPD_distribute_simd:
8564 case OMPD_teams_distribute:
8565 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008566 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008567 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8568 case OMPD_unknown:
8569 llvm_unreachable("Unknown OpenMP directive");
8570 }
8571 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008572 case OMPC_num_teams:
8573 switch (DKind) {
8574 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008575 case OMPD_target_teams_distribute:
8576 case OMPD_target_teams_distribute_simd:
8577 case OMPD_target_teams_distribute_parallel_for:
8578 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008579 CaptureRegion = OMPD_target;
8580 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008581 case OMPD_teams_distribute_parallel_for:
8582 case OMPD_teams_distribute_parallel_for_simd:
8583 case OMPD_teams:
8584 case OMPD_teams_distribute:
8585 case OMPD_teams_distribute_simd:
8586 // Do not capture num_teams-clause expressions.
8587 break;
8588 case OMPD_distribute_parallel_for:
8589 case OMPD_distribute_parallel_for_simd:
8590 case OMPD_task:
8591 case OMPD_taskloop:
8592 case OMPD_taskloop_simd:
8593 case OMPD_target_data:
8594 case OMPD_target_enter_data:
8595 case OMPD_target_exit_data:
8596 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008597 case OMPD_cancel:
8598 case OMPD_parallel:
8599 case OMPD_parallel_sections:
8600 case OMPD_parallel_for:
8601 case OMPD_parallel_for_simd:
8602 case OMPD_target:
8603 case OMPD_target_simd:
8604 case OMPD_target_parallel:
8605 case OMPD_target_parallel_for:
8606 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008607 case OMPD_threadprivate:
8608 case OMPD_taskyield:
8609 case OMPD_barrier:
8610 case OMPD_taskwait:
8611 case OMPD_cancellation_point:
8612 case OMPD_flush:
8613 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008614 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008615 case OMPD_declare_simd:
8616 case OMPD_declare_target:
8617 case OMPD_end_declare_target:
8618 case OMPD_simd:
8619 case OMPD_for:
8620 case OMPD_for_simd:
8621 case OMPD_sections:
8622 case OMPD_section:
8623 case OMPD_single:
8624 case OMPD_master:
8625 case OMPD_critical:
8626 case OMPD_taskgroup:
8627 case OMPD_distribute:
8628 case OMPD_ordered:
8629 case OMPD_atomic:
8630 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008631 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008632 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8633 case OMPD_unknown:
8634 llvm_unreachable("Unknown OpenMP directive");
8635 }
8636 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008637 case OMPC_thread_limit:
8638 switch (DKind) {
8639 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008640 case OMPD_target_teams_distribute:
8641 case OMPD_target_teams_distribute_simd:
8642 case OMPD_target_teams_distribute_parallel_for:
8643 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008644 CaptureRegion = OMPD_target;
8645 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008646 case OMPD_teams_distribute_parallel_for:
8647 case OMPD_teams_distribute_parallel_for_simd:
8648 case OMPD_teams:
8649 case OMPD_teams_distribute:
8650 case OMPD_teams_distribute_simd:
8651 // Do not capture thread_limit-clause expressions.
8652 break;
8653 case OMPD_distribute_parallel_for:
8654 case OMPD_distribute_parallel_for_simd:
8655 case OMPD_task:
8656 case OMPD_taskloop:
8657 case OMPD_taskloop_simd:
8658 case OMPD_target_data:
8659 case OMPD_target_enter_data:
8660 case OMPD_target_exit_data:
8661 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008662 case OMPD_cancel:
8663 case OMPD_parallel:
8664 case OMPD_parallel_sections:
8665 case OMPD_parallel_for:
8666 case OMPD_parallel_for_simd:
8667 case OMPD_target:
8668 case OMPD_target_simd:
8669 case OMPD_target_parallel:
8670 case OMPD_target_parallel_for:
8671 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008672 case OMPD_threadprivate:
8673 case OMPD_taskyield:
8674 case OMPD_barrier:
8675 case OMPD_taskwait:
8676 case OMPD_cancellation_point:
8677 case OMPD_flush:
8678 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008679 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008680 case OMPD_declare_simd:
8681 case OMPD_declare_target:
8682 case OMPD_end_declare_target:
8683 case OMPD_simd:
8684 case OMPD_for:
8685 case OMPD_for_simd:
8686 case OMPD_sections:
8687 case OMPD_section:
8688 case OMPD_single:
8689 case OMPD_master:
8690 case OMPD_critical:
8691 case OMPD_taskgroup:
8692 case OMPD_distribute:
8693 case OMPD_ordered:
8694 case OMPD_atomic:
8695 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008696 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008697 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8698 case OMPD_unknown:
8699 llvm_unreachable("Unknown OpenMP directive");
8700 }
8701 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008702 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008703 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008704 case OMPD_parallel_for:
8705 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008706 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008707 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008708 case OMPD_teams_distribute_parallel_for:
8709 case OMPD_teams_distribute_parallel_for_simd:
8710 case OMPD_target_parallel_for:
8711 case OMPD_target_parallel_for_simd:
8712 case OMPD_target_teams_distribute_parallel_for:
8713 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008714 CaptureRegion = OMPD_parallel;
8715 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008716 case OMPD_for:
8717 case OMPD_for_simd:
8718 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008719 break;
8720 case OMPD_task:
8721 case OMPD_taskloop:
8722 case OMPD_taskloop_simd:
8723 case OMPD_target_data:
8724 case OMPD_target_enter_data:
8725 case OMPD_target_exit_data:
8726 case OMPD_target_update:
8727 case OMPD_teams:
8728 case OMPD_teams_distribute:
8729 case OMPD_teams_distribute_simd:
8730 case OMPD_target_teams_distribute:
8731 case OMPD_target_teams_distribute_simd:
8732 case OMPD_target:
8733 case OMPD_target_simd:
8734 case OMPD_target_parallel:
8735 case OMPD_cancel:
8736 case OMPD_parallel:
8737 case OMPD_parallel_sections:
8738 case OMPD_threadprivate:
8739 case OMPD_taskyield:
8740 case OMPD_barrier:
8741 case OMPD_taskwait:
8742 case OMPD_cancellation_point:
8743 case OMPD_flush:
8744 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008745 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008746 case OMPD_declare_simd:
8747 case OMPD_declare_target:
8748 case OMPD_end_declare_target:
8749 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008750 case OMPD_sections:
8751 case OMPD_section:
8752 case OMPD_single:
8753 case OMPD_master:
8754 case OMPD_critical:
8755 case OMPD_taskgroup:
8756 case OMPD_distribute:
8757 case OMPD_ordered:
8758 case OMPD_atomic:
8759 case OMPD_distribute_simd:
8760 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008761 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008762 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8763 case OMPD_unknown:
8764 llvm_unreachable("Unknown OpenMP directive");
8765 }
8766 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008767 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008768 switch (DKind) {
8769 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008770 case OMPD_teams_distribute_parallel_for_simd:
8771 case OMPD_teams_distribute:
8772 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008773 case OMPD_target_teams_distribute_parallel_for:
8774 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008775 case OMPD_target_teams_distribute:
8776 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008777 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008778 break;
8779 case OMPD_distribute_parallel_for:
8780 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008781 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008782 case OMPD_distribute_simd:
8783 // Do not capture thread_limit-clause expressions.
8784 break;
8785 case OMPD_parallel_for:
8786 case OMPD_parallel_for_simd:
8787 case OMPD_target_parallel_for_simd:
8788 case OMPD_target_parallel_for:
8789 case OMPD_task:
8790 case OMPD_taskloop:
8791 case OMPD_taskloop_simd:
8792 case OMPD_target_data:
8793 case OMPD_target_enter_data:
8794 case OMPD_target_exit_data:
8795 case OMPD_target_update:
8796 case OMPD_teams:
8797 case OMPD_target:
8798 case OMPD_target_simd:
8799 case OMPD_target_parallel:
8800 case OMPD_cancel:
8801 case OMPD_parallel:
8802 case OMPD_parallel_sections:
8803 case OMPD_threadprivate:
8804 case OMPD_taskyield:
8805 case OMPD_barrier:
8806 case OMPD_taskwait:
8807 case OMPD_cancellation_point:
8808 case OMPD_flush:
8809 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008810 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008811 case OMPD_declare_simd:
8812 case OMPD_declare_target:
8813 case OMPD_end_declare_target:
8814 case OMPD_simd:
8815 case OMPD_for:
8816 case OMPD_for_simd:
8817 case OMPD_sections:
8818 case OMPD_section:
8819 case OMPD_single:
8820 case OMPD_master:
8821 case OMPD_critical:
8822 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008823 case OMPD_ordered:
8824 case OMPD_atomic:
8825 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008826 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008827 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8828 case OMPD_unknown:
8829 llvm_unreachable("Unknown OpenMP directive");
8830 }
8831 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008832 case OMPC_device:
8833 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008834 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008835 case OMPD_target_enter_data:
8836 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008837 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008838 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008839 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008840 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008841 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008842 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008843 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00008844 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00008845 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00008846 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008847 CaptureRegion = OMPD_task;
8848 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008849 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008850 // Do not capture device-clause expressions.
8851 break;
8852 case OMPD_teams_distribute_parallel_for:
8853 case OMPD_teams_distribute_parallel_for_simd:
8854 case OMPD_teams:
8855 case OMPD_teams_distribute:
8856 case OMPD_teams_distribute_simd:
8857 case OMPD_distribute_parallel_for:
8858 case OMPD_distribute_parallel_for_simd:
8859 case OMPD_task:
8860 case OMPD_taskloop:
8861 case OMPD_taskloop_simd:
8862 case OMPD_cancel:
8863 case OMPD_parallel:
8864 case OMPD_parallel_sections:
8865 case OMPD_parallel_for:
8866 case OMPD_parallel_for_simd:
8867 case OMPD_threadprivate:
8868 case OMPD_taskyield:
8869 case OMPD_barrier:
8870 case OMPD_taskwait:
8871 case OMPD_cancellation_point:
8872 case OMPD_flush:
8873 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008874 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008875 case OMPD_declare_simd:
8876 case OMPD_declare_target:
8877 case OMPD_end_declare_target:
8878 case OMPD_simd:
8879 case OMPD_for:
8880 case OMPD_for_simd:
8881 case OMPD_sections:
8882 case OMPD_section:
8883 case OMPD_single:
8884 case OMPD_master:
8885 case OMPD_critical:
8886 case OMPD_taskgroup:
8887 case OMPD_distribute:
8888 case OMPD_ordered:
8889 case OMPD_atomic:
8890 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008891 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008892 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8893 case OMPD_unknown:
8894 llvm_unreachable("Unknown OpenMP directive");
8895 }
8896 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008897 case OMPC_firstprivate:
8898 case OMPC_lastprivate:
8899 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008900 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008901 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008902 case OMPC_linear:
8903 case OMPC_default:
8904 case OMPC_proc_bind:
8905 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008906 case OMPC_safelen:
8907 case OMPC_simdlen:
8908 case OMPC_collapse:
8909 case OMPC_private:
8910 case OMPC_shared:
8911 case OMPC_aligned:
8912 case OMPC_copyin:
8913 case OMPC_copyprivate:
8914 case OMPC_ordered:
8915 case OMPC_nowait:
8916 case OMPC_untied:
8917 case OMPC_mergeable:
8918 case OMPC_threadprivate:
8919 case OMPC_flush:
8920 case OMPC_read:
8921 case OMPC_write:
8922 case OMPC_update:
8923 case OMPC_capture:
8924 case OMPC_seq_cst:
8925 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008926 case OMPC_threads:
8927 case OMPC_simd:
8928 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008929 case OMPC_priority:
8930 case OMPC_grainsize:
8931 case OMPC_nogroup:
8932 case OMPC_num_tasks:
8933 case OMPC_hint:
8934 case OMPC_defaultmap:
8935 case OMPC_unknown:
8936 case OMPC_uniform:
8937 case OMPC_to:
8938 case OMPC_from:
8939 case OMPC_use_device_ptr:
8940 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008941 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008942 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008943 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008944 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008945 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008946 llvm_unreachable("Unexpected OpenMP clause.");
8947 }
8948 return CaptureRegion;
8949}
8950
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008951OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8952 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008953 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008954 SourceLocation NameModifierLoc,
8955 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008956 SourceLocation EndLoc) {
8957 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008958 Stmt *HelperValStmt = nullptr;
8959 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008960 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8961 !Condition->isInstantiationDependent() &&
8962 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008963 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008964 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008965 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008966
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008967 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008968
8969 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8970 CaptureRegion =
8971 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008972 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008973 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00008974 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008975 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8976 HelperValStmt = buildPreInits(Context, Captures);
8977 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008978 }
8979
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008980 return new (Context)
8981 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8982 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008983}
8984
Alexey Bataev3778b602014-07-17 07:32:53 +00008985OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8986 SourceLocation StartLoc,
8987 SourceLocation LParenLoc,
8988 SourceLocation EndLoc) {
8989 Expr *ValExpr = Condition;
8990 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8991 !Condition->isInstantiationDependent() &&
8992 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008993 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008994 if (Val.isInvalid())
8995 return nullptr;
8996
Richard Smith03a4aa32016-06-23 19:02:52 +00008997 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008998 }
8999
9000 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9001}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009002ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9003 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009004 if (!Op)
9005 return ExprError();
9006
9007 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9008 public:
9009 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009010 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009011 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9012 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009013 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9014 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009015 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9016 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009017 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9018 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009019 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9020 QualType T,
9021 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009022 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9023 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009024 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9025 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009026 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009027 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009028 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009029 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9030 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009031 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9032 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009033 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9034 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009035 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009036 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009037 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009038 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9039 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009040 llvm_unreachable("conversion functions are permitted");
9041 }
9042 } ConvertDiagnoser;
9043 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9044}
9045
Alexey Bataeve3727102018-04-18 15:57:46 +00009046static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009047 OpenMPClauseKind CKind,
9048 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009049 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9050 !ValExpr->isInstantiationDependent()) {
9051 SourceLocation Loc = ValExpr->getExprLoc();
9052 ExprResult Value =
9053 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9054 if (Value.isInvalid())
9055 return false;
9056
9057 ValExpr = Value.get();
9058 // The expression must evaluate to a non-negative integer value.
9059 llvm::APSInt Result;
9060 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009061 Result.isSigned() &&
9062 !((!StrictlyPositive && Result.isNonNegative()) ||
9063 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009064 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009065 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9066 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009067 return false;
9068 }
9069 }
9070 return true;
9071}
9072
Alexey Bataev568a8332014-03-06 06:15:19 +00009073OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9074 SourceLocation StartLoc,
9075 SourceLocation LParenLoc,
9076 SourceLocation EndLoc) {
9077 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009078 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009079
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009080 // OpenMP [2.5, Restrictions]
9081 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009082 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009083 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009084 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009085
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009086 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009087 OpenMPDirectiveKind CaptureRegion =
9088 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9089 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009090 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009091 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009092 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9093 HelperValStmt = buildPreInits(Context, Captures);
9094 }
9095
9096 return new (Context) OMPNumThreadsClause(
9097 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009098}
9099
Alexey Bataev62c87d22014-03-21 04:51:18 +00009100ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009101 OpenMPClauseKind CKind,
9102 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009103 if (!E)
9104 return ExprError();
9105 if (E->isValueDependent() || E->isTypeDependent() ||
9106 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009107 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009108 llvm::APSInt Result;
9109 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9110 if (ICE.isInvalid())
9111 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009112 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9113 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009114 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009115 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9116 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009117 return ExprError();
9118 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009119 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9120 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9121 << E->getSourceRange();
9122 return ExprError();
9123 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009124 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9125 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009126 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009127 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009128 return ICE;
9129}
9130
9131OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9132 SourceLocation LParenLoc,
9133 SourceLocation EndLoc) {
9134 // OpenMP [2.8.1, simd construct, Description]
9135 // The parameter of the safelen clause must be a constant
9136 // positive integer expression.
9137 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9138 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009139 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009140 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009141 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009142}
9143
Alexey Bataev66b15b52015-08-21 11:14:16 +00009144OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9145 SourceLocation LParenLoc,
9146 SourceLocation EndLoc) {
9147 // OpenMP [2.8.1, simd construct, Description]
9148 // The parameter of the simdlen clause must be a constant
9149 // positive integer expression.
9150 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9151 if (Simdlen.isInvalid())
9152 return nullptr;
9153 return new (Context)
9154 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9155}
9156
Alexander Musman64d33f12014-06-04 07:53:32 +00009157OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9158 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009159 SourceLocation LParenLoc,
9160 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009161 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009162 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009163 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009164 // The parameter of the collapse clause must be a constant
9165 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009166 ExprResult NumForLoopsResult =
9167 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9168 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009169 return nullptr;
9170 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009171 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009172}
9173
Alexey Bataev10e775f2015-07-30 11:36:16 +00009174OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9175 SourceLocation EndLoc,
9176 SourceLocation LParenLoc,
9177 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009178 // OpenMP [2.7.1, loop construct, Description]
9179 // OpenMP [2.8.1, simd construct, Description]
9180 // OpenMP [2.9.6, distribute construct, Description]
9181 // The parameter of the ordered clause must be a constant
9182 // positive integer expression if any.
9183 if (NumForLoops && LParenLoc.isValid()) {
9184 ExprResult NumForLoopsResult =
9185 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9186 if (NumForLoopsResult.isInvalid())
9187 return nullptr;
9188 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009189 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009190 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009191 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009192 auto *Clause = OMPOrderedClause::Create(
9193 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9194 StartLoc, LParenLoc, EndLoc);
9195 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9196 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009197}
9198
Alexey Bataeved09d242014-05-28 05:53:51 +00009199OMPClause *Sema::ActOnOpenMPSimpleClause(
9200 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9201 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009202 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009203 switch (Kind) {
9204 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009205 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009206 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9207 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009208 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009209 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009210 Res = ActOnOpenMPProcBindClause(
9211 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9212 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009213 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009214 case OMPC_atomic_default_mem_order:
9215 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9216 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9217 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9218 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009219 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009220 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009221 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009222 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009223 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009224 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009225 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009226 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009227 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009228 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009229 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009230 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009231 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009232 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009233 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009234 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009235 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009236 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009237 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009238 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009239 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009240 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009241 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009242 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009243 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009244 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009245 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009246 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009247 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009248 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009249 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009250 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009251 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009252 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009253 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009254 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009255 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009256 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009257 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009258 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009259 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009260 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009261 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009262 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009263 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009264 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009265 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009266 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009267 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009268 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009269 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009270 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009271 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009272 llvm_unreachable("Clause is not allowed.");
9273 }
9274 return Res;
9275}
9276
Alexey Bataev6402bca2015-12-28 07:25:51 +00009277static std::string
9278getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9279 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009280 SmallString<256> Buffer;
9281 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009282 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9283 unsigned Skipped = Exclude.size();
9284 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009285 for (unsigned I = First; I < Last; ++I) {
9286 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009287 --Skipped;
9288 continue;
9289 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009290 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9291 if (I == Bound - Skipped)
9292 Out << " or ";
9293 else if (I != Bound + 1 - Skipped)
9294 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009295 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009296 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009297}
9298
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009299OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9300 SourceLocation KindKwLoc,
9301 SourceLocation StartLoc,
9302 SourceLocation LParenLoc,
9303 SourceLocation EndLoc) {
9304 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009305 static_assert(OMPC_DEFAULT_unknown > 0,
9306 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009307 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009308 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9309 /*Last=*/OMPC_DEFAULT_unknown)
9310 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009311 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009312 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009313 switch (Kind) {
9314 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009315 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009316 break;
9317 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009318 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009319 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009320 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009321 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009322 break;
9323 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009324 return new (Context)
9325 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009326}
9327
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009328OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9329 SourceLocation KindKwLoc,
9330 SourceLocation StartLoc,
9331 SourceLocation LParenLoc,
9332 SourceLocation EndLoc) {
9333 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009334 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009335 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9336 /*Last=*/OMPC_PROC_BIND_unknown)
9337 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009338 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009339 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009340 return new (Context)
9341 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009342}
9343
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009344OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9345 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9346 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9347 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9348 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9349 << getListOfPossibleValues(
9350 OMPC_atomic_default_mem_order, /*First=*/0,
9351 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9352 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9353 return nullptr;
9354 }
9355 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9356 LParenLoc, EndLoc);
9357}
9358
Alexey Bataev56dafe82014-06-20 07:16:17 +00009359OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009360 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009361 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009362 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009363 SourceLocation EndLoc) {
9364 OMPClause *Res = nullptr;
9365 switch (Kind) {
9366 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009367 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9368 assert(Argument.size() == NumberOfElements &&
9369 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009370 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009371 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9372 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9373 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9374 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9375 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009376 break;
9377 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009378 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9379 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9380 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9381 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009382 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009383 case OMPC_dist_schedule:
9384 Res = ActOnOpenMPDistScheduleClause(
9385 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9386 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9387 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009388 case OMPC_defaultmap:
9389 enum { Modifier, DefaultmapKind };
9390 Res = ActOnOpenMPDefaultmapClause(
9391 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9392 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009393 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9394 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009395 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009396 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009397 case OMPC_num_threads:
9398 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009399 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009400 case OMPC_collapse:
9401 case OMPC_default:
9402 case OMPC_proc_bind:
9403 case OMPC_private:
9404 case OMPC_firstprivate:
9405 case OMPC_lastprivate:
9406 case OMPC_shared:
9407 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009408 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009409 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009410 case OMPC_linear:
9411 case OMPC_aligned:
9412 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009413 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009414 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009415 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009416 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009417 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009418 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009419 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009420 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009421 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009422 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009423 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009424 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009425 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009426 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009427 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009428 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009429 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009430 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009431 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009432 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009433 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009434 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009435 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009436 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009437 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009438 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009439 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009440 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009441 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009442 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009443 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009444 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009445 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009446 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009447 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009448 llvm_unreachable("Clause is not allowed.");
9449 }
9450 return Res;
9451}
9452
Alexey Bataev6402bca2015-12-28 07:25:51 +00009453static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9454 OpenMPScheduleClauseModifier M2,
9455 SourceLocation M1Loc, SourceLocation M2Loc) {
9456 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9457 SmallVector<unsigned, 2> Excluded;
9458 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9459 Excluded.push_back(M2);
9460 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9461 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9462 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9463 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9464 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9465 << getListOfPossibleValues(OMPC_schedule,
9466 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9467 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9468 Excluded)
9469 << getOpenMPClauseName(OMPC_schedule);
9470 return true;
9471 }
9472 return false;
9473}
9474
Alexey Bataev56dafe82014-06-20 07:16:17 +00009475OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009476 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009477 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009478 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9479 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9480 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9481 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9482 return nullptr;
9483 // OpenMP, 2.7.1, Loop Construct, Restrictions
9484 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9485 // but not both.
9486 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9487 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9488 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9489 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9490 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9491 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9492 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9493 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9494 return nullptr;
9495 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009496 if (Kind == OMPC_SCHEDULE_unknown) {
9497 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009498 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9499 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9500 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9501 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9502 Exclude);
9503 } else {
9504 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9505 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009506 }
9507 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9508 << Values << getOpenMPClauseName(OMPC_schedule);
9509 return nullptr;
9510 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009511 // OpenMP, 2.7.1, Loop Construct, Restrictions
9512 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9513 // schedule(guided).
9514 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9515 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9516 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9517 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9518 diag::err_omp_schedule_nonmonotonic_static);
9519 return nullptr;
9520 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009521 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009522 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009523 if (ChunkSize) {
9524 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9525 !ChunkSize->isInstantiationDependent() &&
9526 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009527 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009528 ExprResult Val =
9529 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9530 if (Val.isInvalid())
9531 return nullptr;
9532
9533 ValExpr = Val.get();
9534
9535 // OpenMP [2.7.1, Restrictions]
9536 // chunk_size must be a loop invariant integer expression with a positive
9537 // value.
9538 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009539 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9540 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9541 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009542 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009543 return nullptr;
9544 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009545 } else if (getOpenMPCaptureRegionForClause(
9546 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9547 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009548 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009549 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009550 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009551 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9552 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009553 }
9554 }
9555 }
9556
Alexey Bataev6402bca2015-12-28 07:25:51 +00009557 return new (Context)
9558 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009559 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009560}
9561
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009562OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9563 SourceLocation StartLoc,
9564 SourceLocation EndLoc) {
9565 OMPClause *Res = nullptr;
9566 switch (Kind) {
9567 case OMPC_ordered:
9568 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9569 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009570 case OMPC_nowait:
9571 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9572 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009573 case OMPC_untied:
9574 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9575 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009576 case OMPC_mergeable:
9577 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9578 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009579 case OMPC_read:
9580 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9581 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009582 case OMPC_write:
9583 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9584 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009585 case OMPC_update:
9586 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9587 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009588 case OMPC_capture:
9589 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9590 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009591 case OMPC_seq_cst:
9592 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9593 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009594 case OMPC_threads:
9595 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9596 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009597 case OMPC_simd:
9598 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9599 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009600 case OMPC_nogroup:
9601 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9602 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009603 case OMPC_unified_address:
9604 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9605 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009606 case OMPC_unified_shared_memory:
9607 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9608 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009609 case OMPC_reverse_offload:
9610 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9611 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009612 case OMPC_dynamic_allocators:
9613 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9614 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009615 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009616 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009617 case OMPC_num_threads:
9618 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009619 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009620 case OMPC_collapse:
9621 case OMPC_schedule:
9622 case OMPC_private:
9623 case OMPC_firstprivate:
9624 case OMPC_lastprivate:
9625 case OMPC_shared:
9626 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009627 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009628 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009629 case OMPC_linear:
9630 case OMPC_aligned:
9631 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009632 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009633 case OMPC_default:
9634 case OMPC_proc_bind:
9635 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009636 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009637 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009638 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009639 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009640 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009641 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009642 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009643 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009644 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009645 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009646 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009647 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009648 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009649 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009650 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009651 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009652 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009653 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009654 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009655 llvm_unreachable("Clause is not allowed.");
9656 }
9657 return Res;
9658}
9659
Alexey Bataev236070f2014-06-20 11:19:47 +00009660OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9661 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009662 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009663 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9664}
9665
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009666OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9667 SourceLocation EndLoc) {
9668 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9669}
9670
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009671OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9672 SourceLocation EndLoc) {
9673 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9674}
9675
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009676OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9677 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009678 return new (Context) OMPReadClause(StartLoc, EndLoc);
9679}
9680
Alexey Bataevdea47612014-07-23 07:46:59 +00009681OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9682 SourceLocation EndLoc) {
9683 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9684}
9685
Alexey Bataev67a4f222014-07-23 10:25:33 +00009686OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9687 SourceLocation EndLoc) {
9688 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9689}
9690
Alexey Bataev459dec02014-07-24 06:46:57 +00009691OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9692 SourceLocation EndLoc) {
9693 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9694}
9695
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009696OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9697 SourceLocation EndLoc) {
9698 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9699}
9700
Alexey Bataev346265e2015-09-25 10:37:12 +00009701OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9702 SourceLocation EndLoc) {
9703 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9704}
9705
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009706OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9707 SourceLocation EndLoc) {
9708 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9709}
9710
Alexey Bataevb825de12015-12-07 10:51:44 +00009711OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9712 SourceLocation EndLoc) {
9713 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9714}
9715
Kelvin Li1408f912018-09-26 04:28:39 +00009716OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9717 SourceLocation EndLoc) {
9718 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
9719}
9720
Patrick Lyster4a370b92018-10-01 13:47:43 +00009721OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9722 SourceLocation EndLoc) {
9723 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9724}
9725
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009726OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9727 SourceLocation EndLoc) {
9728 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
9729}
9730
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009731OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9732 SourceLocation EndLoc) {
9733 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
9734}
9735
Alexey Bataevc5e02582014-06-16 07:08:35 +00009736OMPClause *Sema::ActOnOpenMPVarListClause(
9737 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009738 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
9739 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
9740 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +00009741 OpenMPLinearClauseKind LinKind,
9742 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009743 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
9744 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
9745 SourceLocation StartLoc = Locs.StartLoc;
9746 SourceLocation LParenLoc = Locs.LParenLoc;
9747 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009748 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009749 switch (Kind) {
9750 case OMPC_private:
9751 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9752 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009753 case OMPC_firstprivate:
9754 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9755 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009756 case OMPC_lastprivate:
9757 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9758 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009759 case OMPC_shared:
9760 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9761 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009762 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009763 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009764 EndLoc, ReductionOrMapperIdScopeSpec,
9765 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009766 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009767 case OMPC_task_reduction:
9768 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +00009769 EndLoc, ReductionOrMapperIdScopeSpec,
9770 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +00009771 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009772 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009773 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9774 EndLoc, ReductionOrMapperIdScopeSpec,
9775 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +00009776 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009777 case OMPC_linear:
9778 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009779 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009780 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009781 case OMPC_aligned:
9782 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9783 ColonLoc, EndLoc);
9784 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009785 case OMPC_copyin:
9786 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9787 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009788 case OMPC_copyprivate:
9789 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9790 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009791 case OMPC_flush:
9792 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9793 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009794 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009795 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009796 StartLoc, LParenLoc, EndLoc);
9797 break;
9798 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009799 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
9800 ReductionOrMapperIdScopeSpec,
9801 ReductionOrMapperId, MapType, IsMapTypeImplicit,
9802 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009803 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009804 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +00009805 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
9806 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +00009807 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009808 case OMPC_from:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009809 Res = ActOnOpenMPFromClause(VarList, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +00009810 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009811 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009812 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +00009813 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009814 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +00009815 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +00009816 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009817 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009818 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009819 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009820 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009821 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009822 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009823 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009824 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009825 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009826 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009827 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009828 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009829 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009830 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009831 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009832 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009833 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009834 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009835 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009836 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009837 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009838 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009839 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009840 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009841 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009842 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009843 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009844 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009845 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009846 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009847 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009848 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009849 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +00009850 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009851 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009852 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009853 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009854 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009855 llvm_unreachable("Clause is not allowed.");
9856 }
9857 return Res;
9858}
9859
Alexey Bataev90c228f2016-02-08 09:29:13 +00009860ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009861 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009862 ExprResult Res = BuildDeclRefExpr(
9863 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9864 if (!Res.isUsable())
9865 return ExprError();
9866 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9867 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9868 if (!Res.isUsable())
9869 return ExprError();
9870 }
9871 if (VK != VK_LValue && Res.get()->isGLValue()) {
9872 Res = DefaultLvalueConversion(Res.get());
9873 if (!Res.isUsable())
9874 return ExprError();
9875 }
9876 return Res;
9877}
9878
Alexey Bataev60da77e2016-02-29 05:54:20 +00009879static std::pair<ValueDecl *, bool>
9880getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9881 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009882 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9883 RefExpr->containsUnexpandedParameterPack())
9884 return std::make_pair(nullptr, true);
9885
Alexey Bataevd985eda2016-02-10 11:29:16 +00009886 // OpenMP [3.1, C/C++]
9887 // A list item is a variable name.
9888 // OpenMP [2.9.3.3, Restrictions, p.1]
9889 // A variable that is part of another variable (as an array or
9890 // structure element) cannot appear in a private clause.
9891 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009892 enum {
9893 NoArrayExpr = -1,
9894 ArraySubscript = 0,
9895 OMPArraySection = 1
9896 } IsArrayExpr = NoArrayExpr;
9897 if (AllowArraySection) {
9898 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009899 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009900 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9901 Base = TempASE->getBase()->IgnoreParenImpCasts();
9902 RefExpr = Base;
9903 IsArrayExpr = ArraySubscript;
9904 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009905 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009906 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9907 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9908 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9909 Base = TempASE->getBase()->IgnoreParenImpCasts();
9910 RefExpr = Base;
9911 IsArrayExpr = OMPArraySection;
9912 }
9913 }
9914 ELoc = RefExpr->getExprLoc();
9915 ERange = RefExpr->getSourceRange();
9916 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009917 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9918 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9919 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9920 (S.getCurrentThisType().isNull() || !ME ||
9921 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9922 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009923 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009924 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9925 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009926 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009927 S.Diag(ELoc,
9928 AllowArraySection
9929 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9930 : diag::err_omp_expected_var_name_member_expr)
9931 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9932 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009933 return std::make_pair(nullptr, false);
9934 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009935 return std::make_pair(
9936 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009937}
9938
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009939OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9940 SourceLocation StartLoc,
9941 SourceLocation LParenLoc,
9942 SourceLocation EndLoc) {
9943 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009944 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00009945 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009946 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009947 SourceLocation ELoc;
9948 SourceRange ERange;
9949 Expr *SimpleRefExpr = RefExpr;
9950 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009951 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009952 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009953 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009954 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009955 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009956 ValueDecl *D = Res.first;
9957 if (!D)
9958 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009959
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009960 QualType Type = D->getType();
9961 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009962
9963 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9964 // A variable that appears in a private clause must not have an incomplete
9965 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009966 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009967 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009968 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009969
Joel E. Dennye6234d1422019-01-04 22:11:31 +00009970 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
9971 // A variable that is privatized must not have a const-qualified type
9972 // unless it is of class type with a mutable member. This restriction does
9973 // not apply to the firstprivate clause.
9974 //
9975 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
9976 // A variable that appears in a private clause must not have a
9977 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +00009978 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +00009979 continue;
9980
Alexey Bataev758e55e2013-09-06 18:03:48 +00009981 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9982 // in a Construct]
9983 // Variables with the predetermined data-sharing attributes may not be
9984 // listed in data-sharing attributes clauses, except for the cases
9985 // listed below. For these exceptions only, listing a predetermined
9986 // variable in a data-sharing attribute clause is allowed and overrides
9987 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00009988 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009989 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009990 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9991 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +00009992 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009993 continue;
9994 }
9995
Alexey Bataeve3727102018-04-18 15:57:46 +00009996 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009997 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009998 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00009999 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010000 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10001 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010002 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010003 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010004 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010005 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010006 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010007 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010008 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010009 continue;
10010 }
10011
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010012 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10013 // A list item cannot appear in both a map clause and a data-sharing
10014 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010015 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010016 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010017 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010018 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010019 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10020 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10021 ConflictKind = WhereFoundClauseKind;
10022 return true;
10023 })) {
10024 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010025 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010026 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010027 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010028 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010029 continue;
10030 }
10031 }
10032
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010033 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10034 // A variable of class type (or array thereof) that appears in a private
10035 // clause requires an accessible, unambiguous default constructor for the
10036 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010037 // Generate helper private variable and initialize it with the default
10038 // value. The address of the original variable is replaced by the address of
10039 // the new private variable in CodeGen. This new variable is not added to
10040 // IdResolver, so the code in the OpenMP region uses original variable for
10041 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010042 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010043 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010044 buildVarDecl(*this, ELoc, Type, D->getName(),
10045 D->hasAttrs() ? &D->getAttrs() : nullptr,
10046 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010047 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010048 if (VDPrivate->isInvalidDecl())
10049 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010050 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010051 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010052
Alexey Bataev90c228f2016-02-08 09:29:13 +000010053 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010054 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010055 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010056 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010057 Vars.push_back((VD || CurContext->isDependentContext())
10058 ? RefExpr->IgnoreParens()
10059 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010060 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010061 }
10062
Alexey Bataeved09d242014-05-28 05:53:51 +000010063 if (Vars.empty())
10064 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010065
Alexey Bataev03b340a2014-10-21 03:16:40 +000010066 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10067 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010068}
10069
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010070namespace {
10071class DiagsUninitializedSeveretyRAII {
10072private:
10073 DiagnosticsEngine &Diags;
10074 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010075 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010076
10077public:
10078 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10079 bool IsIgnored)
10080 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10081 if (!IsIgnored) {
10082 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10083 /*Map*/ diag::Severity::Ignored, Loc);
10084 }
10085 }
10086 ~DiagsUninitializedSeveretyRAII() {
10087 if (!IsIgnored)
10088 Diags.popMappings(SavedLoc);
10089 }
10090};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010091}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010092
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010093OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10094 SourceLocation StartLoc,
10095 SourceLocation LParenLoc,
10096 SourceLocation EndLoc) {
10097 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010098 SmallVector<Expr *, 8> PrivateCopies;
10099 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010100 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010101 bool IsImplicitClause =
10102 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010103 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010104
Alexey Bataeve3727102018-04-18 15:57:46 +000010105 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010106 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010107 SourceLocation ELoc;
10108 SourceRange ERange;
10109 Expr *SimpleRefExpr = RefExpr;
10110 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010111 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010112 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010113 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010114 PrivateCopies.push_back(nullptr);
10115 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010116 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010117 ValueDecl *D = Res.first;
10118 if (!D)
10119 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010120
Alexey Bataev60da77e2016-02-29 05:54:20 +000010121 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010122 QualType Type = D->getType();
10123 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010124
10125 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10126 // A variable that appears in a private clause must not have an incomplete
10127 // type or a reference type.
10128 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010129 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010130 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010131 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010132
10133 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10134 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010135 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010136 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010137 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010138
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010139 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010140 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010141 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010142 DSAStackTy::DSAVarData DVar =
10143 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010144 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010145 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010146 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010147 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10148 // A list item that specifies a given variable may not appear in more
10149 // than one clause on the same directive, except that a variable may be
10150 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010151 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10152 // A list item may appear in a firstprivate or lastprivate clause but not
10153 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010154 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010155 (isOpenMPDistributeDirective(CurrDir) ||
10156 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010157 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010158 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010159 << getOpenMPClauseName(DVar.CKind)
10160 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010161 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010162 continue;
10163 }
10164
10165 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10166 // in a Construct]
10167 // Variables with the predetermined data-sharing attributes may not be
10168 // listed in data-sharing attributes clauses, except for the cases
10169 // listed below. For these exceptions only, listing a predetermined
10170 // variable in a data-sharing attribute clause is allowed and overrides
10171 // the variable's predetermined data-sharing attributes.
10172 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10173 // in a Construct, C/C++, p.2]
10174 // Variables with const-qualified type having no mutable member may be
10175 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010176 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010177 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10178 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010179 << getOpenMPClauseName(DVar.CKind)
10180 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010181 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010182 continue;
10183 }
10184
10185 // OpenMP [2.9.3.4, Restrictions, p.2]
10186 // A list item that is private within a parallel region must not appear
10187 // in a firstprivate clause on a worksharing construct if any of the
10188 // worksharing regions arising from the worksharing construct ever bind
10189 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010190 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10191 // A list item that is private within a teams region must not appear in a
10192 // firstprivate clause on a distribute construct if any of the distribute
10193 // regions arising from the distribute construct ever bind to any of the
10194 // teams regions arising from the teams construct.
10195 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10196 // A list item that appears in a reduction clause of a teams construct
10197 // must not appear in a firstprivate clause on a distribute construct if
10198 // any of the distribute regions arising from the distribute construct
10199 // ever bind to any of the teams regions arising from the teams construct.
10200 if ((isOpenMPWorksharingDirective(CurrDir) ||
10201 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010202 !isOpenMPParallelDirective(CurrDir) &&
10203 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010204 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010205 if (DVar.CKind != OMPC_shared &&
10206 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010207 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010208 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010209 Diag(ELoc, diag::err_omp_required_access)
10210 << getOpenMPClauseName(OMPC_firstprivate)
10211 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010212 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010213 continue;
10214 }
10215 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010216 // OpenMP [2.9.3.4, Restrictions, p.3]
10217 // A list item that appears in a reduction clause of a parallel construct
10218 // must not appear in a firstprivate clause on a worksharing or task
10219 // construct if any of the worksharing or task regions arising from the
10220 // worksharing or task construct ever bind to any of the parallel regions
10221 // arising from the parallel construct.
10222 // OpenMP [2.9.3.4, Restrictions, p.4]
10223 // A list item that appears in a reduction clause in worksharing
10224 // construct must not appear in a firstprivate clause in a task construct
10225 // encountered during execution of any of the worksharing regions arising
10226 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010227 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010228 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010229 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10230 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010231 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010232 isOpenMPWorksharingDirective(K) ||
10233 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010234 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010235 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010236 if (DVar.CKind == OMPC_reduction &&
10237 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010238 isOpenMPWorksharingDirective(DVar.DKind) ||
10239 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010240 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10241 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010242 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010243 continue;
10244 }
10245 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010246
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010247 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10248 // A list item cannot appear in both a map clause and a data-sharing
10249 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010250 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010251 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010252 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010253 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010254 [&ConflictKind](
10255 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10256 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010257 ConflictKind = WhereFoundClauseKind;
10258 return true;
10259 })) {
10260 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010261 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010262 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010263 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010264 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010265 continue;
10266 }
10267 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010268 }
10269
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010270 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010271 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010272 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010273 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10274 << getOpenMPClauseName(OMPC_firstprivate) << Type
10275 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10276 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010277 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010278 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010279 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010280 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010281 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010282 continue;
10283 }
10284
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010285 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010286 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010287 buildVarDecl(*this, ELoc, Type, D->getName(),
10288 D->hasAttrs() ? &D->getAttrs() : nullptr,
10289 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010290 // Generate helper private variable and initialize it with the value of the
10291 // original variable. The address of the original variable is replaced by
10292 // the address of the new private variable in the CodeGen. This new variable
10293 // is not added to IdResolver, so the code in the OpenMP region uses
10294 // original variable for proper diagnostics and variable capturing.
10295 Expr *VDInitRefExpr = nullptr;
10296 // For arrays generate initializer for single element and replace it by the
10297 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010298 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010299 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010300 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010301 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010302 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010303 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010304 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10305 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010306 InitializedEntity Entity =
10307 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010308 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10309
10310 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10311 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10312 if (Result.isInvalid())
10313 VDPrivate->setInvalidDecl();
10314 else
10315 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010316 // Remove temp variable declaration.
10317 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010318 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010319 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10320 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010321 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10322 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010323 AddInitializerToDecl(VDPrivate,
10324 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010325 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010326 }
10327 if (VDPrivate->isInvalidDecl()) {
10328 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010329 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010330 diag::note_omp_task_predetermined_firstprivate_here);
10331 }
10332 continue;
10333 }
10334 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010335 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010336 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10337 RefExpr->getExprLoc());
10338 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010339 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010340 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010341 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010342 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010343 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010344 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010345 ExprCaptures.push_back(Ref->getDecl());
10346 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010347 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010348 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010349 Vars.push_back((VD || CurContext->isDependentContext())
10350 ? RefExpr->IgnoreParens()
10351 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010352 PrivateCopies.push_back(VDPrivateRefExpr);
10353 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010354 }
10355
Alexey Bataeved09d242014-05-28 05:53:51 +000010356 if (Vars.empty())
10357 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010358
10359 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010360 Vars, PrivateCopies, Inits,
10361 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010362}
10363
Alexander Musman1bb328c2014-06-04 13:06:39 +000010364OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10365 SourceLocation StartLoc,
10366 SourceLocation LParenLoc,
10367 SourceLocation EndLoc) {
10368 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010369 SmallVector<Expr *, 8> SrcExprs;
10370 SmallVector<Expr *, 8> DstExprs;
10371 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010372 SmallVector<Decl *, 4> ExprCaptures;
10373 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010374 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010375 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010376 SourceLocation ELoc;
10377 SourceRange ERange;
10378 Expr *SimpleRefExpr = RefExpr;
10379 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000010380 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010381 // It will be analyzed later.
10382 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010383 SrcExprs.push_back(nullptr);
10384 DstExprs.push_back(nullptr);
10385 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010386 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010387 ValueDecl *D = Res.first;
10388 if (!D)
10389 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010390
Alexey Bataev74caaf22016-02-20 04:09:36 +000010391 QualType Type = D->getType();
10392 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010393
10394 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10395 // A variable that appears in a lastprivate clause must not have an
10396 // incomplete type or a reference type.
10397 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010398 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010399 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010400 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010401
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010402 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10403 // A variable that is privatized must not have a const-qualified type
10404 // unless it is of class type with a mutable member. This restriction does
10405 // not apply to the firstprivate clause.
10406 //
10407 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10408 // A variable that appears in a lastprivate clause must not have a
10409 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010410 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010411 continue;
10412
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010413 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010414 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10415 // in a Construct]
10416 // Variables with the predetermined data-sharing attributes may not be
10417 // listed in data-sharing attributes clauses, except for the cases
10418 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010419 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10420 // A list item may appear in a firstprivate or lastprivate clause but not
10421 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010422 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010423 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010424 (isOpenMPDistributeDirective(CurrDir) ||
10425 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010426 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10427 Diag(ELoc, diag::err_omp_wrong_dsa)
10428 << getOpenMPClauseName(DVar.CKind)
10429 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010430 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010431 continue;
10432 }
10433
Alexey Bataevf29276e2014-06-18 04:14:57 +000010434 // OpenMP [2.14.3.5, Restrictions, p.2]
10435 // A list item that is private within a parallel region, or that appears in
10436 // the reduction clause of a parallel construct, must not appear in a
10437 // lastprivate clause on a worksharing construct if any of the corresponding
10438 // worksharing regions ever binds to any of the corresponding parallel
10439 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010440 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010441 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010442 !isOpenMPParallelDirective(CurrDir) &&
10443 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010444 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010445 if (DVar.CKind != OMPC_shared) {
10446 Diag(ELoc, diag::err_omp_required_access)
10447 << getOpenMPClauseName(OMPC_lastprivate)
10448 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010449 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010450 continue;
10451 }
10452 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010453
Alexander Musman1bb328c2014-06-04 13:06:39 +000010454 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010455 // A variable of class type (or array thereof) that appears in a
10456 // lastprivate clause requires an accessible, unambiguous default
10457 // constructor for the class type, unless the list item is also specified
10458 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010459 // A variable of class type (or array thereof) that appears in a
10460 // lastprivate clause requires an accessible, unambiguous copy assignment
10461 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010462 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010463 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10464 Type.getUnqualifiedType(), ".lastprivate.src",
10465 D->hasAttrs() ? &D->getAttrs() : nullptr);
10466 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010467 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010468 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010469 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010470 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010471 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010472 // For arrays generate assignment operation for single element and replace
10473 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010474 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10475 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010476 if (AssignmentOp.isInvalid())
10477 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010478 AssignmentOp =
10479 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010480 if (AssignmentOp.isInvalid())
10481 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010482
Alexey Bataev74caaf22016-02-20 04:09:36 +000010483 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010484 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010485 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010486 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010487 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010488 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010489 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010490 ExprCaptures.push_back(Ref->getDecl());
10491 }
10492 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010493 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010494 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010495 ExprResult RefRes = DefaultLvalueConversion(Ref);
10496 if (!RefRes.isUsable())
10497 continue;
10498 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010499 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10500 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010501 if (!PostUpdateRes.isUsable())
10502 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010503 ExprPostUpdates.push_back(
10504 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010505 }
10506 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010507 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010508 Vars.push_back((VD || CurContext->isDependentContext())
10509 ? RefExpr->IgnoreParens()
10510 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010511 SrcExprs.push_back(PseudoSrcExpr);
10512 DstExprs.push_back(PseudoDstExpr);
10513 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010514 }
10515
10516 if (Vars.empty())
10517 return nullptr;
10518
10519 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010520 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010521 buildPreInits(Context, ExprCaptures),
10522 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010523}
10524
Alexey Bataev758e55e2013-09-06 18:03:48 +000010525OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10526 SourceLocation StartLoc,
10527 SourceLocation LParenLoc,
10528 SourceLocation EndLoc) {
10529 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010530 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010531 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010532 SourceLocation ELoc;
10533 SourceRange ERange;
10534 Expr *SimpleRefExpr = RefExpr;
10535 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010536 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010537 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010538 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010539 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010540 ValueDecl *D = Res.first;
10541 if (!D)
10542 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010543
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010544 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010545 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10546 // in a Construct]
10547 // Variables with the predetermined data-sharing attributes may not be
10548 // listed in data-sharing attributes clauses, except for the cases
10549 // listed below. For these exceptions only, listing a predetermined
10550 // variable in a data-sharing attribute clause is allowed and overrides
10551 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010552 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010553 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10554 DVar.RefExpr) {
10555 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10556 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010557 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010558 continue;
10559 }
10560
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010561 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010562 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010563 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010564 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010565 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10566 ? RefExpr->IgnoreParens()
10567 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010568 }
10569
Alexey Bataeved09d242014-05-28 05:53:51 +000010570 if (Vars.empty())
10571 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010572
10573 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10574}
10575
Alexey Bataevc5e02582014-06-16 07:08:35 +000010576namespace {
10577class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10578 DSAStackTy *Stack;
10579
10580public:
10581 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010582 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10583 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010584 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10585 return false;
10586 if (DVar.CKind != OMPC_unknown)
10587 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010588 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010589 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010590 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010591 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010592 }
10593 return false;
10594 }
10595 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010596 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010597 if (Child && Visit(Child))
10598 return true;
10599 }
10600 return false;
10601 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010602 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010603};
Alexey Bataev23b69422014-06-18 07:08:49 +000010604} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010605
Alexey Bataev60da77e2016-02-29 05:54:20 +000010606namespace {
10607// Transform MemberExpression for specified FieldDecl of current class to
10608// DeclRefExpr to specified OMPCapturedExprDecl.
10609class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10610 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010611 ValueDecl *Field = nullptr;
10612 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010613
10614public:
10615 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10616 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10617
10618 ExprResult TransformMemberExpr(MemberExpr *E) {
10619 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10620 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010621 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010622 return CapturedExpr;
10623 }
10624 return BaseTransform::TransformMemberExpr(E);
10625 }
10626 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10627};
10628} // namespace
10629
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010630template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000010631static T filterLookupForUDReductionAndMapper(
10632 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010633 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010634 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010635 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010636 return Res;
10637 }
10638 }
10639 return T();
10640}
10641
Alexey Bataev43b90b72018-09-12 16:31:59 +000010642static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10643 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10644
10645 for (auto RD : D->redecls()) {
10646 // Don't bother with extra checks if we already know this one isn't visible.
10647 if (RD == D)
10648 continue;
10649
10650 auto ND = cast<NamedDecl>(RD);
10651 if (LookupResult::isVisible(SemaRef, ND))
10652 return ND;
10653 }
10654
10655 return nullptr;
10656}
10657
10658static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000010659argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000010660 SourceLocation Loc, QualType Ty,
10661 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10662 // Find all of the associated namespaces and classes based on the
10663 // arguments we have.
10664 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10665 Sema::AssociatedClassSet AssociatedClasses;
10666 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10667 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10668 AssociatedClasses);
10669
10670 // C++ [basic.lookup.argdep]p3:
10671 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10672 // and let Y be the lookup set produced by argument dependent
10673 // lookup (defined as follows). If X contains [...] then Y is
10674 // empty. Otherwise Y is the set of declarations found in the
10675 // namespaces associated with the argument types as described
10676 // below. The set of declarations found by the lookup of the name
10677 // is the union of X and Y.
10678 //
10679 // Here, we compute Y and add its members to the overloaded
10680 // candidate set.
10681 for (auto *NS : AssociatedNamespaces) {
10682 // When considering an associated namespace, the lookup is the
10683 // same as the lookup performed when the associated namespace is
10684 // used as a qualifier (3.4.3.2) except that:
10685 //
10686 // -- Any using-directives in the associated namespace are
10687 // ignored.
10688 //
10689 // -- Any namespace-scope friend functions declared in
10690 // associated classes are visible within their respective
10691 // namespaces even if they are not visible during an ordinary
10692 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000010693 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000010694 for (auto *D : R) {
10695 auto *Underlying = D;
10696 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10697 Underlying = USD->getTargetDecl();
10698
Michael Kruse4304e9d2019-02-19 16:38:20 +000010699 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
10700 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000010701 continue;
10702
10703 if (!SemaRef.isVisible(D)) {
10704 D = findAcceptableDecl(SemaRef, D);
10705 if (!D)
10706 continue;
10707 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10708 Underlying = USD->getTargetDecl();
10709 }
10710 Lookups.emplace_back();
10711 Lookups.back().addDecl(Underlying);
10712 }
10713 }
10714}
10715
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010716static ExprResult
10717buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
10718 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
10719 const DeclarationNameInfo &ReductionId, QualType Ty,
10720 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
10721 if (ReductionIdScopeSpec.isInvalid())
10722 return ExprError();
10723 SmallVector<UnresolvedSet<8>, 4> Lookups;
10724 if (S) {
10725 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10726 Lookup.suppressDiagnostics();
10727 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010728 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010729 do {
10730 S = S->getParent();
10731 } while (S && !S->isDeclScope(D));
10732 if (S)
10733 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000010734 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010735 Lookups.back().append(Lookup.begin(), Lookup.end());
10736 Lookup.clear();
10737 }
10738 } else if (auto *ULE =
10739 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
10740 Lookups.push_back(UnresolvedSet<8>());
10741 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010742 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010743 if (D == PrevD)
10744 Lookups.push_back(UnresolvedSet<8>());
10745 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10746 Lookups.back().addDecl(DRD);
10747 PrevD = D;
10748 }
10749 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000010750 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10751 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010752 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000010753 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010754 return !D->isInvalidDecl() &&
10755 (D->getType()->isDependentType() ||
10756 D->getType()->isInstantiationDependentType() ||
10757 D->getType()->containsUnexpandedParameterPack());
10758 })) {
10759 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000010760 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000010761 if (Set.empty())
10762 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010763 ResSet.append(Set.begin(), Set.end());
10764 // The last item marks the end of all declarations at the specified scope.
10765 ResSet.addDecl(Set[Set.size() - 1]);
10766 }
10767 return UnresolvedLookupExpr::Create(
10768 SemaRef.Context, /*NamingClass=*/nullptr,
10769 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10770 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10771 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000010772 // Lookup inside the classes.
10773 // C++ [over.match.oper]p3:
10774 // For a unary operator @ with an operand of a type whose
10775 // cv-unqualified version is T1, and for a binary operator @ with
10776 // a left operand of a type whose cv-unqualified version is T1 and
10777 // a right operand of a type whose cv-unqualified version is T2,
10778 // three sets of candidate functions, designated member
10779 // candidates, non-member candidates and built-in candidates, are
10780 // constructed as follows:
10781 // -- If T1 is a complete class type or a class currently being
10782 // defined, the set of member candidates is the result of the
10783 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
10784 // the set of member candidates is empty.
10785 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10786 Lookup.suppressDiagnostics();
10787 if (const auto *TyRec = Ty->getAs<RecordType>()) {
10788 // Complete the type if it can be completed.
10789 // If the type is neither complete nor being defined, bail out now.
10790 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
10791 TyRec->getDecl()->getDefinition()) {
10792 Lookup.clear();
10793 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
10794 if (Lookup.empty()) {
10795 Lookups.emplace_back();
10796 Lookups.back().append(Lookup.begin(), Lookup.end());
10797 }
10798 }
10799 }
10800 // Perform ADL.
10801 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Michael Kruse4304e9d2019-02-19 16:38:20 +000010802 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010803 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10804 if (!D->isInvalidDecl() &&
10805 SemaRef.Context.hasSameType(D->getType(), Ty))
10806 return D;
10807 return nullptr;
10808 }))
James Y Knightb92d2902019-02-05 16:05:50 +000010809 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
10810 VK_LValue, Loc);
Michael Kruse4304e9d2019-02-19 16:38:20 +000010811 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010812 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10813 if (!D->isInvalidDecl() &&
10814 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10815 !Ty.isMoreQualifiedThan(D->getType()))
10816 return D;
10817 return nullptr;
10818 })) {
10819 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10820 /*DetectVirtual=*/false);
10821 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10822 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10823 VD->getType().getUnqualifiedType()))) {
10824 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10825 /*DiagID=*/0) !=
10826 Sema::AR_inaccessible) {
10827 SemaRef.BuildBasePathArray(Paths, BasePath);
James Y Knightb92d2902019-02-05 16:05:50 +000010828 return SemaRef.BuildDeclRefExpr(
10829 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010830 }
10831 }
10832 }
10833 }
10834 if (ReductionIdScopeSpec.isSet()) {
10835 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10836 return ExprError();
10837 }
10838 return ExprEmpty();
10839}
10840
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010841namespace {
10842/// Data for the reduction-based clauses.
10843struct ReductionData {
10844 /// List of original reduction items.
10845 SmallVector<Expr *, 8> Vars;
10846 /// List of private copies of the reduction items.
10847 SmallVector<Expr *, 8> Privates;
10848 /// LHS expressions for the reduction_op expressions.
10849 SmallVector<Expr *, 8> LHSs;
10850 /// RHS expressions for the reduction_op expressions.
10851 SmallVector<Expr *, 8> RHSs;
10852 /// Reduction operation expression.
10853 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000010854 /// Taskgroup descriptors for the corresponding reduction items in
10855 /// in_reduction clauses.
10856 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010857 /// List of captures for clause.
10858 SmallVector<Decl *, 4> ExprCaptures;
10859 /// List of postupdate expressions.
10860 SmallVector<Expr *, 4> ExprPostUpdates;
10861 ReductionData() = delete;
10862 /// Reserves required memory for the reduction data.
10863 ReductionData(unsigned Size) {
10864 Vars.reserve(Size);
10865 Privates.reserve(Size);
10866 LHSs.reserve(Size);
10867 RHSs.reserve(Size);
10868 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000010869 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010870 ExprCaptures.reserve(Size);
10871 ExprPostUpdates.reserve(Size);
10872 }
10873 /// Stores reduction item and reduction operation only (required for dependent
10874 /// reduction item).
10875 void push(Expr *Item, Expr *ReductionOp) {
10876 Vars.emplace_back(Item);
10877 Privates.emplace_back(nullptr);
10878 LHSs.emplace_back(nullptr);
10879 RHSs.emplace_back(nullptr);
10880 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010881 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010882 }
10883 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000010884 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10885 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010886 Vars.emplace_back(Item);
10887 Privates.emplace_back(Private);
10888 LHSs.emplace_back(LHS);
10889 RHSs.emplace_back(RHS);
10890 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010891 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010892 }
10893};
10894} // namespace
10895
Alexey Bataeve3727102018-04-18 15:57:46 +000010896static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010897 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10898 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10899 const Expr *Length = OASE->getLength();
10900 if (Length == nullptr) {
10901 // For array sections of the form [1:] or [:], we would need to analyze
10902 // the lower bound...
10903 if (OASE->getColonLoc().isValid())
10904 return false;
10905
10906 // This is an array subscript which has implicit length 1!
10907 SingleElement = true;
10908 ArraySizes.push_back(llvm::APSInt::get(1));
10909 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000010910 Expr::EvalResult Result;
10911 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010912 return false;
10913
Fangrui Song407659a2018-11-30 23:41:18 +000010914 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010915 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10916 ArraySizes.push_back(ConstantLengthValue);
10917 }
10918
10919 // Get the base of this array section and walk up from there.
10920 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10921
10922 // We require length = 1 for all array sections except the right-most to
10923 // guarantee that the memory region is contiguous and has no holes in it.
10924 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10925 Length = TempOASE->getLength();
10926 if (Length == nullptr) {
10927 // For array sections of the form [1:] or [:], we would need to analyze
10928 // the lower bound...
10929 if (OASE->getColonLoc().isValid())
10930 return false;
10931
10932 // This is an array subscript which has implicit length 1!
10933 ArraySizes.push_back(llvm::APSInt::get(1));
10934 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000010935 Expr::EvalResult Result;
10936 if (!Length->EvaluateAsInt(Result, Context))
10937 return false;
10938
10939 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
10940 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010941 return false;
10942
10943 ArraySizes.push_back(ConstantLengthValue);
10944 }
10945 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10946 }
10947
10948 // If we have a single element, we don't need to add the implicit lengths.
10949 if (!SingleElement) {
10950 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10951 // Has implicit length 1!
10952 ArraySizes.push_back(llvm::APSInt::get(1));
10953 Base = TempASE->getBase()->IgnoreParenImpCasts();
10954 }
10955 }
10956
10957 // This array section can be privatized as a single value or as a constant
10958 // sized array.
10959 return true;
10960}
10961
Alexey Bataeve3727102018-04-18 15:57:46 +000010962static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010963 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10964 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10965 SourceLocation ColonLoc, SourceLocation EndLoc,
10966 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010967 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010968 DeclarationName DN = ReductionId.getName();
10969 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010970 BinaryOperatorKind BOK = BO_Comma;
10971
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010972 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010973 // OpenMP [2.14.3.6, reduction clause]
10974 // C
10975 // reduction-identifier is either an identifier or one of the following
10976 // operators: +, -, *, &, |, ^, && and ||
10977 // C++
10978 // reduction-identifier is either an id-expression or one of the following
10979 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010980 switch (OOK) {
10981 case OO_Plus:
10982 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010983 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010984 break;
10985 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010986 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010987 break;
10988 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010989 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010990 break;
10991 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010992 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010993 break;
10994 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010995 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010996 break;
10997 case OO_AmpAmp:
10998 BOK = BO_LAnd;
10999 break;
11000 case OO_PipePipe:
11001 BOK = BO_LOr;
11002 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011003 case OO_New:
11004 case OO_Delete:
11005 case OO_Array_New:
11006 case OO_Array_Delete:
11007 case OO_Slash:
11008 case OO_Percent:
11009 case OO_Tilde:
11010 case OO_Exclaim:
11011 case OO_Equal:
11012 case OO_Less:
11013 case OO_Greater:
11014 case OO_LessEqual:
11015 case OO_GreaterEqual:
11016 case OO_PlusEqual:
11017 case OO_MinusEqual:
11018 case OO_StarEqual:
11019 case OO_SlashEqual:
11020 case OO_PercentEqual:
11021 case OO_CaretEqual:
11022 case OO_AmpEqual:
11023 case OO_PipeEqual:
11024 case OO_LessLess:
11025 case OO_GreaterGreater:
11026 case OO_LessLessEqual:
11027 case OO_GreaterGreaterEqual:
11028 case OO_EqualEqual:
11029 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011030 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011031 case OO_PlusPlus:
11032 case OO_MinusMinus:
11033 case OO_Comma:
11034 case OO_ArrowStar:
11035 case OO_Arrow:
11036 case OO_Call:
11037 case OO_Subscript:
11038 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011039 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011040 case NUM_OVERLOADED_OPERATORS:
11041 llvm_unreachable("Unexpected reduction identifier");
11042 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011043 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011044 if (II->isStr("max"))
11045 BOK = BO_GT;
11046 else if (II->isStr("min"))
11047 BOK = BO_LT;
11048 }
11049 break;
11050 }
11051 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011052 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011053 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011054 else
11055 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011056 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011057
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011058 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11059 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011060 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011061 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011062 // OpenMP [2.1, C/C++]
11063 // A list item is a variable or array section, subject to the restrictions
11064 // specified in Section 2.4 on page 42 and in each of the sections
11065 // describing clauses and directives for which a list appears.
11066 // OpenMP [2.14.3.3, Restrictions, p.1]
11067 // A variable that is part of another variable (as an array or
11068 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011069 if (!FirstIter && IR != ER)
11070 ++IR;
11071 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011072 SourceLocation ELoc;
11073 SourceRange ERange;
11074 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011075 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011076 /*AllowArraySection=*/true);
11077 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011078 // Try to find 'declare reduction' corresponding construct before using
11079 // builtin/overloaded operators.
11080 QualType Type = Context.DependentTy;
11081 CXXCastPath BasePath;
11082 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011083 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011084 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011085 Expr *ReductionOp = nullptr;
11086 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011087 (DeclareReductionRef.isUnset() ||
11088 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011089 ReductionOp = DeclareReductionRef.get();
11090 // It will be analyzed later.
11091 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011092 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011093 ValueDecl *D = Res.first;
11094 if (!D)
11095 continue;
11096
Alexey Bataev88202be2017-07-27 13:20:36 +000011097 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011098 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011099 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11100 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011101 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011102 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011103 } else if (OASE) {
11104 QualType BaseType =
11105 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11106 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011107 Type = ATy->getElementType();
11108 else
11109 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011110 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011111 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011112 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011113 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011114 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011115
Alexey Bataevc5e02582014-06-16 07:08:35 +000011116 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11117 // A variable that appears in a private clause must not have an incomplete
11118 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011119 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011120 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011121 continue;
11122 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011123 // A list item that appears in a reduction clause must not be
11124 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011125 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11126 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011127 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011128
11129 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011130 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11131 // If a list-item is a reference type then it must bind to the same object
11132 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011133 if (!ASE && !OASE) {
11134 if (VD) {
11135 VarDecl *VDDef = VD->getDefinition();
11136 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11137 DSARefChecker Check(Stack);
11138 if (Check.Visit(VDDef->getInit())) {
11139 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11140 << getOpenMPClauseName(ClauseKind) << ERange;
11141 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11142 continue;
11143 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011144 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011145 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011146
Alexey Bataevbc529672018-09-28 19:33:14 +000011147 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11148 // in a Construct]
11149 // Variables with the predetermined data-sharing attributes may not be
11150 // listed in data-sharing attributes clauses, except for the cases
11151 // listed below. For these exceptions only, listing a predetermined
11152 // variable in a data-sharing attribute clause is allowed and overrides
11153 // the variable's predetermined data-sharing attributes.
11154 // OpenMP [2.14.3.6, Restrictions, p.3]
11155 // Any number of reduction clauses can be specified on the directive,
11156 // but a list item can appear only once in the reduction clauses for that
11157 // directive.
11158 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11159 if (DVar.CKind == OMPC_reduction) {
11160 S.Diag(ELoc, diag::err_omp_once_referenced)
11161 << getOpenMPClauseName(ClauseKind);
11162 if (DVar.RefExpr)
11163 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11164 continue;
11165 }
11166 if (DVar.CKind != OMPC_unknown) {
11167 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11168 << getOpenMPClauseName(DVar.CKind)
11169 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011170 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011171 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011172 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011173
11174 // OpenMP [2.14.3.6, Restrictions, p.1]
11175 // A list item that appears in a reduction clause of a worksharing
11176 // construct must be shared in the parallel regions to which any of the
11177 // worksharing regions arising from the worksharing construct bind.
11178 if (isOpenMPWorksharingDirective(CurrDir) &&
11179 !isOpenMPParallelDirective(CurrDir) &&
11180 !isOpenMPTeamsDirective(CurrDir)) {
11181 DVar = Stack->getImplicitDSA(D, true);
11182 if (DVar.CKind != OMPC_shared) {
11183 S.Diag(ELoc, diag::err_omp_required_access)
11184 << getOpenMPClauseName(OMPC_reduction)
11185 << getOpenMPClauseName(OMPC_shared);
11186 reportOriginalDsa(S, Stack, D, DVar);
11187 continue;
11188 }
11189 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011190 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011191
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011192 // Try to find 'declare reduction' corresponding construct before using
11193 // builtin/overloaded operators.
11194 CXXCastPath BasePath;
11195 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011196 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011197 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11198 if (DeclareReductionRef.isInvalid())
11199 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011200 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011201 (DeclareReductionRef.isUnset() ||
11202 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011203 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011204 continue;
11205 }
11206 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11207 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011208 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011209 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011210 << Type << ReductionIdRange;
11211 continue;
11212 }
11213
11214 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11215 // The type of a list item that appears in a reduction clause must be valid
11216 // for the reduction-identifier. For a max or min reduction in C, the type
11217 // of the list item must be an allowed arithmetic data type: char, int,
11218 // float, double, or _Bool, possibly modified with long, short, signed, or
11219 // unsigned. For a max or min reduction in C++, the type of the list item
11220 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11221 // double, or bool, possibly modified with long, short, signed, or unsigned.
11222 if (DeclareReductionRef.isUnset()) {
11223 if ((BOK == BO_GT || BOK == BO_LT) &&
11224 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011225 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11226 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011227 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011228 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011229 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11230 VarDecl::DeclarationOnly;
11231 S.Diag(D->getLocation(),
11232 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011233 << D;
11234 }
11235 continue;
11236 }
11237 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011238 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011239 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11240 << getOpenMPClauseName(ClauseKind);
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 }
11251
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011252 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011253 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11254 D->hasAttrs() ? &D->getAttrs() : nullptr);
11255 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11256 D->hasAttrs() ? &D->getAttrs() : nullptr);
11257 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011258
11259 // Try if we can determine constant lengths for all array sections and avoid
11260 // the VLA.
11261 bool ConstantLengthOASE = false;
11262 if (OASE) {
11263 bool SingleElement;
11264 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011265 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011266 Context, OASE, SingleElement, ArraySizes);
11267
11268 // If we don't have a single element, we must emit a constant array type.
11269 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011270 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011271 PrivateTy = Context.getConstantArrayType(
11272 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011273 }
11274 }
11275
11276 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011277 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011278 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011279 if (!Context.getTargetInfo().isVLASupported() &&
11280 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11281 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11282 S.Diag(ELoc, diag::note_vla_unsupported);
11283 continue;
11284 }
David Majnemer9d168222016-08-05 17:44:54 +000011285 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011286 // Create pseudo array type for private copy. The size for this array will
11287 // be generated during codegen.
11288 // For array subscripts or single variables Private Ty is the same as Type
11289 // (type of the variable or single array element).
11290 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011291 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011292 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011293 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011294 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011295 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011296 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011297 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011298 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011299 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011300 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11301 D->hasAttrs() ? &D->getAttrs() : nullptr,
11302 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011303 // Add initializer for private variable.
11304 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011305 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11306 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011307 if (DeclareReductionRef.isUsable()) {
11308 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11309 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11310 if (DRD->getInitializer()) {
11311 Init = DRDRef;
11312 RHSVD->setInit(DRDRef);
11313 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011314 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011315 } else {
11316 switch (BOK) {
11317 case BO_Add:
11318 case BO_Xor:
11319 case BO_Or:
11320 case BO_LOr:
11321 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11322 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011323 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011324 break;
11325 case BO_Mul:
11326 case BO_LAnd:
11327 if (Type->isScalarType() || Type->isAnyComplexType()) {
11328 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011329 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011330 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011331 break;
11332 case BO_And: {
11333 // '&' reduction op - initializer is '~0'.
11334 QualType OrigType = Type;
11335 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11336 Type = ComplexTy->getElementType();
11337 if (Type->isRealFloatingType()) {
11338 llvm::APFloat InitValue =
11339 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11340 /*isIEEE=*/true);
11341 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11342 Type, ELoc);
11343 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011344 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011345 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11346 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11347 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11348 }
11349 if (Init && OrigType->isAnyComplexType()) {
11350 // Init = 0xFFFF + 0xFFFFi;
11351 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011352 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011353 }
11354 Type = OrigType;
11355 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011356 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011357 case BO_LT:
11358 case BO_GT: {
11359 // 'min' reduction op - initializer is 'Largest representable number in
11360 // the reduction list item type'.
11361 // 'max' reduction op - initializer is 'Least representable number in
11362 // the reduction list item type'.
11363 if (Type->isIntegerType() || Type->isPointerType()) {
11364 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011365 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011366 QualType IntTy =
11367 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11368 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011369 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11370 : llvm::APInt::getMinValue(Size)
11371 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11372 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011373 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11374 if (Type->isPointerType()) {
11375 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011376 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011377 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011378 if (CastExpr.isInvalid())
11379 continue;
11380 Init = CastExpr.get();
11381 }
11382 } else if (Type->isRealFloatingType()) {
11383 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11384 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11385 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11386 Type, ELoc);
11387 }
11388 break;
11389 }
11390 case BO_PtrMemD:
11391 case BO_PtrMemI:
11392 case BO_MulAssign:
11393 case BO_Div:
11394 case BO_Rem:
11395 case BO_Sub:
11396 case BO_Shl:
11397 case BO_Shr:
11398 case BO_LE:
11399 case BO_GE:
11400 case BO_EQ:
11401 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011402 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011403 case BO_AndAssign:
11404 case BO_XorAssign:
11405 case BO_OrAssign:
11406 case BO_Assign:
11407 case BO_AddAssign:
11408 case BO_SubAssign:
11409 case BO_DivAssign:
11410 case BO_RemAssign:
11411 case BO_ShlAssign:
11412 case BO_ShrAssign:
11413 case BO_Comma:
11414 llvm_unreachable("Unexpected reduction operation");
11415 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011416 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011417 if (Init && DeclareReductionRef.isUnset())
11418 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11419 else if (!Init)
11420 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011421 if (RHSVD->isInvalidDecl())
11422 continue;
11423 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011424 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11425 << Type << ReductionIdRange;
11426 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11427 VarDecl::DeclarationOnly;
11428 S.Diag(D->getLocation(),
11429 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011430 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011431 continue;
11432 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011433 // Store initializer for single element in private copy. Will be used during
11434 // codegen.
11435 PrivateVD->setInit(RHSVD->getInit());
11436 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011437 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011438 ExprResult ReductionOp;
11439 if (DeclareReductionRef.isUsable()) {
11440 QualType RedTy = DeclareReductionRef.get()->getType();
11441 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011442 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11443 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011444 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011445 LHS = S.DefaultLvalueConversion(LHS.get());
11446 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011447 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11448 CK_UncheckedDerivedToBase, LHS.get(),
11449 &BasePath, LHS.get()->getValueKind());
11450 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11451 CK_UncheckedDerivedToBase, RHS.get(),
11452 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011453 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011454 FunctionProtoType::ExtProtoInfo EPI;
11455 QualType Params[] = {PtrRedTy, PtrRedTy};
11456 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11457 auto *OVE = new (Context) OpaqueValueExpr(
11458 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011459 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011460 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011461 ReductionOp =
11462 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011463 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011464 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011465 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011466 if (ReductionOp.isUsable()) {
11467 if (BOK != BO_LT && BOK != BO_GT) {
11468 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011469 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011470 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011471 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011472 auto *ConditionalOp = new (Context)
11473 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11474 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011475 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011476 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011477 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011478 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011479 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011480 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11481 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011482 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011483 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011484 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011485 }
11486
Alexey Bataevfa312f32017-07-21 18:48:21 +000011487 // OpenMP [2.15.4.6, Restrictions, p.2]
11488 // A list item that appears in an in_reduction clause of a task construct
11489 // must appear in a task_reduction clause of a construct associated with a
11490 // taskgroup region that includes the participating task in its taskgroup
11491 // set. The construct associated with the innermost region that meets this
11492 // condition must specify the same reduction-identifier as the in_reduction
11493 // clause.
11494 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011495 SourceRange ParentSR;
11496 BinaryOperatorKind ParentBOK;
11497 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011498 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011499 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011500 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11501 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011502 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011503 Stack->getTopMostTaskgroupReductionData(
11504 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011505 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11506 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11507 if (!IsParentBOK && !IsParentReductionOp) {
11508 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11509 continue;
11510 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011511 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11512 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11513 IsParentReductionOp) {
11514 bool EmitError = true;
11515 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11516 llvm::FoldingSetNodeID RedId, ParentRedId;
11517 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11518 DeclareReductionRef.get()->Profile(RedId, Context,
11519 /*Canonical=*/true);
11520 EmitError = RedId != ParentRedId;
11521 }
11522 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011523 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011524 diag::err_omp_reduction_identifier_mismatch)
11525 << ReductionIdRange << RefExpr->getSourceRange();
11526 S.Diag(ParentSR.getBegin(),
11527 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011528 << ParentSR
11529 << (IsParentBOK ? ParentBOKDSA.RefExpr
11530 : ParentReductionOpDSA.RefExpr)
11531 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011532 continue;
11533 }
11534 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011535 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11536 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011537 }
11538
Alexey Bataev60da77e2016-02-29 05:54:20 +000011539 DeclRefExpr *Ref = nullptr;
11540 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011541 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011542 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011543 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011544 VarsExpr =
11545 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11546 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011547 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011548 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011549 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011550 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011551 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011552 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011553 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011554 if (!RefRes.isUsable())
11555 continue;
11556 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011557 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11558 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011559 if (!PostUpdateRes.isUsable())
11560 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011561 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11562 Stack->getCurrentDirective() == OMPD_taskgroup) {
11563 S.Diag(RefExpr->getExprLoc(),
11564 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011565 << RefExpr->getSourceRange();
11566 continue;
11567 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011568 RD.ExprPostUpdates.emplace_back(
11569 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011570 }
11571 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011572 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011573 // All reduction items are still marked as reduction (to do not increase
11574 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011575 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011576 if (CurrDir == OMPD_taskgroup) {
11577 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011578 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11579 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011580 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011581 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011582 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011583 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11584 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011585 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011586 return RD.Vars.empty();
11587}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011588
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011589OMPClause *Sema::ActOnOpenMPReductionClause(
11590 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11591 SourceLocation ColonLoc, SourceLocation EndLoc,
11592 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11593 ArrayRef<Expr *> UnresolvedReductions) {
11594 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011595 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011596 StartLoc, LParenLoc, ColonLoc, EndLoc,
11597 ReductionIdScopeSpec, ReductionId,
11598 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011599 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011600
Alexey Bataevc5e02582014-06-16 07:08:35 +000011601 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011602 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11603 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11604 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11605 buildPreInits(Context, RD.ExprCaptures),
11606 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011607}
11608
Alexey Bataev169d96a2017-07-18 20:17:46 +000011609OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11610 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11611 SourceLocation ColonLoc, SourceLocation EndLoc,
11612 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11613 ArrayRef<Expr *> UnresolvedReductions) {
11614 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011615 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11616 StartLoc, LParenLoc, ColonLoc, EndLoc,
11617 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011618 UnresolvedReductions, RD))
11619 return nullptr;
11620
11621 return OMPTaskReductionClause::Create(
11622 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11623 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11624 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11625 buildPreInits(Context, RD.ExprCaptures),
11626 buildPostUpdate(*this, RD.ExprPostUpdates));
11627}
11628
Alexey Bataevfa312f32017-07-21 18:48:21 +000011629OMPClause *Sema::ActOnOpenMPInReductionClause(
11630 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11631 SourceLocation ColonLoc, SourceLocation EndLoc,
11632 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11633 ArrayRef<Expr *> UnresolvedReductions) {
11634 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011635 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011636 StartLoc, LParenLoc, ColonLoc, EndLoc,
11637 ReductionIdScopeSpec, ReductionId,
11638 UnresolvedReductions, RD))
11639 return nullptr;
11640
11641 return OMPInReductionClause::Create(
11642 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11643 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011644 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011645 buildPreInits(Context, RD.ExprCaptures),
11646 buildPostUpdate(*this, RD.ExprPostUpdates));
11647}
11648
Alexey Bataevecba70f2016-04-12 11:02:11 +000011649bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11650 SourceLocation LinLoc) {
11651 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11652 LinKind == OMPC_LINEAR_unknown) {
11653 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11654 return true;
11655 }
11656 return false;
11657}
11658
Alexey Bataeve3727102018-04-18 15:57:46 +000011659bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000011660 OpenMPLinearClauseKind LinKind,
11661 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011662 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000011663 // A variable must not have an incomplete type or a reference type.
11664 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11665 return true;
11666 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11667 !Type->isReferenceType()) {
11668 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11669 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11670 return true;
11671 }
11672 Type = Type.getNonReferenceType();
11673
Joel E. Dennybae586f2019-01-04 22:12:13 +000011674 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11675 // A variable that is privatized must not have a const-qualified type
11676 // unless it is of class type with a mutable member. This restriction does
11677 // not apply to the firstprivate clause.
11678 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000011679 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011680
11681 // A list item must be of integral or pointer type.
11682 Type = Type.getUnqualifiedType().getCanonicalType();
11683 const auto *Ty = Type.getTypePtrOrNull();
11684 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11685 !Ty->isPointerType())) {
11686 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
11687 if (D) {
11688 bool IsDecl =
11689 !VD ||
11690 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11691 Diag(D->getLocation(),
11692 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11693 << D;
11694 }
11695 return true;
11696 }
11697 return false;
11698}
11699
Alexey Bataev182227b2015-08-20 10:54:39 +000011700OMPClause *Sema::ActOnOpenMPLinearClause(
11701 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
11702 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
11703 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011704 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011705 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000011706 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000011707 SmallVector<Decl *, 4> ExprCaptures;
11708 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011709 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000011710 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000011711 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011712 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011713 SourceLocation ELoc;
11714 SourceRange ERange;
11715 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011716 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011717 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011718 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011719 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011720 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000011721 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000011722 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011723 ValueDecl *D = Res.first;
11724 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000011725 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000011726
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011727 QualType Type = D->getType();
11728 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000011729
11730 // OpenMP [2.14.3.7, linear clause]
11731 // A list-item cannot appear in more than one linear clause.
11732 // A list-item that appears in a linear clause cannot appear in any
11733 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000011734 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000011735 if (DVar.RefExpr) {
11736 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11737 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000011738 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000011739 continue;
11740 }
11741
Alexey Bataevecba70f2016-04-12 11:02:11 +000011742 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000011743 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011744 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000011745
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011746 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000011747 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011748 buildVarDecl(*this, ELoc, Type, D->getName(),
11749 D->hasAttrs() ? &D->getAttrs() : nullptr,
11750 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011751 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011752 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011753 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011754 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011755 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011756 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000011757 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011758 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000011759 ExprCaptures.push_back(Ref->getDecl());
11760 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11761 ExprResult RefRes = DefaultLvalueConversion(Ref);
11762 if (!RefRes.isUsable())
11763 continue;
11764 ExprResult PostUpdateRes =
11765 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11766 SimpleRefExpr, RefRes.get());
11767 if (!PostUpdateRes.isUsable())
11768 continue;
11769 ExprPostUpdates.push_back(
11770 IgnoredValueConversions(PostUpdateRes.get()).get());
11771 }
11772 }
11773 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011774 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011775 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011776 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011777 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011778 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011779 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011780 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011781
11782 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011783 Vars.push_back((VD || CurContext->isDependentContext())
11784 ? RefExpr->IgnoreParens()
11785 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011786 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000011787 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000011788 }
11789
11790 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011791 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011792
11793 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000011794 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011795 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11796 !Step->isInstantiationDependent() &&
11797 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011798 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011799 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000011800 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011801 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011802 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000011803
Alexander Musman3276a272015-03-21 10:12:56 +000011804 // Build var to save the step value.
11805 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011806 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000011807 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011808 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011809 ExprResult CalcStep =
11810 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011811 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000011812
Alexander Musman8dba6642014-04-22 13:09:42 +000011813 // Warn about zero linear step (it would be probably better specified as
11814 // making corresponding variables 'const').
11815 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000011816 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11817 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000011818 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11819 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000011820 if (!IsConstant && CalcStep.isUsable()) {
11821 // Calculate the step beforehand instead of doing this on each iteration.
11822 // (This is not used if the number of iterations may be kfold-ed).
11823 CalcStepExpr = CalcStep.get();
11824 }
Alexander Musman8dba6642014-04-22 13:09:42 +000011825 }
11826
Alexey Bataev182227b2015-08-20 10:54:39 +000011827 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11828 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011829 StepExpr, CalcStepExpr,
11830 buildPreInits(Context, ExprCaptures),
11831 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000011832}
11833
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011834static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11835 Expr *NumIterations, Sema &SemaRef,
11836 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000011837 // Walk the vars and build update/final expressions for the CodeGen.
11838 SmallVector<Expr *, 8> Updates;
11839 SmallVector<Expr *, 8> Finals;
11840 Expr *Step = Clause.getStep();
11841 Expr *CalcStep = Clause.getCalcStep();
11842 // OpenMP [2.14.3.7, linear clause]
11843 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000011844 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000011845 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011846 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000011847 Step = cast<BinaryOperator>(CalcStep)->getLHS();
11848 bool HasErrors = false;
11849 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011850 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000011851 OpenMPLinearClauseKind LinKind = Clause.getModifier();
11852 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011853 SourceLocation ELoc;
11854 SourceRange ERange;
11855 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011856 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011857 ValueDecl *D = Res.first;
11858 if (Res.second || !D) {
11859 Updates.push_back(nullptr);
11860 Finals.push_back(nullptr);
11861 HasErrors = true;
11862 continue;
11863 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011864 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000011865 // OpenMP [2.15.11, distribute simd Construct]
11866 // A list item may not appear in a linear clause, unless it is the loop
11867 // iteration variable.
11868 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11869 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11870 SemaRef.Diag(ELoc,
11871 diag::err_omp_linear_distribute_var_non_loop_iteration);
11872 Updates.push_back(nullptr);
11873 Finals.push_back(nullptr);
11874 HasErrors = true;
11875 continue;
11876 }
Alexander Musman3276a272015-03-21 10:12:56 +000011877 Expr *InitExpr = *CurInit;
11878
11879 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000011880 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011881 Expr *CapturedRef;
11882 if (LinKind == OMPC_LINEAR_uval)
11883 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11884 else
11885 CapturedRef =
11886 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11887 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11888 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011889
11890 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011891 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000011892 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011893 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000011894 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011895 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011896 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011897 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011898 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011899 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000011900
11901 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011902 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000011903 if (!Info.first)
11904 Final =
11905 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11906 InitExpr, NumIterations, Step, /*Subtract=*/false);
11907 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011908 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011909 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011910 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011911
Alexander Musman3276a272015-03-21 10:12:56 +000011912 if (!Update.isUsable() || !Final.isUsable()) {
11913 Updates.push_back(nullptr);
11914 Finals.push_back(nullptr);
11915 HasErrors = true;
11916 } else {
11917 Updates.push_back(Update.get());
11918 Finals.push_back(Final.get());
11919 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011920 ++CurInit;
11921 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011922 }
11923 Clause.setUpdates(Updates);
11924 Clause.setFinals(Finals);
11925 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011926}
11927
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011928OMPClause *Sema::ActOnOpenMPAlignedClause(
11929 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11930 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011931 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000011932 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011933 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11934 SourceLocation ELoc;
11935 SourceRange ERange;
11936 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011937 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000011938 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011939 // It will be analyzed later.
11940 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011941 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011942 ValueDecl *D = Res.first;
11943 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011944 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011945
Alexey Bataev1efd1662016-03-29 10:59:56 +000011946 QualType QType = D->getType();
11947 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011948
11949 // OpenMP [2.8.1, simd construct, Restrictions]
11950 // The type of list items appearing in the aligned clause must be
11951 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011952 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011953 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011954 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011955 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011956 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011957 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011958 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011959 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011960 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011961 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011962 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011963 continue;
11964 }
11965
11966 // OpenMP [2.8.1, simd construct, Restrictions]
11967 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000011968 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011969 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011970 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11971 << getOpenMPClauseName(OMPC_aligned);
11972 continue;
11973 }
11974
Alexey Bataev1efd1662016-03-29 10:59:56 +000011975 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011976 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000011977 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11978 Vars.push_back(DefaultFunctionArrayConversion(
11979 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11980 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011981 }
11982
11983 // OpenMP [2.8.1, simd construct, Description]
11984 // The parameter of the aligned clause, alignment, must be a constant
11985 // positive integer expression.
11986 // If no optional parameter is specified, implementation-defined default
11987 // alignments for SIMD instructions on the target platforms are assumed.
11988 if (Alignment != nullptr) {
11989 ExprResult AlignResult =
11990 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11991 if (AlignResult.isInvalid())
11992 return nullptr;
11993 Alignment = AlignResult.get();
11994 }
11995 if (Vars.empty())
11996 return nullptr;
11997
11998 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11999 EndLoc, Vars, Alignment);
12000}
12001
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012002OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12003 SourceLocation StartLoc,
12004 SourceLocation LParenLoc,
12005 SourceLocation EndLoc) {
12006 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012007 SmallVector<Expr *, 8> SrcExprs;
12008 SmallVector<Expr *, 8> DstExprs;
12009 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012010 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012011 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12012 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012013 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012014 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012015 SrcExprs.push_back(nullptr);
12016 DstExprs.push_back(nullptr);
12017 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012018 continue;
12019 }
12020
Alexey Bataeved09d242014-05-28 05:53:51 +000012021 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012022 // OpenMP [2.1, C/C++]
12023 // A list item is a variable name.
12024 // OpenMP [2.14.4.1, Restrictions, p.1]
12025 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012026 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012027 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012028 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12029 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012030 continue;
12031 }
12032
12033 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012034 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012035
12036 QualType Type = VD->getType();
12037 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12038 // It will be analyzed later.
12039 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012040 SrcExprs.push_back(nullptr);
12041 DstExprs.push_back(nullptr);
12042 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012043 continue;
12044 }
12045
12046 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12047 // A list item that appears in a copyin clause must be threadprivate.
12048 if (!DSAStack->isThreadPrivate(VD)) {
12049 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012050 << getOpenMPClauseName(OMPC_copyin)
12051 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012052 continue;
12053 }
12054
12055 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12056 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012057 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012058 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012059 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12060 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012061 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012062 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012063 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012064 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012065 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012066 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012067 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012068 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012069 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012070 // For arrays generate assignment operation for single element and replace
12071 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012072 ExprResult AssignmentOp =
12073 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12074 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012075 if (AssignmentOp.isInvalid())
12076 continue;
12077 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012078 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012079 if (AssignmentOp.isInvalid())
12080 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012081
12082 DSAStack->addDSA(VD, DE, OMPC_copyin);
12083 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012084 SrcExprs.push_back(PseudoSrcExpr);
12085 DstExprs.push_back(PseudoDstExpr);
12086 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012087 }
12088
Alexey Bataeved09d242014-05-28 05:53:51 +000012089 if (Vars.empty())
12090 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012091
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012092 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12093 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012094}
12095
Alexey Bataevbae9a792014-06-27 10:37:06 +000012096OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12097 SourceLocation StartLoc,
12098 SourceLocation LParenLoc,
12099 SourceLocation EndLoc) {
12100 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012101 SmallVector<Expr *, 8> SrcExprs;
12102 SmallVector<Expr *, 8> DstExprs;
12103 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012104 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012105 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12106 SourceLocation ELoc;
12107 SourceRange ERange;
12108 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012109 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012110 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012111 // It will be analyzed later.
12112 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012113 SrcExprs.push_back(nullptr);
12114 DstExprs.push_back(nullptr);
12115 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012116 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012117 ValueDecl *D = Res.first;
12118 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012119 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012120
Alexey Bataeve122da12016-03-17 10:50:17 +000012121 QualType Type = D->getType();
12122 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012123
12124 // OpenMP [2.14.4.2, Restrictions, p.2]
12125 // A list item that appears in a copyprivate clause may not appear in a
12126 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012127 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012128 DSAStackTy::DSAVarData DVar =
12129 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012130 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12131 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012132 Diag(ELoc, diag::err_omp_wrong_dsa)
12133 << getOpenMPClauseName(DVar.CKind)
12134 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012135 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012136 continue;
12137 }
12138
12139 // OpenMP [2.11.4.2, Restrictions, p.1]
12140 // All list items that appear in a copyprivate clause must be either
12141 // threadprivate or private in the enclosing context.
12142 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012143 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012144 if (DVar.CKind == OMPC_shared) {
12145 Diag(ELoc, diag::err_omp_required_access)
12146 << getOpenMPClauseName(OMPC_copyprivate)
12147 << "threadprivate or private in the enclosing context";
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 }
12153
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012154 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012155 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012156 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012157 << getOpenMPClauseName(OMPC_copyprivate) << Type
12158 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012159 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012160 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012161 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012162 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012163 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012164 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012165 continue;
12166 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012167
Alexey Bataevbae9a792014-06-27 10:37:06 +000012168 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12169 // A variable of class type (or array thereof) that appears in a
12170 // copyin clause requires an accessible, unambiguous copy assignment
12171 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012172 Type = Context.getBaseElementType(Type.getNonReferenceType())
12173 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012174 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012175 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012176 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012177 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12178 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012179 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012180 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012181 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12182 ExprResult AssignmentOp = BuildBinOp(
12183 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012184 if (AssignmentOp.isInvalid())
12185 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012186 AssignmentOp =
12187 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012188 if (AssignmentOp.isInvalid())
12189 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012190
12191 // No need to mark vars as copyprivate, they are already threadprivate or
12192 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012193 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012194 Vars.push_back(
12195 VD ? RefExpr->IgnoreParens()
12196 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012197 SrcExprs.push_back(PseudoSrcExpr);
12198 DstExprs.push_back(PseudoDstExpr);
12199 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012200 }
12201
12202 if (Vars.empty())
12203 return nullptr;
12204
Alexey Bataeva63048e2015-03-23 06:18:07 +000012205 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12206 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012207}
12208
Alexey Bataev6125da92014-07-21 11:26:11 +000012209OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12210 SourceLocation StartLoc,
12211 SourceLocation LParenLoc,
12212 SourceLocation EndLoc) {
12213 if (VarList.empty())
12214 return nullptr;
12215
12216 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12217}
Alexey Bataevdea47612014-07-23 07:46:59 +000012218
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012219OMPClause *
12220Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12221 SourceLocation DepLoc, SourceLocation ColonLoc,
12222 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12223 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012224 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012225 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012226 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012227 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012228 return nullptr;
12229 }
12230 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012231 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12232 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012233 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012234 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012235 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12236 /*Last=*/OMPC_DEPEND_unknown, Except)
12237 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012238 return nullptr;
12239 }
12240 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012241 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012242 llvm::APSInt DepCounter(/*BitWidth=*/32);
12243 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012244 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12245 if (const Expr *OrderedCountExpr =
12246 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012247 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12248 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012249 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012250 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012251 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012252 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12253 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12254 // It will be analyzed later.
12255 Vars.push_back(RefExpr);
12256 continue;
12257 }
12258
12259 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012260 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012261 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012262 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012263 DepCounter >= TotalDepCount) {
12264 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12265 continue;
12266 }
12267 ++DepCounter;
12268 // OpenMP [2.13.9, Summary]
12269 // depend(dependence-type : vec), where dependence-type is:
12270 // 'sink' and where vec is the iteration vector, which has the form:
12271 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12272 // where n is the value specified by the ordered clause in the loop
12273 // directive, xi denotes the loop iteration variable of the i-th nested
12274 // loop associated with the loop directive, and di is a constant
12275 // non-negative integer.
12276 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012277 // It will be analyzed later.
12278 Vars.push_back(RefExpr);
12279 continue;
12280 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012281 SimpleExpr = SimpleExpr->IgnoreImplicit();
12282 OverloadedOperatorKind OOK = OO_None;
12283 SourceLocation OOLoc;
12284 Expr *LHS = SimpleExpr;
12285 Expr *RHS = nullptr;
12286 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12287 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12288 OOLoc = BO->getOperatorLoc();
12289 LHS = BO->getLHS()->IgnoreParenImpCasts();
12290 RHS = BO->getRHS()->IgnoreParenImpCasts();
12291 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12292 OOK = OCE->getOperator();
12293 OOLoc = OCE->getOperatorLoc();
12294 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12295 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12296 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12297 OOK = MCE->getMethodDecl()
12298 ->getNameInfo()
12299 .getName()
12300 .getCXXOverloadedOperator();
12301 OOLoc = MCE->getCallee()->getExprLoc();
12302 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12303 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012304 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012305 SourceLocation ELoc;
12306 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012307 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012308 if (Res.second) {
12309 // It will be analyzed later.
12310 Vars.push_back(RefExpr);
12311 }
12312 ValueDecl *D = Res.first;
12313 if (!D)
12314 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012315
Alexey Bataev17daedf2018-02-15 22:42:57 +000012316 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12317 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12318 continue;
12319 }
12320 if (RHS) {
12321 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12322 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12323 if (RHSRes.isInvalid())
12324 continue;
12325 }
12326 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012327 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012328 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012329 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012330 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012331 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012332 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12333 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012334 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012335 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012336 continue;
12337 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012338 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012339 } else {
12340 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12341 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12342 (ASE &&
12343 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12344 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12345 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12346 << RefExpr->getSourceRange();
12347 continue;
12348 }
12349 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12350 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12351 ExprResult Res =
12352 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12353 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12354 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12355 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12356 << RefExpr->getSourceRange();
12357 continue;
12358 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012359 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012360 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012361 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012362
12363 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12364 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012365 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012366 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12367 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12368 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12369 }
12370 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12371 Vars.empty())
12372 return nullptr;
12373
Alexey Bataev8b427062016-05-25 12:36:08 +000012374 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012375 DepKind, DepLoc, ColonLoc, Vars,
12376 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012377 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12378 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012379 DSAStack->addDoacrossDependClause(C, OpsOffs);
12380 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012381}
Michael Wonge710d542015-08-07 16:16:36 +000012382
12383OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12384 SourceLocation LParenLoc,
12385 SourceLocation EndLoc) {
12386 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012387 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012388
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012389 // OpenMP [2.9.1, Restrictions]
12390 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012391 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012392 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012393 return nullptr;
12394
Alexey Bataev931e19b2017-10-02 16:32:39 +000012395 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012396 OpenMPDirectiveKind CaptureRegion =
12397 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12398 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012399 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012400 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012401 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12402 HelperValStmt = buildPreInits(Context, Captures);
12403 }
12404
Alexey Bataev8451efa2018-01-15 19:06:12 +000012405 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12406 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012407}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012408
Alexey Bataeve3727102018-04-18 15:57:46 +000012409static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012410 DSAStackTy *Stack, QualType QTy,
12411 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012412 NamedDecl *ND;
12413 if (QTy->isIncompleteType(&ND)) {
12414 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12415 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012416 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012417 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12418 !QTy.isTrivialType(SemaRef.Context))
12419 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012420 return true;
12421}
12422
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012423/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012424/// (array section or array subscript) does NOT specify the whole size of the
12425/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012426static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012427 const Expr *E,
12428 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012429 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012430
12431 // If this is an array subscript, it refers to the whole size if the size of
12432 // the dimension is constant and equals 1. Also, an array section assumes the
12433 // format of an array subscript if no colon is used.
12434 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012435 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012436 return ATy->getSize().getSExtValue() != 1;
12437 // Size can't be evaluated statically.
12438 return false;
12439 }
12440
12441 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012442 const Expr *LowerBound = OASE->getLowerBound();
12443 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012444
12445 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012446 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012447 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012448 Expr::EvalResult Result;
12449 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012450 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012451
12452 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012453 if (ConstLowerBound.getSExtValue())
12454 return true;
12455 }
12456
12457 // If we don't have a length we covering the whole dimension.
12458 if (!Length)
12459 return false;
12460
12461 // If the base is a pointer, we don't have a way to get the size of the
12462 // pointee.
12463 if (BaseQTy->isPointerType())
12464 return false;
12465
12466 // We can only check if the length is the same as the size of the dimension
12467 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012468 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012469 if (!CATy)
12470 return false;
12471
Fangrui Song407659a2018-11-30 23:41:18 +000012472 Expr::EvalResult Result;
12473 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012474 return false; // Can't get the integer value as a constant.
12475
Fangrui Song407659a2018-11-30 23:41:18 +000012476 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012477 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12478}
12479
12480// Return true if it can be proven that the provided array expression (array
12481// section or array subscript) does NOT specify a single element of the array
12482// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012483static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012484 const Expr *E,
12485 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012486 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012487
12488 // An array subscript always refer to a single element. Also, an array section
12489 // assumes the format of an array subscript if no colon is used.
12490 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12491 return false;
12492
12493 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012494 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012495
12496 // If we don't have a length we have to check if the array has unitary size
12497 // for this dimension. Also, we should always expect a length if the base type
12498 // is pointer.
12499 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012500 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012501 return ATy->getSize().getSExtValue() != 1;
12502 // We cannot assume anything.
12503 return false;
12504 }
12505
12506 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012507 Expr::EvalResult Result;
12508 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012509 return false; // Can't get the integer value as a constant.
12510
Fangrui Song407659a2018-11-30 23:41:18 +000012511 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012512 return ConstLength.getSExtValue() != 1;
12513}
12514
Samuel Antao661c0902016-05-26 17:39:58 +000012515// Return the expression of the base of the mappable expression or null if it
12516// cannot be determined and do all the necessary checks to see if the expression
12517// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012518// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012519static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012520 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012521 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012522 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012523 SourceLocation ELoc = E->getExprLoc();
12524 SourceRange ERange = E->getSourceRange();
12525
12526 // The base of elements of list in a map clause have to be either:
12527 // - a reference to variable or field.
12528 // - a member expression.
12529 // - an array expression.
12530 //
12531 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12532 // reference to 'r'.
12533 //
12534 // If we have:
12535 //
12536 // struct SS {
12537 // Bla S;
12538 // foo() {
12539 // #pragma omp target map (S.Arr[:12]);
12540 // }
12541 // }
12542 //
12543 // We want to retrieve the member expression 'this->S';
12544
Alexey Bataeve3727102018-04-18 15:57:46 +000012545 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012546
Samuel Antao5de996e2016-01-22 20:21:36 +000012547 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12548 // If a list item is an array section, it must specify contiguous storage.
12549 //
12550 // For this restriction it is sufficient that we make sure only references
12551 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012552 // exist except in the rightmost expression (unless they cover the whole
12553 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012554 //
12555 // r.ArrS[3:5].Arr[6:7]
12556 //
12557 // r.ArrS[3:5].x
12558 //
12559 // but these would be valid:
12560 // r.ArrS[3].Arr[6:7]
12561 //
12562 // r.ArrS[3].x
12563
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012564 bool AllowUnitySizeArraySection = true;
12565 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012566
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012567 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012568 E = E->IgnoreParenImpCasts();
12569
12570 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12571 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012572 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012573
12574 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012575
12576 // If we got a reference to a declaration, we should not expect any array
12577 // section before that.
12578 AllowUnitySizeArraySection = false;
12579 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012580
12581 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012582 CurComponents.emplace_back(CurE, CurE->getDecl());
12583 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012584 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012585
12586 if (isa<CXXThisExpr>(BaseE))
12587 // We found a base expression: this->Val.
12588 RelevantExpr = CurE;
12589 else
12590 E = BaseE;
12591
12592 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012593 if (!NoDiagnose) {
12594 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12595 << CurE->getSourceRange();
12596 return nullptr;
12597 }
12598 if (RelevantExpr)
12599 return nullptr;
12600 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012601 }
12602
12603 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12604
12605 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12606 // A bit-field cannot appear in a map clause.
12607 //
12608 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012609 if (!NoDiagnose) {
12610 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12611 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12612 return nullptr;
12613 }
12614 if (RelevantExpr)
12615 return nullptr;
12616 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012617 }
12618
12619 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12620 // If the type of a list item is a reference to a type T then the type
12621 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012622 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012623
12624 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12625 // A list item cannot be a variable that is a member of a structure with
12626 // a union type.
12627 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012628 if (CurType->isUnionType()) {
12629 if (!NoDiagnose) {
12630 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12631 << CurE->getSourceRange();
12632 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012633 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012634 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012635 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012636
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012637 // If we got a member expression, we should not expect any array section
12638 // before that:
12639 //
12640 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12641 // If a list item is an element of a structure, only the rightmost symbol
12642 // of the variable reference can be an array section.
12643 //
12644 AllowUnitySizeArraySection = false;
12645 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012646
12647 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012648 CurComponents.emplace_back(CurE, FD);
12649 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012650 E = CurE->getBase()->IgnoreParenImpCasts();
12651
12652 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012653 if (!NoDiagnose) {
12654 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12655 << 0 << CurE->getSourceRange();
12656 return nullptr;
12657 }
12658 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012659 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012660
12661 // If we got an array subscript that express the whole dimension we
12662 // can have any array expressions before. If it only expressing part of
12663 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000012664 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012665 E->getType()))
12666 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012667
Patrick Lystere13b1e32019-01-02 19:28:48 +000012668 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12669 Expr::EvalResult Result;
12670 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12671 if (!Result.Val.getInt().isNullValue()) {
12672 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12673 diag::err_omp_invalid_map_this_expr);
12674 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12675 diag::note_omp_invalid_subscript_on_this_ptr_map);
12676 }
12677 }
12678 RelevantExpr = TE;
12679 }
12680
Samuel Antao90927002016-04-26 14:54:23 +000012681 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012682 CurComponents.emplace_back(CurE, nullptr);
12683 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012684 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000012685 E = CurE->getBase()->IgnoreParenImpCasts();
12686
Alexey Bataev27041fa2017-12-05 15:22:49 +000012687 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012688 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12689
Samuel Antao5de996e2016-01-22 20:21:36 +000012690 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12691 // If the type of a list item is a reference to a type T then the type
12692 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000012693 if (CurType->isReferenceType())
12694 CurType = CurType->getPointeeType();
12695
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012696 bool IsPointer = CurType->isAnyPointerType();
12697
12698 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012699 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12700 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012701 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012702 }
12703
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012704 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000012705 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012706 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000012707 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012708
Samuel Antaodab51bb2016-07-18 23:22:11 +000012709 if (AllowWholeSizeArraySection) {
12710 // Any array section is currently allowed. Allowing a whole size array
12711 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012712 //
12713 // If this array section refers to the whole dimension we can still
12714 // accept other array sections before this one, except if the base is a
12715 // pointer. Otherwise, only unitary sections are accepted.
12716 if (NotWhole || IsPointer)
12717 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000012718 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012719 // A unity or whole array section is not allowed and that is not
12720 // compatible with the properties of the current array section.
12721 SemaRef.Diag(
12722 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
12723 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012724 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012725 }
Samuel Antao90927002016-04-26 14:54:23 +000012726
Patrick Lystere13b1e32019-01-02 19:28:48 +000012727 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12728 Expr::EvalResult ResultR;
12729 Expr::EvalResult ResultL;
12730 if (CurE->getLength()->EvaluateAsInt(ResultR,
12731 SemaRef.getASTContext())) {
12732 if (!ResultR.Val.getInt().isOneValue()) {
12733 SemaRef.Diag(CurE->getLength()->getExprLoc(),
12734 diag::err_omp_invalid_map_this_expr);
12735 SemaRef.Diag(CurE->getLength()->getExprLoc(),
12736 diag::note_omp_invalid_length_on_this_ptr_mapping);
12737 }
12738 }
12739 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
12740 ResultL, SemaRef.getASTContext())) {
12741 if (!ResultL.Val.getInt().isNullValue()) {
12742 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12743 diag::err_omp_invalid_map_this_expr);
12744 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12745 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
12746 }
12747 }
12748 RelevantExpr = TE;
12749 }
12750
Samuel Antao90927002016-04-26 14:54:23 +000012751 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012752 CurComponents.emplace_back(CurE, nullptr);
12753 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012754 if (!NoDiagnose) {
12755 // If nothing else worked, this is not a valid map clause expression.
12756 SemaRef.Diag(
12757 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
12758 << ERange;
12759 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000012760 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012761 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012762 }
12763
12764 return RelevantExpr;
12765}
12766
12767// Return true if expression E associated with value VD has conflicts with other
12768// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000012769static bool checkMapConflicts(
12770 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000012771 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000012772 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
12773 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012774 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000012775 SourceLocation ELoc = E->getExprLoc();
12776 SourceRange ERange = E->getSourceRange();
12777
12778 // In order to easily check the conflicts we need to match each component of
12779 // the expression under test with the components of the expressions that are
12780 // already in the stack.
12781
Samuel Antao5de996e2016-01-22 20:21:36 +000012782 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000012783 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000012784 "Map clause expression with unexpected base!");
12785
12786 // Variables to help detecting enclosing problems in data environment nests.
12787 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000012788 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012789
Samuel Antao90927002016-04-26 14:54:23 +000012790 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
12791 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000012792 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
12793 ERange, CKind, &EnclosingExpr,
12794 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
12795 StackComponents,
12796 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012797 assert(!StackComponents.empty() &&
12798 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000012799 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000012800 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000012801 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012802
Samuel Antao90927002016-04-26 14:54:23 +000012803 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000012804 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000012805
Samuel Antao5de996e2016-01-22 20:21:36 +000012806 // Expressions must start from the same base. Here we detect at which
12807 // point both expressions diverge from each other and see if we can
12808 // detect if the memory referred to both expressions is contiguous and
12809 // do not overlap.
12810 auto CI = CurComponents.rbegin();
12811 auto CE = CurComponents.rend();
12812 auto SI = StackComponents.rbegin();
12813 auto SE = StackComponents.rend();
12814 for (; CI != CE && SI != SE; ++CI, ++SI) {
12815
12816 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12817 // At most one list item can be an array item derived from a given
12818 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000012819 if (CurrentRegionOnly &&
12820 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12821 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12822 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12823 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12824 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000012825 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000012826 << CI->getAssociatedExpression()->getSourceRange();
12827 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12828 diag::note_used_here)
12829 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000012830 return true;
12831 }
12832
12833 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000012834 if (CI->getAssociatedExpression()->getStmtClass() !=
12835 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000012836 break;
12837
12838 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000012839 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000012840 break;
12841 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000012842 // Check if the extra components of the expressions in the enclosing
12843 // data environment are redundant for the current base declaration.
12844 // If they are, the maps completely overlap, which is legal.
12845 for (; SI != SE; ++SI) {
12846 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000012847 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000012848 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000012849 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012850 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000012851 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012852 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000012853 Type =
12854 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12855 }
12856 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012857 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000012858 SemaRef, SI->getAssociatedExpression(), Type))
12859 break;
12860 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012861
12862 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12863 // List items of map clauses in the same construct must not share
12864 // original storage.
12865 //
12866 // If the expressions are exactly the same or one is a subset of the
12867 // other, it means they are sharing storage.
12868 if (CI == CE && SI == SE) {
12869 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012870 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000012871 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012872 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012873 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012874 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12875 << ERange;
12876 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012877 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12878 << RE->getSourceRange();
12879 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012880 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012881 // If we find the same expression in the enclosing data environment,
12882 // that is legal.
12883 IsEnclosedByDataEnvironmentExpr = true;
12884 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000012885 }
12886
Samuel Antao90927002016-04-26 14:54:23 +000012887 QualType DerivedType =
12888 std::prev(CI)->getAssociatedDeclaration()->getType();
12889 SourceLocation DerivedLoc =
12890 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000012891
12892 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12893 // If the type of a list item is a reference to a type T then the type
12894 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012895 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012896
12897 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12898 // A variable for which the type is pointer and an array section
12899 // derived from that variable must not appear as list items of map
12900 // clauses of the same construct.
12901 //
12902 // Also, cover one of the cases in:
12903 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12904 // If any part of the original storage of a list item has corresponding
12905 // storage in the device data environment, all of the original storage
12906 // must have corresponding storage in the device data environment.
12907 //
12908 if (DerivedType->isAnyPointerType()) {
12909 if (CI == CE || SI == SE) {
12910 SemaRef.Diag(
12911 DerivedLoc,
12912 diag::err_omp_pointer_mapped_along_with_derived_section)
12913 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012914 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12915 << RE->getSourceRange();
12916 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000012917 }
12918 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000012919 SI->getAssociatedExpression()->getStmtClass() ||
12920 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12921 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012922 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000012923 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000012924 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012925 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12926 << RE->getSourceRange();
12927 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012928 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012929 }
12930
12931 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12932 // List items of map clauses in the same construct must not share
12933 // original storage.
12934 //
12935 // An expression is a subset of the other.
12936 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012937 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000012938 if (CI != CE || SI != SE) {
12939 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
12940 // a pointer.
12941 auto Begin =
12942 CI != CE ? CurComponents.begin() : StackComponents.begin();
12943 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
12944 auto It = Begin;
12945 while (It != End && !It->getAssociatedDeclaration())
12946 std::advance(It, 1);
12947 assert(It != End &&
12948 "Expected at least one component with the declaration.");
12949 if (It != Begin && It->getAssociatedDeclaration()
12950 ->getType()
12951 .getCanonicalType()
12952 ->isAnyPointerType()) {
12953 IsEnclosedByDataEnvironmentExpr = false;
12954 EnclosingExpr = nullptr;
12955 return false;
12956 }
12957 }
Samuel Antao661c0902016-05-26 17:39:58 +000012958 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012959 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012960 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012961 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12962 << ERange;
12963 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012964 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12965 << RE->getSourceRange();
12966 return true;
12967 }
12968
12969 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012970 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012971 if (!CurrentRegionOnly && SI != SE)
12972 EnclosingExpr = RE;
12973
12974 // The current expression is a subset of the expression in the data
12975 // environment.
12976 IsEnclosedByDataEnvironmentExpr |=
12977 (!CurrentRegionOnly && CI != CE && SI == SE);
12978
12979 return false;
12980 });
12981
12982 if (CurrentRegionOnly)
12983 return FoundError;
12984
12985 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12986 // If any part of the original storage of a list item has corresponding
12987 // storage in the device data environment, all of the original storage must
12988 // have corresponding storage in the device data environment.
12989 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12990 // If a list item is an element of a structure, and a different element of
12991 // the structure has a corresponding list item in the device data environment
12992 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000012993 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000012994 // data environment prior to the task encountering the construct.
12995 //
12996 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12997 SemaRef.Diag(ELoc,
12998 diag::err_omp_original_storage_is_shared_and_does_not_contain)
12999 << ERange;
13000 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13001 << EnclosingExpr->getSourceRange();
13002 return true;
13003 }
13004
13005 return FoundError;
13006}
13007
Michael Kruse4304e9d2019-02-19 16:38:20 +000013008// Look up the user-defined mapper given the mapper name and mapped type, and
13009// build a reference to it.
13010ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13011 CXXScopeSpec &MapperIdScopeSpec,
13012 const DeclarationNameInfo &MapperId,
13013 QualType Type, Expr *UnresolvedMapper) {
13014 if (MapperIdScopeSpec.isInvalid())
13015 return ExprError();
13016 // Find all user-defined mappers with the given MapperId.
13017 SmallVector<UnresolvedSet<8>, 4> Lookups;
13018 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13019 Lookup.suppressDiagnostics();
13020 if (S) {
13021 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13022 NamedDecl *D = Lookup.getRepresentativeDecl();
13023 while (S && !S->isDeclScope(D))
13024 S = S->getParent();
13025 if (S)
13026 S = S->getParent();
13027 Lookups.emplace_back();
13028 Lookups.back().append(Lookup.begin(), Lookup.end());
13029 Lookup.clear();
13030 }
13031 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13032 // Extract the user-defined mappers with the given MapperId.
13033 Lookups.push_back(UnresolvedSet<8>());
13034 for (NamedDecl *D : ULE->decls()) {
13035 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13036 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13037 Lookups.back().addDecl(DMD);
13038 }
13039 }
13040 // Defer the lookup for dependent types. The results will be passed through
13041 // UnresolvedMapper on instantiation.
13042 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13043 Type->isInstantiationDependentType() ||
13044 Type->containsUnexpandedParameterPack() ||
13045 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13046 return !D->isInvalidDecl() &&
13047 (D->getType()->isDependentType() ||
13048 D->getType()->isInstantiationDependentType() ||
13049 D->getType()->containsUnexpandedParameterPack());
13050 })) {
13051 UnresolvedSet<8> URS;
13052 for (const UnresolvedSet<8> &Set : Lookups) {
13053 if (Set.empty())
13054 continue;
13055 URS.append(Set.begin(), Set.end());
13056 }
13057 return UnresolvedLookupExpr::Create(
13058 SemaRef.Context, /*NamingClass=*/nullptr,
13059 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13060 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13061 }
13062 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13063 // The type must be of struct, union or class type in C and C++
13064 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13065 return ExprEmpty();
13066 SourceLocation Loc = MapperId.getLoc();
13067 // Perform argument dependent lookup.
13068 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13069 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13070 // Return the first user-defined mapper with the desired type.
13071 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13072 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13073 if (!D->isInvalidDecl() &&
13074 SemaRef.Context.hasSameType(D->getType(), Type))
13075 return D;
13076 return nullptr;
13077 }))
13078 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13079 // Find the first user-defined mapper with a type derived from the desired
13080 // type.
13081 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13082 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13083 if (!D->isInvalidDecl() &&
13084 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13085 !Type.isMoreQualifiedThan(D->getType()))
13086 return D;
13087 return nullptr;
13088 })) {
13089 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13090 /*DetectVirtual=*/false);
13091 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13092 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13093 VD->getType().getUnqualifiedType()))) {
13094 if (SemaRef.CheckBaseClassAccess(
13095 Loc, VD->getType(), Type, Paths.front(),
13096 /*DiagID=*/0) != Sema::AR_inaccessible) {
13097 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13098 }
13099 }
13100 }
13101 }
13102 // Report error if a mapper is specified, but cannot be found.
13103 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13104 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13105 << Type << MapperId.getName();
13106 return ExprError();
13107 }
13108 return ExprEmpty();
13109}
13110
Samuel Antao661c0902016-05-26 17:39:58 +000013111namespace {
13112// Utility struct that gathers all the related lists associated with a mappable
13113// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013114struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013115 // The list of expressions.
13116 ArrayRef<Expr *> VarList;
13117 // The list of processed expressions.
13118 SmallVector<Expr *, 16> ProcessedVarList;
13119 // The mappble components for each expression.
13120 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13121 // The base declaration of the variable.
13122 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013123 // The reference to the user-defined mapper associated with every expression.
13124 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013125
13126 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13127 // We have a list of components and base declarations for each entry in the
13128 // variable list.
13129 VarComponents.reserve(VarList.size());
13130 VarBaseDeclarations.reserve(VarList.size());
13131 }
13132};
13133}
13134
13135// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013136// \a CKind. In the check process the valid expressions, mappable expression
13137// components, variables, and user-defined mappers are extracted and used to
13138// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13139// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13140// and \a MapperId are expected to be valid if the clause kind is 'map'.
13141static void checkMappableExpressionList(
13142 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13143 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013144 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13145 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013146 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013147 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013148 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13149 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013150 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013151
13152 // If the identifier of user-defined mapper is not specified, it is "default".
13153 // We do not change the actual name in this clause to distinguish whether a
13154 // mapper is specified explicitly, i.e., it is not explicitly specified when
13155 // MapperId.getName() is empty.
13156 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13157 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13158 MapperId.setName(DeclNames.getIdentifier(
13159 &SemaRef.getASTContext().Idents.get("default")));
13160 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013161
13162 // Iterators to find the current unresolved mapper expression.
13163 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13164 bool UpdateUMIt = false;
13165 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013166
Samuel Antao90927002016-04-26 14:54:23 +000013167 // Keep track of the mappable components and base declarations in this clause.
13168 // Each entry in the list is going to have a list of components associated. We
13169 // record each set of the components so that we can build the clause later on.
13170 // In the end we should have the same amount of declarations and component
13171 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013172
Alexey Bataeve3727102018-04-18 15:57:46 +000013173 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013174 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013175 SourceLocation ELoc = RE->getExprLoc();
13176
Michael Kruse4304e9d2019-02-19 16:38:20 +000013177 // Find the current unresolved mapper expression.
13178 if (UpdateUMIt && UMIt != UMEnd) {
13179 UMIt++;
13180 assert(
13181 UMIt != UMEnd &&
13182 "Expect the size of UnresolvedMappers to match with that of VarList");
13183 }
13184 UpdateUMIt = true;
13185 if (UMIt != UMEnd)
13186 UnresolvedMapper = *UMIt;
13187
Alexey Bataeve3727102018-04-18 15:57:46 +000013188 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013189
13190 if (VE->isValueDependent() || VE->isTypeDependent() ||
13191 VE->isInstantiationDependent() ||
13192 VE->containsUnexpandedParameterPack()) {
Michael Kruse01f670d2019-02-22 22:29:42 +000013193 if (CKind != OMPC_from) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000013194 // Try to find the associated user-defined mapper.
13195 ExprResult ER = buildUserDefinedMapperRef(
Michael Kruse01f670d2019-02-22 22:29:42 +000013196 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013197 VE->getType().getCanonicalType(), UnresolvedMapper);
13198 if (ER.isInvalid())
13199 continue;
13200 MVLI.UDMapperList.push_back(ER.get());
Michael Kruse4304e9d2019-02-19 16:38:20 +000013201 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013202 // We can only analyze this information once the missing information is
13203 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013204 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013205 continue;
13206 }
13207
Alexey Bataeve3727102018-04-18 15:57:46 +000013208 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013209
Samuel Antao5de996e2016-01-22 20:21:36 +000013210 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013211 SemaRef.Diag(ELoc,
13212 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013213 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013214 continue;
13215 }
13216
Samuel Antao90927002016-04-26 14:54:23 +000013217 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13218 ValueDecl *CurDeclaration = nullptr;
13219
13220 // Obtain the array or member expression bases if required. Also, fill the
13221 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013222 const Expr *BE = checkMapClauseExpressionBase(
13223 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013224 if (!BE)
13225 continue;
13226
Samuel Antao90927002016-04-26 14:54:23 +000013227 assert(!CurComponents.empty() &&
13228 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013229
Patrick Lystere13b1e32019-01-02 19:28:48 +000013230 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13231 // Add store "this" pointer to class in DSAStackTy for future checking
13232 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse01f670d2019-02-22 22:29:42 +000013233 if (CKind != OMPC_from) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000013234 // Try to find the associated user-defined mapper.
13235 ExprResult ER = buildUserDefinedMapperRef(
Michael Kruse01f670d2019-02-22 22:29:42 +000013236 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013237 VE->getType().getCanonicalType(), UnresolvedMapper);
13238 if (ER.isInvalid())
13239 continue;
13240 MVLI.UDMapperList.push_back(ER.get());
Michael Kruse4304e9d2019-02-19 16:38:20 +000013241 }
Patrick Lystere13b1e32019-01-02 19:28:48 +000013242 // Skip restriction checking for variable or field declarations
13243 MVLI.ProcessedVarList.push_back(RE);
13244 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13245 MVLI.VarComponents.back().append(CurComponents.begin(),
13246 CurComponents.end());
13247 MVLI.VarBaseDeclarations.push_back(nullptr);
13248 continue;
13249 }
13250
Samuel Antao90927002016-04-26 14:54:23 +000013251 // For the following checks, we rely on the base declaration which is
13252 // expected to be associated with the last component. The declaration is
13253 // expected to be a variable or a field (if 'this' is being mapped).
13254 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13255 assert(CurDeclaration && "Null decl on map clause.");
13256 assert(
13257 CurDeclaration->isCanonicalDecl() &&
13258 "Expecting components to have associated only canonical declarations.");
13259
13260 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013261 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013262
13263 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013264 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013265
13266 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013267 // threadprivate variables cannot appear in a map clause.
13268 // OpenMP 4.5 [2.10.5, target update Construct]
13269 // threadprivate variables cannot appear in a from clause.
13270 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013271 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013272 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13273 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013274 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013275 continue;
13276 }
13277
Samuel Antao5de996e2016-01-22 20:21:36 +000013278 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13279 // A list item cannot appear in both a map clause and a data-sharing
13280 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013281
Samuel Antao5de996e2016-01-22 20:21:36 +000013282 // Check conflicts with other map clause expressions. We check the conflicts
13283 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013284 // environment, because the restrictions are different. We only have to
13285 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013286 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013287 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013288 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013289 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013290 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013291 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013292 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013293
Samuel Antao661c0902016-05-26 17:39:58 +000013294 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013295 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13296 // If the type of a list item is a reference to a type T then the type will
13297 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013298 auto I = llvm::find_if(
13299 CurComponents,
13300 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13301 return MC.getAssociatedDeclaration();
13302 });
13303 assert(I != CurComponents.end() && "Null decl on map clause.");
13304 QualType Type =
13305 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013306
Samuel Antao661c0902016-05-26 17:39:58 +000013307 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13308 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013309 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013310 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013311 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013312 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013313 continue;
13314
Samuel Antao661c0902016-05-26 17:39:58 +000013315 if (CKind == OMPC_map) {
13316 // target enter data
13317 // OpenMP [2.10.2, Restrictions, p. 99]
13318 // A map-type must be specified in all map clauses and must be either
13319 // to or alloc.
13320 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13321 if (DKind == OMPD_target_enter_data &&
13322 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13323 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13324 << (IsMapTypeImplicit ? 1 : 0)
13325 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13326 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013327 continue;
13328 }
Samuel Antao661c0902016-05-26 17:39:58 +000013329
13330 // target exit_data
13331 // OpenMP [2.10.3, Restrictions, p. 102]
13332 // A map-type must be specified in all map clauses and must be either
13333 // from, release, or delete.
13334 if (DKind == OMPD_target_exit_data &&
13335 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13336 MapType == OMPC_MAP_delete)) {
13337 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13338 << (IsMapTypeImplicit ? 1 : 0)
13339 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13340 << getOpenMPDirectiveName(DKind);
13341 continue;
13342 }
13343
13344 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13345 // A list item cannot appear in both a map clause and a data-sharing
13346 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013347 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13348 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013349 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013350 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013351 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013352 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013353 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013354 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013355 continue;
13356 }
13357 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013358 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013359
Michael Kruse01f670d2019-02-22 22:29:42 +000013360 // Try to find the associated user-defined mapper.
13361 if (CKind != OMPC_from) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000013362 ExprResult ER = buildUserDefinedMapperRef(
Michael Kruse01f670d2019-02-22 22:29:42 +000013363 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013364 Type.getCanonicalType(), UnresolvedMapper);
13365 if (ER.isInvalid())
13366 continue;
13367 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013368 }
13369
Samuel Antao90927002016-04-26 14:54:23 +000013370 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013371 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013372
13373 // Store the components in the stack so that they can be used to check
13374 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013375 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13376 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013377
13378 // Save the components and declaration to create the clause. For purposes of
13379 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013380 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013381 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13382 MVLI.VarComponents.back().append(CurComponents.begin(),
13383 CurComponents.end());
13384 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13385 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013386 }
Samuel Antao661c0902016-05-26 17:39:58 +000013387}
13388
Michael Kruse4304e9d2019-02-19 16:38:20 +000013389OMPClause *Sema::ActOnOpenMPMapClause(
13390 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13391 ArrayRef<SourceLocation> MapTypeModifiersLoc,
13392 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13393 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13394 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13395 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13396 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13397 OMPC_MAP_MODIFIER_unknown,
13398 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000013399 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13400
13401 // Process map-type-modifiers, flag errors for duplicate modifiers.
13402 unsigned Count = 0;
13403 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13404 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13405 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13406 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13407 continue;
13408 }
13409 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013410 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013411 Modifiers[Count] = MapTypeModifiers[I];
13412 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13413 ++Count;
13414 }
13415
Michael Kruse4304e9d2019-02-19 16:38:20 +000013416 MappableVarListInfo MVLI(VarList);
13417 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013418 MapperIdScopeSpec, MapperId, UnresolvedMappers,
13419 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000013420
Samuel Antao5de996e2016-01-22 20:21:36 +000013421 // We need to produce a map clause even if we don't have variables so that
13422 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000013423 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13424 MVLI.VarBaseDeclarations, MVLI.VarComponents,
13425 MVLI.UDMapperList, Modifiers, ModifiersLoc,
13426 MapperIdScopeSpec.getWithLocInContext(Context),
13427 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013428}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013429
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013430QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13431 TypeResult ParsedType) {
13432 assert(ParsedType.isUsable());
13433
13434 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13435 if (ReductionType.isNull())
13436 return QualType();
13437
13438 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13439 // A type name in a declare reduction directive cannot be a function type, an
13440 // array type, a reference type, or a type qualified with const, volatile or
13441 // restrict.
13442 if (ReductionType.hasQualifiers()) {
13443 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13444 return QualType();
13445 }
13446
13447 if (ReductionType->isFunctionType()) {
13448 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13449 return QualType();
13450 }
13451 if (ReductionType->isReferenceType()) {
13452 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13453 return QualType();
13454 }
13455 if (ReductionType->isArrayType()) {
13456 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13457 return QualType();
13458 }
13459 return ReductionType;
13460}
13461
13462Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13463 Scope *S, DeclContext *DC, DeclarationName Name,
13464 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13465 AccessSpecifier AS, Decl *PrevDeclInScope) {
13466 SmallVector<Decl *, 8> Decls;
13467 Decls.reserve(ReductionTypes.size());
13468
13469 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013470 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013471 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13472 // A reduction-identifier may not be re-declared in the current scope for the
13473 // same type or for a type that is compatible according to the base language
13474 // rules.
13475 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13476 OMPDeclareReductionDecl *PrevDRD = nullptr;
13477 bool InCompoundScope = true;
13478 if (S != nullptr) {
13479 // Find previous declaration with the same name not referenced in other
13480 // declarations.
13481 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13482 InCompoundScope =
13483 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13484 LookupName(Lookup, S);
13485 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13486 /*AllowInlineNamespace=*/false);
13487 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013488 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013489 while (Filter.hasNext()) {
13490 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13491 if (InCompoundScope) {
13492 auto I = UsedAsPrevious.find(PrevDecl);
13493 if (I == UsedAsPrevious.end())
13494 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013495 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013496 UsedAsPrevious[D] = true;
13497 }
13498 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13499 PrevDecl->getLocation();
13500 }
13501 Filter.done();
13502 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013503 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013504 if (!PrevData.second) {
13505 PrevDRD = PrevData.first;
13506 break;
13507 }
13508 }
13509 }
13510 } else if (PrevDeclInScope != nullptr) {
13511 auto *PrevDRDInScope = PrevDRD =
13512 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13513 do {
13514 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13515 PrevDRDInScope->getLocation();
13516 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13517 } while (PrevDRDInScope != nullptr);
13518 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013519 for (const auto &TyData : ReductionTypes) {
13520 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013521 bool Invalid = false;
13522 if (I != PreviousRedeclTypes.end()) {
13523 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13524 << TyData.first;
13525 Diag(I->second, diag::note_previous_definition);
13526 Invalid = true;
13527 }
13528 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13529 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13530 Name, TyData.first, PrevDRD);
13531 DC->addDecl(DRD);
13532 DRD->setAccess(AS);
13533 Decls.push_back(DRD);
13534 if (Invalid)
13535 DRD->setInvalidDecl();
13536 else
13537 PrevDRD = DRD;
13538 }
13539
13540 return DeclGroupPtrTy::make(
13541 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13542}
13543
13544void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13545 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13546
13547 // Enter new function scope.
13548 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013549 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013550 getCurFunction()->setHasOMPDeclareReductionCombiner();
13551
13552 if (S != nullptr)
13553 PushDeclContext(S, DRD);
13554 else
13555 CurContext = DRD;
13556
Faisal Valid143a0c2017-04-01 21:30:49 +000013557 PushExpressionEvaluationContext(
13558 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013559
13560 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013561 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13562 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13563 // uses semantics of argument handles by value, but it should be passed by
13564 // reference. C lang does not support references, so pass all parameters as
13565 // pointers.
13566 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013567 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013568 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013569 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13570 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13571 // uses semantics of argument handles by value, but it should be passed by
13572 // reference. C lang does not support references, so pass all parameters as
13573 // pointers.
13574 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013575 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013576 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13577 if (S != nullptr) {
13578 PushOnScopeChains(OmpInParm, S);
13579 PushOnScopeChains(OmpOutParm, S);
13580 } else {
13581 DRD->addDecl(OmpInParm);
13582 DRD->addDecl(OmpOutParm);
13583 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013584 Expr *InE =
13585 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13586 Expr *OutE =
13587 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13588 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013589}
13590
13591void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13592 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13593 DiscardCleanupsInEvaluationContext();
13594 PopExpressionEvaluationContext();
13595
13596 PopDeclContext();
13597 PopFunctionScopeInfo();
13598
13599 if (Combiner != nullptr)
13600 DRD->setCombiner(Combiner);
13601 else
13602 DRD->setInvalidDecl();
13603}
13604
Alexey Bataev070f43a2017-09-06 14:49:58 +000013605VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013606 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13607
13608 // Enter new function scope.
13609 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013610 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013611
13612 if (S != nullptr)
13613 PushDeclContext(S, DRD);
13614 else
13615 CurContext = DRD;
13616
Faisal Valid143a0c2017-04-01 21:30:49 +000013617 PushExpressionEvaluationContext(
13618 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013619
13620 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013621 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13622 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13623 // uses semantics of argument handles by value, but it should be passed by
13624 // reference. C lang does not support references, so pass all parameters as
13625 // pointers.
13626 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013627 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013628 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013629 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13630 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13631 // uses semantics of argument handles by value, but it should be passed by
13632 // reference. C lang does not support references, so pass all parameters as
13633 // pointers.
13634 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013635 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013636 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013637 if (S != nullptr) {
13638 PushOnScopeChains(OmpPrivParm, S);
13639 PushOnScopeChains(OmpOrigParm, S);
13640 } else {
13641 DRD->addDecl(OmpPrivParm);
13642 DRD->addDecl(OmpOrigParm);
13643 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013644 Expr *OrigE =
13645 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13646 Expr *PrivE =
13647 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13648 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013649 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013650}
13651
Alexey Bataev070f43a2017-09-06 14:49:58 +000013652void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13653 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013654 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13655 DiscardCleanupsInEvaluationContext();
13656 PopExpressionEvaluationContext();
13657
13658 PopDeclContext();
13659 PopFunctionScopeInfo();
13660
Alexey Bataev070f43a2017-09-06 14:49:58 +000013661 if (Initializer != nullptr) {
13662 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13663 } else if (OmpPrivParm->hasInit()) {
13664 DRD->setInitializer(OmpPrivParm->getInit(),
13665 OmpPrivParm->isDirectInit()
13666 ? OMPDeclareReductionDecl::DirectInit
13667 : OMPDeclareReductionDecl::CopyInit);
13668 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013669 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000013670 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013671}
13672
13673Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13674 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013675 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013676 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013677 if (S)
13678 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13679 /*AddToContext=*/false);
13680 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013681 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013682 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013683 }
13684 return DeclReductions;
13685}
13686
Michael Kruse251e1482019-02-01 20:25:04 +000013687TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
13688 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13689 QualType T = TInfo->getType();
13690 if (D.isInvalidType())
13691 return true;
13692
13693 if (getLangOpts().CPlusPlus) {
13694 // Check that there are no default arguments (C++ only).
13695 CheckExtraCXXDefaultArguments(D);
13696 }
13697
13698 return CreateParsedType(T, TInfo);
13699}
13700
13701QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
13702 TypeResult ParsedType) {
13703 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
13704
13705 QualType MapperType = GetTypeFromParser(ParsedType.get());
13706 assert(!MapperType.isNull() && "Expect valid mapper type");
13707
13708 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13709 // The type must be of struct, union or class type in C and C++
13710 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
13711 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
13712 return QualType();
13713 }
13714 return MapperType;
13715}
13716
13717OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
13718 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
13719 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
13720 Decl *PrevDeclInScope) {
13721 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
13722 forRedeclarationInCurContext());
13723 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13724 // A mapper-identifier may not be redeclared in the current scope for the
13725 // same type or for a type that is compatible according to the base language
13726 // rules.
13727 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13728 OMPDeclareMapperDecl *PrevDMD = nullptr;
13729 bool InCompoundScope = true;
13730 if (S != nullptr) {
13731 // Find previous declaration with the same name not referenced in other
13732 // declarations.
13733 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13734 InCompoundScope =
13735 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13736 LookupName(Lookup, S);
13737 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13738 /*AllowInlineNamespace=*/false);
13739 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
13740 LookupResult::Filter Filter = Lookup.makeFilter();
13741 while (Filter.hasNext()) {
13742 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
13743 if (InCompoundScope) {
13744 auto I = UsedAsPrevious.find(PrevDecl);
13745 if (I == UsedAsPrevious.end())
13746 UsedAsPrevious[PrevDecl] = false;
13747 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
13748 UsedAsPrevious[D] = true;
13749 }
13750 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13751 PrevDecl->getLocation();
13752 }
13753 Filter.done();
13754 if (InCompoundScope) {
13755 for (const auto &PrevData : UsedAsPrevious) {
13756 if (!PrevData.second) {
13757 PrevDMD = PrevData.first;
13758 break;
13759 }
13760 }
13761 }
13762 } else if (PrevDeclInScope) {
13763 auto *PrevDMDInScope = PrevDMD =
13764 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
13765 do {
13766 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
13767 PrevDMDInScope->getLocation();
13768 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
13769 } while (PrevDMDInScope != nullptr);
13770 }
13771 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
13772 bool Invalid = false;
13773 if (I != PreviousRedeclTypes.end()) {
13774 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
13775 << MapperType << Name;
13776 Diag(I->second, diag::note_previous_definition);
13777 Invalid = true;
13778 }
13779 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
13780 MapperType, VN, PrevDMD);
13781 DC->addDecl(DMD);
13782 DMD->setAccess(AS);
13783 if (Invalid)
13784 DMD->setInvalidDecl();
13785
13786 // Enter new function scope.
13787 PushFunctionScope();
13788 setFunctionHasBranchProtectedScope();
13789
13790 CurContext = DMD;
13791
13792 return DMD;
13793}
13794
13795void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
13796 Scope *S,
13797 QualType MapperType,
13798 SourceLocation StartLoc,
13799 DeclarationName VN) {
13800 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
13801 if (S)
13802 PushOnScopeChains(VD, S);
13803 else
13804 DMD->addDecl(VD);
13805 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
13806 DMD->setMapperVarRef(MapperVarRefExpr);
13807}
13808
13809Sema::DeclGroupPtrTy
13810Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
13811 ArrayRef<OMPClause *> ClauseList) {
13812 PopDeclContext();
13813 PopFunctionScopeInfo();
13814
13815 if (D) {
13816 if (S)
13817 PushOnScopeChains(D, S, /*AddToContext=*/false);
13818 D->CreateClauses(Context, ClauseList);
13819 }
13820
13821 return DeclGroupPtrTy::make(DeclGroupRef(D));
13822}
13823
David Majnemer9d168222016-08-05 17:44:54 +000013824OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000013825 SourceLocation StartLoc,
13826 SourceLocation LParenLoc,
13827 SourceLocation EndLoc) {
13828 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013829 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000013830
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013831 // OpenMP [teams Constrcut, Restrictions]
13832 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013833 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000013834 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013835 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000013836
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013837 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013838 OpenMPDirectiveKind CaptureRegion =
13839 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
13840 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013841 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013842 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013843 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13844 HelperValStmt = buildPreInits(Context, Captures);
13845 }
13846
13847 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
13848 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000013849}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013850
13851OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
13852 SourceLocation StartLoc,
13853 SourceLocation LParenLoc,
13854 SourceLocation EndLoc) {
13855 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013856 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013857
13858 // OpenMP [teams Constrcut, Restrictions]
13859 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013860 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000013861 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013862 return nullptr;
13863
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013864 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013865 OpenMPDirectiveKind CaptureRegion =
13866 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
13867 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013868 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013869 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013870 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13871 HelperValStmt = buildPreInits(Context, Captures);
13872 }
13873
13874 return new (Context) OMPThreadLimitClause(
13875 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013876}
Alexey Bataeva0569352015-12-01 10:17:31 +000013877
13878OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
13879 SourceLocation StartLoc,
13880 SourceLocation LParenLoc,
13881 SourceLocation EndLoc) {
13882 Expr *ValExpr = Priority;
13883
13884 // OpenMP [2.9.1, task Constrcut]
13885 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013886 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000013887 /*StrictlyPositive=*/false))
13888 return nullptr;
13889
13890 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13891}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000013892
13893OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
13894 SourceLocation StartLoc,
13895 SourceLocation LParenLoc,
13896 SourceLocation EndLoc) {
13897 Expr *ValExpr = Grainsize;
13898
13899 // OpenMP [2.9.2, taskloop Constrcut]
13900 // The parameter of the grainsize clause must be a positive integer
13901 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013902 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000013903 /*StrictlyPositive=*/true))
13904 return nullptr;
13905
13906 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13907}
Alexey Bataev382967a2015-12-08 12:06:20 +000013908
13909OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
13910 SourceLocation StartLoc,
13911 SourceLocation LParenLoc,
13912 SourceLocation EndLoc) {
13913 Expr *ValExpr = NumTasks;
13914
13915 // OpenMP [2.9.2, taskloop Constrcut]
13916 // The parameter of the num_tasks clause must be a positive integer
13917 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013918 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000013919 /*StrictlyPositive=*/true))
13920 return nullptr;
13921
13922 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13923}
13924
Alexey Bataev28c75412015-12-15 08:19:24 +000013925OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
13926 SourceLocation LParenLoc,
13927 SourceLocation EndLoc) {
13928 // OpenMP [2.13.2, critical construct, Description]
13929 // ... where hint-expression is an integer constant expression that evaluates
13930 // to a valid lock hint.
13931 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
13932 if (HintExpr.isInvalid())
13933 return nullptr;
13934 return new (Context)
13935 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
13936}
13937
Carlo Bertollib4adf552016-01-15 18:50:31 +000013938OMPClause *Sema::ActOnOpenMPDistScheduleClause(
13939 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13940 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
13941 SourceLocation EndLoc) {
13942 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
13943 std::string Values;
13944 Values += "'";
13945 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
13946 Values += "'";
13947 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13948 << Values << getOpenMPClauseName(OMPC_dist_schedule);
13949 return nullptr;
13950 }
13951 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000013952 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000013953 if (ChunkSize) {
13954 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13955 !ChunkSize->isInstantiationDependent() &&
13956 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013957 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000013958 ExprResult Val =
13959 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13960 if (Val.isInvalid())
13961 return nullptr;
13962
13963 ValExpr = Val.get();
13964
13965 // OpenMP [2.7.1, Restrictions]
13966 // chunk_size must be a loop invariant integer expression with a positive
13967 // value.
13968 llvm::APSInt Result;
13969 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13970 if (Result.isSigned() && !Result.isStrictlyPositive()) {
13971 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13972 << "dist_schedule" << ChunkSize->getSourceRange();
13973 return nullptr;
13974 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000013975 } else if (getOpenMPCaptureRegionForClause(
13976 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
13977 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000013978 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013979 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013980 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000013981 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13982 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000013983 }
13984 }
13985 }
13986
13987 return new (Context)
13988 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000013989 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000013990}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013991
13992OMPClause *Sema::ActOnOpenMPDefaultmapClause(
13993 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
13994 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
13995 SourceLocation KindLoc, SourceLocation EndLoc) {
13996 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000013997 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013998 std::string Value;
13999 SourceLocation Loc;
14000 Value += "'";
14001 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14002 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014003 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014004 Loc = MLoc;
14005 } else {
14006 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014007 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014008 Loc = KindLoc;
14009 }
14010 Value += "'";
14011 Diag(Loc, diag::err_omp_unexpected_clause_value)
14012 << Value << getOpenMPClauseName(OMPC_defaultmap);
14013 return nullptr;
14014 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014015 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014016
14017 return new (Context)
14018 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14019}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014020
14021bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14022 DeclContext *CurLexicalContext = getCurLexicalContext();
14023 if (!CurLexicalContext->isFileContext() &&
14024 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014025 !CurLexicalContext->isExternCXXContext() &&
14026 !isa<CXXRecordDecl>(CurLexicalContext) &&
14027 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14028 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14029 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014030 Diag(Loc, diag::err_omp_region_not_file_context);
14031 return false;
14032 }
Kelvin Libc38e632018-09-10 02:07:09 +000014033 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014034 return true;
14035}
14036
14037void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014038 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014039 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014040 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014041}
14042
David Majnemer9d168222016-08-05 17:44:54 +000014043void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14044 CXXScopeSpec &ScopeSpec,
14045 const DeclarationNameInfo &Id,
14046 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14047 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014048 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14049 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14050
14051 if (Lookup.isAmbiguous())
14052 return;
14053 Lookup.suppressDiagnostics();
14054
14055 if (!Lookup.isSingleResult()) {
14056 if (TypoCorrection Corrected =
14057 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
14058 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
14059 CTK_ErrorRecovery)) {
14060 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14061 << Id.getName());
14062 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14063 return;
14064 }
14065
14066 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14067 return;
14068 }
14069
14070 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014071 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14072 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014073 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14074 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014075 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14076 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14077 cast<ValueDecl>(ND));
14078 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014079 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014080 ND->addAttr(A);
14081 if (ASTMutationListener *ML = Context.getASTMutationListener())
14082 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014083 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014084 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014085 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14086 << Id.getName();
14087 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014088 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014089 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014090 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014091}
14092
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014093static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14094 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014095 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014096 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014097 auto *VD = cast<VarDecl>(D);
14098 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14099 return;
14100 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14101 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014102}
14103
14104static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14105 Sema &SemaRef, DSAStackTy *Stack,
14106 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014107 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14108 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14109 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014110}
14111
Kelvin Li1ce87c72017-12-12 20:08:12 +000014112void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14113 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014114 if (!D || D->isInvalidDecl())
14115 return;
14116 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014117 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014118 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014119 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014120 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14121 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014122 return;
14123 // 2.10.6: threadprivate variable cannot appear in a declare target
14124 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014125 if (DSAStack->isThreadPrivate(VD)) {
14126 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014127 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014128 return;
14129 }
14130 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014131 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14132 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014133 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014134 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14135 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14136 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014137 assert(IdLoc.isValid() && "Source location is expected");
14138 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14139 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14140 return;
14141 }
14142 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014143 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14144 // Problem if any with var declared with incomplete type will be reported
14145 // as normal, so no need to check it here.
14146 if ((E || !VD->getType()->isIncompleteType()) &&
14147 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14148 return;
14149 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14150 // Checking declaration inside declare target region.
14151 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14152 isa<FunctionTemplateDecl>(D)) {
14153 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14154 Context, OMPDeclareTargetDeclAttr::MT_To);
14155 D->addAttr(A);
14156 if (ASTMutationListener *ML = Context.getASTMutationListener())
14157 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14158 }
14159 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014160 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014161 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014162 if (!E)
14163 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014164 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14165}
Samuel Antao661c0902016-05-26 17:39:58 +000014166
14167OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014168 CXXScopeSpec &MapperIdScopeSpec,
14169 DeclarationNameInfo &MapperId,
14170 const OMPVarListLocTy &Locs,
14171 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014172 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014173 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14174 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014175 if (MVLI.ProcessedVarList.empty())
14176 return nullptr;
14177
Michael Kruse01f670d2019-02-22 22:29:42 +000014178 return OMPToClause::Create(
14179 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14180 MVLI.VarComponents, MVLI.UDMapperList,
14181 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014182}
Samuel Antaoec172c62016-05-26 17:49:04 +000014183
14184OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014185 const OMPVarListLocTy &Locs) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014186 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014187 CXXScopeSpec MapperIdScopeSpec;
14188 DeclarationNameInfo MapperId;
14189 ArrayRef<Expr *> UnresolvedMappers;
14190 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14191 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014192 if (MVLI.ProcessedVarList.empty())
14193 return nullptr;
14194
Michael Kruse4304e9d2019-02-19 16:38:20 +000014195 return OMPFromClause::Create(Context, Locs, MVLI.ProcessedVarList,
14196 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Samuel Antaoec172c62016-05-26 17:49:04 +000014197}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014198
14199OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014200 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014201 MappableVarListInfo MVLI(VarList);
14202 SmallVector<Expr *, 8> PrivateCopies;
14203 SmallVector<Expr *, 8> Inits;
14204
Alexey Bataeve3727102018-04-18 15:57:46 +000014205 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014206 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14207 SourceLocation ELoc;
14208 SourceRange ERange;
14209 Expr *SimpleRefExpr = RefExpr;
14210 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14211 if (Res.second) {
14212 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014213 MVLI.ProcessedVarList.push_back(RefExpr);
14214 PrivateCopies.push_back(nullptr);
14215 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014216 }
14217 ValueDecl *D = Res.first;
14218 if (!D)
14219 continue;
14220
14221 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014222 Type = Type.getNonReferenceType().getUnqualifiedType();
14223
14224 auto *VD = dyn_cast<VarDecl>(D);
14225
14226 // Item should be a pointer or reference to pointer.
14227 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014228 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14229 << 0 << RefExpr->getSourceRange();
14230 continue;
14231 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014232
14233 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014234 auto VDPrivate =
14235 buildVarDecl(*this, ELoc, Type, D->getName(),
14236 D->hasAttrs() ? &D->getAttrs() : nullptr,
14237 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014238 if (VDPrivate->isInvalidDecl())
14239 continue;
14240
14241 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014242 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014243 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14244
14245 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014246 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014247 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014248 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14249 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014250 AddInitializerToDecl(VDPrivate,
14251 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014252 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014253
14254 // If required, build a capture to implement the privatization initialized
14255 // with the current list item value.
14256 DeclRefExpr *Ref = nullptr;
14257 if (!VD)
14258 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14259 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14260 PrivateCopies.push_back(VDPrivateRefExpr);
14261 Inits.push_back(VDInitRefExpr);
14262
14263 // We need to add a data sharing attribute for this variable to make sure it
14264 // is correctly captured. A variable that shows up in a use_device_ptr has
14265 // similar properties of a first private variable.
14266 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14267
14268 // Create a mappable component for the list item. List items in this clause
14269 // only need a component.
14270 MVLI.VarBaseDeclarations.push_back(D);
14271 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14272 MVLI.VarComponents.back().push_back(
14273 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014274 }
14275
Samuel Antaocc10b852016-07-28 14:23:26 +000014276 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014277 return nullptr;
14278
Samuel Antaocc10b852016-07-28 14:23:26 +000014279 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014280 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14281 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014282}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014283
14284OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014285 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014286 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014287 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014288 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014289 SourceLocation ELoc;
14290 SourceRange ERange;
14291 Expr *SimpleRefExpr = RefExpr;
14292 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14293 if (Res.second) {
14294 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014295 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014296 }
14297 ValueDecl *D = Res.first;
14298 if (!D)
14299 continue;
14300
14301 QualType Type = D->getType();
14302 // item should be a pointer or array or reference to pointer or array
14303 if (!Type.getNonReferenceType()->isPointerType() &&
14304 !Type.getNonReferenceType()->isArrayType()) {
14305 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14306 << 0 << RefExpr->getSourceRange();
14307 continue;
14308 }
Samuel Antao6890b092016-07-28 14:25:09 +000014309
14310 // Check if the declaration in the clause does not show up in any data
14311 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014312 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014313 if (isOpenMPPrivate(DVar.CKind)) {
14314 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14315 << getOpenMPClauseName(DVar.CKind)
14316 << getOpenMPClauseName(OMPC_is_device_ptr)
14317 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014318 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014319 continue;
14320 }
14321
Alexey Bataeve3727102018-04-18 15:57:46 +000014322 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014323 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014324 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014325 [&ConflictExpr](
14326 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14327 OpenMPClauseKind) -> bool {
14328 ConflictExpr = R.front().getAssociatedExpression();
14329 return true;
14330 })) {
14331 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14332 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14333 << ConflictExpr->getSourceRange();
14334 continue;
14335 }
14336
14337 // Store the components in the stack so that they can be used to check
14338 // against other clauses later on.
14339 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14340 DSAStack->addMappableExpressionComponents(
14341 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14342
14343 // Record the expression we've just processed.
14344 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14345
14346 // Create a mappable component for the list item. List items in this clause
14347 // only need a component. We use a null declaration to signal fields in
14348 // 'this'.
14349 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14350 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14351 "Unexpected device pointer expression!");
14352 MVLI.VarBaseDeclarations.push_back(
14353 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14354 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14355 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014356 }
14357
Samuel Antao6890b092016-07-28 14:25:09 +000014358 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014359 return nullptr;
14360
Michael Kruse4304e9d2019-02-19 16:38:20 +000014361 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14362 MVLI.VarBaseDeclarations,
14363 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014364}