Bug Summary

File:clang/lib/Sema/SemaOpenMP.cpp
Warning:line 1216, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaOpenMP.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-04-14-063029-18377-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp

1//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements semantic analysis for OpenMP directives and
10/// clauses.
11///
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclOpenMP.h"
21#include "clang/AST/OpenMPClause.h"
22#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeOrdering.h"
26#include "clang/Basic/DiagnosticSema.h"
27#include "clang/Basic/OpenMPKinds.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/SemaInternal.h"
35#include "llvm/ADT/IndexedMap.h"
36#include "llvm/ADT/PointerEmbeddedInt.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/Frontend/OpenMP/OMPConstants.h"
40#include <set>
41
42using namespace clang;
43using namespace llvm::omp;
44
45//===----------------------------------------------------------------------===//
46// Stack of data-sharing attributes for variables
47//===----------------------------------------------------------------------===//
48
49static const Expr *checkMapClauseExpressionBase(
50 Sema &SemaRef, Expr *E,
51 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
52 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose);
53
54namespace {
55/// Default data sharing attributes, which can be applied to directive.
56enum DefaultDataSharingAttributes {
57 DSA_unspecified = 0, /// Data sharing attribute not specified.
58 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
59 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
60 DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'.
61};
62
63/// Stack for tracking declarations used in OpenMP directives and
64/// clauses and their data-sharing attributes.
65class DSAStackTy {
66public:
67 struct DSAVarData {
68 OpenMPDirectiveKind DKind = OMPD_unknown;
69 OpenMPClauseKind CKind = OMPC_unknown;
70 unsigned Modifier = 0;
71 const Expr *RefExpr = nullptr;
72 DeclRefExpr *PrivateCopy = nullptr;
73 SourceLocation ImplicitDSALoc;
74 bool AppliedToPointee = false;
75 DSAVarData() = default;
76 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
77 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
78 SourceLocation ImplicitDSALoc, unsigned Modifier,
79 bool AppliedToPointee)
80 : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
81 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
82 AppliedToPointee(AppliedToPointee) {}
83 };
84 using OperatorOffsetTy =
85 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
86 using DoacrossDependMapTy =
87 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
88 /// Kind of the declaration used in the uses_allocators clauses.
89 enum class UsesAllocatorsDeclKind {
90 /// Predefined allocator
91 PredefinedAllocator,
92 /// User-defined allocator
93 UserDefinedAllocator,
94 /// The declaration that represent allocator trait
95 AllocatorTrait,
96 };
97
98private:
99 struct DSAInfo {
100 OpenMPClauseKind Attributes = OMPC_unknown;
101 unsigned Modifier = 0;
102 /// Pointer to a reference expression and a flag which shows that the
103 /// variable is marked as lastprivate(true) or not (false).
104 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
105 DeclRefExpr *PrivateCopy = nullptr;
106 /// true if the attribute is applied to the pointee, not the variable
107 /// itself.
108 bool AppliedToPointee = false;
109 };
110 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
111 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
112 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
113 using LoopControlVariablesMapTy =
114 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
115 /// Struct that associates a component with the clause kind where they are
116 /// found.
117 struct MappedExprComponentTy {
118 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
119 OpenMPClauseKind Kind = OMPC_unknown;
120 };
121 using MappedExprComponentsTy =
122 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
123 using CriticalsWithHintsTy =
124 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
125 struct ReductionData {
126 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
127 SourceRange ReductionRange;
128 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
129 ReductionData() = default;
130 void set(BinaryOperatorKind BO, SourceRange RR) {
131 ReductionRange = RR;
132 ReductionOp = BO;
133 }
134 void set(const Expr *RefExpr, SourceRange RR) {
135 ReductionRange = RR;
136 ReductionOp = RefExpr;
137 }
138 };
139 using DeclReductionMapTy =
140 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
141 struct DefaultmapInfo {
142 OpenMPDefaultmapClauseModifier ImplicitBehavior =
143 OMPC_DEFAULTMAP_MODIFIER_unknown;
144 SourceLocation SLoc;
145 DefaultmapInfo() = default;
146 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
147 : ImplicitBehavior(M), SLoc(Loc) {}
148 };
149
150 struct SharingMapTy {
151 DeclSAMapTy SharingMap;
152 DeclReductionMapTy ReductionMap;
153 UsedRefMapTy AlignedMap;
154 UsedRefMapTy NontemporalMap;
155 MappedExprComponentsTy MappedExprComponents;
156 LoopControlVariablesMapTy LCVMap;
157 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
158 SourceLocation DefaultAttrLoc;
159 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
160 OpenMPDirectiveKind Directive = OMPD_unknown;
161 DeclarationNameInfo DirectiveName;
162 Scope *CurScope = nullptr;
163 DeclContext *Context = nullptr;
164 SourceLocation ConstructLoc;
165 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
166 /// get the data (loop counters etc.) about enclosing loop-based construct.
167 /// This data is required during codegen.
168 DoacrossDependMapTy DoacrossDepends;
169 /// First argument (Expr *) contains optional argument of the
170 /// 'ordered' clause, the second one is true if the regions has 'ordered'
171 /// clause, false otherwise.
172 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
173 unsigned AssociatedLoops = 1;
174 bool HasMutipleLoops = false;
175 const Decl *PossiblyLoopCounter = nullptr;
176 bool NowaitRegion = false;
177 bool CancelRegion = false;
178 bool LoopStart = false;
179 bool BodyComplete = false;
180 SourceLocation PrevScanLocation;
181 SourceLocation PrevOrderedLocation;
182 SourceLocation InnerTeamsRegionLoc;
183 /// Reference to the taskgroup task_reduction reference expression.
184 Expr *TaskgroupReductionRef = nullptr;
185 llvm::DenseSet<QualType> MappedClassesQualTypes;
186 SmallVector<Expr *, 4> InnerUsedAllocators;
187 llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
188 /// List of globals marked as declare target link in this target region
189 /// (isOpenMPTargetExecutionDirective(Directive) == true).
190 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
191 /// List of decls used in inclusive/exclusive clauses of the scan directive.
192 llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
193 llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
194 UsesAllocatorsDecls;
195 Expr *DeclareMapperVar = nullptr;
196 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
197 Scope *CurScope, SourceLocation Loc)
198 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
199 ConstructLoc(Loc) {}
200 SharingMapTy() = default;
201 };
202
203 using StackTy = SmallVector<SharingMapTy, 4>;
204
205 /// Stack of used declaration and their data-sharing attributes.
206 DeclSAMapTy Threadprivates;
207 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
208 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
209 /// true, if check for DSA must be from parent directive, false, if
210 /// from current directive.
211 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
212 Sema &SemaRef;
213 bool ForceCapturing = false;
214 /// true if all the variables in the target executable directives must be
215 /// captured by reference.
216 bool ForceCaptureByReferenceInTargetExecutable = false;
217 CriticalsWithHintsTy Criticals;
218 unsigned IgnoredStackElements = 0;
219
220 /// Iterators over the stack iterate in order from innermost to outermost
221 /// directive.
222 using const_iterator = StackTy::const_reverse_iterator;
223 const_iterator begin() const {
224 return Stack.empty() ? const_iterator()
225 : Stack.back().first.rbegin() + IgnoredStackElements;
226 }
227 const_iterator end() const {
228 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
229 }
230 using iterator = StackTy::reverse_iterator;
231 iterator begin() {
232 return Stack.empty() ? iterator()
233 : Stack.back().first.rbegin() + IgnoredStackElements;
234 }
235 iterator end() {
236 return Stack.empty() ? iterator() : Stack.back().first.rend();
237 }
238
239 // Convenience operations to get at the elements of the stack.
240
241 bool isStackEmpty() const {
242 return Stack.empty() ||
243 Stack.back().second != CurrentNonCapturingFunctionScope ||
244 Stack.back().first.size() <= IgnoredStackElements;
245 }
246 size_t getStackSize() const {
247 return isStackEmpty() ? 0
248 : Stack.back().first.size() - IgnoredStackElements;
249 }
250
251 SharingMapTy *getTopOfStackOrNull() {
252 size_t Size = getStackSize();
253 if (Size == 0)
254 return nullptr;
255 return &Stack.back().first[Size - 1];
256 }
257 const SharingMapTy *getTopOfStackOrNull() const {
258 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
259 }
260 SharingMapTy &getTopOfStack() {
261 assert(!isStackEmpty() && "no current directive")((!isStackEmpty() && "no current directive") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && \"no current directive\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 261, __PRETTY_FUNCTION__))
;
262 return *getTopOfStackOrNull();
263 }
264 const SharingMapTy &getTopOfStack() const {
265 return const_cast<DSAStackTy&>(*this).getTopOfStack();
266 }
267
268 SharingMapTy *getSecondOnStackOrNull() {
269 size_t Size = getStackSize();
270 if (Size <= 1)
271 return nullptr;
272 return &Stack.back().first[Size - 2];
273 }
274 const SharingMapTy *getSecondOnStackOrNull() const {
275 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
276 }
277
278 /// Get the stack element at a certain level (previously returned by
279 /// \c getNestingLevel).
280 ///
281 /// Note that nesting levels count from outermost to innermost, and this is
282 /// the reverse of our iteration order where new inner levels are pushed at
283 /// the front of the stack.
284 SharingMapTy &getStackElemAtLevel(unsigned Level) {
285 assert(Level < getStackSize() && "no such stack element")((Level < getStackSize() && "no such stack element"
) ? static_cast<void> (0) : __assert_fail ("Level < getStackSize() && \"no such stack element\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 285, __PRETTY_FUNCTION__))
;
286 return Stack.back().first[Level];
287 }
288 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
289 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
290 }
291
292 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
293
294 /// Checks if the variable is a local for OpenMP region.
295 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
296
297 /// Vector of previously declared requires directives
298 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
299 /// omp_allocator_handle_t type.
300 QualType OMPAllocatorHandleT;
301 /// omp_depend_t type.
302 QualType OMPDependT;
303 /// omp_event_handle_t type.
304 QualType OMPEventHandleT;
305 /// omp_alloctrait_t type.
306 QualType OMPAlloctraitT;
307 /// Expression for the predefined allocators.
308 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
309 nullptr};
310 /// Vector of previously encountered target directives
311 SmallVector<SourceLocation, 2> TargetLocations;
312 SourceLocation AtomicLocation;
313
314public:
315 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
316
317 /// Sets omp_allocator_handle_t type.
318 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
319 /// Gets omp_allocator_handle_t type.
320 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
321 /// Sets omp_alloctrait_t type.
322 void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
323 /// Gets omp_alloctrait_t type.
324 QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
325 /// Sets the given default allocator.
326 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
327 Expr *Allocator) {
328 OMPPredefinedAllocators[AllocatorKind] = Allocator;
329 }
330 /// Returns the specified default allocator.
331 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
332 return OMPPredefinedAllocators[AllocatorKind];
333 }
334 /// Sets omp_depend_t type.
335 void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
336 /// Gets omp_depend_t type.
337 QualType getOMPDependT() const { return OMPDependT; }
338
339 /// Sets omp_event_handle_t type.
340 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
341 /// Gets omp_event_handle_t type.
342 QualType getOMPEventHandleT() const { return OMPEventHandleT; }
343
344 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
345 OpenMPClauseKind getClauseParsingMode() const {
346 assert(isClauseParsingMode() && "Must be in clause parsing mode.")((isClauseParsingMode() && "Must be in clause parsing mode."
) ? static_cast<void> (0) : __assert_fail ("isClauseParsingMode() && \"Must be in clause parsing mode.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 346, __PRETTY_FUNCTION__))
;
347 return ClauseKindMode;
348 }
349 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
350
351 bool isBodyComplete() const {
352 const SharingMapTy *Top = getTopOfStackOrNull();
353 return Top && Top->BodyComplete;
354 }
355 void setBodyComplete() {
356 getTopOfStack().BodyComplete = true;
357 }
358
359 bool isForceVarCapturing() const { return ForceCapturing; }
360 void setForceVarCapturing(bool V) { ForceCapturing = V; }
361
362 void setForceCaptureByReferenceInTargetExecutable(bool V) {
363 ForceCaptureByReferenceInTargetExecutable = V;
364 }
365 bool isForceCaptureByReferenceInTargetExecutable() const {
366 return ForceCaptureByReferenceInTargetExecutable;
367 }
368
369 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
370 Scope *CurScope, SourceLocation Loc) {
371 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 372, __PRETTY_FUNCTION__))
372 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 372, __PRETTY_FUNCTION__))
;
373 if (Stack.empty() ||
374 Stack.back().second != CurrentNonCapturingFunctionScope)
375 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
376 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
377 Stack.back().first.back().DefaultAttrLoc = Loc;
378 }
379
380 void pop() {
381 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 382, __PRETTY_FUNCTION__))
382 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 382, __PRETTY_FUNCTION__))
;
383 assert(!Stack.back().first.empty() &&((!Stack.back().first.empty() && "Data-sharing attributes stack is empty!"
) ? static_cast<void> (0) : __assert_fail ("!Stack.back().first.empty() && \"Data-sharing attributes stack is empty!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 384, __PRETTY_FUNCTION__))
384 "Data-sharing attributes stack is empty!")((!Stack.back().first.empty() && "Data-sharing attributes stack is empty!"
) ? static_cast<void> (0) : __assert_fail ("!Stack.back().first.empty() && \"Data-sharing attributes stack is empty!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 384, __PRETTY_FUNCTION__))
;
385 Stack.back().first.pop_back();
386 }
387
388 /// RAII object to temporarily leave the scope of a directive when we want to
389 /// logically operate in its parent.
390 class ParentDirectiveScope {
391 DSAStackTy &Self;
392 bool Active;
393 public:
394 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
395 : Self(Self), Active(false) {
396 if (Activate)
397 enable();
398 }
399 ~ParentDirectiveScope() { disable(); }
400 void disable() {
401 if (Active) {
402 --Self.IgnoredStackElements;
403 Active = false;
404 }
405 }
406 void enable() {
407 if (!Active) {
408 ++Self.IgnoredStackElements;
409 Active = true;
410 }
411 }
412 };
413
414 /// Marks that we're started loop parsing.
415 void loopInit() {
416 assert(isOpenMPLoopDirective(getCurrentDirective()) &&((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 417, __PRETTY_FUNCTION__))
417 "Expected loop-based directive.")((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 417, __PRETTY_FUNCTION__))
;
418 getTopOfStack().LoopStart = true;
419 }
420 /// Start capturing of the variables in the loop context.
421 void loopStart() {
422 assert(isOpenMPLoopDirective(getCurrentDirective()) &&((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 423, __PRETTY_FUNCTION__))
423 "Expected loop-based directive.")((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 423, __PRETTY_FUNCTION__))
;
424 getTopOfStack().LoopStart = false;
425 }
426 /// true, if variables are captured, false otherwise.
427 bool isLoopStarted() const {
428 assert(isOpenMPLoopDirective(getCurrentDirective()) &&((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 429, __PRETTY_FUNCTION__))
429 "Expected loop-based directive.")((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 429, __PRETTY_FUNCTION__))
;
430 return !getTopOfStack().LoopStart;
431 }
432 /// Marks (or clears) declaration as possibly loop counter.
433 void resetPossibleLoopCounter(const Decl *D = nullptr) {
434 getTopOfStack().PossiblyLoopCounter =
435 D ? D->getCanonicalDecl() : D;
436 }
437 /// Gets the possible loop counter decl.
438 const Decl *getPossiblyLoopCunter() const {
439 return getTopOfStack().PossiblyLoopCounter;
440 }
441 /// Start new OpenMP region stack in new non-capturing function.
442 void pushFunction() {
443 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 444, __PRETTY_FUNCTION__))
444 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 444, __PRETTY_FUNCTION__))
;
445 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
446 assert(!isa<CapturingScopeInfo>(CurFnScope))((!isa<CapturingScopeInfo>(CurFnScope)) ? static_cast<
void> (0) : __assert_fail ("!isa<CapturingScopeInfo>(CurFnScope)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 446, __PRETTY_FUNCTION__))
;
447 CurrentNonCapturingFunctionScope = CurFnScope;
448 }
449 /// Pop region stack for non-capturing function.
450 void popFunction(const FunctionScopeInfo *OldFSI) {
451 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 452, __PRETTY_FUNCTION__))
452 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 452, __PRETTY_FUNCTION__))
;
453 if (!Stack.empty() && Stack.back().second == OldFSI) {
454 assert(Stack.back().first.empty())((Stack.back().first.empty()) ? static_cast<void> (0) :
__assert_fail ("Stack.back().first.empty()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 454, __PRETTY_FUNCTION__))
;
455 Stack.pop_back();
456 }
457 CurrentNonCapturingFunctionScope = nullptr;
458 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
459 if (!isa<CapturingScopeInfo>(FSI)) {
460 CurrentNonCapturingFunctionScope = FSI;
461 break;
462 }
463 }
464 }
465
466 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
467 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
468 }
469 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
470 getCriticalWithHint(const DeclarationNameInfo &Name) const {
471 auto I = Criticals.find(Name.getAsString());
472 if (I != Criticals.end())
473 return I->second;
474 return std::make_pair(nullptr, llvm::APSInt());
475 }
476 /// If 'aligned' declaration for given variable \a D was not seen yet,
477 /// add it and return NULL; otherwise return previous occurrence's expression
478 /// for diagnostics.
479 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
480 /// If 'nontemporal' declaration for given variable \a D was not seen yet,
481 /// add it and return NULL; otherwise return previous occurrence's expression
482 /// for diagnostics.
483 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
484
485 /// Register specified variable as loop control variable.
486 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
487 /// Check if the specified variable is a loop control variable for
488 /// current region.
489 /// \return The index of the loop control variable in the list of associated
490 /// for-loops (from outer to inner).
491 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
492 /// Check if the specified variable is a loop control variable for
493 /// parent region.
494 /// \return The index of the loop control variable in the list of associated
495 /// for-loops (from outer to inner).
496 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
497 /// Check if the specified variable is a loop control variable for
498 /// current region.
499 /// \return The index of the loop control variable in the list of associated
500 /// for-loops (from outer to inner).
501 const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
502 unsigned Level) const;
503 /// Get the loop control variable for the I-th loop (or nullptr) in
504 /// parent directive.
505 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
506
507 /// Marks the specified decl \p D as used in scan directive.
508 void markDeclAsUsedInScanDirective(ValueDecl *D) {
509 if (SharingMapTy *Stack = getSecondOnStackOrNull())
510 Stack->UsedInScanDirective.insert(D);
511 }
512
513 /// Checks if the specified declaration was used in the inner scan directive.
514 bool isUsedInScanDirective(ValueDecl *D) const {
515 if (const SharingMapTy *Stack = getTopOfStackOrNull())
516 return Stack->UsedInScanDirective.count(D) > 0;
517 return false;
518 }
519
520 /// Adds explicit data sharing attribute to the specified declaration.
521 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
522 DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
523 bool AppliedToPointee = false);
524
525 /// Adds additional information for the reduction items with the reduction id
526 /// represented as an operator.
527 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
528 BinaryOperatorKind BOK);
529 /// Adds additional information for the reduction items with the reduction id
530 /// represented as reduction identifier.
531 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
532 const Expr *ReductionRef);
533 /// Returns the location and reduction operation from the innermost parent
534 /// region for the given \p D.
535 const DSAVarData
536 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
537 BinaryOperatorKind &BOK,
538 Expr *&TaskgroupDescriptor) const;
539 /// Returns the location and reduction operation from the innermost parent
540 /// region for the given \p D.
541 const DSAVarData
542 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
543 const Expr *&ReductionRef,
544 Expr *&TaskgroupDescriptor) const;
545 /// Return reduction reference expression for the current taskgroup or
546 /// parallel/worksharing directives with task reductions.
547 Expr *getTaskgroupReductionRef() const {
548 assert((getTopOfStack().Directive == OMPD_taskgroup ||(((getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "taskgroup reference expression requested for non taskgroup or "
"parallel/worksharing directive.") ? static_cast<void>
(0) : __assert_fail ("(getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"taskgroup reference expression requested for non taskgroup or \" \"parallel/worksharing directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 553, __PRETTY_FUNCTION__))
549 ((isOpenMPParallelDirective(getTopOfStack().Directive) ||(((getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "taskgroup reference expression requested for non taskgroup or "
"parallel/worksharing directive.") ? static_cast<void>
(0) : __assert_fail ("(getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"taskgroup reference expression requested for non taskgroup or \" \"parallel/worksharing directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 553, __PRETTY_FUNCTION__))
550 isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&(((getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "taskgroup reference expression requested for non taskgroup or "
"parallel/worksharing directive.") ? static_cast<void>
(0) : __assert_fail ("(getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"taskgroup reference expression requested for non taskgroup or \" \"parallel/worksharing directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 553, __PRETTY_FUNCTION__))
551 !isOpenMPSimdDirective(getTopOfStack().Directive))) &&(((getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "taskgroup reference expression requested for non taskgroup or "
"parallel/worksharing directive.") ? static_cast<void>
(0) : __assert_fail ("(getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"taskgroup reference expression requested for non taskgroup or \" \"parallel/worksharing directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 553, __PRETTY_FUNCTION__))
552 "taskgroup reference expression requested for non taskgroup or "(((getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "taskgroup reference expression requested for non taskgroup or "
"parallel/worksharing directive.") ? static_cast<void>
(0) : __assert_fail ("(getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"taskgroup reference expression requested for non taskgroup or \" \"parallel/worksharing directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 553, __PRETTY_FUNCTION__))
553 "parallel/worksharing directive.")(((getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "taskgroup reference expression requested for non taskgroup or "
"parallel/worksharing directive.") ? static_cast<void>
(0) : __assert_fail ("(getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"taskgroup reference expression requested for non taskgroup or \" \"parallel/worksharing directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 553, __PRETTY_FUNCTION__))
;
554 return getTopOfStack().TaskgroupReductionRef;
555 }
556 /// Checks if the given \p VD declaration is actually a taskgroup reduction
557 /// descriptor variable at the \p Level of OpenMP regions.
558 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
559 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
560 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
561 ->getDecl() == VD;
562 }
563
564 /// Returns data sharing attributes from top of the stack for the
565 /// specified declaration.
566 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
567 /// Returns data-sharing attributes for the specified declaration.
568 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
569 /// Returns data-sharing attributes for the specified declaration.
570 const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
571 /// Checks if the specified variables has data-sharing attributes which
572 /// match specified \a CPred predicate in any directive which matches \a DPred
573 /// predicate.
574 const DSAVarData
575 hasDSA(ValueDecl *D,
576 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
577 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
578 bool FromParent) const;
579 /// Checks if the specified variables has data-sharing attributes which
580 /// match specified \a CPred predicate in any innermost directive which
581 /// matches \a DPred predicate.
582 const DSAVarData
583 hasInnermostDSA(ValueDecl *D,
584 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
585 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
586 bool FromParent) const;
587 /// Checks if the specified variables has explicit data-sharing
588 /// attributes which match specified \a CPred predicate at the specified
589 /// OpenMP region.
590 bool
591 hasExplicitDSA(const ValueDecl *D,
592 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
593 unsigned Level, bool NotLastprivate = false) const;
594
595 /// Returns true if the directive at level \Level matches in the
596 /// specified \a DPred predicate.
597 bool hasExplicitDirective(
598 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
599 unsigned Level) const;
600
601 /// Finds a directive which matches specified \a DPred predicate.
602 bool hasDirective(
603 const llvm::function_ref<bool(
604 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
605 DPred,
606 bool FromParent) const;
607
608 /// Returns currently analyzed directive.
609 OpenMPDirectiveKind getCurrentDirective() const {
610 const SharingMapTy *Top = getTopOfStackOrNull();
611 return Top ? Top->Directive : OMPD_unknown;
612 }
613 /// Returns directive kind at specified level.
614 OpenMPDirectiveKind getDirective(unsigned Level) const {
615 assert(!isStackEmpty() && "No directive at specified level.")((!isStackEmpty() && "No directive at specified level."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"No directive at specified level.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 615, __PRETTY_FUNCTION__))
;
616 return getStackElemAtLevel(Level).Directive;
617 }
618 /// Returns the capture region at the specified level.
619 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
620 unsigned OpenMPCaptureLevel) const {
621 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
622 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
623 return CaptureRegions[OpenMPCaptureLevel];
624 }
625 /// Returns parent directive.
626 OpenMPDirectiveKind getParentDirective() const {
627 const SharingMapTy *Parent = getSecondOnStackOrNull();
628 return Parent ? Parent->Directive : OMPD_unknown;
629 }
630
631 /// Add requires decl to internal vector
632 void addRequiresDecl(OMPRequiresDecl *RD) {
633 RequiresDecls.push_back(RD);
634 }
635
636 /// Checks if the defined 'requires' directive has specified type of clause.
637 template <typename ClauseType>
638 bool hasRequiresDeclWithClause() const {
639 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
640 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
641 return isa<ClauseType>(C);
642 });
643 });
644 }
645
646 /// Checks for a duplicate clause amongst previously declared requires
647 /// directives
648 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
649 bool IsDuplicate = false;
650 for (OMPClause *CNew : ClauseList) {
651 for (const OMPRequiresDecl *D : RequiresDecls) {
652 for (const OMPClause *CPrev : D->clauselists()) {
653 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
654 SemaRef.Diag(CNew->getBeginLoc(),
655 diag::err_omp_requires_clause_redeclaration)
656 << getOpenMPClauseName(CNew->getClauseKind());
657 SemaRef.Diag(CPrev->getBeginLoc(),
658 diag::note_omp_requires_previous_clause)
659 << getOpenMPClauseName(CPrev->getClauseKind());
660 IsDuplicate = true;
661 }
662 }
663 }
664 }
665 return IsDuplicate;
666 }
667
668 /// Add location of previously encountered target to internal vector
669 void addTargetDirLocation(SourceLocation LocStart) {
670 TargetLocations.push_back(LocStart);
671 }
672
673 /// Add location for the first encountered atomicc directive.
674 void addAtomicDirectiveLoc(SourceLocation Loc) {
675 if (AtomicLocation.isInvalid())
676 AtomicLocation = Loc;
677 }
678
679 /// Returns the location of the first encountered atomic directive in the
680 /// module.
681 SourceLocation getAtomicDirectiveLoc() const {
682 return AtomicLocation;
683 }
684
685 // Return previously encountered target region locations.
686 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
687 return TargetLocations;
688 }
689
690 /// Set default data sharing attribute to none.
691 void setDefaultDSANone(SourceLocation Loc) {
692 getTopOfStack().DefaultAttr = DSA_none;
693 getTopOfStack().DefaultAttrLoc = Loc;
694 }
695 /// Set default data sharing attribute to shared.
696 void setDefaultDSAShared(SourceLocation Loc) {
697 getTopOfStack().DefaultAttr = DSA_shared;
698 getTopOfStack().DefaultAttrLoc = Loc;
699 }
700 /// Set default data sharing attribute to firstprivate.
701 void setDefaultDSAFirstPrivate(SourceLocation Loc) {
702 getTopOfStack().DefaultAttr = DSA_firstprivate;
703 getTopOfStack().DefaultAttrLoc = Loc;
704 }
705 /// Set default data mapping attribute to Modifier:Kind
706 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
707 OpenMPDefaultmapClauseKind Kind,
708 SourceLocation Loc) {
709 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
710 DMI.ImplicitBehavior = M;
711 DMI.SLoc = Loc;
712 }
713 /// Check whether the implicit-behavior has been set in defaultmap
714 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
715 if (VariableCategory == OMPC_DEFAULTMAP_unknown)
716 return getTopOfStack()
717 .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
718 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
719 getTopOfStack()
720 .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
721 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
722 getTopOfStack()
723 .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
724 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
725 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
726 OMPC_DEFAULTMAP_MODIFIER_unknown;
727 }
728
729 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
730 return getStackSize() <= Level ? DSA_unspecified
731 : getStackElemAtLevel(Level).DefaultAttr;
732 }
733 DefaultDataSharingAttributes getDefaultDSA() const {
734 return isStackEmpty() ? DSA_unspecified
735 : getTopOfStack().DefaultAttr;
736 }
737 SourceLocation getDefaultDSALocation() const {
738 return isStackEmpty() ? SourceLocation()
739 : getTopOfStack().DefaultAttrLoc;
740 }
741 OpenMPDefaultmapClauseModifier
742 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
743 return isStackEmpty()
744 ? OMPC_DEFAULTMAP_MODIFIER_unknown
745 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
746 }
747 OpenMPDefaultmapClauseModifier
748 getDefaultmapModifierAtLevel(unsigned Level,
749 OpenMPDefaultmapClauseKind Kind) const {
750 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
751 }
752 bool isDefaultmapCapturedByRef(unsigned Level,
753 OpenMPDefaultmapClauseKind Kind) const {
754 OpenMPDefaultmapClauseModifier M =
755 getDefaultmapModifierAtLevel(Level, Kind);
756 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
757 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
758 (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
759 (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
760 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
761 }
762 return true;
763 }
764 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
765 OpenMPDefaultmapClauseKind Kind) {
766 switch (Kind) {
767 case OMPC_DEFAULTMAP_scalar:
768 case OMPC_DEFAULTMAP_pointer:
769 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
770 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
771 (M == OMPC_DEFAULTMAP_MODIFIER_default);
772 case OMPC_DEFAULTMAP_aggregate:
773 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
774 default:
775 break;
776 }
777 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum")::llvm::llvm_unreachable_internal("Unexpected OpenMPDefaultmapClauseKind enum"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 777)
;
778 }
779 bool mustBeFirstprivateAtLevel(unsigned Level,
780 OpenMPDefaultmapClauseKind Kind) const {
781 OpenMPDefaultmapClauseModifier M =
782 getDefaultmapModifierAtLevel(Level, Kind);
783 return mustBeFirstprivateBase(M, Kind);
784 }
785 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
786 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
787 return mustBeFirstprivateBase(M, Kind);
788 }
789
790 /// Checks if the specified variable is a threadprivate.
791 bool isThreadPrivate(VarDecl *D) {
792 const DSAVarData DVar = getTopDSA(D, false);
793 return isOpenMPThreadPrivate(DVar.CKind);
794 }
795
796 /// Marks current region as ordered (it has an 'ordered' clause).
797 void setOrderedRegion(bool IsOrdered, const Expr *Param,
798 OMPOrderedClause *Clause) {
799 if (IsOrdered)
800 getTopOfStack().OrderedRegion.emplace(Param, Clause);
801 else
802 getTopOfStack().OrderedRegion.reset();
803 }
804 /// Returns true, if region is ordered (has associated 'ordered' clause),
805 /// false - otherwise.
806 bool isOrderedRegion() const {
807 if (const SharingMapTy *Top = getTopOfStackOrNull())
808 return Top->OrderedRegion.hasValue();
809 return false;
810 }
811 /// Returns optional parameter for the ordered region.
812 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
813 if (const SharingMapTy *Top = getTopOfStackOrNull())
814 if (Top->OrderedRegion.hasValue())
815 return Top->OrderedRegion.getValue();
816 return std::make_pair(nullptr, nullptr);
817 }
818 /// Returns true, if parent region is ordered (has associated
819 /// 'ordered' clause), false - otherwise.
820 bool isParentOrderedRegion() const {
821 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
822 return Parent->OrderedRegion.hasValue();
823 return false;
824 }
825 /// Returns optional parameter for the ordered region.
826 std::pair<const Expr *, OMPOrderedClause *>
827 getParentOrderedRegionParam() const {
828 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
829 if (Parent->OrderedRegion.hasValue())
830 return Parent->OrderedRegion.getValue();
831 return std::make_pair(nullptr, nullptr);
832 }
833 /// Marks current region as nowait (it has a 'nowait' clause).
834 void setNowaitRegion(bool IsNowait = true) {
835 getTopOfStack().NowaitRegion = IsNowait;
836 }
837 /// Returns true, if parent region is nowait (has associated
838 /// 'nowait' clause), false - otherwise.
839 bool isParentNowaitRegion() const {
840 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
841 return Parent->NowaitRegion;
842 return false;
843 }
844 /// Marks parent region as cancel region.
845 void setParentCancelRegion(bool Cancel = true) {
846 if (SharingMapTy *Parent = getSecondOnStackOrNull())
847 Parent->CancelRegion |= Cancel;
848 }
849 /// Return true if current region has inner cancel construct.
850 bool isCancelRegion() const {
851 const SharingMapTy *Top = getTopOfStackOrNull();
852 return Top ? Top->CancelRegion : false;
853 }
854
855 /// Mark that parent region already has scan directive.
856 void setParentHasScanDirective(SourceLocation Loc) {
857 if (SharingMapTy *Parent = getSecondOnStackOrNull())
858 Parent->PrevScanLocation = Loc;
859 }
860 /// Return true if current region has inner cancel construct.
861 bool doesParentHasScanDirective() const {
862 const SharingMapTy *Top = getSecondOnStackOrNull();
863 return Top ? Top->PrevScanLocation.isValid() : false;
864 }
865 /// Return true if current region has inner cancel construct.
866 SourceLocation getParentScanDirectiveLoc() const {
867 const SharingMapTy *Top = getSecondOnStackOrNull();
868 return Top ? Top->PrevScanLocation : SourceLocation();
869 }
870 /// Mark that parent region already has ordered directive.
871 void setParentHasOrderedDirective(SourceLocation Loc) {
872 if (SharingMapTy *Parent = getSecondOnStackOrNull())
873 Parent->PrevOrderedLocation = Loc;
874 }
875 /// Return true if current region has inner ordered construct.
876 bool doesParentHasOrderedDirective() const {
877 const SharingMapTy *Top = getSecondOnStackOrNull();
878 return Top ? Top->PrevOrderedLocation.isValid() : false;
879 }
880 /// Returns the location of the previously specified ordered directive.
881 SourceLocation getParentOrderedDirectiveLoc() const {
882 const SharingMapTy *Top = getSecondOnStackOrNull();
883 return Top ? Top->PrevOrderedLocation : SourceLocation();
884 }
885
886 /// Set collapse value for the region.
887 void setAssociatedLoops(unsigned Val) {
888 getTopOfStack().AssociatedLoops = Val;
889 if (Val > 1)
890 getTopOfStack().HasMutipleLoops = true;
891 }
892 /// Return collapse value for region.
893 unsigned getAssociatedLoops() const {
894 const SharingMapTy *Top = getTopOfStackOrNull();
895 return Top ? Top->AssociatedLoops : 0;
896 }
897 /// Returns true if the construct is associated with multiple loops.
898 bool hasMutipleLoops() const {
899 const SharingMapTy *Top = getTopOfStackOrNull();
900 return Top ? Top->HasMutipleLoops : false;
901 }
902
903 /// Marks current target region as one with closely nested teams
904 /// region.
905 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
906 if (SharingMapTy *Parent = getSecondOnStackOrNull())
907 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
908 }
909 /// Returns true, if current region has closely nested teams region.
910 bool hasInnerTeamsRegion() const {
911 return getInnerTeamsRegionLoc().isValid();
912 }
913 /// Returns location of the nested teams region (if any).
914 SourceLocation getInnerTeamsRegionLoc() const {
915 const SharingMapTy *Top = getTopOfStackOrNull();
916 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
917 }
918
919 Scope *getCurScope() const {
920 const SharingMapTy *Top = getTopOfStackOrNull();
921 return Top ? Top->CurScope : nullptr;
922 }
923 void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
924 SourceLocation getConstructLoc() const {
925 const SharingMapTy *Top = getTopOfStackOrNull();
926 return Top ? Top->ConstructLoc : SourceLocation();
927 }
928
929 /// Do the check specified in \a Check to all component lists and return true
930 /// if any issue is found.
931 bool checkMappableExprComponentListsForDecl(
932 const ValueDecl *VD, bool CurrentRegionOnly,
933 const llvm::function_ref<
934 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
935 OpenMPClauseKind)>
936 Check) const {
937 if (isStackEmpty())
938 return false;
939 auto SI = begin();
940 auto SE = end();
941
942 if (SI == SE)
943 return false;
944
945 if (CurrentRegionOnly)
946 SE = std::next(SI);
947 else
948 std::advance(SI, 1);
949
950 for (; SI != SE; ++SI) {
951 auto MI = SI->MappedExprComponents.find(VD);
952 if (MI != SI->MappedExprComponents.end())
953 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
954 MI->second.Components)
955 if (Check(L, MI->second.Kind))
956 return true;
957 }
958 return false;
959 }
960
961 /// Do the check specified in \a Check to all component lists at a given level
962 /// and return true if any issue is found.
963 bool checkMappableExprComponentListsForDeclAtLevel(
964 const ValueDecl *VD, unsigned Level,
965 const llvm::function_ref<
966 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
967 OpenMPClauseKind)>
968 Check) const {
969 if (getStackSize() <= Level)
970 return false;
971
972 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
973 auto MI = StackElem.MappedExprComponents.find(VD);
974 if (MI != StackElem.MappedExprComponents.end())
975 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
976 MI->second.Components)
977 if (Check(L, MI->second.Kind))
978 return true;
979 return false;
980 }
981
982 /// Create a new mappable expression component list associated with a given
983 /// declaration and initialize it with the provided list of components.
984 void addMappableExpressionComponents(
985 const ValueDecl *VD,
986 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
987 OpenMPClauseKind WhereFoundClauseKind) {
988 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
989 // Create new entry and append the new components there.
990 MEC.Components.resize(MEC.Components.size() + 1);
991 MEC.Components.back().append(Components.begin(), Components.end());
992 MEC.Kind = WhereFoundClauseKind;
993 }
994
995 unsigned getNestingLevel() const {
996 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 996, __PRETTY_FUNCTION__))
;
997 return getStackSize() - 1;
998 }
999 void addDoacrossDependClause(OMPDependClause *C,
1000 const OperatorOffsetTy &OpsOffs) {
1001 SharingMapTy *Parent = getSecondOnStackOrNull();
1002 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive))((Parent && isOpenMPWorksharingDirective(Parent->Directive
)) ? static_cast<void> (0) : __assert_fail ("Parent && isOpenMPWorksharingDirective(Parent->Directive)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1002, __PRETTY_FUNCTION__))
;
1003 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
1004 }
1005 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
1006 getDoacrossDependClauses() const {
1007 const SharingMapTy &StackElem = getTopOfStack();
1008 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
1009 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
1010 return llvm::make_range(Ref.begin(), Ref.end());
1011 }
1012 return llvm::make_range(StackElem.DoacrossDepends.end(),
1013 StackElem.DoacrossDepends.end());
1014 }
1015
1016 // Store types of classes which have been explicitly mapped
1017 void addMappedClassesQualTypes(QualType QT) {
1018 SharingMapTy &StackElem = getTopOfStack();
1019 StackElem.MappedClassesQualTypes.insert(QT);
1020 }
1021
1022 // Return set of mapped classes types
1023 bool isClassPreviouslyMapped(QualType QT) const {
1024 const SharingMapTy &StackElem = getTopOfStack();
1025 return StackElem.MappedClassesQualTypes.count(QT) != 0;
1026 }
1027
1028 /// Adds global declare target to the parent target region.
1029 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1030 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(((*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->
getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && "Expected declare target link global."
) ? static_cast<void> (0) : __assert_fail ("*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && \"Expected declare target link global.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1032, __PRETTY_FUNCTION__))
1031 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&((*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->
getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && "Expected declare target link global."
) ? static_cast<void> (0) : __assert_fail ("*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && \"Expected declare target link global.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1032, __PRETTY_FUNCTION__))
1032 "Expected declare target link global.")((*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->
getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && "Expected declare target link global."
) ? static_cast<void> (0) : __assert_fail ("*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && \"Expected declare target link global.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1032, __PRETTY_FUNCTION__))
;
1033 for (auto &Elem : *this) {
1034 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1035 Elem.DeclareTargetLinkVarDecls.push_back(E);
1036 return;
1037 }
1038 }
1039 }
1040
1041 /// Returns the list of globals with declare target link if current directive
1042 /// is target.
1043 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1044 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&((isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
"Expected target executable directive.") ? static_cast<void
> (0) : __assert_fail ("isOpenMPTargetExecutionDirective(getCurrentDirective()) && \"Expected target executable directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1045, __PRETTY_FUNCTION__))
1045 "Expected target executable directive.")((isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
"Expected target executable directive.") ? static_cast<void
> (0) : __assert_fail ("isOpenMPTargetExecutionDirective(getCurrentDirective()) && \"Expected target executable directive.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1045, __PRETTY_FUNCTION__))
;
1046 return getTopOfStack().DeclareTargetLinkVarDecls;
1047 }
1048
1049 /// Adds list of allocators expressions.
1050 void addInnerAllocatorExpr(Expr *E) {
1051 getTopOfStack().InnerUsedAllocators.push_back(E);
1052 }
1053 /// Return list of used allocators.
1054 ArrayRef<Expr *> getInnerAllocators() const {
1055 return getTopOfStack().InnerUsedAllocators;
1056 }
1057 /// Marks the declaration as implicitly firstprivate nin the task-based
1058 /// regions.
1059 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1060 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1061 }
1062 /// Checks if the decl is implicitly firstprivate in the task-based region.
1063 bool isImplicitTaskFirstprivate(Decl *D) const {
1064 return getTopOfStack().ImplicitTaskFirstprivates.count(D) > 0;
1065 }
1066
1067 /// Marks decl as used in uses_allocators clause as the allocator.
1068 void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1069 getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1070 }
1071 /// Checks if specified decl is used in uses allocator clause as the
1072 /// allocator.
1073 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level,
1074 const Decl *D) const {
1075 const SharingMapTy &StackElem = getTopOfStack();
1076 auto I = StackElem.UsesAllocatorsDecls.find(D);
1077 if (I == StackElem.UsesAllocatorsDecls.end())
1078 return None;
1079 return I->getSecond();
1080 }
1081 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const {
1082 const SharingMapTy &StackElem = getTopOfStack();
1083 auto I = StackElem.UsesAllocatorsDecls.find(D);
1084 if (I == StackElem.UsesAllocatorsDecls.end())
1085 return None;
1086 return I->getSecond();
1087 }
1088
1089 void addDeclareMapperVarRef(Expr *Ref) {
1090 SharingMapTy &StackElem = getTopOfStack();
1091 StackElem.DeclareMapperVar = Ref;
1092 }
1093 const Expr *getDeclareMapperVarRef() const {
1094 const SharingMapTy *Top = getTopOfStackOrNull();
1095 return Top ? Top->DeclareMapperVar : nullptr;
1096 }
1097};
1098
1099bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1100 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1101}
1102
1103bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1104 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1105 DKind == OMPD_unknown;
1106}
1107
1108} // namespace
1109
1110static const Expr *getExprAsWritten(const Expr *E) {
1111 if (const auto *FE = dyn_cast<FullExpr>(E))
1112 E = FE->getSubExpr();
1113
1114 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1115 E = MTE->getSubExpr();
1116
1117 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1118 E = Binder->getSubExpr();
1119
1120 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1121 E = ICE->getSubExprAsWritten();
1122 return E->IgnoreParens();
1123}
1124
1125static Expr *getExprAsWritten(Expr *E) {
1126 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1127}
1128
1129static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1130 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1131 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1132 D = ME->getMemberDecl();
1133 const auto *VD = dyn_cast<VarDecl>(D);
1134 const auto *FD = dyn_cast<FieldDecl>(D);
1135 if (VD != nullptr) {
1136 VD = VD->getCanonicalDecl();
1137 D = VD;
1138 } else {
1139 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1139, __PRETTY_FUNCTION__))
;
1140 FD = FD->getCanonicalDecl();
1141 D = FD;
1142 }
1143 return D;
1144}
1145
1146static ValueDecl *getCanonicalDecl(ValueDecl *D) {
1147 return const_cast<ValueDecl *>(
1148 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1149}
1150
1151DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1152 ValueDecl *D) const {
1153 D = getCanonicalDecl(D);
1154 auto *VD = dyn_cast<VarDecl>(D);
13
Assuming 'D' is not a 'VarDecl'
14
'VD' initialized to a null pointer value
1155 const auto *FD = dyn_cast<FieldDecl>(D);
15
Assuming 'D' is not a 'FieldDecl'
1156 DSAVarData DVar;
1157 if (Iter == end()) {
16
Calling 'operator==<const (anonymous namespace)::DSAStackTy::SharingMapTy *>'
19
Returning from 'operator==<const (anonymous namespace)::DSAStackTy::SharingMapTy *>'
20
Taking false branch
1158 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1159 // in a region but not in construct]
1160 // File-scope or namespace-scope variables referenced in called routines
1161 // in the region are shared unless they appear in a threadprivate
1162 // directive.
1163 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
1164 DVar.CKind = OMPC_shared;
1165
1166 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1167 // in a region but not in construct]
1168 // Variables with static storage duration that are declared in called
1169 // routines in the region are shared.
1170 if (VD && VD->hasGlobalStorage())
1171 DVar.CKind = OMPC_shared;
1172
1173 // Non-static data members are shared by default.
1174 if (FD)
1175 DVar.CKind = OMPC_shared;
1176
1177 return DVar;
1178 }
1179
1180 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1181 // in a Construct, C/C++, predetermined, p.1]
1182 // Variables with automatic storage duration that are declared in a scope
1183 // inside the construct are private.
1184 if (VD
20.1
'VD' is null
20.1
'VD' is null
&& isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1185 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1186 DVar.CKind = OMPC_private;
1187 return DVar;
1188 }
1189
1190 DVar.DKind = Iter->Directive;
1191 // Explicitly specified attributes and local variables with predetermined
1192 // attributes.
1193 if (Iter->SharingMap.count(D)) {
21
Assuming the condition is false
22
Taking false branch
1194 const DSAInfo &Data = Iter->SharingMap.lookup(D);
1195 DVar.RefExpr = Data.RefExpr.getPointer();
1196 DVar.PrivateCopy = Data.PrivateCopy;
1197 DVar.CKind = Data.Attributes;
1198 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1199 DVar.Modifier = Data.Modifier;
1200 DVar.AppliedToPointee = Data.AppliedToPointee;
1201 return DVar;
1202 }
1203
1204 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1205 // in a Construct, C/C++, implicitly determined, p.1]
1206 // In a parallel or task construct, the data-sharing attributes of these
1207 // variables are determined by the default clause, if present.
1208 switch (Iter->DefaultAttr) {
23
Control jumps to 'case DSA_firstprivate:' at line 1215
1209 case DSA_shared:
1210 DVar.CKind = OMPC_shared;
1211 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1212 return DVar;
1213 case DSA_none:
1214 return DVar;
1215 case DSA_firstprivate:
1216 if (VD->getStorageDuration() == SD_Static &&
24
Called C++ object pointer is null
1217 VD->getDeclContext()->isFileContext()) {
1218 DVar.CKind = OMPC_unknown;
1219 } else {
1220 DVar.CKind = OMPC_firstprivate;
1221 }
1222 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1223 return DVar;
1224 case DSA_unspecified:
1225 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1226 // in a Construct, implicitly determined, p.2]
1227 // In a parallel construct, if no default clause is present, these
1228 // variables are shared.
1229 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1230 if ((isOpenMPParallelDirective(DVar.DKind) &&
1231 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1232 isOpenMPTeamsDirective(DVar.DKind)) {
1233 DVar.CKind = OMPC_shared;
1234 return DVar;
1235 }
1236
1237 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1238 // in a Construct, implicitly determined, p.4]
1239 // In a task construct, if no default clause is present, a variable that in
1240 // the enclosing context is determined to be shared by all implicit tasks
1241 // bound to the current team is shared.
1242 if (isOpenMPTaskingDirective(DVar.DKind)) {
1243 DSAVarData DVarTemp;
1244 const_iterator I = Iter, E = end();
1245 do {
1246 ++I;
1247 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1248 // Referenced in a Construct, implicitly determined, p.6]
1249 // In a task construct, if no default clause is present, a variable
1250 // whose data-sharing attribute is not determined by the rules above is
1251 // firstprivate.
1252 DVarTemp = getDSA(I, D);
1253 if (DVarTemp.CKind != OMPC_shared) {
1254 DVar.RefExpr = nullptr;
1255 DVar.CKind = OMPC_firstprivate;
1256 return DVar;
1257 }
1258 } while (I != E && !isImplicitTaskingRegion(I->Directive));
1259 DVar.CKind =
1260 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1261 return DVar;
1262 }
1263 }
1264 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1265 // in a Construct, implicitly determined, p.3]
1266 // For constructs other than task, if no default clause is present, these
1267 // variables inherit their data-sharing attributes from the enclosing
1268 // context.
1269 return getDSA(++Iter, D);
1270}
1271
1272const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1273 const Expr *NewDE) {
1274 assert(!isStackEmpty() && "Data sharing attributes stack is empty")((!isStackEmpty() && "Data sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1274, __PRETTY_FUNCTION__))
;
1275 D = getCanonicalDecl(D);
1276 SharingMapTy &StackElem = getTopOfStack();
1277 auto It = StackElem.AlignedMap.find(D);
1278 if (It == StackElem.AlignedMap.end()) {
1279 assert(NewDE && "Unexpected nullptr expr to be added into aligned map")((NewDE && "Unexpected nullptr expr to be added into aligned map"
) ? static_cast<void> (0) : __assert_fail ("NewDE && \"Unexpected nullptr expr to be added into aligned map\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1279, __PRETTY_FUNCTION__))
;
1280 StackElem.AlignedMap[D] = NewDE;
1281 return nullptr;
1282 }
1283 assert(It->second && "Unexpected nullptr expr in the aligned map")((It->second && "Unexpected nullptr expr in the aligned map"
) ? static_cast<void> (0) : __assert_fail ("It->second && \"Unexpected nullptr expr in the aligned map\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1283, __PRETTY_FUNCTION__))
;
1284 return It->second;
1285}
1286
1287const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1288 const Expr *NewDE) {
1289 assert(!isStackEmpty() && "Data sharing attributes stack is empty")((!isStackEmpty() && "Data sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1289, __PRETTY_FUNCTION__))
;
1290 D = getCanonicalDecl(D);
1291 SharingMapTy &StackElem = getTopOfStack();
1292 auto It = StackElem.NontemporalMap.find(D);
1293 if (It == StackElem.NontemporalMap.end()) {
1294 assert(NewDE && "Unexpected nullptr expr to be added into aligned map")((NewDE && "Unexpected nullptr expr to be added into aligned map"
) ? static_cast<void> (0) : __assert_fail ("NewDE && \"Unexpected nullptr expr to be added into aligned map\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1294, __PRETTY_FUNCTION__))
;
1295 StackElem.NontemporalMap[D] = NewDE;
1296 return nullptr;
1297 }
1298 assert(It->second && "Unexpected nullptr expr in the aligned map")((It->second && "Unexpected nullptr expr in the aligned map"
) ? static_cast<void> (0) : __assert_fail ("It->second && \"Unexpected nullptr expr in the aligned map\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1298, __PRETTY_FUNCTION__))
;
1299 return It->second;
1300}
1301
1302void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1303 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1303, __PRETTY_FUNCTION__))
;
1304 D = getCanonicalDecl(D);
1305 SharingMapTy &StackElem = getTopOfStack();
1306 StackElem.LCVMap.try_emplace(
1307 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1308}
1309
1310const DSAStackTy::LCDeclInfo
1311DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1312 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1312, __PRETTY_FUNCTION__))
;
1313 D = getCanonicalDecl(D);
1314 const SharingMapTy &StackElem = getTopOfStack();
1315 auto It = StackElem.LCVMap.find(D);
1316 if (It != StackElem.LCVMap.end())
1317 return It->second;
1318 return {0, nullptr};
1319}
1320
1321const DSAStackTy::LCDeclInfo
1322DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1323 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1323, __PRETTY_FUNCTION__))
;
1324 D = getCanonicalDecl(D);
1325 for (unsigned I = Level + 1; I > 0; --I) {
1326 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1327 auto It = StackElem.LCVMap.find(D);
1328 if (It != StackElem.LCVMap.end())
1329 return It->second;
1330 }
1331 return {0, nullptr};
1332}
1333
1334const DSAStackTy::LCDeclInfo
1335DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1336 const SharingMapTy *Parent = getSecondOnStackOrNull();
1337 assert(Parent && "Data-sharing attributes stack is empty")((Parent && "Data-sharing attributes stack is empty")
? static_cast<void> (0) : __assert_fail ("Parent && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1337, __PRETTY_FUNCTION__))
;
1338 D = getCanonicalDecl(D);
1339 auto It = Parent->LCVMap.find(D);
1340 if (It != Parent->LCVMap.end())
1341 return It->second;
1342 return {0, nullptr};
1343}
1344
1345const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1346 const SharingMapTy *Parent = getSecondOnStackOrNull();
1347 assert(Parent && "Data-sharing attributes stack is empty")((Parent && "Data-sharing attributes stack is empty")
? static_cast<void> (0) : __assert_fail ("Parent && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1347, __PRETTY_FUNCTION__))
;
1348 if (Parent->LCVMap.size() < I)
1349 return nullptr;
1350 for (const auto &Pair : Parent->LCVMap)
1351 if (Pair.second.first == I)
1352 return Pair.first;
1353 return nullptr;
1354}
1355
1356void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1357 DeclRefExpr *PrivateCopy, unsigned Modifier,
1358 bool AppliedToPointee) {
1359 D = getCanonicalDecl(D);
1360 if (A == OMPC_threadprivate) {
1361 DSAInfo &Data = Threadprivates[D];
1362 Data.Attributes = A;
1363 Data.RefExpr.setPointer(E);
1364 Data.PrivateCopy = nullptr;
1365 Data.Modifier = Modifier;
1366 } else {
1367 DSAInfo &Data = getTopOfStack().SharingMap[D];
1368 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1371, __PRETTY_FUNCTION__))
1369 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1371, __PRETTY_FUNCTION__))
1370 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1371, __PRETTY_FUNCTION__))
1371 (isLoopControlVariable(D).first && A == OMPC_private))((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1371, __PRETTY_FUNCTION__))
;
1372 Data.Modifier = Modifier;
1373 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1374 Data.RefExpr.setInt(/*IntVal=*/true);
1375 return;
1376 }
1377 const bool IsLastprivate =
1378 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1379 Data.Attributes = A;
1380 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1381 Data.PrivateCopy = PrivateCopy;
1382 Data.AppliedToPointee = AppliedToPointee;
1383 if (PrivateCopy) {
1384 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1385 Data.Modifier = Modifier;
1386 Data.Attributes = A;
1387 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1388 Data.PrivateCopy = nullptr;
1389 Data.AppliedToPointee = AppliedToPointee;
1390 }
1391 }
1392}
1393
1394/// Build a variable declaration for OpenMP loop iteration variable.
1395static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1396 StringRef Name, const AttrVec *Attrs = nullptr,
1397 DeclRefExpr *OrigRef = nullptr) {
1398 DeclContext *DC = SemaRef.CurContext;
1399 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1400 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1401 auto *Decl =
1402 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1403 if (Attrs) {
1404 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1405 I != E; ++I)
1406 Decl->addAttr(*I);
1407 }
1408 Decl->setImplicit();
1409 if (OrigRef) {
1410 Decl->addAttr(
1411 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1412 }
1413 return Decl;
1414}
1415
1416static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1417 SourceLocation Loc,
1418 bool RefersToCapture = false) {
1419 D->setReferenced();
1420 D->markUsed(S.Context);
1421 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1422 SourceLocation(), D, RefersToCapture, Loc, Ty,
1423 VK_LValue);
1424}
1425
1426void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1427 BinaryOperatorKind BOK) {
1428 D = getCanonicalDecl(D);
1429 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1429, __PRETTY_FUNCTION__))
;
1430 assert(((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1432, __PRETTY_FUNCTION__))
1431 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1432, __PRETTY_FUNCTION__))
1432 "Additional reduction info may be specified only for reduction items.")((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1432, __PRETTY_FUNCTION__))
;
1433 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1434 assert(ReductionData.ReductionRange.isInvalid() &&((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1440, __PRETTY_FUNCTION__))
1435 (getTopOfStack().Directive == OMPD_taskgroup ||((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1440, __PRETTY_FUNCTION__))
1436 ((isOpenMPParallelDirective(getTopOfStack().Directive) ||((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1440, __PRETTY_FUNCTION__))
1437 isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1440, __PRETTY_FUNCTION__))
1438 !isOpenMPSimdDirective(getTopOfStack().Directive))) &&((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1440, __PRETTY_FUNCTION__))
1439 "Additional reduction info may be specified only once for reduction "((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1440, __PRETTY_FUNCTION__))
1440 "items.")((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1440, __PRETTY_FUNCTION__))
;
1441 ReductionData.set(BOK, SR);
1442 Expr *&TaskgroupReductionRef =
1443 getTopOfStack().TaskgroupReductionRef;
1444 if (!TaskgroupReductionRef) {
1445 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1446 SemaRef.Context.VoidPtrTy, ".task_red.");
1447 TaskgroupReductionRef =
1448 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1449 }
1450}
1451
1452void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1453 const Expr *ReductionRef) {
1454 D = getCanonicalDecl(D);
1455 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1455, __PRETTY_FUNCTION__))
;
1456 assert(((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1458, __PRETTY_FUNCTION__))
1457 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1458, __PRETTY_FUNCTION__))
1458 "Additional reduction info may be specified only for reduction items.")((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1458, __PRETTY_FUNCTION__))
;
1459 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1460 assert(ReductionData.ReductionRange.isInvalid() &&((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1466, __PRETTY_FUNCTION__))
1461 (getTopOfStack().Directive == OMPD_taskgroup ||((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1466, __PRETTY_FUNCTION__))
1462 ((isOpenMPParallelDirective(getTopOfStack().Directive) ||((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1466, __PRETTY_FUNCTION__))
1463 isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1466, __PRETTY_FUNCTION__))
1464 !isOpenMPSimdDirective(getTopOfStack().Directive))) &&((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1466, __PRETTY_FUNCTION__))
1465 "Additional reduction info may be specified only once for reduction "((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1466, __PRETTY_FUNCTION__))
1466 "items.")((ReductionData.ReductionRange.isInvalid() && (getTopOfStack
().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective
(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack
().Directive)) && !isOpenMPSimdDirective(getTopOfStack
().Directive))) && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && (getTopOfStack().Directive == OMPD_taskgroup || ((isOpenMPParallelDirective(getTopOfStack().Directive) || isOpenMPWorksharingDirective(getTopOfStack().Directive)) && !isOpenMPSimdDirective(getTopOfStack().Directive))) && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1466, __PRETTY_FUNCTION__))
;
1467 ReductionData.set(ReductionRef, SR);
1468 Expr *&TaskgroupReductionRef =
1469 getTopOfStack().TaskgroupReductionRef;
1470 if (!TaskgroupReductionRef) {
1471 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1472 SemaRef.Context.VoidPtrTy, ".task_red.");
1473 TaskgroupReductionRef =
1474 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1475 }
1476}
1477
1478const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1479 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1480 Expr *&TaskgroupDescriptor) const {
1481 D = getCanonicalDecl(D);
1482 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.")((!isStackEmpty() && "Data-sharing attributes stack is empty."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1482, __PRETTY_FUNCTION__))
;
1483 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1484 const DSAInfo &Data = I->SharingMap.lookup(D);
1485 if (Data.Attributes != OMPC_reduction ||
1486 Data.Modifier != OMPC_REDUCTION_task)
1487 continue;
1488 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1489 if (!ReductionData.ReductionOp ||
1490 ReductionData.ReductionOp.is<const Expr *>())
1491 return DSAVarData();
1492 SR = ReductionData.ReductionRange;
1493 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1494 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1496, __PRETTY_FUNCTION__))
1495 "expression for the descriptor is not "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1496, __PRETTY_FUNCTION__))
1496 "set.")((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1496, __PRETTY_FUNCTION__))
;
1497 TaskgroupDescriptor = I->TaskgroupReductionRef;
1498 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1499 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1500 /*AppliedToPointee=*/false);
1501 }
1502 return DSAVarData();
1503}
1504
1505const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1506 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1507 Expr *&TaskgroupDescriptor) const {
1508 D = getCanonicalDecl(D);
1509 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.")((!isStackEmpty() && "Data-sharing attributes stack is empty."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1509, __PRETTY_FUNCTION__))
;
1510 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1511 const DSAInfo &Data = I->SharingMap.lookup(D);
1512 if (Data.Attributes != OMPC_reduction ||
1513 Data.Modifier != OMPC_REDUCTION_task)
1514 continue;
1515 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1516 if (!ReductionData.ReductionOp ||
1517 !ReductionData.ReductionOp.is<const Expr *>())
1518 return DSAVarData();
1519 SR = ReductionData.ReductionRange;
1520 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1521 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1523, __PRETTY_FUNCTION__))
1522 "expression for the descriptor is not "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1523, __PRETTY_FUNCTION__))
1523 "set.")((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1523, __PRETTY_FUNCTION__))
;
1524 TaskgroupDescriptor = I->TaskgroupReductionRef;
1525 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1526 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1527 /*AppliedToPointee=*/false);
1528 }
1529 return DSAVarData();
1530}
1531
1532bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1533 D = D->getCanonicalDecl();
1534 for (const_iterator E = end(); I != E; ++I) {
1535 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1536 isOpenMPTargetExecutionDirective(I->Directive)) {
1537 if (I->CurScope) {
1538 Scope *TopScope = I->CurScope->getParent();
1539 Scope *CurScope = getCurScope();
1540 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1541 CurScope = CurScope->getParent();
1542 return CurScope != TopScope;
1543 }
1544 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
1545 if (I->Context == DC)
1546 return true;
1547 return false;
1548 }
1549 }
1550 return false;
1551}
1552
1553static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1554 bool AcceptIfMutable = true,
1555 bool *IsClassType = nullptr) {
1556 ASTContext &Context = SemaRef.getASTContext();
1557 Type = Type.getNonReferenceType().getCanonicalType();
1558 bool IsConstant = Type.isConstant(Context);
1559 Type = Context.getBaseElementType(Type);
1560 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1561 ? Type->getAsCXXRecordDecl()
1562 : nullptr;
1563 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1564 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1565 RD = CTD->getTemplatedDecl();
1566 if (IsClassType)
1567 *IsClassType = RD;
1568 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1569 RD->hasDefinition() && RD->hasMutableFields());
1570}
1571
1572static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1573 QualType Type, OpenMPClauseKind CKind,
1574 SourceLocation ELoc,
1575 bool AcceptIfMutable = true,
1576 bool ListItemNotVar = false) {
1577 ASTContext &Context = SemaRef.getASTContext();
1578 bool IsClassType;
1579 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1580 unsigned Diag = ListItemNotVar
1581 ? diag::err_omp_const_list_item
1582 : IsClassType ? diag::err_omp_const_not_mutable_variable
1583 : diag::err_omp_const_variable;
1584 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1585 if (!ListItemNotVar && D) {
1586 const VarDecl *VD = dyn_cast<VarDecl>(D);
1587 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1588 VarDecl::DeclarationOnly;
1589 SemaRef.Diag(D->getLocation(),
1590 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1591 << D;
1592 }
1593 return true;
1594 }
1595 return false;
1596}
1597
1598const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1599 bool FromParent) {
1600 D = getCanonicalDecl(D);
1601 DSAVarData DVar;
1602
1603 auto *VD = dyn_cast<VarDecl>(D);
1604 auto TI = Threadprivates.find(D);
1605 if (TI != Threadprivates.end()) {
1606 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1607 DVar.CKind = OMPC_threadprivate;
1608 DVar.Modifier = TI->getSecond().Modifier;
1609 return DVar;
1610 }
1611 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1612 DVar.RefExpr = buildDeclRefExpr(
1613 SemaRef, VD, D->getType().getNonReferenceType(),
1614 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1615 DVar.CKind = OMPC_threadprivate;
1616 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1617 return DVar;
1618 }
1619 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1620 // in a Construct, C/C++, predetermined, p.1]
1621 // Variables appearing in threadprivate directives are threadprivate.
1622 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1623 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1624 SemaRef.getLangOpts().OpenMPUseTLS &&
1625 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1626 (VD && VD->getStorageClass() == SC_Register &&
1627 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1628 DVar.RefExpr = buildDeclRefExpr(
1629 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1630 DVar.CKind = OMPC_threadprivate;
1631 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1632 return DVar;
1633 }
1634 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1635 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1636 !isLoopControlVariable(D).first) {
1637 const_iterator IterTarget =
1638 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1639 return isOpenMPTargetExecutionDirective(Data.Directive);
1640 });
1641 if (IterTarget != end()) {
1642 const_iterator ParentIterTarget = IterTarget + 1;
1643 for (const_iterator Iter = begin();
1644 Iter != ParentIterTarget; ++Iter) {
1645 if (isOpenMPLocal(VD, Iter)) {
1646 DVar.RefExpr =
1647 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1648 D->getLocation());
1649 DVar.CKind = OMPC_threadprivate;
1650 return DVar;
1651 }
1652 }
1653 if (!isClauseParsingMode() || IterTarget != begin()) {
1654 auto DSAIter = IterTarget->SharingMap.find(D);
1655 if (DSAIter != IterTarget->SharingMap.end() &&
1656 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1657 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1658 DVar.CKind = OMPC_threadprivate;
1659 return DVar;
1660 }
1661 const_iterator End = end();
1662 if (!SemaRef.isOpenMPCapturedByRef(
1663 D, std::distance(ParentIterTarget, End),
1664 /*OpenMPCaptureLevel=*/0)) {
1665 DVar.RefExpr =
1666 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1667 IterTarget->ConstructLoc);
1668 DVar.CKind = OMPC_threadprivate;
1669 return DVar;
1670 }
1671 }
1672 }
1673 }
1674
1675 if (isStackEmpty())
1676 // Not in OpenMP execution region and top scope was already checked.
1677 return DVar;
1678
1679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1680 // in a Construct, C/C++, predetermined, p.4]
1681 // Static data members are shared.
1682 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1683 // in a Construct, C/C++, predetermined, p.7]
1684 // Variables with static storage duration that are declared in a scope
1685 // inside the construct are shared.
1686 if (VD && VD->isStaticDataMember()) {
1687 // Check for explicitly specified attributes.
1688 const_iterator I = begin();
1689 const_iterator EndI = end();
1690 if (FromParent && I != EndI)
1691 ++I;
1692 if (I != EndI) {
1693 auto It = I->SharingMap.find(D);
1694 if (It != I->SharingMap.end()) {
1695 const DSAInfo &Data = It->getSecond();
1696 DVar.RefExpr = Data.RefExpr.getPointer();
1697 DVar.PrivateCopy = Data.PrivateCopy;
1698 DVar.CKind = Data.Attributes;
1699 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1700 DVar.DKind = I->Directive;
1701 DVar.Modifier = Data.Modifier;
1702 DVar.AppliedToPointee = Data.AppliedToPointee;
1703 return DVar;
1704 }
1705 }
1706
1707 DVar.CKind = OMPC_shared;
1708 return DVar;
1709 }
1710
1711 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1712 // The predetermined shared attribute for const-qualified types having no
1713 // mutable members was removed after OpenMP 3.1.
1714 if (SemaRef.LangOpts.OpenMP <= 31) {
1715 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1716 // in a Construct, C/C++, predetermined, p.6]
1717 // Variables with const qualified type having no mutable member are
1718 // shared.
1719 if (isConstNotMutableType(SemaRef, D->getType())) {
1720 // Variables with const-qualified type having no mutable member may be
1721 // listed in a firstprivate clause, even if they are static data members.
1722 DSAVarData DVarTemp = hasInnermostDSA(
1723 D,
1724 [](OpenMPClauseKind C, bool) {
1725 return C == OMPC_firstprivate || C == OMPC_shared;
1726 },
1727 MatchesAlways, FromParent);
1728 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1729 return DVarTemp;
1730
1731 DVar.CKind = OMPC_shared;
1732 return DVar;
1733 }
1734 }
1735
1736 // Explicitly specified attributes and local variables with predetermined
1737 // attributes.
1738 const_iterator I = begin();
1739 const_iterator EndI = end();
1740 if (FromParent && I != EndI)
1741 ++I;
1742 if (I == EndI)
1743 return DVar;
1744 auto It = I->SharingMap.find(D);
1745 if (It != I->SharingMap.end()) {
1746 const DSAInfo &Data = It->getSecond();
1747 DVar.RefExpr = Data.RefExpr.getPointer();
1748 DVar.PrivateCopy = Data.PrivateCopy;
1749 DVar.CKind = Data.Attributes;
1750 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1751 DVar.DKind = I->Directive;
1752 DVar.Modifier = Data.Modifier;
1753 DVar.AppliedToPointee = Data.AppliedToPointee;
1754 }
1755
1756 return DVar;
1757}
1758
1759const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1760 bool FromParent) const {
1761 if (isStackEmpty()) {
1762 const_iterator I;
1763 return getDSA(I, D);
1764 }
1765 D = getCanonicalDecl(D);
1766 const_iterator StartI = begin();
1767 const_iterator EndI = end();
1768 if (FromParent && StartI != EndI)
1769 ++StartI;
1770 return getDSA(StartI, D);
1771}
1772
1773const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1774 unsigned Level) const {
1775 if (getStackSize() <= Level)
10
Assuming the condition is false
11
Taking false branch
1776 return DSAVarData();
1777 D = getCanonicalDecl(D);
1778 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
1779 return getDSA(StartI, D);
12
Calling 'DSAStackTy::getDSA'
1780}
1781
1782const DSAStackTy::DSAVarData
1783DSAStackTy::hasDSA(ValueDecl *D,
1784 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1785 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1786 bool FromParent) const {
1787 if (isStackEmpty())
1788 return {};
1789 D = getCanonicalDecl(D);
1790 const_iterator I = begin();
1791 const_iterator EndI = end();
1792 if (FromParent && I != EndI)
1793 ++I;
1794 for (; I != EndI; ++I) {
1795 if (!DPred(I->Directive) &&
1796 !isImplicitOrExplicitTaskingRegion(I->Directive))
1797 continue;
1798 const_iterator NewI = I;
1799 DSAVarData DVar = getDSA(NewI, D);
1800 if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee))
1801 return DVar;
1802 }
1803 return {};
1804}
1805
1806const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1807 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1808 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1809 bool FromParent) const {
1810 if (isStackEmpty())
1811 return {};
1812 D = getCanonicalDecl(D);
1813 const_iterator StartI = begin();
1814 const_iterator EndI = end();
1815 if (FromParent && StartI != EndI)
1816 ++StartI;
1817 if (StartI == EndI || !DPred(StartI->Directive))
1818 return {};
1819 const_iterator NewI = StartI;
1820 DSAVarData DVar = getDSA(NewI, D);
1821 return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
1822 ? DVar
1823 : DSAVarData();
1824}
1825
1826bool DSAStackTy::hasExplicitDSA(
1827 const ValueDecl *D,
1828 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
1829 unsigned Level, bool NotLastprivate) const {
1830 if (getStackSize() <= Level)
1831 return false;
1832 D = getCanonicalDecl(D);
1833 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1834 auto I = StackElem.SharingMap.find(D);
1835 if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
1836 CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
1837 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1838 return true;
1839 // Check predetermined rules for the loop control variables.
1840 auto LI = StackElem.LCVMap.find(D);
1841 if (LI != StackElem.LCVMap.end())
1842 return CPred(OMPC_private, /*AppliedToPointee=*/false);
1843 return false;
1844}
1845
1846bool DSAStackTy::hasExplicitDirective(
1847 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1848 unsigned Level) const {
1849 if (getStackSize() <= Level)
1850 return false;
1851 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1852 return DPred(StackElem.Directive);
1853}
1854
1855bool DSAStackTy::hasDirective(
1856 const llvm::function_ref<bool(OpenMPDirectiveKind,
1857 const DeclarationNameInfo &, SourceLocation)>
1858 DPred,
1859 bool FromParent) const {
1860 // We look only in the enclosing region.
1861 size_t Skip = FromParent ? 2 : 1;
1862 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1863 I != E; ++I) {
1864 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1865 return true;
1866 }
1867 return false;
1868}
1869
1870void Sema::InitDataSharingAttributesStack() {
1871 VarDataSharingAttributesStack = new DSAStackTy(*this);
1872}
1873
1874#define DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1875
1876void Sema::pushOpenMPFunctionRegion() {
1877 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->pushFunction();
1878}
1879
1880void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1881 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->popFunction(OldFSI);
1882}
1883
1884static bool isOpenMPDeviceDelayedContext(Sema &S) {
1885 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&((S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1886, __PRETTY_FUNCTION__))
1886 "Expected OpenMP device compilation.")((S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1886, __PRETTY_FUNCTION__))
;
1887 return !S.isInOpenMPTargetExecutionDirective();
1888}
1889
1890namespace {
1891/// Status of the function emission on the host/device.
1892enum class FunctionEmissionStatus {
1893 Emitted,
1894 Discarded,
1895 Unknown,
1896};
1897} // anonymous namespace
1898
1899Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1900 unsigned DiagID,
1901 FunctionDecl *FD) {
1902 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&((LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("LangOpts.OpenMP && LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1903, __PRETTY_FUNCTION__))
1903 "Expected OpenMP device compilation.")((LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("LangOpts.OpenMP && LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1903, __PRETTY_FUNCTION__))
;
1904
1905 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1906 if (FD) {
1907 FunctionEmissionStatus FES = getEmissionStatus(FD);
1908 switch (FES) {
1909 case FunctionEmissionStatus::Emitted:
1910 Kind = SemaDiagnosticBuilder::K_Immediate;
1911 break;
1912 case FunctionEmissionStatus::Unknown:
1913 // TODO: We should always delay diagnostics here in case a target
1914 // region is in a function we do not emit. However, as the
1915 // current diagnostics are associated with the function containing
1916 // the target region and we do not emit that one, we would miss out
1917 // on diagnostics for the target region itself. We need to anchor
1918 // the diagnostics with the new generated function *or* ensure we
1919 // emit diagnostics associated with the surrounding function.
1920 Kind = isOpenMPDeviceDelayedContext(*this)
1921 ? SemaDiagnosticBuilder::K_Deferred
1922 : SemaDiagnosticBuilder::K_Immediate;
1923 break;
1924 case FunctionEmissionStatus::TemplateDiscarded:
1925 case FunctionEmissionStatus::OMPDiscarded:
1926 Kind = SemaDiagnosticBuilder::K_Nop;
1927 break;
1928 case FunctionEmissionStatus::CUDADiscarded:
1929 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation")::llvm::llvm_unreachable_internal("CUDADiscarded unexpected in OpenMP device compilation"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1929)
;
1930 break;
1931 }
1932 }
1933
1934 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1935}
1936
1937Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1938 unsigned DiagID,
1939 FunctionDecl *FD) {
1940 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&((LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
"Expected OpenMP host compilation.") ? static_cast<void>
(0) : __assert_fail ("LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && \"Expected OpenMP host compilation.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1941, __PRETTY_FUNCTION__))
1941 "Expected OpenMP host compilation.")((LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
"Expected OpenMP host compilation.") ? static_cast<void>
(0) : __assert_fail ("LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && \"Expected OpenMP host compilation.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1941, __PRETTY_FUNCTION__))
;
1942
1943 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
1944 if (FD) {
1945 FunctionEmissionStatus FES = getEmissionStatus(FD);
1946 switch (FES) {
1947 case FunctionEmissionStatus::Emitted:
1948 Kind = SemaDiagnosticBuilder::K_Immediate;
1949 break;
1950 case FunctionEmissionStatus::Unknown:
1951 Kind = SemaDiagnosticBuilder::K_Deferred;
1952 break;
1953 case FunctionEmissionStatus::TemplateDiscarded:
1954 case FunctionEmissionStatus::OMPDiscarded:
1955 case FunctionEmissionStatus::CUDADiscarded:
1956 Kind = SemaDiagnosticBuilder::K_Nop;
1957 break;
1958 }
1959 }
1960
1961 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
1962}
1963
1964static OpenMPDefaultmapClauseKind
1965getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1966 if (LO.OpenMP <= 45) {
1967 if (VD->getType().getNonReferenceType()->isScalarType())
1968 return OMPC_DEFAULTMAP_scalar;
1969 return OMPC_DEFAULTMAP_aggregate;
1970 }
1971 if (VD->getType().getNonReferenceType()->isAnyPointerType())
1972 return OMPC_DEFAULTMAP_pointer;
1973 if (VD->getType().getNonReferenceType()->isScalarType())
1974 return OMPC_DEFAULTMAP_scalar;
1975 return OMPC_DEFAULTMAP_aggregate;
1976}
1977
1978bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1979 unsigned OpenMPCaptureLevel) const {
1980 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 1980, __PRETTY_FUNCTION__))
;
1981
1982 ASTContext &Ctx = getASTContext();
1983 bool IsByRef = true;
1984
1985 // Find the directive that is associated with the provided scope.
1986 D = cast<ValueDecl>(D->getCanonicalDecl());
1987 QualType Ty = D->getType();
1988
1989 bool IsVariableUsedInMapClause = false;
1990 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1991 // This table summarizes how a given variable should be passed to the device
1992 // given its type and the clauses where it appears. This table is based on
1993 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1994 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1995 //
1996 // =========================================================================
1997 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1998 // | |(tofrom:scalar)| | pvt | | | |
1999 // =========================================================================
2000 // | scl | | | | - | | bycopy|
2001 // | scl | | - | x | - | - | bycopy|
2002 // | scl | | x | - | - | - | null |
2003 // | scl | x | | | - | | byref |
2004 // | scl | x | - | x | - | - | bycopy|
2005 // | scl | x | x | - | - | - | null |
2006 // | scl | | - | - | - | x | byref |
2007 // | scl | x | - | - | - | x | byref |
2008 //
2009 // | agg | n.a. | | | - | | byref |
2010 // | agg | n.a. | - | x | - | - | byref |
2011 // | agg | n.a. | x | - | - | - | null |
2012 // | agg | n.a. | - | - | - | x | byref |
2013 // | agg | n.a. | - | - | - | x[] | byref |
2014 //
2015 // | ptr | n.a. | | | - | | bycopy|
2016 // | ptr | n.a. | - | x | - | - | bycopy|
2017 // | ptr | n.a. | x | - | - | - | null |
2018 // | ptr | n.a. | - | - | - | x | byref |
2019 // | ptr | n.a. | - | - | - | x[] | bycopy|
2020 // | ptr | n.a. | - | - | x | | bycopy|
2021 // | ptr | n.a. | - | - | x | x | bycopy|
2022 // | ptr | n.a. | - | - | x | x[] | bycopy|
2023 // =========================================================================
2024 // Legend:
2025 // scl - scalar
2026 // ptr - pointer
2027 // agg - aggregate
2028 // x - applies
2029 // - - invalid in this combination
2030 // [] - mapped with an array section
2031 // byref - should be mapped by reference
2032 // byval - should be mapped by value
2033 // null - initialize a local variable to null on the device
2034 //
2035 // Observations:
2036 // - All scalar declarations that show up in a map clause have to be passed
2037 // by reference, because they may have been mapped in the enclosing data
2038 // environment.
2039 // - If the scalar value does not fit the size of uintptr, it has to be
2040 // passed by reference, regardless the result in the table above.
2041 // - For pointers mapped by value that have either an implicit map or an
2042 // array section, the runtime library may pass the NULL value to the
2043 // device instead of the value passed to it by the compiler.
2044
2045 if (Ty->isReferenceType())
2046 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2047
2048 // Locate map clauses and see if the variable being captured is referred to
2049 // in any of those clauses. Here we only care about variables, not fields,
2050 // because fields are part of aggregates.
2051 bool IsVariableAssociatedWithSection = false;
2052
2053 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDeclAtLevel(
2054 D, Level,
2055 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
2056 OMPClauseMappableExprCommon::MappableExprComponentListRef
2057 MapExprComponents,
2058 OpenMPClauseKind WhereFoundClauseKind) {
2059 // Only the map clause information influences how a variable is
2060 // captured. E.g. is_device_ptr does not require changing the default
2061 // behavior.
2062 if (WhereFoundClauseKind != OMPC_map)
2063 return false;
2064
2065 auto EI = MapExprComponents.rbegin();
2066 auto EE = MapExprComponents.rend();
2067
2068 assert(EI != EE && "Invalid map expression!")((EI != EE && "Invalid map expression!") ? static_cast
<void> (0) : __assert_fail ("EI != EE && \"Invalid map expression!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2068, __PRETTY_FUNCTION__))
;
2069
2070 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
2071 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
2072
2073 ++EI;
2074 if (EI == EE)
2075 return false;
2076
2077 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
2078 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
2079 isa<MemberExpr>(EI->getAssociatedExpression()) ||
2080 isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
2081 IsVariableAssociatedWithSection = true;
2082 // There is nothing more we need to know about this variable.
2083 return true;
2084 }
2085
2086 // Keep looking for more map info.
2087 return false;
2088 });
2089
2090 if (IsVariableUsedInMapClause) {
2091 // If variable is identified in a map clause it is always captured by
2092 // reference except if it is a pointer that is dereferenced somehow.
2093 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2094 } else {
2095 // By default, all the data that has a scalar type is mapped by copy
2096 // (except for reduction variables).
2097 // Defaultmap scalar is mutual exclusive to defaultmap pointer
2098 IsByRef = (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceCaptureByReferenceInTargetExecutable() &&
2099 !Ty->isAnyPointerType()) ||
2100 !Ty->isScalarType() ||
2101 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isDefaultmapCapturedByRef(
2102 Level, getVariableCategoryFromDecl(LangOpts, D)) ||
2103 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2104 D,
2105 [](OpenMPClauseKind K, bool AppliedToPointee) {
2106 return K == OMPC_reduction && !AppliedToPointee;
2107 },
2108 Level);
2109 }
2110 }
2111
2112 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2113 IsByRef =
2114 ((IsVariableUsedInMapClause &&
2115 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2116 OMPD_target) ||
2117 !(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2118 D,
2119 [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2120 return K == OMPC_firstprivate ||
2121 (K == OMPC_reduction && AppliedToPointee);
2122 },
2123 Level, /*NotLastprivate=*/true) ||
2124 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isUsesAllocatorsDecl(Level, D))) &&
2125 // If the variable is artificial and must be captured by value - try to
2126 // capture by value.
2127 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2128 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2129 // If the variable is implicitly firstprivate and scalar - capture by
2130 // copy
2131 !(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() == DSA_firstprivate &&
2132 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2133 D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2134 Level) &&
2135 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D, Level).first);
2136 }
2137
2138 // When passing data by copy, we need to make sure it fits the uintptr size
2139 // and alignment, because the runtime library only deals with uintptr types.
2140 // If it does not fit the uintptr size, we need to pass the data by reference
2141 // instead.
2142 if (!IsByRef &&
2143 (Ctx.getTypeSizeInChars(Ty) >
2144 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
2145 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2146 IsByRef = true;
2147 }
2148
2149 return IsByRef;
2150}
2151
2152unsigned Sema::getOpenMPNestingLevel() const {
2153 assert(getLangOpts().OpenMP)((getLangOpts().OpenMP) ? static_cast<void> (0) : __assert_fail
("getLangOpts().OpenMP", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2153, __PRETTY_FUNCTION__))
;
2154 return DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getNestingLevel();
2155}
2156
2157bool Sema::isInOpenMPTargetExecutionDirective() const {
2158 return (isOpenMPTargetExecutionDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
2159 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode()) ||
2160 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDirective(
2161 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2162 SourceLocation) -> bool {
2163 return isOpenMPTargetExecutionDirective(K);
2164 },
2165 false);
2166}
2167
2168VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
2169 unsigned StopAt) {
2170 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2170, __PRETTY_FUNCTION__))
;
2171 D = getCanonicalDecl(D);
2172
2173 auto *VD = dyn_cast<VarDecl>(D);
2174 // Do not capture constexpr variables.
2175 if (VD && VD->isConstexpr())
2176 return nullptr;
2177
2178 // If we want to determine whether the variable should be captured from the
2179 // perspective of the current capturing scope, and we've already left all the
2180 // capturing scopes of the top directive on the stack, check from the
2181 // perspective of its parent directive (if any) instead.
2182 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2183 *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, CheckScopeInfo && DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isBodyComplete());
2184
2185 // If we are attempting to capture a global variable in a directive with
2186 // 'target' we return true so that this global is also mapped to the device.
2187 //
2188 if (VD && !VD->hasLocalStorage() &&
2189 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2190 if (isInOpenMPDeclareTargetContext()) {
2191 // Try to mark variable as declare target if it is used in capturing
2192 // regions.
2193 if (LangOpts.OpenMP <= 45 &&
2194 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2195 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
2196 return nullptr;
2197 }
2198 if (isInOpenMPTargetExecutionDirective()) {
2199 // If the declaration is enclosed in a 'declare target' directive,
2200 // then it should not be captured.
2201 //
2202 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2203 return nullptr;
2204 CapturedRegionScopeInfo *CSI = nullptr;
2205 for (FunctionScopeInfo *FSI : llvm::drop_begin(
2206 llvm::reverse(FunctionScopes),
2207 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2208 if (!isa<CapturingScopeInfo>(FSI))
2209 return nullptr;
2210 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2211 if (RSI->CapRegionKind == CR_OpenMP) {
2212 CSI = RSI;
2213 break;
2214 }
2215 }
2216 assert(CSI && "Failed to find CapturedRegionScopeInfo")((CSI && "Failed to find CapturedRegionScopeInfo") ? static_cast
<void> (0) : __assert_fail ("CSI && \"Failed to find CapturedRegionScopeInfo\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2216, __PRETTY_FUNCTION__))
;
2217 SmallVector<OpenMPDirectiveKind, 4> Regions;
2218 getOpenMPCaptureRegions(Regions,
2219 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(CSI->OpenMPLevel));
2220 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2221 return VD;
2222 }
2223 }
2224
2225 if (CheckScopeInfo) {
2226 bool OpenMPFound = false;
2227 for (unsigned I = StopAt + 1; I > 0; --I) {
2228 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2229 if(!isa<CapturingScopeInfo>(FSI))
2230 return nullptr;
2231 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2232 if (RSI->CapRegionKind == CR_OpenMP) {
2233 OpenMPFound = true;
2234 break;
2235 }
2236 }
2237 if (!OpenMPFound)
2238 return nullptr;
2239 }
2240
2241 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() != OMPD_unknown &&
2242 (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode() ||
2243 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentDirective() != OMPD_unknown)) {
2244 auto &&Info = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D);
2245 if (Info.first ||
2246 (VD && VD->hasLocalStorage() &&
2247 isImplicitOrExplicitTaskingRegion(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) ||
2248 (VD && DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceVarCapturing()))
2249 return VD ? VD : Info.second;
2250 DSAStackTy::DSAVarData DVarTop =
2251 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode());
2252 if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2253 (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
2254 return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2255 // Threadprivate variables must not be captured.
2256 if (isOpenMPThreadPrivate(DVarTop.CKind))
2257 return nullptr;
2258 // The variable is not private or it is the variable in the directive with
2259 // default(none) clause and not used in any clause.
2260 DSAStackTy::DSAVarData DVarPrivate = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDSA(
2261 D,
2262 [](OpenMPClauseKind C, bool AppliedToPointee) {
2263 return isOpenMPPrivate(C) && !AppliedToPointee;
2264 },
2265 [](OpenMPDirectiveKind) { return true; },
2266 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode());
2267 // Global shared must not be captured.
2268 if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2269 ((DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() != DSA_none &&
2270 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() != DSA_firstprivate) ||
2271 DVarTop.CKind == OMPC_shared))
2272 return nullptr;
2273 if (DVarPrivate.CKind != OMPC_unknown ||
2274 (VD && (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() == DSA_none ||
2275 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() == DSA_firstprivate)))
2276 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2277 }
2278 return nullptr;
2279}
2280
2281void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2282 unsigned Level) const {
2283 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(Level));
2284}
2285
2286void Sema::startOpenMPLoop() {
2287 assert(LangOpts.OpenMP && "OpenMP must be enabled.")((LangOpts.OpenMP && "OpenMP must be enabled.") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP must be enabled.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2287, __PRETTY_FUNCTION__))
;
2288 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
2289 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopInit();
2290}
2291
2292void Sema::startOpenMPCXXRangeFor() {
2293 assert(LangOpts.OpenMP && "OpenMP must be enabled.")((LangOpts.OpenMP && "OpenMP must be enabled.") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP must be enabled.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2293, __PRETTY_FUNCTION__))
;
2294 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
2295 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->resetPossibleLoopCounter();
2296 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopStart();
2297 }
2298}
2299
2300OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
2301 unsigned CapLevel) const {
2302 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2302, __PRETTY_FUNCTION__))
;
2303 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(
2304 [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); },
2305 Level)) {
2306 bool IsTriviallyCopyable =
2307 D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
2308 !D->getType()
2309 .getNonReferenceType()
2310 .getCanonicalType()
2311 ->getAsCXXRecordDecl();
2312 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(Level);
2313 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2314 getOpenMPCaptureRegions(CaptureRegions, DKind);
2315 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2316 (IsTriviallyCopyable ||
2317 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2318 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2319 D,
2320 [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2321 Level, /*NotLastprivate=*/true))
2322 return OMPC_firstprivate;
2323 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getImplicitDSA(D, Level);
2324 if (DVar.CKind != OMPC_shared &&
2325 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2326 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addImplicitTaskFirstprivate(Level, D);
2327 return OMPC_firstprivate;
2328 }
2329 }
2330 }
2331 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
2332 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops() > 0 &&
2333 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopStarted()) {
2334 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->resetPossibleLoopCounter(D);
2335 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopStart();
2336 return OMPC_private;
2337 }
2338 if ((DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2339 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D).first) &&
2340 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2341 D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2342 Level) &&
2343 !isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
2344 return OMPC_private;
2345 }
2346 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2347 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2348 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceVarCapturing() &&
2349 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2350 D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2351 Level))
2352 return OMPC_private;
2353 }
2354 // User-defined allocators are private since they must be defined in the
2355 // context of target region.
2356 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2357 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isUsesAllocatorsDecl(Level, D).getValueOr(
2358 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2359 DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2360 return OMPC_private;
2361 return (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2362 D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2363 Level) ||
2364 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode() &&
2365 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getClauseParsingMode() == OMPC_private) ||
2366 // Consider taskgroup reduction descriptor variable a private
2367 // to avoid possible capture in the region.
2368 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(
2369 [](OpenMPDirectiveKind K) {
2370 return K == OMPD_taskgroup ||
2371 ((isOpenMPParallelDirective(K) ||
2372 isOpenMPWorksharingDirective(K)) &&
2373 !isOpenMPSimdDirective(K));
2374 },
2375 Level) &&
2376 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isTaskgroupReductionRef(D, Level)))
2377 ? OMPC_private
2378 : OMPC_unknown;
2379}
2380
2381void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2382 unsigned Level) {
2383 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2383, __PRETTY_FUNCTION__))
;
2384 D = getCanonicalDecl(D);
2385 OpenMPClauseKind OMPC = OMPC_unknown;
2386 for (unsigned I = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getNestingLevel() + 1; I > Level; --I) {
2387 const unsigned NewLevel = I - 1;
2388 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2389 D,
2390 [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2391 if (isOpenMPPrivate(K) && !AppliedToPointee) {
2392 OMPC = K;
2393 return true;
2394 }
2395 return false;
2396 },
2397 NewLevel))
2398 break;
2399 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDeclAtLevel(
2400 D, NewLevel,
2401 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2402 OpenMPClauseKind) { return true; })) {
2403 OMPC = OMPC_map;
2404 break;
2405 }
2406 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2407 NewLevel)) {
2408 OMPC = OMPC_map;
2409 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->mustBeFirstprivateAtLevel(
2410 NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
2411 OMPC = OMPC_firstprivate;
2412 break;
2413 }
2414 }
2415 if (OMPC != OMPC_unknown)
2416 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
2417}
2418
2419bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2420 unsigned CaptureLevel) const {
2421 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2421, __PRETTY_FUNCTION__))
;
2422 // Return true if the current level is no longer enclosed in a target region.
2423
2424 SmallVector<OpenMPDirectiveKind, 4> Regions;
2425 getOpenMPCaptureRegions(Regions, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(Level));
2426 const auto *VD = dyn_cast<VarDecl>(D);
2427 return VD && !VD->hasLocalStorage() &&
2428 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2429 Level) &&
2430 Regions[CaptureLevel] != OMPD_task;
2431}
2432
2433bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
2434 unsigned CaptureLevel) const {
2435 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2435, __PRETTY_FUNCTION__))
;
1
Assuming field 'OpenMP' is not equal to 0
2
'?' condition is true
2436 // Return true if the current level is no longer enclosed in a target region.
2437
2438 if (const auto *VD
3.1
'VD' is non-null
3.1
'VD' is non-null
= dyn_cast<VarDecl>(D)) {
3
Assuming 'D' is a 'VarDecl'
4
Taking true branch
2439 if (!VD->hasLocalStorage()) {
5
Taking true branch
2440 if (isInOpenMPTargetExecutionDirective())
6
Taking false branch
2441 return true;
2442 DSAStackTy::DSAVarData TopDVar =
2443 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
2444 unsigned NumLevels =
2445 getOpenMPCaptureLevels(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(Level));
2446 if (Level == 0)
7
Assuming 'Level' is not equal to 0
8
Taking false branch
2447 return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared;
2448 do {
2449 --Level;
2450 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getImplicitDSA(D, Level)
;
9
Calling 'DSAStackTy::getImplicitDSA'
2451 if (DVar.CKind != OMPC_shared)
2452 return true;
2453 } while (Level > 0);
2454 }
2455 }
2456 return true;
2457}
2458
2459void Sema::DestroyDataSharingAttributesStack() { delete DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
; }
2460
2461void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
2462 OMPTraitInfo &TI) {
2463 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2464}
2465
2466void Sema::ActOnOpenMPEndDeclareVariant() {
2467 assert(isInOpenMPDeclareVariantScope() &&((isInOpenMPDeclareVariantScope() && "Not in OpenMP declare variant scope!"
) ? static_cast<void> (0) : __assert_fail ("isInOpenMPDeclareVariantScope() && \"Not in OpenMP declare variant scope!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2468, __PRETTY_FUNCTION__))
2468 "Not in OpenMP declare variant scope!")((isInOpenMPDeclareVariantScope() && "Not in OpenMP declare variant scope!"
) ? static_cast<void> (0) : __assert_fail ("isInOpenMPDeclareVariantScope() && \"Not in OpenMP declare variant scope!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2468, __PRETTY_FUNCTION__))
;
2469
2470 OMPDeclareVariantScopes.pop_back();
2471}
2472
2473void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
2474 const FunctionDecl *Callee,
2475 SourceLocation Loc) {
2476 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.")((LangOpts.OpenMP && "Expected OpenMP compilation mode."
) ? static_cast<void> (0) : __assert_fail ("LangOpts.OpenMP && \"Expected OpenMP compilation mode.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2476, __PRETTY_FUNCTION__))
;
2477 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2478 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2479 // Ignore host functions during device analyzis.
2480 if (LangOpts.OpenMPIsDevice && DevTy &&
2481 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2482 return;
2483 // Ignore nohost functions during host analyzis.
2484 if (!LangOpts.OpenMPIsDevice && DevTy &&
2485 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2486 return;
2487 const FunctionDecl *FD = Callee->getMostRecentDecl();
2488 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2489 if (LangOpts.OpenMPIsDevice && DevTy &&
2490 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2491 // Diagnose host function called during device codegen.
2492 StringRef HostDevTy =
2493 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2494 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2495 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2496 diag::note_omp_marked_device_type_here)
2497 << HostDevTy;
2498 return;
2499 }
2500 if (!LangOpts.OpenMPIsDevice && DevTy &&
2501 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2502 // Diagnose nohost function called during host codegen.
2503 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2504 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2505 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2506 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2507 diag::note_omp_marked_device_type_here)
2508 << NoHostDevTy;
2509 }
2510}
2511
2512void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2513 const DeclarationNameInfo &DirName,
2514 Scope *CurScope, SourceLocation Loc) {
2515 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->push(DKind, DirName, CurScope, Loc);
2516 PushExpressionEvaluationContext(
2517 ExpressionEvaluationContext::PotentiallyEvaluated);
2518}
2519
2520void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2521 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setClauseParsingMode(K);
2522}
2523
2524void Sema::EndOpenMPClause() {
2525 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setClauseParsingMode(/*K=*/OMPC_unknown);
2526}
2527
2528static std::pair<ValueDecl *, bool>
2529getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2530 SourceRange &ERange, bool AllowArraySection = false);
2531
2532/// Check consistency of the reduction clauses.
2533static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2534 ArrayRef<OMPClause *> Clauses) {
2535 bool InscanFound = false;
2536 SourceLocation InscanLoc;
2537 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2538 // A reduction clause without the inscan reduction-modifier may not appear on
2539 // a construct on which a reduction clause with the inscan reduction-modifier
2540 // appears.
2541 for (OMPClause *C : Clauses) {
2542 if (C->getClauseKind() != OMPC_reduction)
2543 continue;
2544 auto *RC = cast<OMPReductionClause>(C);
2545 if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2546 InscanFound = true;
2547 InscanLoc = RC->getModifierLoc();
2548 continue;
2549 }
2550 if (RC->getModifier() == OMPC_REDUCTION_task) {
2551 // OpenMP 5.0, 2.19.5.4 reduction Clause.
2552 // A reduction clause with the task reduction-modifier may only appear on
2553 // a parallel construct, a worksharing construct or a combined or
2554 // composite construct for which any of the aforementioned constructs is a
2555 // constituent construct and simd or loop are not constituent constructs.
2556 OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2557 if (!(isOpenMPParallelDirective(CurDir) ||
2558 isOpenMPWorksharingDirective(CurDir)) ||
2559 isOpenMPSimdDirective(CurDir))
2560 S.Diag(RC->getModifierLoc(),
2561 diag::err_omp_reduction_task_not_parallel_or_worksharing);
2562 continue;
2563 }
2564 }
2565 if (InscanFound) {
2566 for (OMPClause *C : Clauses) {
2567 if (C->getClauseKind() != OMPC_reduction)
2568 continue;
2569 auto *RC = cast<OMPReductionClause>(C);
2570 if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2571 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2572 ? RC->getBeginLoc()
2573 : RC->getModifierLoc(),
2574 diag::err_omp_inscan_reduction_expected);
2575 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2576 continue;
2577 }
2578 for (Expr *Ref : RC->varlists()) {
2579 assert(Ref && "NULL expr in OpenMP nontemporal clause.")((Ref && "NULL expr in OpenMP nontemporal clause.") ?
static_cast<void> (0) : __assert_fail ("Ref && \"NULL expr in OpenMP nontemporal clause.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2579, __PRETTY_FUNCTION__))
;
2580 SourceLocation ELoc;
2581 SourceRange ERange;
2582 Expr *SimpleRefExpr = Ref;
2583 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
2584 /*AllowArraySection=*/true);
2585 ValueDecl *D = Res.first;
2586 if (!D)
2587 continue;
2588 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
2589 S.Diag(Ref->getExprLoc(),
2590 diag::err_omp_reduction_not_inclusive_exclusive)
2591 << Ref->getSourceRange();
2592 }
2593 }
2594 }
2595 }
2596}
2597
2598static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2599 ArrayRef<OMPClause *> Clauses);
2600static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2601 bool WithInit);
2602
2603static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2604 const ValueDecl *D,
2605 const DSAStackTy::DSAVarData &DVar,
2606 bool IsLoopIterVar = false);
2607
2608void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2609 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2610 // A variable of class type (or array thereof) that appears in a lastprivate
2611 // clause requires an accessible, unambiguous default constructor for the
2612 // class type, unless the list item is also specified in a firstprivate
2613 // clause.
2614 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2615 for (OMPClause *C : D->clauses()) {
2616 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2617 SmallVector<Expr *, 8> PrivateCopies;
2618 for (Expr *DE : Clause->varlists()) {
2619 if (DE->isValueDependent() || DE->isTypeDependent()) {
2620 PrivateCopies.push_back(nullptr);
2621 continue;
2622 }
2623 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2624 auto *VD = cast<VarDecl>(DRE->getDecl());
2625 QualType Type = VD->getType().getNonReferenceType();
2626 const DSAStackTy::DSAVarData DVar =
2627 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(VD, /*FromParent=*/false);
2628 if (DVar.CKind == OMPC_lastprivate) {
2629 // Generate helper private variable and initialize it with the
2630 // default value. The address of the original variable is replaced
2631 // by the address of the new private variable in CodeGen. This new
2632 // variable is not added to IdResolver, so the code in the OpenMP
2633 // region uses original variable for proper diagnostics.
2634 VarDecl *VDPrivate = buildVarDecl(
2635 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2636 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2637 ActOnUninitializedDecl(VDPrivate);
2638 if (VDPrivate->isInvalidDecl()) {
2639 PrivateCopies.push_back(nullptr);
2640 continue;
2641 }
2642 PrivateCopies.push_back(buildDeclRefExpr(
2643 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2644 } else {
2645 // The variable is also a firstprivate, so initialization sequence
2646 // for private copy is generated already.
2647 PrivateCopies.push_back(nullptr);
2648 }
2649 }
2650 Clause->setPrivateCopies(PrivateCopies);
2651 continue;
2652 }
2653 // Finalize nontemporal clause by handling private copies, if any.
2654 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2655 SmallVector<Expr *, 8> PrivateRefs;
2656 for (Expr *RefExpr : Clause->varlists()) {
2657 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.")((RefExpr && "NULL expr in OpenMP nontemporal clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP nontemporal clause.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 2657, __PRETTY_FUNCTION__))
;
2658 SourceLocation ELoc;
2659 SourceRange ERange;
2660 Expr *SimpleRefExpr = RefExpr;
2661 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2662 if (Res.second)
2663 // It will be analyzed later.
2664 PrivateRefs.push_back(RefExpr);
2665 ValueDecl *D = Res.first;
2666 if (!D)
2667 continue;
2668
2669 const DSAStackTy::DSAVarData DVar =
2670 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
2671 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2672 : SimpleRefExpr);
2673 }
2674 Clause->setPrivateRefs(PrivateRefs);
2675 continue;
2676 }
2677 if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
2678 for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
2679 OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
2680 auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
2681 if (!DRE)
2682 continue;
2683 ValueDecl *VD = DRE->getDecl();
2684 if (!VD || !isa<VarDecl>(VD))
2685 continue;
2686 DSAStackTy::DSAVarData DVar =
2687 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(VD, /*FromParent=*/false);
2688 // OpenMP [2.12.5, target Construct]
2689 // Memory allocators that appear in a uses_allocators clause cannot
2690 // appear in other data-sharing attribute clauses or data-mapping
2691 // attribute clauses in the same construct.
2692 Expr *MapExpr = nullptr;
2693 if (DVar.RefExpr ||
2694 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDecl(
2695 VD, /*CurrentRegionOnly=*/true,
2696 [VD, &MapExpr](
2697 OMPClauseMappableExprCommon::MappableExprComponentListRef
2698 MapExprComponents,
2699 OpenMPClauseKind C) {
2700 auto MI = MapExprComponents.rbegin();
2701 auto ME = MapExprComponents.rend();
2702 if (MI != ME &&
2703 MI->getAssociatedDeclaration()->getCanonicalDecl() ==
2704 VD->getCanonicalDecl()) {
2705 MapExpr = MI->getAssociatedExpression();
2706 return true;
2707 }
2708 return false;
2709 })) {
2710 Diag(D.Allocator->getExprLoc(),
2711 diag::err_omp_allocator_used_in_clauses)
2712 << D.Allocator->getSourceRange();
2713 if (DVar.RefExpr)
2714 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VD, DVar);
2715 else
2716 Diag(MapExpr->getExprLoc(), diag::note_used_here)
2717 << MapExpr->getSourceRange();
2718 }
2719 }
2720 continue;
2721 }
2722 }
2723 // Check allocate clauses.
2724 if (!CurContext->isDependentContext())
2725 checkAllocateClauses(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D->clauses());
2726 checkReductionClauses(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D->clauses());
2727 }
2728
2729 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->pop();
2730 DiscardCleanupsInEvaluationContext();
2731 PopExpressionEvaluationContext();
2732}
2733
2734static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2735 Expr *NumIterations, Sema &SemaRef,
2736 Scope *S, DSAStackTy *Stack);
2737
2738namespace {
2739
2740class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2741private:
2742 Sema &SemaRef;
2743
2744public:
2745 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2746 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2747 NamedDecl *ND = Candidate.getCorrectionDecl();
2748 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2749 return VD->hasGlobalStorage() &&
2750 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2751 SemaRef.getCurScope());
2752 }
2753 return false;
2754 }
2755
2756 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2757 return std::make_unique<VarDeclFilterCCC>(*this);
2758 }
2759
2760};
2761
2762class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2763private:
2764 Sema &SemaRef;
2765
2766public:
2767 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2768 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2769 NamedDecl *ND = Candidate.getCorrectionDecl();
2770 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2771 isa<FunctionDecl>(ND))) {
2772 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2773 SemaRef.getCurScope());
2774 }
2775 return false;
2776 }
2777
2778 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2779 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2780 }
2781};
2782
2783} // namespace
2784
2785ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2786 CXXScopeSpec &ScopeSpec,
2787 const DeclarationNameInfo &Id,
2788 OpenMPDirectiveKind Kind) {
2789 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2790 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2791
2792 if (Lookup.isAmbiguous())
2793 return ExprError();
2794
2795 VarDecl *VD;
2796 if (!Lookup.isSingleResult()) {
2797 VarDeclFilterCCC CCC(*this);
2798 if (TypoCorrection Corrected =
2799 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2800 CTK_ErrorRecovery)) {
2801 diagnoseTypo(Corrected,
2802 PDiag(Lookup.empty()
2803 ? diag::err_undeclared_var_use_suggest
2804 : diag::err_omp_expected_var_arg_suggest)
2805 << Id.getName());
2806 VD = Corrected.getCorrectionDeclAs<VarDecl>();
2807 } else {
2808 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2809 : diag::err_omp_expected_var_arg)
2810 << Id.getName();
2811 return ExprError();
2812 }
2813 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2814 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2815 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2816 return ExprError();
2817 }
2818 Lookup.suppressDiagnostics();
2819
2820 // OpenMP [2.9.2, Syntax, C/C++]
2821 // Variables must be file-scope, namespace-scope, or static block-scope.
2822 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2823 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2824 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2825 bool IsDecl =
2826 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2827 Diag(VD->getLocation(),
2828 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2829 << VD;
2830 return ExprError();
2831 }
2832
2833 VarDecl *CanonicalVD = VD->getCanonicalDecl();
2834 NamedDecl *ND = CanonicalVD;
2835 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2836 // A threadprivate directive for file-scope variables must appear outside
2837 // any definition or declaration.
2838 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2839 !getCurLexicalContext()->isTranslationUnit()) {
2840 Diag(Id.getLoc(), diag::err_omp_var_scope)
2841 << getOpenMPDirectiveName(Kind) << VD;
2842 bool IsDecl =
2843 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2844 Diag(VD->getLocation(),
2845 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2846 << VD;
2847 return ExprError();
2848 }
2849 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2850 // A threadprivate directive for static class member variables must appear
2851 // in the class definition, in the same scope in which the member
2852 // variables are declared.
2853 if (CanonicalVD->isStaticDataMember() &&
2854 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2855 Diag(Id.getLoc(), diag::err_omp_var_scope)
2856 << getOpenMPDirectiveName(Kind) << VD;
2857 bool IsDecl =
2858 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2859 Diag(VD->getLocation(),
2860 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2861 << VD;
2862 return ExprError();
2863 }
2864 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2865 // A threadprivate directive for namespace-scope variables must appear
2866 // outside any definition or declaration other than the namespace
2867 // definition itself.
2868 if (CanonicalVD->getDeclContext()->isNamespace() &&
2869 (!getCurLexicalContext()->isFileContext() ||
2870 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2871 Diag(Id.getLoc(), diag::err_omp_var_scope)
2872 << getOpenMPDirectiveName(Kind) << VD;
2873 bool IsDecl =
2874 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2875 Diag(VD->getLocation(),
2876 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2877 << VD;
2878 return ExprError();
2879 }
2880 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2881 // A threadprivate directive for static block-scope variables must appear
2882 // in the scope of the variable and not in a nested scope.
2883 if (CanonicalVD->isLocalVarDecl() && CurScope &&
2884 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2885 Diag(Id.getLoc(), diag::err_omp_var_scope)
2886 << getOpenMPDirectiveName(Kind) << VD;
2887 bool IsDecl =
2888 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2889 Diag(VD->getLocation(),
2890 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2891 << VD;
2892 return ExprError();
2893 }
2894
2895 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2896 // A threadprivate directive must lexically precede all references to any
2897 // of the variables in its list.
2898 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2899 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
2900 Diag(Id.getLoc(), diag::err_omp_var_used)
2901 << getOpenMPDirectiveName(Kind) << VD;
2902 return ExprError();
2903 }
2904
2905 QualType ExprType = VD->getType().getNonReferenceType();
2906 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2907 SourceLocation(), VD,
2908 /*RefersToEnclosingVariableOrCapture=*/false,
2909 Id.getLoc(), ExprType, VK_LValue);
2910}
2911
2912Sema::DeclGroupPtrTy
2913Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2914 ArrayRef<Expr *> VarList) {
2915 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2916 CurContext->addDecl(D);
2917 return DeclGroupPtrTy::make(DeclGroupRef(D));
2918 }
2919 return nullptr;
2920}
2921
2922namespace {
2923class LocalVarRefChecker final
2924 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2925 Sema &SemaRef;
2926
2927public:
2928 bool VisitDeclRefExpr(const DeclRefExpr *E) {
2929 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2930 if (VD->hasLocalStorage()) {
2931 SemaRef.Diag(E->getBeginLoc(),
2932 diag::err_omp_local_var_in_threadprivate_init)
2933 << E->getSourceRange();
2934 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2935 << VD << VD->getSourceRange();
2936 return true;
2937 }
2938 }
2939 return false;
2940 }
2941 bool VisitStmt(const Stmt *S) {
2942 for (const Stmt *Child : S->children()) {
2943 if (Child && Visit(Child))
2944 return true;
2945 }
2946 return false;
2947 }
2948 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2949};
2950} // namespace
2951
2952OMPThreadPrivateDecl *
2953Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2954 SmallVector<Expr *, 8> Vars;
2955 for (Expr *RefExpr : VarList) {
2956 auto *DE = cast<DeclRefExpr>(RefExpr);
2957 auto *VD = cast<VarDecl>(DE->getDecl());
2958 SourceLocation ILoc = DE->getExprLoc();
2959
2960 // Mark variable as used.
2961 VD->setReferenced();
2962 VD->markUsed(Context);
2963
2964 QualType QType = VD->getType();
2965 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2966 // It will be analyzed later.
2967 Vars.push_back(DE);
2968 continue;
2969 }
2970
2971 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2972 // A threadprivate variable must not have an incomplete type.
2973 if (RequireCompleteType(ILoc, VD->getType(),
2974 diag::err_omp_threadprivate_incomplete_type)) {
2975 continue;
2976 }
2977
2978 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2979 // A threadprivate variable must not have a reference type.
2980 if (VD->getType()->isReferenceType()) {
2981 Diag(ILoc, diag::err_omp_ref_type_arg)
2982 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2983 bool IsDecl =
2984 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2985 Diag(VD->getLocation(),
2986 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2987 << VD;
2988 continue;
2989 }
2990
2991 // Check if this is a TLS variable. If TLS is not being supported, produce
2992 // the corresponding diagnostic.
2993 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2994 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2995 getLangOpts().OpenMPUseTLS &&
2996 getASTContext().getTargetInfo().isTLSSupported())) ||
2997 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2998 !VD->isLocalVarDecl())) {
2999 Diag(ILoc, diag::err_omp_var_thread_local)
3000 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3001 bool IsDecl =
3002 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
3003 Diag(VD->getLocation(),
3004 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3005 << VD;
3006 continue;
3007 }
3008
3009 // Check if initial value of threadprivate variable reference variable with
3010 // local storage (it is not supported by runtime).
3011 if (const Expr *Init = VD->getAnyInitializer()) {
3012 LocalVarRefChecker Checker(*this);
3013 if (Checker.Visit(Init))
3014 continue;
3015 }
3016
3017 Vars.push_back(RefExpr);
3018 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(VD, DE, OMPC_threadprivate);
3019 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3020 Context, SourceRange(Loc, Loc)));
3021 if (ASTMutationListener *ML = Context.getASTMutationListener())
3022 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3023 }
3024 OMPThreadPrivateDecl *D = nullptr;
3025 if (!Vars.empty()) {
3026 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
3027 Vars);
3028 D->setAccess(AS_public);
3029 }
3030 return D;
3031}
3032
3033static OMPAllocateDeclAttr::AllocatorTypeTy
3034getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3035 if (!Allocator)
3036 return OMPAllocateDeclAttr::OMPNullMemAlloc;
3037 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3038 Allocator->isInstantiationDependent() ||
3039 Allocator->containsUnexpandedParameterPack())
3040 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3041 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3042 const Expr *AE = Allocator->IgnoreParenImpCasts();
3043 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3044 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3045 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3046 llvm::FoldingSetNodeID AEId, DAEId;
3047 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3048 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
3049 if (AEId == DAEId) {
3050 AllocatorKindRes = AllocatorKind;
3051 break;
3052 }
3053 }
3054 return AllocatorKindRes;
3055}
3056
3057static bool checkPreviousOMPAllocateAttribute(
3058 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3059 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3060 if (!VD->hasAttr<OMPAllocateDeclAttr>())
3061 return false;
3062 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3063 Expr *PrevAllocator = A->getAllocator();
3064 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3065 getAllocatorKind(S, Stack, PrevAllocator);
3066 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3067 if (AllocatorsMatch &&
3068 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3069 Allocator && PrevAllocator) {
3070 const Expr *AE = Allocator->IgnoreParenImpCasts();
3071 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3072 llvm::FoldingSetNodeID AEId, PAEId;
3073 AE->Profile(AEId, S.Context, /*Canonical=*/true);
3074 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3075 AllocatorsMatch = AEId == PAEId;
3076 }
3077 if (!AllocatorsMatch) {
3078 SmallString<256> AllocatorBuffer;
3079 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3080 if (Allocator)
3081 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3082 SmallString<256> PrevAllocatorBuffer;
3083 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3084 if (PrevAllocator)
3085 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3086 S.getPrintingPolicy());
3087
3088 SourceLocation AllocatorLoc =
3089 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3090 SourceRange AllocatorRange =
3091 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3092 SourceLocation PrevAllocatorLoc =
3093 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3094 SourceRange PrevAllocatorRange =
3095 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3096 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3097 << (Allocator ? 1 : 0) << AllocatorStream.str()
3098 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3099 << AllocatorRange;
3100 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3101 << PrevAllocatorRange;
3102 return true;
3103 }
3104 return false;
3105}
3106
3107static void
3108applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
3109 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3110 Expr *Allocator, SourceRange SR) {
3111 if (VD->hasAttr<OMPAllocateDeclAttr>())
3112 return;
3113 if (Allocator &&
3114 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3115 Allocator->isInstantiationDependent() ||
3116 Allocator->containsUnexpandedParameterPack()))
3117 return;
3118 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3119 Allocator, SR);
3120 VD->addAttr(A);
3121 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
3122 ML->DeclarationMarkedOpenMPAllocate(VD, A);
3123}
3124
3125Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
3126 SourceLocation Loc, ArrayRef<Expr *> VarList,
3127 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
3128 assert(Clauses.size() <= 1 && "Expected at most one clause.")((Clauses.size() <= 1 && "Expected at most one clause."
) ? static_cast<void> (0) : __assert_fail ("Clauses.size() <= 1 && \"Expected at most one clause.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 3128, __PRETTY_FUNCTION__))
;
3129 Expr *Allocator = nullptr;
3130 if (Clauses.empty()) {
3131 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3132 // allocate directives that appear in a target region must specify an
3133 // allocator clause unless a requires directive with the dynamic_allocators
3134 // clause is present in the same compilation unit.
3135 if (LangOpts.OpenMPIsDevice &&
3136 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3137 targetDiag(Loc, diag::err_expected_allocator_clause);
3138 } else {
3139 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
3140 }
3141 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3142 getAllocatorKind(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, Allocator);
3143 SmallVector<Expr *, 8> Vars;
3144 for (Expr *RefExpr : VarList) {
3145 auto *DE = cast<DeclRefExpr>(RefExpr);
3146 auto *VD = cast<VarDecl>(DE->getDecl());
3147
3148 // Check if this is a TLS variable or global register.
3149 if (VD->getTLSKind() != VarDecl::TLS_None ||
3150 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3151 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3152 !VD->isLocalVarDecl()))
3153 continue;
3154
3155 // If the used several times in the allocate directive, the same allocator
3156 // must be used.
3157 if (checkPreviousOMPAllocateAttribute(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, RefExpr, VD,
3158 AllocatorKind, Allocator))
3159 continue;
3160
3161 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3162 // If a list item has a static storage type, the allocator expression in the
3163 // allocator clause must be a constant expression that evaluates to one of
3164 // the predefined memory allocator values.
3165 if (Allocator && VD->hasGlobalStorage()) {
3166 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3167 Diag(Allocator->getExprLoc(),
3168 diag::err_omp_expected_predefined_allocator)
3169 << Allocator->getSourceRange();
3170 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
3171 VarDecl::DeclarationOnly;
3172 Diag(VD->getLocation(),
3173 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3174 << VD;
3175 continue;
3176 }
3177 }
3178
3179 Vars.push_back(RefExpr);
3180 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
3181 DE->getSourceRange());
3182 }
3183 if (Vars.empty())
3184 return nullptr;
3185 if (!Owner)
3186 Owner = getCurLexicalContext();
3187 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
3188 D->setAccess(AS_public);
3189 Owner->addDecl(D);
3190 return DeclGroupPtrTy::make(DeclGroupRef(D));
3191}
3192
3193Sema::DeclGroupPtrTy
3194Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
3195 ArrayRef<OMPClause *> ClauseList) {
3196 OMPRequiresDecl *D = nullptr;
3197 if (!CurContext->isFileContext()) {
3198 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3199 } else {
3200 D = CheckOMPRequiresDecl(Loc, ClauseList);
3201 if (D) {
3202 CurContext->addDecl(D);
3203 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addRequiresDecl(D);
3204 }
3205 }
3206 return DeclGroupPtrTy::make(DeclGroupRef(D));
3207}
3208
3209void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
3210 OpenMPDirectiveKind DKind,
3211 ArrayRef<StringRef> Assumptions,
3212 bool SkippedClauses) {
3213 if (!SkippedClauses && Assumptions.empty())
3214 Diag(Loc, diag::err_omp_no_clause_for_directive)
3215 << llvm::omp::getAllAssumeClauseOptions()
3216 << llvm::omp::getOpenMPDirectiveName(DKind);
3217
3218 auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
3219 if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3220 OMPAssumeScoped.push_back(AA);
3221 return;
3222 }
3223
3224 // Global assumes without assumption clauses are ignored.
3225 if (Assumptions.empty())
3226 return;
3227
3228 assert(DKind == llvm::omp::Directive::OMPD_assumes &&((DKind == llvm::omp::Directive::OMPD_assumes && "Unexpected omp assumption directive!"
) ? static_cast<void> (0) : __assert_fail ("DKind == llvm::omp::Directive::OMPD_assumes && \"Unexpected omp assumption directive!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 3229, __PRETTY_FUNCTION__))
3229 "Unexpected omp assumption directive!")((DKind == llvm::omp::Directive::OMPD_assumes && "Unexpected omp assumption directive!"
) ? static_cast<void> (0) : __assert_fail ("DKind == llvm::omp::Directive::OMPD_assumes && \"Unexpected omp assumption directive!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 3229, __PRETTY_FUNCTION__))
;
3230 OMPAssumeGlobal.push_back(AA);
3231
3232 // The OMPAssumeGlobal scope above will take care of new declarations but
3233 // we also want to apply the assumption to existing ones, e.g., to
3234 // declarations in included headers. To this end, we traverse all existing
3235 // declaration contexts and annotate function declarations here.
3236 SmallVector<DeclContext *, 8> DeclContexts;
3237 auto *Ctx = CurContext;
3238 while (Ctx->getLexicalParent())
3239 Ctx = Ctx->getLexicalParent();
3240 DeclContexts.push_back(Ctx);
3241 while (!DeclContexts.empty()) {
3242 DeclContext *DC = DeclContexts.pop_back_val();
3243 for (auto *SubDC : DC->decls()) {
3244 if (SubDC->isInvalidDecl())
3245 continue;
3246 if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3247 DeclContexts.push_back(CTD->getTemplatedDecl());
3248 for (auto *S : CTD->specializations())
3249 DeclContexts.push_back(S);
3250 continue;
3251 }
3252 if (auto *DC = dyn_cast<DeclContext>(SubDC))
3253 DeclContexts.push_back(DC);
3254 if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3255 F->addAttr(AA);
3256 continue;
3257 }
3258 }
3259 }
3260}
3261
3262void Sema::ActOnOpenMPEndAssumesDirective() {
3263 assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!")((isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!"
) ? static_cast<void> (0) : __assert_fail ("isInOpenMPAssumeScope() && \"Not in OpenMP assumes scope!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 3263, __PRETTY_FUNCTION__))
;
3264 OMPAssumeScoped.pop_back();
3265}
3266
3267OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
3268 ArrayRef<OMPClause *> ClauseList) {
3269 /// For target specific clauses, the requires directive cannot be
3270 /// specified after the handling of any of the target regions in the
3271 /// current compilation unit.
3272 ArrayRef<SourceLocation> TargetLocations =
3273 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getEncounteredTargetLocs();
3274 SourceLocation AtomicLoc = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAtomicDirectiveLoc();
3275 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3276 for (const OMPClause *CNew : ClauseList) {
3277 // Check if any of the requires clauses affect target regions.
3278 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
3279 isa<OMPUnifiedAddressClause>(CNew) ||
3280 isa<OMPReverseOffloadClause>(CNew) ||
3281 isa<OMPDynamicAllocatorsClause>(CNew)) {
3282 Diag(Loc, diag::err_omp_directive_before_requires)
3283 << "target" << getOpenMPClauseName(CNew->getClauseKind());
3284 for (SourceLocation TargetLoc : TargetLocations) {
3285 Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3286 << "target";
3287 }
3288 } else if (!AtomicLoc.isInvalid() &&
3289 isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
3290 Diag(Loc, diag::err_omp_directive_before_requires)
3291 << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
3292 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3293 << "atomic";
3294 }
3295 }
3296 }
3297
3298 if (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDuplicateRequiresClause(ClauseList))
3299 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
3300 ClauseList);
3301 return nullptr;
3302}
3303
3304static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3305 const ValueDecl *D,
3306 const DSAStackTy::DSAVarData &DVar,
3307 bool IsLoopIterVar) {
3308 if (DVar.RefExpr) {
3309 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3310 << getOpenMPClauseName(DVar.CKind);
3311 return;
3312 }
3313 enum {
3314 PDSA_StaticMemberShared,
3315 PDSA_StaticLocalVarShared,
3316 PDSA_LoopIterVarPrivate,
3317 PDSA_LoopIterVarLinear,
3318 PDSA_LoopIterVarLastprivate,
3319 PDSA_ConstVarShared,
3320 PDSA_GlobalVarShared,
3321 PDSA_TaskVarFirstprivate,
3322 PDSA_LocalVarPrivate,
3323 PDSA_Implicit
3324 } Reason = PDSA_Implicit;
3325 bool ReportHint = false;
3326 auto ReportLoc = D->getLocation();
3327 auto *VD = dyn_cast<VarDecl>(D);
3328 if (IsLoopIterVar) {
3329 if (DVar.CKind == OMPC_private)
3330 Reason = PDSA_LoopIterVarPrivate;
3331 else if (DVar.CKind == OMPC_lastprivate)
3332 Reason = PDSA_LoopIterVarLastprivate;
3333 else
3334 Reason = PDSA_LoopIterVarLinear;
3335 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3336 DVar.CKind == OMPC_firstprivate) {
3337 Reason = PDSA_TaskVarFirstprivate;
3338 ReportLoc = DVar.ImplicitDSALoc;
3339 } else if (VD && VD->isStaticLocal())
3340 Reason = PDSA_StaticLocalVarShared;
3341 else if (VD && VD->isStaticDataMember())
3342 Reason = PDSA_StaticMemberShared;
3343 else if (VD && VD->isFileVarDecl())
3344 Reason = PDSA_GlobalVarShared;
3345 else if (D->getType().isConstant(SemaRef.getASTContext()))
3346 Reason = PDSA_ConstVarShared;
3347 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3348 ReportHint = true;
3349 Reason = PDSA_LocalVarPrivate;
3350 }
3351 if (Reason != PDSA_Implicit) {
3352 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3353 << Reason << ReportHint
3354 << getOpenMPDirectiveName(Stack->getCurrentDirective());
3355 } else if (DVar.ImplicitDSALoc.isValid()) {
3356 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3357 << getOpenMPClauseName(DVar.CKind);
3358 }
3359}
3360
3361static OpenMPMapClauseKind
3362getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
3363 bool IsAggregateOrDeclareTarget) {
3364 OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
3365 switch (M) {
3366 case OMPC_DEFAULTMAP_MODIFIER_alloc:
3367 Kind = OMPC_MAP_alloc;
3368 break;
3369 case OMPC_DEFAULTMAP_MODIFIER_to:
3370 Kind = OMPC_MAP_to;
3371 break;
3372 case OMPC_DEFAULTMAP_MODIFIER_from:
3373 Kind = OMPC_MAP_from;
3374 break;
3375 case OMPC_DEFAULTMAP_MODIFIER_tofrom:
3376 Kind = OMPC_MAP_tofrom;
3377 break;
3378 case OMPC_DEFAULTMAP_MODIFIER_present:
3379 // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
3380 // If implicit-behavior is present, each variable referenced in the
3381 // construct in the category specified by variable-category is treated as if
3382 // it had been listed in a map clause with the map-type of alloc and
3383 // map-type-modifier of present.
3384 Kind = OMPC_MAP_alloc;
3385 break;
3386 case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
3387 case OMPC_DEFAULTMAP_MODIFIER_last:
3388 llvm_unreachable("Unexpected defaultmap implicit behavior")::llvm::llvm_unreachable_internal("Unexpected defaultmap implicit behavior"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 3388)
;
3389 case OMPC_DEFAULTMAP_MODIFIER_none:
3390 case OMPC_DEFAULTMAP_MODIFIER_default:
3391 case OMPC_DEFAULTMAP_MODIFIER_unknown:
3392 // IsAggregateOrDeclareTarget could be true if:
3393 // 1. the implicit behavior for aggregate is tofrom
3394 // 2. it's a declare target link
3395 if (IsAggregateOrDeclareTarget) {
3396 Kind = OMPC_MAP_tofrom;
3397 break;
3398 }
3399 llvm_unreachable("Unexpected defaultmap implicit behavior")::llvm::llvm_unreachable_internal("Unexpected defaultmap implicit behavior"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 3399)
;
3400 }
3401 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known")((Kind != OMPC_MAP_unknown && "Expect map kind to be known"
) ? static_cast<void> (0) : __assert_fail ("Kind != OMPC_MAP_unknown && \"Expect map kind to be known\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 3401, __PRETTY_FUNCTION__))
;
3402 return Kind;
3403}
3404
3405namespace {
3406class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
3407 DSAStackTy *Stack;
3408 Sema &SemaRef;
3409 bool ErrorFound = false;
3410 bool TryCaptureCXXThisMembers = false;
3411 CapturedStmt *CS = nullptr;
3412 const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
3413 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
3414 llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
3415 llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
3416 ImplicitMapModifier[DefaultmapKindNum];
3417 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
3418 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
3419
3420 void VisitSubCaptures(OMPExecutableDirective *S) {
3421 // Check implicitly captured variables.
3422 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
3423 return;
3424 if (S->getDirectiveKind() == OMPD_atomic ||
3425 S->getDirectiveKind() == OMPD_critical ||
3426 S->getDirectiveKind() == OMPD_section ||
3427 S->getDirectiveKind() == OMPD_master ||
3428 S->getDirectiveKind() == OMPD_masked ||
3429 isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
3430 Visit(S->getAssociatedStmt());
3431 return;
3432 }
3433 visitSubCaptures(S->getInnermostCapturedStmt());
3434 // Try to capture inner this->member references to generate correct mappings
3435 // and diagnostics.
3436 if (TryCaptureCXXThisMembers ||
3437 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3438 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
3439 [](const CapturedStmt::Capture &C) {
3440 return C.capturesThis();
3441 }))) {
3442 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
3443 TryCaptureCXXThisMembers = true;
3444 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
3445 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
3446 }
3447 // In tasks firstprivates are not captured anymore, need to analyze them
3448 // explicitly.
3449 if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
3450 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
3451 for (OMPClause *C : S->clauses())
3452 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
3453 for (Expr *Ref : FC->varlists())
3454 Visit(Ref);
3455 }
3456 }
3457 }
3458
3459public:
3460 void VisitDeclRefExpr(DeclRefExpr *E) {
3461 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
3462 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
3463 E->isInstantiationDependent())
3464 return;
3465 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3466 // Check the datasharing rules for the expressions in the clauses.
3467 if (!CS) {
3468 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
3469 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
3470 Visit(CED->getInit());
3471 return;
3472 }
3473 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
3474 // Do not analyze internal variables and do not enclose them into
3475 // implicit clauses.
3476 return;
3477 VD = VD->getCanonicalDecl();
3478 // Skip internally declared variables.
3479 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
3480 !Stack->isImplicitTaskFirstprivate(VD))
3481 return;
3482 // Skip allocators in uses_allocators clauses.
3483 if (Stack->isUsesAllocatorsDecl(VD).hasValue())
3484 return;
3485
3486 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
3487 // Check if the variable has explicit DSA set and stop analysis if it so.
3488 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
3489 return;
3490
3491 // Skip internally declared static variables.
3492 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3493 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3494 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
3495 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3496 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
3497 !Stack->isImplicitTaskFirstprivate(VD))
3498 return;
3499
3500 SourceLocation ELoc = E->getExprLoc();
3501 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3502 // The default(none) clause requires that each variable that is referenced
3503 // in the construct, and does not have a predetermined data-sharing
3504 // attribute, must have its data-sharing attribute explicitly determined
3505 // by being listed in a data-sharing attribute clause.
3506 if (DVar.CKind == OMPC_unknown &&
3507 (Stack->getDefaultDSA() == DSA_none ||
3508 Stack->getDefaultDSA() == DSA_firstprivate) &&
3509 isImplicitOrExplicitTaskingRegion(DKind) &&
3510 VarsWithInheritedDSA.count(VD) == 0) {
3511 bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
3512 if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) {
3513 DSAStackTy::DSAVarData DVar =
3514 Stack->getImplicitDSA(VD, /*FromParent=*/false);
3515 InheritedDSA = DVar.CKind == OMPC_unknown;
3516 }
3517 if (InheritedDSA)
3518 VarsWithInheritedDSA[VD] = E;
3519 return;
3520 }
3521
3522 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3523 // If implicit-behavior is none, each variable referenced in the
3524 // construct that does not have a predetermined data-sharing attribute
3525 // and does not appear in a to or link clause on a declare target
3526 // directive must be listed in a data-mapping attribute clause, a
3527 // data-haring attribute clause (including a data-sharing attribute
3528 // clause on a combined construct where target. is one of the
3529 // constituent constructs), or an is_device_ptr clause.
3530 OpenMPDefaultmapClauseKind ClauseKind =
3531 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
3532 if (SemaRef.getLangOpts().OpenMP >= 50) {
3533 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3534 OMPC_DEFAULTMAP_MODIFIER_none;
3535 if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3536 VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3537 // Only check for data-mapping attribute and is_device_ptr here
3538 // since we have already make sure that the declaration does not
3539 // have a data-sharing attribute above
3540 if (!Stack->checkMappableExprComponentListsForDecl(
3541 VD, /*CurrentRegionOnly=*/true,
3542 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3543 MapExprComponents,
3544 OpenMPClauseKind) {
3545 auto MI = MapExprComponents.rbegin();
3546 auto ME = MapExprComponents.rend();
3547 return MI != ME && MI->getAssociatedDeclaration() == VD;
3548 })) {
3549 VarsWithInheritedDSA[VD] = E;
3550 return;
3551 }
3552 }
3553 }
3554 if (SemaRef.getLangOpts().OpenMP > 50) {
3555 bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
3556 OMPC_DEFAULTMAP_MODIFIER_present;
3557 if (IsModifierPresent) {
3558 if (llvm::find(ImplicitMapModifier[ClauseKind],
3559 OMPC_MAP_MODIFIER_present) ==
3560 std::end(ImplicitMapModifier[ClauseKind])) {
3561 ImplicitMapModifier[ClauseKind].push_back(
3562 OMPC_MAP_MODIFIER_present);
3563 }
3564 }
3565 }
3566
3567 if (isOpenMPTargetExecutionDirective(DKind) &&
3568 !Stack->isLoopControlVariable(VD).first) {
3569 if (!Stack->checkMappableExprComponentListsForDecl(
3570 VD, /*CurrentRegionOnly=*/true,
3571 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
3572 StackComponents,
3573 OpenMPClauseKind) {
3574 if (SemaRef.LangOpts.OpenMP >= 50)
3575 return !StackComponents.empty();
3576 // Variable is used if it has been marked as an array, array
3577 // section, array shaping or the variable iself.
3578 return StackComponents.size() == 1 ||
3579 std::all_of(
3580 std::next(StackComponents.rbegin()),
3581 StackComponents.rend(),
3582 [](const OMPClauseMappableExprCommon::
3583 MappableComponent &MC) {
3584 return MC.getAssociatedDeclaration() ==
3585 nullptr &&
3586 (isa<OMPArraySectionExpr>(
3587 MC.getAssociatedExpression()) ||
3588 isa<OMPArrayShapingExpr>(
3589 MC.getAssociatedExpression()) ||
3590 isa<ArraySubscriptExpr>(
3591 MC.getAssociatedExpression()));
3592 });
3593 })) {
3594 bool IsFirstprivate = false;
3595 // By default lambdas are captured as firstprivates.
3596 if (const auto *RD =
3597 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
3598 IsFirstprivate = RD->isLambda();
3599 IsFirstprivate =
3600 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3601 if (IsFirstprivate) {
3602 ImplicitFirstprivate.emplace_back(E);
3603 } else {
3604 OpenMPDefaultmapClauseModifier M =
3605 Stack->getDefaultmapModifier(ClauseKind);
3606 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3607 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3608 ImplicitMap[ClauseKind][Kind].emplace_back(E);
3609 }
3610 return;
3611 }
3612 }
3613
3614 // OpenMP [2.9.3.6, Restrictions, p.2]
3615 // A list item that appears in a reduction clause of the innermost
3616 // enclosing worksharing or parallel construct may not be accessed in an
3617 // explicit task.
3618 DVar = Stack->hasInnermostDSA(
3619 VD,
3620 [](OpenMPClauseKind C, bool AppliedToPointee) {
3621 return C == OMPC_reduction && !AppliedToPointee;
3622 },
3623 [](OpenMPDirectiveKind K) {
3624 return isOpenMPParallelDirective(K) ||
3625 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3626 },
3627 /*FromParent=*/true);
3628 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3629 ErrorFound = true;
3630 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3631 reportOriginalDsa(SemaRef, Stack, VD, DVar);
3632 return;
3633 }
3634
3635 // Define implicit data-sharing attributes for task.
3636 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
3637 if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
3638 (Stack->getDefaultDSA() == DSA_firstprivate &&
3639 DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) &&
3640 !Stack->isLoopControlVariable(VD).first) {
3641 ImplicitFirstprivate.push_back(E);
3642 return;
3643 }
3644
3645 // Store implicitly used globals with declare target link for parent
3646 // target.
3647 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3648 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3649 Stack->addToParentTargetRegionLinkGlobals(E);
3650 return;
3651 }
3652 }
3653 }
3654 void VisitMemberExpr(MemberExpr *E) {
3655 if (E->isTypeDependent() || E->isValueDependent() ||
3656 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3657 return;
3658 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3659 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
3660 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
3661 if (!FD)
3662 return;
3663 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
3664 // Check if the variable has explicit DSA set and stop analysis if it
3665 // so.
3666 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3667 return;
3668
3669 if (isOpenMPTargetExecutionDirective(DKind) &&
3670 !Stack->isLoopControlVariable(FD).first &&
3671 !Stack->checkMappableExprComponentListsForDecl(
3672 FD, /*CurrentRegionOnly=*/true,
3673 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3674 StackComponents,
3675 OpenMPClauseKind) {
3676 return isa<CXXThisExpr>(
3677 cast<MemberExpr>(
3678 StackComponents.back().getAssociatedExpression())
3679 ->getBase()
3680 ->IgnoreParens());
3681 })) {
3682 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3683 // A bit-field cannot appear in a map clause.
3684 //
3685 if (FD->isBitField())
3686 return;
3687
3688 // Check to see if the member expression is referencing a class that
3689 // has already been explicitly mapped
3690 if (Stack->isClassPreviouslyMapped(TE->getType()))
3691 return;
3692
3693 OpenMPDefaultmapClauseModifier Modifier =
3694 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3695 OpenMPDefaultmapClauseKind ClauseKind =
3696 getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
3697 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3698 Modifier, /*IsAggregateOrDeclareTarget*/ true);
3699 ImplicitMap[ClauseKind][Kind].emplace_back(E);
3700 return;
3701 }
3702
3703 SourceLocation ELoc = E->getExprLoc();
3704 // OpenMP [2.9.3.6, Restrictions, p.2]
3705 // A list item that appears in a reduction clause of the innermost
3706 // enclosing worksharing or parallel construct may not be accessed in
3707 // an explicit task.
3708 DVar = Stack->hasInnermostDSA(
3709 FD,
3710 [](OpenMPClauseKind C, bool AppliedToPointee) {
3711 return C == OMPC_reduction && !AppliedToPointee;
3712 },
3713 [](OpenMPDirectiveKind K) {
3714 return isOpenMPParallelDirective(K) ||
3715 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3716 },
3717 /*FromParent=*/true);
3718 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3719 ErrorFound = true;
3720 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
3721 reportOriginalDsa(SemaRef, Stack, FD, DVar);
3722 return;
3723 }
3724
3725 // Define implicit data-sharing attributes for task.
3726 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
3727 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
3728 !Stack->isLoopControlVariable(FD).first) {
3729 // Check if there is a captured expression for the current field in the
3730 // region. Do not mark it as firstprivate unless there is no captured
3731 // expression.
3732 // TODO: try to make it firstprivate.
3733 if (DVar.CKind != OMPC_unknown)
3734 ImplicitFirstprivate.push_back(E);
3735 }
3736 return;
3737 }
3738 if (isOpenMPTargetExecutionDirective(DKind)) {
3739 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
3740 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
3741 Stack->getCurrentDirective(),
3742 /*NoDiagnose=*/true))
3743 return;
3744 const auto *VD = cast<ValueDecl>(
3745 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3746 if (!Stack->checkMappableExprComponentListsForDecl(
3747 VD, /*CurrentRegionOnly=*/true,
3748 [&CurComponents](
3749 OMPClauseMappableExprCommon::MappableExprComponentListRef
3750 StackComponents,
3751 OpenMPClauseKind) {
3752 auto CCI = CurComponents.rbegin();
3753 auto CCE = CurComponents.rend();
3754 for (const auto &SC : llvm::reverse(StackComponents)) {
3755 // Do both expressions have the same kind?
3756 if (CCI->getAssociatedExpression()->getStmtClass() !=
3757 SC.getAssociatedExpression()->getStmtClass())
3758 if (!((isa<OMPArraySectionExpr>(
3759 SC.getAssociatedExpression()) ||
3760 isa<OMPArrayShapingExpr>(
3761 SC.getAssociatedExpression())) &&
3762 isa<ArraySubscriptExpr>(
3763 CCI->getAssociatedExpression())))
3764 return false;
3765
3766 const Decl *CCD = CCI->getAssociatedDeclaration();
3767 const Decl *SCD = SC.getAssociatedDeclaration();
3768 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3769 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3770 if (SCD != CCD)
3771 return false;
3772 std::advance(CCI, 1);
3773 if (CCI == CCE)
3774 break;
3775 }
3776 return true;
3777 })) {
3778 Visit(E->getBase());
3779 }
3780 } else if (!TryCaptureCXXThisMembers) {
3781 Visit(E->getBase());
3782 }
3783 }
3784 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3785 for (OMPClause *C : S->clauses()) {
3786 // Skip analysis of arguments of implicitly defined firstprivate clause
3787 // for task|target directives.
3788 // Skip analysis of arguments of implicitly defined map clause for target
3789 // directives.
3790 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3791 C->isImplicit() &&
3792 !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
3793 for (Stmt *CC : C->children()) {
3794 if (CC)
3795 Visit(CC);
3796 }
3797 }
3798 }
3799 // Check implicitly captured variables.
3800 VisitSubCaptures(S);
3801 }
3802
3803 void VisitOMPTileDirective(OMPTileDirective *S) {
3804 // #pragma omp tile does not introduce data sharing.
3805 VisitStmt(S);
3806 }
3807
3808 void VisitStmt(Stmt *S) {
3809 for (Stmt *C : S->children()) {
3810 if (C) {
3811 // Check implicitly captured variables in the task-based directives to
3812 // check if they must be firstprivatized.
3813 Visit(C);
3814 }
3815 }
3816 }
3817
3818 void visitSubCaptures(CapturedStmt *S) {
3819 for (const CapturedStmt::Capture &Cap : S->captures()) {
3820 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3821 continue;
3822 VarDecl *VD = Cap.getCapturedVar();
3823 // Do not try to map the variable if it or its sub-component was mapped
3824 // already.
3825 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3826 Stack->checkMappableExprComponentListsForDecl(
3827 VD, /*CurrentRegionOnly=*/true,
3828 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3829 OpenMPClauseKind) { return true; }))
3830 continue;
3831 DeclRefExpr *DRE = buildDeclRefExpr(
3832 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3833 Cap.getLocation(), /*RefersToCapture=*/true);
3834 Visit(DRE);
3835 }
3836 }
3837 bool isErrorFound() const { return ErrorFound; }
3838 ArrayRef<Expr *> getImplicitFirstprivate() const {
3839 return ImplicitFirstprivate;
3840 }
3841 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
3842 OpenMPMapClauseKind MK) const {
3843 return ImplicitMap[DK][MK];
3844 }
3845 ArrayRef<OpenMPMapModifierKind>
3846 getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
3847 return ImplicitMapModifier[Kind];
3848 }
3849 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3850 return VarsWithInheritedDSA;
3851 }
3852
3853 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3854 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3855 // Process declare target link variables for the target directives.
3856 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3857 for (DeclRefExpr *E : Stack->getLinkGlobals())
3858 Visit(E);
3859 }
3860 }
3861};
3862} // namespace
3863
3864void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3865 switch (DKind) {
3866 case OMPD_parallel:
3867 case OMPD_parallel_for:
3868 case OMPD_parallel_for_simd:
3869 case OMPD_parallel_sections:
3870 case OMPD_parallel_master:
3871 case OMPD_teams:
3872 case OMPD_teams_distribute:
3873 case OMPD_teams_distribute_simd: {
3874 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3875 QualType KmpInt32PtrTy =
3876 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3877 Sema::CapturedParamNameType Params[] = {
3878 std::make_pair(".global_tid.", KmpInt32PtrTy),
3879 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3880 std::make_pair(StringRef(), QualType()) // __context with shared vars
3881 };
3882 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3883 Params);
3884 break;
3885 }
3886 case OMPD_target_teams:
3887 case OMPD_target_parallel:
3888 case OMPD_target_parallel_for:
3889 case OMPD_target_parallel_for_simd:
3890 case OMPD_target_teams_distribute:
3891 case OMPD_target_teams_distribute_simd: {
3892 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3893 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3894 QualType KmpInt32PtrTy =
3895 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3896 QualType Args[] = {VoidPtrTy};
3897 FunctionProtoType::ExtProtoInfo EPI;
3898 EPI.Variadic = true;
3899 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3900 Sema::CapturedParamNameType Params[] = {
3901 std::make_pair(".global_tid.", KmpInt32Ty),
3902 std::make_pair(".part_id.", KmpInt32PtrTy),
3903 std::make_pair(".privates.", VoidPtrTy),
3904 std::make_pair(
3905 ".copy_fn.",
3906 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3907 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3908 std::make_pair(StringRef(), QualType()) // __context with shared vars
3909 };
3910 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3911 Params, /*OpenMPCaptureLevel=*/0);
3912 // Mark this captured region as inlined, because we don't use outlined
3913 // function directly.
3914 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3915 AlwaysInlineAttr::CreateImplicit(
3916 Context, {}, AttributeCommonInfo::AS_Keyword,
3917 AlwaysInlineAttr::Keyword_forceinline));
3918 Sema::CapturedParamNameType ParamsTarget[] = {
3919 std::make_pair(StringRef(), QualType()) // __context with shared vars
3920 };
3921 // Start a captured region for 'target' with no implicit parameters.
3922 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3923 ParamsTarget, /*OpenMPCaptureLevel=*/1);
3924 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3925 std::make_pair(".global_tid.", KmpInt32PtrTy),
3926 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3927 std::make_pair(StringRef(), QualType()) // __context with shared vars
3928 };
3929 // Start a captured region for 'teams' or 'parallel'. Both regions have
3930 // the same implicit parameters.
3931 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3932 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3933 break;
3934 }
3935 case OMPD_target:
3936 case OMPD_target_simd: {
3937 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3938 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3939 QualType KmpInt32PtrTy =
3940 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3941 QualType Args[] = {VoidPtrTy};
3942 FunctionProtoType::ExtProtoInfo EPI;
3943 EPI.Variadic = true;
3944 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3945 Sema::CapturedParamNameType Params[] = {
3946 std::make_pair(".global_tid.", KmpInt32Ty),
3947 std::make_pair(".part_id.", KmpInt32PtrTy),
3948 std::make_pair(".privates.", VoidPtrTy),
3949 std::make_pair(
3950 ".copy_fn.",
3951 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3952 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3953 std::make_pair(StringRef(), QualType()) // __context with shared vars
3954 };
3955 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3956 Params, /*OpenMPCaptureLevel=*/0);
3957 // Mark this captured region as inlined, because we don't use outlined
3958 // function directly.
3959 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3960 AlwaysInlineAttr::CreateImplicit(
3961 Context, {}, AttributeCommonInfo::AS_Keyword,
3962 AlwaysInlineAttr::Keyword_forceinline));
3963 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3964 std::make_pair(StringRef(), QualType()),
3965 /*OpenMPCaptureLevel=*/1);
3966 break;
3967 }
3968 case OMPD_atomic:
3969 case OMPD_critical:
3970 case OMPD_section:
3971 case OMPD_master:
3972 case OMPD_masked:
3973 case OMPD_tile:
3974 break;
3975 case OMPD_simd:
3976 case OMPD_for:
3977 case OMPD_for_simd:
3978 case OMPD_sections:
3979 case OMPD_single:
3980 case OMPD_taskgroup:
3981 case OMPD_distribute:
3982 case OMPD_distribute_simd:
3983 case OMPD_ordered:
3984 case OMPD_target_data:
3985 case OMPD_dispatch: {
3986 Sema::CapturedParamNameType Params[] = {
3987 std::make_pair(StringRef(), QualType()) // __context with shared vars
3988 };
3989 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3990 Params);
3991 break;
3992 }
3993 case OMPD_task: {
3994 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3995 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3996 QualType KmpInt32PtrTy =
3997 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3998 QualType Args[] = {VoidPtrTy};
3999 FunctionProtoType::ExtProtoInfo EPI;
4000 EPI.Variadic = true;
4001 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4002 Sema::CapturedParamNameType Params[] = {
4003 std::make_pair(".global_tid.", KmpInt32Ty),
4004 std::make_pair(".part_id.", KmpInt32PtrTy),
4005 std::make_pair(".privates.", VoidPtrTy),
4006 std::make_pair(
4007 ".copy_fn.",
4008 Context.getPointerType(CopyFnType).withConst().withRestrict()),
4009 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4010 std::make_pair(StringRef(), QualType()) // __context with shared vars
4011 };
4012 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4013 Params);
4014 // Mark this captured region as inlined, because we don't use outlined
4015 // function directly.
4016 getCurCapturedRegion()->TheCapturedDecl->addAttr(
4017 AlwaysInlineAttr::CreateImplicit(
4018 Context, {}, AttributeCommonInfo::AS_Keyword,
4019 AlwaysInlineAttr::Keyword_forceinline));
4020 break;
4021 }
4022 case OMPD_taskloop:
4023 case OMPD_taskloop_simd:
4024 case OMPD_master_taskloop:
4025 case OMPD_master_taskloop_simd: {
4026 QualType KmpInt32Ty =
4027 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4028 .withConst();
4029 QualType KmpUInt64Ty =
4030 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4031 .withConst();
4032 QualType KmpInt64Ty =
4033 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4034 .withConst();
4035 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4036 QualType KmpInt32PtrTy =
4037 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4038 QualType Args[] = {VoidPtrTy};
4039 FunctionProtoType::ExtProtoInfo EPI;
4040 EPI.Variadic = true;
4041 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4042 Sema::CapturedParamNameType Params[] = {
4043 std::make_pair(".global_tid.", KmpInt32Ty),
4044 std::make_pair(".part_id.", KmpInt32PtrTy),
4045 std::make_pair(".privates.", VoidPtrTy),
4046 std::make_pair(
4047 ".copy_fn.",
4048 Context.getPointerType(CopyFnType).withConst().withRestrict()),
4049 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4050 std::make_pair(".lb.", KmpUInt64Ty),
4051 std::make_pair(".ub.", KmpUInt64Ty),
4052 std::make_pair(".st.", KmpInt64Ty),
4053 std::make_pair(".liter.", KmpInt32Ty),
4054 std::make_pair(".reductions.", VoidPtrTy),
4055 std::make_pair(StringRef(), QualType()) // __context with shared vars
4056 };
4057 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4058 Params);
4059 // Mark this captured region as inlined, because we don't use outlined
4060 // function directly.
4061 getCurCapturedRegion()->TheCapturedDecl->addAttr(
4062 AlwaysInlineAttr::CreateImplicit(
4063 Context, {}, AttributeCommonInfo::AS_Keyword,
4064 AlwaysInlineAttr::Keyword_forceinline));
4065 break;
4066 }
4067 case OMPD_parallel_master_taskloop:
4068 case OMPD_parallel_master_taskloop_simd: {
4069 QualType KmpInt32Ty =
4070 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
4071 .withConst();
4072 QualType KmpUInt64Ty =
4073 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
4074 .withConst();
4075 QualType KmpInt64Ty =
4076 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
4077 .withConst();
4078 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4079 QualType KmpInt32PtrTy =
4080 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4081 Sema::CapturedParamNameType ParamsParallel[] = {
4082 std::make_pair(".global_tid.", KmpInt32PtrTy),
4083 std::make_pair(".bound_tid.", KmpInt32PtrTy),
4084 std::make_pair(StringRef(), QualType()) // __context with shared vars
4085 };
4086 // Start a captured region for 'parallel'.
4087 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4088 ParamsParallel, /*OpenMPCaptureLevel=*/0);
4089 QualType Args[] = {VoidPtrTy};
4090 FunctionProtoType::ExtProtoInfo EPI;
4091 EPI.Variadic = true;
4092 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4093 Sema::CapturedParamNameType Params[] = {
4094 std::make_pair(".global_tid.", KmpInt32Ty),
4095 std::make_pair(".part_id.", KmpInt32PtrTy),
4096 std::make_pair(".privates.", VoidPtrTy),
4097 std::make_pair(
4098 ".copy_fn.",
4099 Context.getPointerType(CopyFnType).withConst().withRestrict()),
4100 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4101 std::make_pair(".lb.", KmpUInt64Ty),
4102 std::make_pair(".ub.", KmpUInt64Ty),
4103 std::make_pair(".st.", KmpInt64Ty),
4104 std::make_pair(".liter.", KmpInt32Ty),
4105 std::make_pair(".reductions.", VoidPtrTy),
4106 std::make_pair(StringRef(), QualType()) // __context with shared vars
4107 };
4108 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4109 Params, /*OpenMPCaptureLevel=*/1);
4110 // Mark this captured region as inlined, because we don't use outlined
4111 // function directly.
4112 getCurCapturedRegion()->TheCapturedDecl->addAttr(
4113 AlwaysInlineAttr::CreateImplicit(
4114 Context, {}, AttributeCommonInfo::AS_Keyword,
4115 AlwaysInlineAttr::Keyword_forceinline));
4116 break;
4117 }
4118 case OMPD_distribute_parallel_for_simd:
4119 case OMPD_distribute_parallel_for: {
4120 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4121 QualType KmpInt32PtrTy =
4122 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4123 Sema::CapturedParamNameType Params[] = {
4124 std::make_pair(".global_tid.", KmpInt32PtrTy),
4125 std::make_pair(".bound_tid.", KmpInt32PtrTy),
4126 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4127 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4128 std::make_pair(StringRef(), QualType()) // __context with shared vars
4129 };
4130 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4131 Params);
4132 break;
4133 }
4134 case OMPD_target_teams_distribute_parallel_for:
4135 case OMPD_target_teams_distribute_parallel_for_simd: {
4136 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4137 QualType KmpInt32PtrTy =
4138 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4139 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4140
4141 QualType Args[] = {VoidPtrTy};
4142 FunctionProtoType::ExtProtoInfo EPI;
4143 EPI.Variadic = true;
4144 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4145 Sema::CapturedParamNameType Params[] = {
4146 std::make_pair(".global_tid.", KmpInt32Ty),
4147 std::make_pair(".part_id.", KmpInt32PtrTy),
4148 std::make_pair(".privates.", VoidPtrTy),
4149 std::make_pair(
4150 ".copy_fn.",
4151 Context.getPointerType(CopyFnType).withConst().withRestrict()),
4152 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4153 std::make_pair(StringRef(), QualType()) // __context with shared vars
4154 };
4155 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4156 Params, /*OpenMPCaptureLevel=*/0);
4157 // Mark this captured region as inlined, because we don't use outlined
4158 // function directly.
4159 getCurCapturedRegion()->TheCapturedDecl->addAttr(
4160 AlwaysInlineAttr::CreateImplicit(
4161 Context, {}, AttributeCommonInfo::AS_Keyword,
4162 AlwaysInlineAttr::Keyword_forceinline));
4163 Sema::CapturedParamNameType ParamsTarget[] = {
4164 std::make_pair(StringRef(), QualType()) // __context with shared vars
4165 };
4166 // Start a captured region for 'target' with no implicit parameters.
4167 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4168 ParamsTarget, /*OpenMPCaptureLevel=*/1);
4169
4170 Sema::CapturedParamNameType ParamsTeams[] = {
4171 std::make_pair(".global_tid.", KmpInt32PtrTy),
4172 std::make_pair(".bound_tid.", KmpInt32PtrTy),
4173 std::make_pair(StringRef(), QualType()) // __context with shared vars
4174 };
4175 // Start a captured region for 'target' with no implicit parameters.
4176 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4177 ParamsTeams, /*OpenMPCaptureLevel=*/2);
4178
4179 Sema::CapturedParamNameType ParamsParallel[] = {
4180 std::make_pair(".global_tid.", KmpInt32PtrTy),
4181 std::make_pair(".bound_tid.", KmpInt32PtrTy),
4182 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4183 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4184 std::make_pair(StringRef(), QualType()) // __context with shared vars
4185 };
4186 // Start a captured region for 'teams' or 'parallel'. Both regions have
4187 // the same implicit parameters.
4188 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4189 ParamsParallel, /*OpenMPCaptureLevel=*/3);
4190 break;
4191 }
4192
4193 case OMPD_teams_distribute_parallel_for:
4194 case OMPD_teams_distribute_parallel_for_simd: {
4195 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4196 QualType KmpInt32PtrTy =
4197 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4198
4199 Sema::CapturedParamNameType ParamsTeams[] = {
4200 std::make_pair(".global_tid.", KmpInt32PtrTy),
4201 std::make_pair(".bound_tid.", KmpInt32PtrTy),
4202 std::make_pair(StringRef(), QualType()) // __context with shared vars
4203 };
4204 // Start a captured region for 'target' with no implicit parameters.
4205 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4206 ParamsTeams, /*OpenMPCaptureLevel=*/0);
4207
4208 Sema::CapturedParamNameType ParamsParallel[] = {
4209 std::make_pair(".global_tid.", KmpInt32PtrTy),
4210 std::make_pair(".bound_tid.", KmpInt32PtrTy),
4211 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
4212 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
4213 std::make_pair(StringRef(), QualType()) // __context with shared vars
4214 };
4215 // Start a captured region for 'teams' or 'parallel'. Both regions have
4216 // the same implicit parameters.
4217 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4218 ParamsParallel, /*OpenMPCaptureLevel=*/1);
4219 break;
4220 }
4221 case OMPD_target_update:
4222 case OMPD_target_enter_data:
4223 case OMPD_target_exit_data: {
4224 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4225 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4226 QualType KmpInt32PtrTy =
4227 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4228 QualType Args[] = {VoidPtrTy};
4229 FunctionProtoType::ExtProtoInfo EPI;
4230 EPI.Variadic = true;
4231 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4232 Sema::CapturedParamNameType Params[] = {
4233 std::make_pair(".global_tid.", KmpInt32Ty),
4234 std::make_pair(".part_id.", KmpInt32PtrTy),
4235 std::make_pair(".privates.", VoidPtrTy),
4236 std::make_pair(
4237 ".copy_fn.",
4238 Context.getPointerType(CopyFnType).withConst().withRestrict()),
4239 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4240 std::make_pair(StringRef(), QualType()) // __context with shared vars
4241 };
4242 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
4243 Params);
4244 // Mark this captured region as inlined, because we don't use outlined
4245 // function directly.
4246 getCurCapturedRegion()->TheCapturedDecl->addAttr(
4247 AlwaysInlineAttr::CreateImplicit(
4248 Context, {}, AttributeCommonInfo::AS_Keyword,
4249 AlwaysInlineAttr::Keyword_forceinline));
4250 break;
4251 }
4252 case OMPD_threadprivate:
4253 case OMPD_allocate:
4254 case OMPD_taskyield:
4255 case OMPD_barrier:
4256 case OMPD_taskwait:
4257 case OMPD_cancellation_point:
4258 case OMPD_cancel:
4259 case OMPD_flush:
4260 case OMPD_depobj:
4261 case OMPD_scan:
4262 case OMPD_declare_reduction:
4263 case OMPD_declare_mapper:
4264 case OMPD_declare_simd:
4265 case OMPD_declare_target:
4266 case OMPD_end_declare_target:
4267 case OMPD_requires:
4268 case OMPD_declare_variant:
4269 case OMPD_begin_declare_variant:
4270 case OMPD_end_declare_variant:
4271 llvm_unreachable("OpenMP Directive is not allowed")::llvm::llvm_unreachable_internal("OpenMP Directive is not allowed"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 4271)
;
4272 case OMPD_unknown:
4273 default:
4274 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 4274)
;
4275 }
4276 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setContext(CurContext);
4277}
4278
4279int Sema::getNumberOfConstructScopes(unsigned Level) const {
4280 return getOpenMPCaptureLevels(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(Level));
4281}
4282
4283int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
4284 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4285 getOpenMPCaptureRegions(CaptureRegions, DKind);
4286 return CaptureRegions.size();
4287}
4288
4289static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
4290 Expr *CaptureExpr, bool WithInit,
4291 bool AsExpression) {
4292 assert(CaptureExpr)((CaptureExpr) ? static_cast<void> (0) : __assert_fail (
"CaptureExpr", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 4292, __PRETTY_FUNCTION__))
;
4293 ASTContext &C = S.getASTContext();
4294 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
4295 QualType Ty = Init->getType();
4296 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
4297 if (S.getLangOpts().CPlusPlus) {
4298 Ty = C.getLValueReferenceType(Ty);
4299 } else {
4300 Ty = C.getPointerType(Ty);
4301 ExprResult Res =
4302 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
4303 if (!Res.isUsable())
4304 return nullptr;
4305 Init = Res.get();
4306 }
4307 WithInit = true;
4308 }
4309 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
4310 CaptureExpr->getBeginLoc());
4311 if (!WithInit)
4312 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
4313 S.CurContext->addHiddenDecl(CED);
4314 Sema::TentativeAnalysisScope Trap(S);
4315 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
4316 return CED;
4317}
4318
4319static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
4320 bool WithInit) {
4321 OMPCapturedExprDecl *CD;
4322 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
4323 CD = cast<OMPCapturedExprDecl>(VD);
4324 else
4325 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
4326 /*AsExpression=*/false);
4327 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4328 CaptureExpr->getExprLoc());
4329}
4330
4331static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
4332 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
4333 if (!Ref) {
4334 OMPCapturedExprDecl *CD = buildCaptureDecl(
4335 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
4336 /*WithInit=*/true, /*AsExpression=*/true);
4337 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
4338 CaptureExpr->getExprLoc());
4339 }
4340 ExprResult Res = Ref;
4341 if (!S.getLangOpts().CPlusPlus &&
4342 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
4343 Ref->getType()->isPointerType()) {
4344 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
4345 if (!Res.isUsable())
4346 return ExprError();
4347 }
4348 return S.DefaultLvalueConversion(Res.get());
4349}
4350
4351namespace {
4352// OpenMP directives parsed in this section are represented as a
4353// CapturedStatement with an associated statement. If a syntax error
4354// is detected during the parsing of the associated statement, the
4355// compiler must abort processing and close the CapturedStatement.
4356//
4357// Combined directives such as 'target parallel' have more than one
4358// nested CapturedStatements. This RAII ensures that we unwind out
4359// of all the nested CapturedStatements when an error is found.
4360class CaptureRegionUnwinderRAII {
4361private:
4362 Sema &S;
4363 bool &ErrorFound;
4364 OpenMPDirectiveKind DKind = OMPD_unknown;
4365
4366public:
4367 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
4368 OpenMPDirectiveKind DKind)
4369 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
4370 ~CaptureRegionUnwinderRAII() {
4371 if (ErrorFound) {
4372 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
4373 while (--ThisCaptureLevel >= 0)
4374 S.ActOnCapturedRegionError();
4375 }
4376 }
4377};
4378} // namespace
4379
4380void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
4381 // Capture variables captured by reference in lambdas for target-based
4382 // directives.
4383 if (!CurContext->isDependentContext() &&
4384 (isOpenMPTargetExecutionDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) ||
4385 isOpenMPTargetDataManagementDirective(
4386 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))) {
4387 QualType Type = V->getType();
4388 if (const auto *RD = Type.getCanonicalType()
4389 .getNonReferenceType()
4390 ->getAsCXXRecordDecl()) {
4391 bool SavedForceCaptureByReferenceInTargetExecutable =
4392 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceCaptureByReferenceInTargetExecutable();
4393 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceCaptureByReferenceInTargetExecutable(
4394 /*V=*/true);
4395 if (RD->isLambda()) {
4396 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
4397 FieldDecl *ThisCapture;
4398 RD->getCaptureFields(Captures, ThisCapture);
4399 for (const LambdaCapture &LC : RD->captures()) {
4400 if (LC.getCaptureKind() == LCK_ByRef) {
4401 VarDecl *VD = LC.getCapturedVar();
4402 DeclContext *VDC = VD->getDeclContext();
4403 if (!VDC->Encloses(CurContext))
4404 continue;
4405 MarkVariableReferenced(LC.getLocation(), VD);
4406 } else if (LC.getCaptureKind() == LCK_This) {
4407 QualType ThisTy = getCurrentThisType();
4408 if (!ThisTy.isNull() &&
4409 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
4410 CheckCXXThisCapture(LC.getLocation());
4411 }
4412 }
4413 }
4414 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceCaptureByReferenceInTargetExecutable(
4415 SavedForceCaptureByReferenceInTargetExecutable);
4416 }
4417 }
4418}
4419
4420static bool checkOrderedOrderSpecified(Sema &S,
4421 const ArrayRef<OMPClause *> Clauses) {
4422 const OMPOrderedClause *Ordered = nullptr;
4423 const OMPOrderClause *Order = nullptr;
4424
4425 for (const OMPClause *Clause : Clauses) {
4426 if (Clause->getClauseKind() == OMPC_ordered)
4427 Ordered = cast<OMPOrderedClause>(Clause);
4428 else if (Clause->getClauseKind() == OMPC_order) {
4429 Order = cast<OMPOrderClause>(Clause);
4430 if (Order->getKind() != OMPC_ORDER_concurrent)
4431 Order = nullptr;
4432 }
4433 if (Ordered && Order)
4434 break;
4435 }
4436
4437 if (Ordered && Order) {
4438 S.Diag(Order->getKindKwLoc(),
4439 diag::err_omp_simple_clause_incompatible_with_ordered)
4440 << getOpenMPClauseName(OMPC_order)
4441 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
4442 << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
4443 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
4444 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
4445 return true;
4446 }
4447 return false;
4448}
4449
4450StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
4451 ArrayRef<OMPClause *> Clauses) {
4452 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() == OMPD_atomic ||
4453 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() == OMPD_critical ||
4454 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() == OMPD_section ||
4455 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() == OMPD_master ||
4456 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() == OMPD_masked)
4457 return S;
4458
4459 bool ErrorFound = false;
4460 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
4461 *this, ErrorFound, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
4462 if (!S.isUsable()) {
4463 ErrorFound = true;
4464 return StmtError();
4465 }
4466
4467 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4468 getOpenMPCaptureRegions(CaptureRegions, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
4469 OMPOrderedClause *OC = nullptr;
4470 OMPScheduleClause *SC = nullptr;
4471 SmallVector<const OMPLinearClause *, 4> LCs;
4472 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
4473 // This is required for proper codegen.
4474 for (OMPClause *Clause : Clauses) {
4475 if (!LangOpts.OpenMPSimd &&
4476 isOpenMPTaskingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
4477 Clause->getClauseKind() == OMPC_in_reduction) {
4478 // Capture taskgroup task_reduction descriptors inside the tasking regions
4479 // with the corresponding in_reduction items.
4480 auto *IRC = cast<OMPInReductionClause>(Clause);
4481 for (Expr *E : IRC->taskgroup_descriptors())
4482 if (E)
4483 MarkDeclarationsReferencedInExpr(E);
4484 }
4485 if (isOpenMPPrivate(Clause->getClauseKind()) ||
4486 Clause->getClauseKind() == OMPC_copyprivate ||
4487 (getLangOpts().OpenMPUseTLS &&
4488 getASTContext().getTargetInfo().isTLSSupported() &&
4489 Clause->getClauseKind() == OMPC_copyin)) {
4490 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
4491 // Mark all variables in private list clauses as used in inner region.
4492 for (Stmt *VarRef : Clause->children()) {
4493 if (auto *E = cast_or_null<Expr>(VarRef)) {
4494 MarkDeclarationsReferencedInExpr(E);
4495 }
4496 }
4497 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceVarCapturing(/*V=*/false);
4498 } else if (isOpenMPLoopTransformationDirective(
4499 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
4500 assert(CaptureRegions.empty() &&((CaptureRegions.empty() && "No captured regions in loop transformation directives."
) ? static_cast<void> (0) : __assert_fail ("CaptureRegions.empty() && \"No captured regions in loop transformation directives.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 4501, __PRETTY_FUNCTION__))
4501 "No captured regions in loop transformation directives.")((CaptureRegions.empty() && "No captured regions in loop transformation directives."
) ? static_cast<void> (0) : __assert_fail ("CaptureRegions.empty() && \"No captured regions in loop transformation directives.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 4501, __PRETTY_FUNCTION__))
;
4502 } else if (CaptureRegions.size() > 1 ||
4503 CaptureRegions.back() != OMPD_unknown) {
4504 if (auto *C = OMPClauseWithPreInit::get(Clause))
4505 PICs.push_back(C);
4506 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
4507 if (Expr *E = C->getPostUpdateExpr())
4508 MarkDeclarationsReferencedInExpr(E);
4509 }
4510 }
4511 if (Clause->getClauseKind() == OMPC_schedule)
4512 SC = cast<OMPScheduleClause>(Clause);
4513 else if (Clause->getClauseKind() == OMPC_ordered)
4514 OC = cast<OMPOrderedClause>(Clause);
4515 else if (Clause->getClauseKind() == OMPC_linear)
4516 LCs.push_back(cast<OMPLinearClause>(Clause));
4517 }
4518 // Capture allocator expressions if used.
4519 for (Expr *E : DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getInnerAllocators())
4520 MarkDeclarationsReferencedInExpr(E);
4521 // OpenMP, 2.7.1 Loop Construct, Restrictions
4522 // The nonmonotonic modifier cannot be specified if an ordered clause is
4523 // specified.
4524 if (SC &&
4525 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
4526 SC->getSecondScheduleModifier() ==
4527 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
4528 OC) {
4529 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
4530 ? SC->getFirstScheduleModifierLoc()
4531 : SC->getSecondScheduleModifierLoc(),
4532 diag::err_omp_simple_clause_incompatible_with_ordered)
4533 << getOpenMPClauseName(OMPC_schedule)
4534 << getOpenMPSimpleClauseTypeName(OMPC_schedule,
4535 OMPC_SCHEDULE_MODIFIER_nonmonotonic)
4536 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4537 ErrorFound = true;
4538 }
4539 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
4540 // If an order(concurrent) clause is present, an ordered clause may not appear
4541 // on the same directive.
4542 if (checkOrderedOrderSpecified(*this, Clauses))
4543 ErrorFound = true;
4544 if (!LCs.empty() && OC && OC->getNumForLoops()) {
4545 for (const OMPLinearClause *C : LCs) {
4546 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
4547 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
4548 }
4549 ErrorFound = true;
4550 }
4551 if (isOpenMPWorksharingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
4552 isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) && OC &&
4553 OC->getNumForLoops()) {
4554 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
4555 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
4556 ErrorFound = true;
4557 }
4558 if (ErrorFound) {
4559 return StmtError();
4560 }
4561 StmtResult SR = S;
4562 unsigned CompletedRegions = 0;
4563 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
4564 // Mark all variables in private list clauses as used in inner region.
4565 // Required for proper codegen of combined directives.
4566 // TODO: add processing for other clauses.
4567 if (ThisCaptureRegion != OMPD_unknown) {
4568 for (const clang::OMPClauseWithPreInit *C : PICs) {
4569 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4570 // Find the particular capture region for the clause if the
4571 // directive is a combined one with multiple capture regions.
4572 // If the directive is not a combined one, the capture region
4573 // associated with the clause is OMPD_unknown and is generated
4574 // only once.
4575 if (CaptureRegion == ThisCaptureRegion ||
4576 CaptureRegion == OMPD_unknown) {
4577 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
4578 for (Decl *D : DS->decls())
4579 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4580 }
4581 }
4582 }
4583 }
4584 if (ThisCaptureRegion == OMPD_target) {
4585 // Capture allocator traits in the target region. They are used implicitly
4586 // and, thus, are not captured by default.
4587 for (OMPClause *C : Clauses) {
4588 if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
4589 for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
4590 ++I) {
4591 OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
4592 if (Expr *E = D.AllocatorTraits)
4593 MarkDeclarationsReferencedInExpr(E);
4594 }
4595 continue;
4596 }
4597 }
4598 }
4599 if (++CompletedRegions == CaptureRegions.size())
4600 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setBodyComplete();
4601 SR = ActOnCapturedRegionEnd(SR.get());
4602 }
4603 return SR;
4604}
4605
4606static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4607 OpenMPDirectiveKind CancelRegion,
4608 SourceLocation StartLoc) {
4609 // CancelRegion is only needed for cancel and cancellation_point.
4610 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4611 return false;
4612
4613 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4614 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4615 return false;
4616
4617 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4618 << getOpenMPDirectiveName(CancelRegion);
4619 return true;
4620}
4621
4622static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
4623 OpenMPDirectiveKind CurrentRegion,
4624 const DeclarationNameInfo &CurrentName,
4625 OpenMPDirectiveKind CancelRegion,
4626 SourceLocation StartLoc) {
4627 if (Stack->getCurScope()) {
4628 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4629 OpenMPDirectiveKind OffendingRegion = ParentRegion;
4630 bool NestingProhibited = false;
4631 bool CloseNesting = true;
4632 bool OrphanSeen = false;
4633 enum {
4634 NoRecommend,
4635 ShouldBeInParallelRegion,
4636 ShouldBeInOrderedRegion,
4637 ShouldBeInTargetRegion,
4638 ShouldBeInTeamsRegion,
4639 ShouldBeInLoopSimdRegion,
4640 } Recommend = NoRecommend;
4641 if (isOpenMPSimdDirective(ParentRegion) &&
4642 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4643 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4644 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
4645 CurrentRegion != OMPD_scan))) {
4646 // OpenMP [2.16, Nesting of Regions]
4647 // OpenMP constructs may not be nested inside a simd region.
4648 // OpenMP [2.8.1,simd Construct, Restrictions]
4649 // An ordered construct with the simd clause is the only OpenMP
4650 // construct that can appear in the simd region.
4651 // Allowing a SIMD construct nested in another SIMD construct is an
4652 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4653 // message.
4654 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4655 // The only OpenMP constructs that can be encountered during execution of
4656 // a simd region are the atomic construct, the loop construct, the simd
4657 // construct and the ordered construct with the simd clause.
4658 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4659 ? diag::err_omp_prohibited_region_simd
4660 : diag::warn_omp_nesting_simd)
4661 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
4662 return CurrentRegion != OMPD_simd;
4663 }
4664 if (ParentRegion == OMPD_atomic) {
4665 // OpenMP [2.16, Nesting of Regions]
4666 // OpenMP constructs may not be nested inside an atomic region.
4667 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4668 return true;
4669 }
4670 if (CurrentRegion == OMPD_section) {
4671 // OpenMP [2.7.2, sections Construct, Restrictions]
4672 // Orphaned section directives are prohibited. That is, the section
4673 // directives must appear within the sections construct and must not be
4674 // encountered elsewhere in the sections region.
4675 if (ParentRegion != OMPD_sections &&
4676 ParentRegion != OMPD_parallel_sections) {
4677 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4678 << (ParentRegion != OMPD_unknown)
4679 << getOpenMPDirectiveName(ParentRegion);
4680 return true;
4681 }
4682 return false;
4683 }
4684 // Allow some constructs (except teams and cancellation constructs) to be
4685 // orphaned (they could be used in functions, called from OpenMP regions
4686 // with the required preconditions).
4687 if (ParentRegion == OMPD_unknown &&
4688 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4689 CurrentRegion != OMPD_cancellation_point &&
4690 CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
4691 return false;
4692 if (CurrentRegion == OMPD_cancellation_point ||
4693 CurrentRegion == OMPD_cancel) {
4694 // OpenMP [2.16, Nesting of Regions]
4695 // A cancellation point construct for which construct-type-clause is
4696 // taskgroup must be nested inside a task construct. A cancellation
4697 // point construct for which construct-type-clause is not taskgroup must
4698 // be closely nested inside an OpenMP construct that matches the type
4699 // specified in construct-type-clause.
4700 // A cancel construct for which construct-type-clause is taskgroup must be
4701 // nested inside a task construct. A cancel construct for which
4702 // construct-type-clause is not taskgroup must be closely nested inside an
4703 // OpenMP construct that matches the type specified in
4704 // construct-type-clause.
4705 NestingProhibited =
4706 !((CancelRegion == OMPD_parallel &&
4707 (ParentRegion == OMPD_parallel ||
4708 ParentRegion == OMPD_target_parallel)) ||
4709 (CancelRegion == OMPD_for &&
4710 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
4711 ParentRegion == OMPD_target_parallel_for ||
4712 ParentRegion == OMPD_distribute_parallel_for ||
4713 ParentRegion == OMPD_teams_distribute_parallel_for ||
4714 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
4715 (CancelRegion == OMPD_taskgroup &&
4716 (ParentRegion == OMPD_task ||
4717 (SemaRef.getLangOpts().OpenMP >= 50 &&
4718 (ParentRegion == OMPD_taskloop ||
4719 ParentRegion == OMPD_master_taskloop ||
4720 ParentRegion == OMPD_parallel_master_taskloop)))) ||
4721 (CancelRegion == OMPD_sections &&
4722 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4723 ParentRegion == OMPD_parallel_sections)));
4724 OrphanSeen = ParentRegion == OMPD_unknown;
4725 } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
4726 // OpenMP 5.1 [2.22, Nesting of Regions]
4727 // A masked region may not be closely nested inside a worksharing, loop,
4728 // atomic, task, or taskloop region.
4729 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4730 isOpenMPTaskingDirective(ParentRegion);
4731 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4732 // OpenMP [2.16, Nesting of Regions]
4733 // A critical region may not be nested (closely or otherwise) inside a
4734 // critical region with the same name. Note that this restriction is not
4735 // sufficient to prevent deadlock.
4736 SourceLocation PreviousCriticalLoc;
4737 bool DeadLock = Stack->hasDirective(
4738 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4739 const DeclarationNameInfo &DNI,
4740 SourceLocation Loc) {
4741 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4742 PreviousCriticalLoc = Loc;
4743 return true;
4744 }
4745 return false;
4746 },
4747 false /* skip top directive */);
4748 if (DeadLock) {
4749 SemaRef.Diag(StartLoc,
4750 diag::err_omp_prohibited_region_critical_same_name)
4751 << CurrentName.getName();
4752 if (PreviousCriticalLoc.isValid())
4753 SemaRef.Diag(PreviousCriticalLoc,
4754 diag::note_omp_previous_critical_region);
4755 return true;
4756 }
4757 } else if (CurrentRegion == OMPD_barrier) {
4758 // OpenMP 5.1 [2.22, Nesting of Regions]
4759 // A barrier region may not be closely nested inside a worksharing, loop,
4760 // task, taskloop, critical, ordered, atomic, or masked region.
4761 NestingProhibited =
4762 isOpenMPWorksharingDirective(ParentRegion) ||
4763 isOpenMPTaskingDirective(ParentRegion) ||
4764 ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4765 ParentRegion == OMPD_parallel_master ||
4766 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4767 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
4768 !isOpenMPParallelDirective(CurrentRegion) &&
4769 !isOpenMPTeamsDirective(CurrentRegion)) {
4770 // OpenMP 5.1 [2.22, Nesting of Regions]
4771 // A loop region that binds to a parallel region or a worksharing region
4772 // may not be closely nested inside a worksharing, loop, task, taskloop,
4773 // critical, ordered, atomic, or masked region.
4774 NestingProhibited =
4775 isOpenMPWorksharingDirective(ParentRegion) ||
4776 isOpenMPTaskingDirective(ParentRegion) ||
4777 ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
4778 ParentRegion == OMPD_parallel_master ||
4779 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
4780 Recommend = ShouldBeInParallelRegion;
4781 } else if (CurrentRegion == OMPD_ordered) {
4782 // OpenMP [2.16, Nesting of Regions]
4783 // An ordered region may not be closely nested inside a critical,
4784 // atomic, or explicit task region.
4785 // An ordered region must be closely nested inside a loop region (or
4786 // parallel loop region) with an ordered clause.
4787 // OpenMP [2.8.1,simd Construct, Restrictions]
4788 // An ordered construct with the simd clause is the only OpenMP construct
4789 // that can appear in the simd region.
4790 NestingProhibited = ParentRegion == OMPD_critical ||
4791 isOpenMPTaskingDirective(ParentRegion) ||
4792 !(isOpenMPSimdDirective(ParentRegion) ||
4793 Stack->isParentOrderedRegion());
4794 Recommend = ShouldBeInOrderedRegion;
4795 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
4796 // OpenMP [2.16, Nesting of Regions]
4797 // If specified, a teams construct must be contained within a target
4798 // construct.
4799 NestingProhibited =
4800 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4801 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4802 ParentRegion != OMPD_target);
4803 OrphanSeen = ParentRegion == OMPD_unknown;
4804 Recommend = ShouldBeInTargetRegion;
4805 } else if (CurrentRegion == OMPD_scan) {
4806 // OpenMP [2.16, Nesting of Regions]
4807 // If specified, a teams construct must be contained within a target
4808 // construct.
4809 NestingProhibited =
4810 SemaRef.LangOpts.OpenMP < 50 ||
4811 (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
4812 ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
4813 ParentRegion != OMPD_parallel_for_simd);
4814 OrphanSeen = ParentRegion == OMPD_unknown;
4815 Recommend = ShouldBeInLoopSimdRegion;
4816 }
4817 if (!NestingProhibited &&
4818 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4819 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4820 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
4821 // OpenMP [2.16, Nesting of Regions]
4822 // distribute, parallel, parallel sections, parallel workshare, and the
4823 // parallel loop and parallel loop SIMD constructs are the only OpenMP
4824 // constructs that can be closely nested in the teams region.
4825 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4826 !isOpenMPDistributeDirective(CurrentRegion);
4827 Recommend = ShouldBeInParallelRegion;
4828 }
4829 if (!NestingProhibited &&
4830 isOpenMPNestingDistributeDirective(CurrentRegion)) {
4831 // OpenMP 4.5 [2.17 Nesting of Regions]
4832 // The region associated with the distribute construct must be strictly
4833 // nested inside a teams region
4834 NestingProhibited =
4835 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
4836 Recommend = ShouldBeInTeamsRegion;
4837 }
4838 if (!NestingProhibited &&
4839 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4840 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4841 // OpenMP 4.5 [2.17 Nesting of Regions]
4842 // If a target, target update, target data, target enter data, or
4843 // target exit data construct is encountered during execution of a
4844 // target region, the behavior is unspecified.
4845 NestingProhibited = Stack->hasDirective(
4846 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
4847 SourceLocation) {
4848 if (isOpenMPTargetExecutionDirective(K)) {
4849 OffendingRegion = K;
4850 return true;
4851 }
4852 return false;
4853 },
4854 false /* don't skip top directive */);
4855 CloseNesting = false;
4856 }
4857 if (NestingProhibited) {
4858 if (OrphanSeen) {
4859 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4860 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4861 } else {
4862 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4863 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4864 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4865 }
4866 return true;
4867 }
4868 }
4869 return false;
4870}
4871
4872struct Kind2Unsigned {
4873 using argument_type = OpenMPDirectiveKind;
4874 unsigned operator()(argument_type DK) { return unsigned(DK); }
4875};
4876static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4877 ArrayRef<OMPClause *> Clauses,
4878 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4879 bool ErrorFound = false;
4880 unsigned NamedModifiersNumber = 0;
4881 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4882 FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
4883 SmallVector<SourceLocation, 4> NameModifierLoc;
4884 for (const OMPClause *C : Clauses) {
4885 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4886 // At most one if clause without a directive-name-modifier can appear on
4887 // the directive.
4888 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4889 if (FoundNameModifiers[CurNM]) {
4890 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
4891 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4892 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4893 ErrorFound = true;
4894 } else if (CurNM != OMPD_unknown) {
4895 NameModifierLoc.push_back(IC->getNameModifierLoc());
4896 ++NamedModifiersNumber;
4897 }
4898 FoundNameModifiers[CurNM] = IC;
4899 if (CurNM == OMPD_unknown)
4900 continue;
4901 // Check if the specified name modifier is allowed for the current
4902 // directive.
4903 // At most one if clause with the particular directive-name-modifier can
4904 // appear on the directive.
4905 bool MatchFound = false;
4906 for (auto NM : AllowedNameModifiers) {
4907 if (CurNM == NM) {
4908 MatchFound = true;
4909 break;
4910 }
4911 }
4912 if (!MatchFound) {
4913 S.Diag(IC->getNameModifierLoc(),
4914 diag::err_omp_wrong_if_directive_name_modifier)
4915 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4916 ErrorFound = true;
4917 }
4918 }
4919 }
4920 // If any if clause on the directive includes a directive-name-modifier then
4921 // all if clauses on the directive must include a directive-name-modifier.
4922 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4923 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4924 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4925 diag::err_omp_no_more_if_clause);
4926 } else {
4927 std::string Values;
4928 std::string Sep(", ");
4929 unsigned AllowedCnt = 0;
4930 unsigned TotalAllowedNum =
4931 AllowedNameModifiers.size() - NamedModifiersNumber;
4932 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4933 ++Cnt) {
4934 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4935 if (!FoundNameModifiers[NM]) {
4936 Values += "'";
4937 Values += getOpenMPDirectiveName(NM);
4938 Values += "'";
4939 if (AllowedCnt + 2 == TotalAllowedNum)
4940 Values += " or ";
4941 else if (AllowedCnt + 1 != TotalAllowedNum)
4942 Values += Sep;
4943 ++AllowedCnt;
4944 }
4945 }
4946 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4947 diag::err_omp_unnamed_if_clause)
4948 << (TotalAllowedNum > 1) << Values;
4949 }
4950 for (SourceLocation Loc : NameModifierLoc) {
4951 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4952 }
4953 ErrorFound = true;
4954 }
4955 return ErrorFound;
4956}
4957
4958static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4959 SourceLocation &ELoc,
4960 SourceRange &ERange,
4961 bool AllowArraySection) {
4962 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4963 RefExpr->containsUnexpandedParameterPack())
4964 return std::make_pair(nullptr, true);
4965
4966 // OpenMP [3.1, C/C++]
4967 // A list item is a variable name.
4968 // OpenMP [2.9.3.3, Restrictions, p.1]
4969 // A variable that is part of another variable (as an array or
4970 // structure element) cannot appear in a private clause.
4971 RefExpr = RefExpr->IgnoreParens();
4972 enum {
4973 NoArrayExpr = -1,
4974 ArraySubscript = 0,
4975 OMPArraySection = 1
4976 } IsArrayExpr = NoArrayExpr;
4977 if (AllowArraySection) {
4978 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4979 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4980 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4981 Base = TempASE->getBase()->IgnoreParenImpCasts();
4982 RefExpr = Base;
4983 IsArrayExpr = ArraySubscript;
4984 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4985 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4986 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4987 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4988 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4989 Base = TempASE->getBase()->IgnoreParenImpCasts();
4990 RefExpr = Base;
4991 IsArrayExpr = OMPArraySection;
4992 }
4993 }
4994 ELoc = RefExpr->getExprLoc();
4995 ERange = RefExpr->getSourceRange();
4996 RefExpr = RefExpr->IgnoreParenImpCasts();
4997 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4998 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4999 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
5000 (S.getCurrentThisType().isNull() || !ME ||
5001 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
5002 !isa<FieldDecl>(ME->getMemberDecl()))) {
5003 if (IsArrayExpr != NoArrayExpr) {
5004 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
5005 << ERange;
5006 } else {
5007 S.Diag(ELoc,
5008 AllowArraySection
5009 ? diag::err_omp_expected_var_name_member_expr_or_array_item
5010 : diag::err_omp_expected_var_name_member_expr)
5011 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5012 }
5013 return std::make_pair(nullptr, false);
5014 }
5015 return std::make_pair(
5016 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5017}
5018
5019namespace {
5020/// Checks if the allocator is used in uses_allocators clause to be allowed in
5021/// target regions.
5022class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5023 DSAStackTy *S = nullptr;
5024
5025public:
5026 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5027 return S->isUsesAllocatorsDecl(E->getDecl())
5028 .getValueOr(
5029 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5030 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5031 }
5032 bool VisitStmt(const Stmt *S) {
5033 for (const Stmt *Child : S->children()) {
5034 if (Child && Visit(Child))
5035 return true;
5036 }
5037 return false;
5038 }
5039 explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5040};
5041} // namespace
5042
5043static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5044 ArrayRef<OMPClause *> Clauses) {
5045 assert(!S.CurContext->isDependentContext() &&((!S.CurContext->isDependentContext() && "Expected non-dependent context."
) ? static_cast<void> (0) : __assert_fail ("!S.CurContext->isDependentContext() && \"Expected non-dependent context.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5046, __PRETTY_FUNCTION__))
5046 "Expected non-dependent context.")((!S.CurContext->isDependentContext() && "Expected non-dependent context."
) ? static_cast<void> (0) : __assert_fail ("!S.CurContext->isDependentContext() && \"Expected non-dependent context.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5046, __PRETTY_FUNCTION__))
;
5047 auto AllocateRange =
5048 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5049 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
5050 DeclToCopy;
5051 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5052 return isOpenMPPrivate(C->getClauseKind());
5053 });
5054 for (OMPClause *Cl : PrivateRange) {
5055 MutableArrayRef<Expr *>::iterator I, It, Et;
5056 if (Cl->getClauseKind() == OMPC_private) {
5057 auto *PC = cast<OMPPrivateClause>(Cl);
5058 I = PC->private_copies().begin();
5059 It = PC->varlist_begin();
5060 Et = PC->varlist_end();
5061 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5062 auto *PC = cast<OMPFirstprivateClause>(Cl);
5063 I = PC->private_copies().begin();
5064 It = PC->varlist_begin();
5065 Et = PC->varlist_end();
5066 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5067 auto *PC = cast<OMPLastprivateClause>(Cl);
5068 I = PC->private_copies().begin();
5069 It = PC->varlist_begin();
5070 Et = PC->varlist_end();
5071 } else if (Cl->getClauseKind() == OMPC_linear) {
5072 auto *PC = cast<OMPLinearClause>(Cl);
5073 I = PC->privates().begin();
5074 It = PC->varlist_begin();
5075 Et = PC->varlist_end();
5076 } else if (Cl->getClauseKind() == OMPC_reduction) {
5077 auto *PC = cast<OMPReductionClause>(Cl);
5078 I = PC->privates().begin();
5079 It = PC->varlist_begin();
5080 Et = PC->varlist_end();
5081 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5082 auto *PC = cast<OMPTaskReductionClause>(Cl);
5083 I = PC->privates().begin();
5084 It = PC->varlist_begin();
5085 Et = PC->varlist_end();
5086 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5087 auto *PC = cast<OMPInReductionClause>(Cl);
5088 I = PC->privates().begin();
5089 It = PC->varlist_begin();
5090 Et = PC->varlist_end();
5091 } else {
5092 llvm_unreachable("Expected private clause.")::llvm::llvm_unreachable_internal("Expected private clause.",
"/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5092)
;
5093 }
5094 for (Expr *E : llvm::make_range(It, Et)) {
5095 if (!*I) {
5096 ++I;
5097 continue;
5098 }
5099 SourceLocation ELoc;
5100 SourceRange ERange;
5101 Expr *SimpleRefExpr = E;
5102 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5103 /*AllowArraySection=*/true);
5104 DeclToCopy.try_emplace(Res.first,
5105 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5106 ++I;
5107 }
5108 }
5109 for (OMPClause *C : AllocateRange) {
5110 auto *AC = cast<OMPAllocateClause>(C);
5111 if (S.getLangOpts().OpenMP >= 50 &&
5112 !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
5113 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
5114 AC->getAllocator()) {
5115 Expr *Allocator = AC->getAllocator();
5116 // OpenMP, 2.12.5 target Construct
5117 // Memory allocators that do not appear in a uses_allocators clause cannot
5118 // appear as an allocator in an allocate clause or be used in the target
5119 // region unless a requires directive with the dynamic_allocators clause
5120 // is present in the same compilation unit.
5121 AllocatorChecker Checker(Stack);
5122 if (Checker.Visit(Allocator))
5123 S.Diag(Allocator->getExprLoc(),
5124 diag::err_omp_allocator_not_in_uses_allocators)
5125 << Allocator->getSourceRange();
5126 }
5127 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
5128 getAllocatorKind(S, Stack, AC->getAllocator());
5129 // OpenMP, 2.11.4 allocate Clause, Restrictions.
5130 // For task, taskloop or target directives, allocation requests to memory
5131 // allocators with the trait access set to thread result in unspecified
5132 // behavior.
5133 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
5134 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
5135 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
5136 S.Diag(AC->getAllocator()->getExprLoc(),
5137 diag::warn_omp_allocate_thread_on_task_target_directive)
5138 << getOpenMPDirectiveName(Stack->getCurrentDirective());
5139 }
5140 for (Expr *E : AC->varlists()) {
5141 SourceLocation ELoc;
5142 SourceRange ERange;
5143 Expr *SimpleRefExpr = E;
5144 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
5145 ValueDecl *VD = Res.first;
5146 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
5147 if (!isOpenMPPrivate(Data.CKind)) {
5148 S.Diag(E->getExprLoc(),
5149 diag::err_omp_expected_private_copy_for_allocate);
5150 continue;
5151 }
5152 VarDecl *PrivateVD = DeclToCopy[VD];
5153 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
5154 AllocatorKind, AC->getAllocator()))
5155 continue;
5156 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
5157 E->getSourceRange());
5158 }
5159 }
5160}
5161
5162namespace {
5163/// Rewrite statements and expressions for Sema \p Actions CurContext.
5164///
5165/// Used to wrap already parsed statements/expressions into a new CapturedStmt
5166/// context. DeclRefExpr used inside the new context are changed to refer to the
5167/// captured variable instead.
5168class CaptureVars : public TreeTransform<CaptureVars> {
5169 using BaseTransform = TreeTransform<CaptureVars>;
5170
5171public:
5172 CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
5173
5174 bool AlwaysRebuild() { return true; }
5175};
5176} // namespace
5177
5178static VarDecl *precomputeExpr(Sema &Actions,
5179 SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
5180 StringRef Name) {
5181 Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
5182 VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
5183 dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
5184 auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
5185 Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
5186 Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
5187 BodyStmts.push_back(NewDeclStmt);
5188 return NewVar;
5189}
5190
5191/// Create a closure that computes the number of iterations of a loop.
5192///
5193/// \param Actions The Sema object.
5194/// \param LogicalTy Type for the logical iteration number.
5195/// \param Rel Comparison operator of the loop condition.
5196/// \param StartExpr Value of the loop counter at the first iteration.
5197/// \param StopExpr Expression the loop counter is compared against in the loop
5198/// condition. \param StepExpr Amount of increment after each iteration.
5199///
5200/// \return Closure (CapturedStmt) of the distance calculation.
5201static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
5202 BinaryOperator::Opcode Rel,
5203 Expr *StartExpr, Expr *StopExpr,
5204 Expr *StepExpr) {
5205 ASTContext &Ctx = Actions.getASTContext();
5206 TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
5207
5208 // Captured regions currently don't support return values, we use an
5209 // out-parameter instead. All inputs are implicit captures.
5210 // TODO: Instead of capturing each DeclRefExpr occurring in
5211 // StartExpr/StopExpr/Step, these could also be passed as a value capture.
5212 QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
5213 Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
5214 {StringRef(), QualType()}};
5215 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5216
5217 Stmt *Body;
5218 {
5219 Sema::CompoundScopeRAII CompoundScope(Actions);
5220 CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
5221
5222 // Get the LValue expression for the result.
5223 ImplicitParamDecl *DistParam = CS->getParam(0);
5224 DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
5225 DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5226
5227 SmallVector<Stmt *, 4> BodyStmts;
5228
5229 // Capture all referenced variable references.
5230 // TODO: Instead of computing NewStart/NewStop/NewStep inside the
5231 // CapturedStmt, we could compute them before and capture the result, to be
5232 // used jointly with the LoopVar function.
5233 VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
5234 VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
5235 VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
5236 auto BuildVarRef = [&](VarDecl *VD) {
5237 return buildDeclRefExpr(Actions, VD, VD->getType(), {});
5238 };
5239
5240 IntegerLiteral *Zero = IntegerLiteral::Create(
5241 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
5242 Expr *Dist;
5243 if (Rel == BO_NE) {
5244 // When using a != comparison, the increment can be +1 or -1. This can be
5245 // dynamic at runtime, so we need to check for the direction.
5246 Expr *IsNegStep = AssertSuccess(
5247 Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
5248
5249 // Positive increment.
5250 Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
5251 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5252 ForwardRange = AssertSuccess(
5253 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
5254 Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
5255 nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
5256
5257 // Negative increment.
5258 Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
5259 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5260 BackwardRange = AssertSuccess(
5261 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
5262 Expr *NegIncAmount = AssertSuccess(
5263 Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
5264 Expr *BackwardDist = AssertSuccess(
5265 Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
5266
5267 // Use the appropriate case.
5268 Dist = AssertSuccess(Actions.ActOnConditionalOp(
5269 {}, {}, IsNegStep, BackwardDist, ForwardDist));
5270 } else {
5271 assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&(((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT
) && "Expected one of these relational operators") ? static_cast
<void> (0) : __assert_fail ("(Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) && \"Expected one of these relational operators\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5272, __PRETTY_FUNCTION__))
5272 "Expected one of these relational operators")(((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT
) && "Expected one of these relational operators") ? static_cast
<void> (0) : __assert_fail ("(Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) && \"Expected one of these relational operators\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5272, __PRETTY_FUNCTION__))
;
5273
5274 // We can derive the direction from any other comparison operator. It is
5275 // non well-formed OpenMP if Step increments/decrements in the other
5276 // directions. Whether at least the first iteration passes the loop
5277 // condition.
5278 Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
5279 nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5280
5281 // Compute the range between first and last counter value.
5282 Expr *Range;
5283 if (Rel == BO_GE || Rel == BO_GT)
5284 Range = AssertSuccess(Actions.BuildBinOp(
5285 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
5286 else
5287 Range = AssertSuccess(Actions.BuildBinOp(
5288 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
5289
5290 // Ensure unsigned range space.
5291 Range =
5292 AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
5293
5294 if (Rel == BO_LE || Rel == BO_GE) {
5295 // Add one to the range if the relational operator is inclusive.
5296 Range =
5297 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_PreInc, Range));
5298 }
5299
5300 // Divide by the absolute step amount.
5301 Expr *Divisor = BuildVarRef(NewStep);
5302 if (Rel == BO_GE || Rel == BO_GT)
5303 Divisor =
5304 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
5305 Dist = AssertSuccess(
5306 Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor));
5307
5308 // If there is not at least one iteration, the range contains garbage. Fix
5309 // to zero in this case.
5310 Dist = AssertSuccess(
5311 Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
5312 }
5313
5314 // Assign the result to the out-parameter.
5315 Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
5316 Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
5317 BodyStmts.push_back(ResultAssign);
5318
5319 Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
5320 }
5321
5322 return cast<CapturedStmt>(
5323 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5324}
5325
5326/// Create a closure that computes the loop variable from the logical iteration
5327/// number.
5328///
5329/// \param Actions The Sema object.
5330/// \param LoopVarTy Type for the loop variable used for result value.
5331/// \param LogicalTy Type for the logical iteration number.
5332/// \param StartExpr Value of the loop counter at the first iteration.
5333/// \param Step Amount of increment after each iteration.
5334/// \param Deref Whether the loop variable is a dereference of the loop
5335/// counter variable.
5336///
5337/// \return Closure (CapturedStmt) of the loop value calculation.
5338static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
5339 QualType LogicalTy,
5340 DeclRefExpr *StartExpr, Expr *Step,
5341 bool Deref) {
5342 ASTContext &Ctx = Actions.getASTContext();
5343
5344 // Pass the result as an out-parameter. Passing as return value would require
5345 // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
5346 // invoke a copy constructor.
5347 QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
5348 Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
5349 {"Logical", LogicalTy},
5350 {StringRef(), QualType()}};
5351 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
5352
5353 // Capture the initial iterator which represents the LoopVar value at the
5354 // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
5355 // it in every iteration, capture it by value before it is modified.
5356 VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
5357 bool Invalid = Actions.tryCaptureVariable(StartVar, {},
5358 Sema::TryCapture_ExplicitByVal, {});
5359 (void)Invalid;
5360 assert(!Invalid && "Expecting capture-by-value to work.")((!Invalid && "Expecting capture-by-value to work.") ?
static_cast<void> (0) : __assert_fail ("!Invalid && \"Expecting capture-by-value to work.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5360, __PRETTY_FUNCTION__))
;
5361
5362 Expr *Body;
5363 {
5364 Sema::CompoundScopeRAII CompoundScope(Actions);
5365 auto *CS = cast<CapturedDecl>(Actions.CurContext);
5366
5367 ImplicitParamDecl *TargetParam = CS->getParam(0);
5368 DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
5369 TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5370 ImplicitParamDecl *IndvarParam = CS->getParam(1);
5371 DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
5372 IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
5373
5374 // Capture the Start expression.
5375 CaptureVars Recap(Actions);
5376 Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
5377 Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
5378
5379 Expr *Skip = AssertSuccess(
5380 Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
5381 // TODO: Explicitly cast to the iterator's difference_type instead of
5382 // relying on implicit conversion.
5383 Expr *Advanced =
5384 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
5385
5386 if (Deref) {
5387 // For range-based for-loops convert the loop counter value to a concrete
5388 // loop variable value by dereferencing the iterator.
5389 Advanced =
5390 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
5391 }
5392
5393 // Assign the result to the output parameter.
5394 Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
5395 BO_Assign, TargetRef, Advanced));
5396 }
5397 return cast<CapturedStmt>(
5398 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
5399}
5400
5401StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
5402 ASTContext &Ctx = getASTContext();
5403
5404 // Extract the common elements of ForStmt and CXXForRangeStmt:
5405 // Loop variable, repeat condition, increment
5406 Expr *Cond, *Inc;
5407 VarDecl *LIVDecl, *LUVDecl;
5408 if (auto *For = dyn_cast<ForStmt>(AStmt)) {
5409 Stmt *Init = For->getInit();
5410 if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
5411 // For statement declares loop variable.
5412 LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
5413 } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
5414 // For statement reuses variable.
5415 assert(LCAssign->getOpcode() == BO_Assign &&((LCAssign->getOpcode() == BO_Assign && "init part must be a loop variable assignment"
) ? static_cast<void> (0) : __assert_fail ("LCAssign->getOpcode() == BO_Assign && \"init part must be a loop variable assignment\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5416, __PRETTY_FUNCTION__))
5416 "init part must be a loop variable assignment")((LCAssign->getOpcode() == BO_Assign && "init part must be a loop variable assignment"
) ? static_cast<void> (0) : __assert_fail ("LCAssign->getOpcode() == BO_Assign && \"init part must be a loop variable assignment\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5416, __PRETTY_FUNCTION__))
;
5417 auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
5418 LIVDecl = cast<VarDecl>(CounterRef->getDecl());
5419 } else
5420 llvm_unreachable("Cannot determine loop variable")::llvm::llvm_unreachable_internal("Cannot determine loop variable"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5420)
;
5421 LUVDecl = LIVDecl;
5422
5423 Cond = For->getCond();
5424 Inc = For->getInc();
5425 } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
5426 DeclStmt *BeginStmt = RangeFor->getBeginStmt();
5427 LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
5428 LUVDecl = RangeFor->getLoopVariable();
5429
5430 Cond = RangeFor->getCond();
5431 Inc = RangeFor->getInc();
5432 } else
5433 llvm_unreachable("unhandled kind of loop")::llvm::llvm_unreachable_internal("unhandled kind of loop", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5433)
;
5434
5435 QualType CounterTy = LIVDecl->getType();
5436 QualType LVTy = LUVDecl->getType();
5437
5438 // Analyze the loop condition.
5439 Expr *LHS, *RHS;
5440 BinaryOperator::Opcode CondRel;
5441 Cond = Cond->IgnoreImplicit();
5442 if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
5443 LHS = CondBinExpr->getLHS();
5444 RHS = CondBinExpr->getRHS();
5445 CondRel = CondBinExpr->getOpcode();
5446 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
5447 assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands")((CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands"
) ? static_cast<void> (0) : __assert_fail ("CondCXXOp->getNumArgs() == 2 && \"Comparison should have 2 operands\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5447, __PRETTY_FUNCTION__))
;
5448 LHS = CondCXXOp->getArg(0);
5449 RHS = CondCXXOp->getArg(1);
5450 switch (CondCXXOp->getOperator()) {
5451 case OO_ExclaimEqual:
5452 CondRel = BO_NE;
5453 break;
5454 case OO_Less:
5455 CondRel = BO_LT;
5456 break;
5457 case OO_LessEqual:
5458 CondRel = BO_LE;
5459 break;
5460 case OO_Greater:
5461 CondRel = BO_GT;
5462 break;
5463 case OO_GreaterEqual:
5464 CondRel = BO_GE;
5465 break;
5466 default:
5467 llvm_unreachable("unexpected iterator operator")::llvm::llvm_unreachable_internal("unexpected iterator operator"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5467)
;
5468 }
5469 } else
5470 llvm_unreachable("unexpected loop condition")::llvm::llvm_unreachable_internal("unexpected loop condition"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5470)
;
5471
5472 // Normalize such that the loop counter is on the LHS.
5473 if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
5474 cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
5475 std::swap(LHS, RHS);
5476 CondRel = BinaryOperator::reverseComparisonOp(CondRel);
5477 }
5478 auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
5479
5480 // Decide the bit width for the logical iteration counter. By default use the
5481 // unsigned ptrdiff_t integer size (for iterators and pointers).
5482 // TODO: For iterators, use iterator::difference_type,
5483 // std::iterator_traits<>::difference_type or decltype(it - end).
5484 QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
5485 if (CounterTy->isIntegerType()) {
5486 unsigned BitWidth = Ctx.getIntWidth(CounterTy);
5487 LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
5488 }
5489
5490 // Analyze the loop increment.
5491 Expr *Step;
5492 if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
5493 int Direction;
5494 switch (IncUn->getOpcode()) {
5495 case UO_PreInc:
5496 case UO_PostInc:
5497 Direction = 1;
5498 break;
5499 case UO_PreDec:
5500 case UO_PostDec:
5501 Direction = -1;
5502 break;
5503 default:
5504 llvm_unreachable("unhandled unary increment operator")::llvm::llvm_unreachable_internal("unhandled unary increment operator"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5504)
;
5505 }
5506 Step = IntegerLiteral::Create(
5507 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
5508 } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
5509 if (IncBin->getOpcode() == BO_AddAssign) {
5510 Step = IncBin->getRHS();
5511 } else if (IncBin->getOpcode() == BO_SubAssign) {
5512 Step =
5513 AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
5514 } else
5515 llvm_unreachable("unhandled binary increment operator")::llvm::llvm_unreachable_internal("unhandled binary increment operator"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5515)
;
5516 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
5517 switch (CondCXXOp->getOperator()) {
5518 case OO_PlusPlus:
5519 Step = IntegerLiteral::Create(
5520 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
5521 break;
5522 case OO_MinusMinus:
5523 Step = IntegerLiteral::Create(
5524 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
5525 break;
5526 case OO_PlusEqual:
5527 Step = CondCXXOp->getArg(1);
5528 break;
5529 case OO_MinusEqual:
5530 Step = AssertSuccess(
5531 BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
5532 break;
5533 default:
5534 llvm_unreachable("unhandled overloaded increment operator")::llvm::llvm_unreachable_internal("unhandled overloaded increment operator"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5534)
;
5535 }
5536 } else
5537 llvm_unreachable("unknown increment expression")::llvm::llvm_unreachable_internal("unknown increment expression"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaOpenMP.cpp"
, 5537)
;
5538
5539 CapturedStmt *DistanceFunc =
5540 buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
5541 CapturedStmt *LoopVarFunc = buildLoopVarFunc(
5542 *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
5543 DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
5544 {}, nullptr, nullptr, {}, nullptr);
5545 return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
5546 LoopVarFunc, LVRef);
5547}
5548
5549static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
5550 CXXScopeSpec &MapperIdScopeSpec,
5551 const DeclarationNameInfo &MapperId,
5552 QualType Type,
5553 Expr *UnresolvedMapper);
5554
5555/// Perform DFS through the structure/class data members trying to find
5556/// member(s) with user-defined 'default' mapper and generate implicit map
5557/// clauses for such members with the found 'default' mapper.
5558static void
5559processImplicitMapsWithDefaultMappers(Sema &S, DSASta