Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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