Bug Summary

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