Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaOpenMP.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp
1//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements semantic analysis for OpenMP directives and
10/// clauses.
11///
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclOpenMP.h"
21#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/AST/TypeOrdering.h"
25#include "clang/Basic/OpenMPKinds.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
30#include "clang/Sema/SemaInternal.h"
31#include "llvm/ADT/PointerEmbeddedInt.h"
32using namespace clang;
33
34//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
38static const Expr *checkMapClauseExpressionBase(
39 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41 OpenMPClauseKind CKind, bool NoDiagnose);
42
43namespace {
44/// Default data sharing attributes, which can be applied to directive.
45enum DefaultDataSharingAttributes {
46 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
49};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
55};
56
57/// Stack for tracking declarations used in OpenMP directives and
58/// clauses and their data-sharing attributes.
59class DSAStackTy {
60public:
61 struct DSAVarData {
62 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
64 const Expr *RefExpr = nullptr;
65 DeclRefExpr *PrivateCopy = nullptr;
66 SourceLocation ImplicitDSALoc;
67 DSAVarData() = default;
68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
71 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
73 };
74 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
76 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
78
79private:
80 struct DSAInfo {
81 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
84 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
85 DeclRefExpr *PrivateCopy = nullptr;
86 };
87 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
92 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
98 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
102 struct ReductionData {
103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
104 SourceRange ReductionRange;
105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
118
119 struct SharingMapTy {
120 DeclSAMapTy SharingMap;
121 DeclReductionMapTy ReductionMap;
122 AlignedMapTy AlignedMap;
123 MappedExprComponentsTy MappedExprComponents;
124 LoopControlVariablesMapTy LCVMap;
125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
126 SourceLocation DefaultAttrLoc;
127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
129 OpenMPDirectiveKind Directive = OMPD_unknown;
130 DeclarationNameInfo DirectiveName;
131 Scope *CurScope = nullptr;
132 SourceLocation ConstructLoc;
133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
137 /// First argument (Expr *) contains optional argument of the
138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
141 unsigned AssociatedLoops = 1;
142 bool HasMutipleLoops = false;
143 const Decl *PossiblyLoopCounter = nullptr;
144 bool NowaitRegion = false;
145 bool CancelRegion = false;
146 bool LoopStart = false;
147 bool BodyComplete = false;
148 SourceLocation InnerTeamsRegionLoc;
149 /// Reference to the taskgroup task_reduction reference expression.
150 Expr *TaskgroupReductionRef = nullptr;
151 llvm::DenseSet<QualType> MappedClassesQualTypes;
152 /// List of globals marked as declare target link in this target region
153 /// (isOpenMPTargetExecutionDirective(Directive) == true).
154 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
155 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
156 Scope *CurScope, SourceLocation Loc)
157 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
158 ConstructLoc(Loc) {}
159 SharingMapTy() = default;
160 };
161
162 using StackTy = SmallVector<SharingMapTy, 4>;
163
164 /// Stack of used declaration and their data-sharing attributes.
165 DeclSAMapTy Threadprivates;
166 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
167 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
168 /// true, if check for DSA must be from parent directive, false, if
169 /// from current directive.
170 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
171 Sema &SemaRef;
172 bool ForceCapturing = false;
173 /// true if all the variables in the target executable directives must be
174 /// captured by reference.
175 bool ForceCaptureByReferenceInTargetExecutable = false;
176 CriticalsWithHintsTy Criticals;
177 unsigned IgnoredStackElements = 0;
178
179 /// Iterators over the stack iterate in order from innermost to outermost
180 /// directive.
181 using const_iterator = StackTy::const_reverse_iterator;
182 const_iterator begin() const {
183 return Stack.empty() ? const_iterator()
184 : Stack.back().first.rbegin() + IgnoredStackElements;
185 }
186 const_iterator end() const {
187 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
188 }
189 using iterator = StackTy::reverse_iterator;
190 iterator begin() {
191 return Stack.empty() ? iterator()
192 : Stack.back().first.rbegin() + IgnoredStackElements;
193 }
194 iterator end() {
195 return Stack.empty() ? iterator() : Stack.back().first.rend();
196 }
197
198 // Convenience operations to get at the elements of the stack.
199
200 bool isStackEmpty() const {
201 return Stack.empty() ||
202 Stack.back().second != CurrentNonCapturingFunctionScope ||
203 Stack.back().first.size() <= IgnoredStackElements;
204 }
205 size_t getStackSize() const {
206 return isStackEmpty() ? 0
207 : Stack.back().first.size() - IgnoredStackElements;
208 }
209
210 SharingMapTy *getTopOfStackOrNull() {
211 size_t Size = getStackSize();
212 if (Size == 0)
213 return nullptr;
214 return &Stack.back().first[Size - 1];
215 }
216 const SharingMapTy *getTopOfStackOrNull() const {
217 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
218 }
219 SharingMapTy &getTopOfStack() {
220 assert(!isStackEmpty() && "no current directive")((!isStackEmpty() && "no current directive") ? static_cast
<void> (0) : __assert_fail ("!isStackEmpty() && \"no current directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 220, __PRETTY_FUNCTION__))
;
221 return *getTopOfStackOrNull();
222 }
223 const SharingMapTy &getTopOfStack() const {
224 return const_cast<DSAStackTy&>(*this).getTopOfStack();
225 }
226
227 SharingMapTy *getSecondOnStackOrNull() {
228 size_t Size = getStackSize();
229 if (Size <= 1)
230 return nullptr;
231 return &Stack.back().first[Size - 2];
232 }
233 const SharingMapTy *getSecondOnStackOrNull() const {
234 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
235 }
236
237 /// Get the stack element at a certain level (previously returned by
238 /// \c getNestingLevel).
239 ///
240 /// Note that nesting levels count from outermost to innermost, and this is
241 /// the reverse of our iteration order where new inner levels are pushed at
242 /// the front of the stack.
243 SharingMapTy &getStackElemAtLevel(unsigned Level) {
244 assert(Level < getStackSize() && "no such stack element")((Level < getStackSize() && "no such stack element"
) ? static_cast<void> (0) : __assert_fail ("Level < getStackSize() && \"no such stack element\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 244, __PRETTY_FUNCTION__))
;
245 return Stack.back().first[Level];
246 }
247 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
248 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
249 }
250
251 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
252
253 /// Checks if the variable is a local for OpenMP region.
254 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
255
256 /// Vector of previously declared requires directives
257 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
258 /// omp_allocator_handle_t type.
259 QualType OMPAllocatorHandleT;
260 /// Expression for the predefined allocators.
261 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
262 nullptr};
263 /// Vector of previously encountered target directives
264 SmallVector<SourceLocation, 2> TargetLocations;
265
266public:
267 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
268
269 /// Sets omp_allocator_handle_t type.
270 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
271 /// Gets omp_allocator_handle_t type.
272 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
273 /// Sets the given default allocator.
274 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
275 Expr *Allocator) {
276 OMPPredefinedAllocators[AllocatorKind] = Allocator;
277 }
278 /// Returns the specified default allocator.
279 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
280 return OMPPredefinedAllocators[AllocatorKind];
281 }
282
283 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
12
Assuming field 'ClauseKindMode' is equal to OMPC_unknown
13
Returning zero, which participates in a condition later
284 OpenMPClauseKind getClauseParsingMode() const {
285 assert(isClauseParsingMode() && "Must be in clause parsing mode.")((isClauseParsingMode() && "Must be in clause parsing mode."
) ? static_cast<void> (0) : __assert_fail ("isClauseParsingMode() && \"Must be in clause parsing mode.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 285, __PRETTY_FUNCTION__))
;
286 return ClauseKindMode;
287 }
288 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
289
290 bool isBodyComplete() const {
291 const SharingMapTy *Top = getTopOfStackOrNull();
292 return Top && Top->BodyComplete;
293 }
294 void setBodyComplete() {
295 getTopOfStack().BodyComplete = true;
296 }
297
298 bool isForceVarCapturing() const { return ForceCapturing; }
299 void setForceVarCapturing(bool V) { ForceCapturing = V; }
300
301 void setForceCaptureByReferenceInTargetExecutable(bool V) {
302 ForceCaptureByReferenceInTargetExecutable = V;
303 }
304 bool isForceCaptureByReferenceInTargetExecutable() const {
305 return ForceCaptureByReferenceInTargetExecutable;
306 }
307
308 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
309 Scope *CurScope, SourceLocation Loc) {
310 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 311, __PRETTY_FUNCTION__))
311 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 311, __PRETTY_FUNCTION__))
;
312 if (Stack.empty() ||
313 Stack.back().second != CurrentNonCapturingFunctionScope)
314 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
315 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
316 Stack.back().first.back().DefaultAttrLoc = Loc;
317 }
318
319 void pop() {
320 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 321, __PRETTY_FUNCTION__))
321 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 321, __PRETTY_FUNCTION__))
;
322 assert(!Stack.back().first.empty() &&((!Stack.back().first.empty() && "Data-sharing attributes stack is empty!"
) ? static_cast<void> (0) : __assert_fail ("!Stack.back().first.empty() && \"Data-sharing attributes stack is empty!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 323, __PRETTY_FUNCTION__))
323 "Data-sharing attributes stack is empty!")((!Stack.back().first.empty() && "Data-sharing attributes stack is empty!"
) ? static_cast<void> (0) : __assert_fail ("!Stack.back().first.empty() && \"Data-sharing attributes stack is empty!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 323, __PRETTY_FUNCTION__))
;
324 Stack.back().first.pop_back();
325 }
326
327 /// RAII object to temporarily leave the scope of a directive when we want to
328 /// logically operate in its parent.
329 class ParentDirectiveScope {
330 DSAStackTy &Self;
331 bool Active;
332 public:
333 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
334 : Self(Self), Active(false) {
335 if (Activate)
336 enable();
337 }
338 ~ParentDirectiveScope() { disable(); }
339 void disable() {
340 if (Active) {
341 --Self.IgnoredStackElements;
342 Active = false;
343 }
344 }
345 void enable() {
346 if (!Active) {
347 ++Self.IgnoredStackElements;
348 Active = true;
349 }
350 }
351 };
352
353 /// Marks that we're started loop parsing.
354 void loopInit() {
355 assert(isOpenMPLoopDirective(getCurrentDirective()) &&((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 356, __PRETTY_FUNCTION__))
356 "Expected loop-based directive.")((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 356, __PRETTY_FUNCTION__))
;
357 getTopOfStack().LoopStart = true;
358 }
359 /// Start capturing of the variables in the loop context.
360 void loopStart() {
361 assert(isOpenMPLoopDirective(getCurrentDirective()) &&((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 362, __PRETTY_FUNCTION__))
362 "Expected loop-based directive.")((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 362, __PRETTY_FUNCTION__))
;
363 getTopOfStack().LoopStart = false;
364 }
365 /// true, if variables are captured, false otherwise.
366 bool isLoopStarted() const {
367 assert(isOpenMPLoopDirective(getCurrentDirective()) &&((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 368, __PRETTY_FUNCTION__))
368 "Expected loop-based directive.")((isOpenMPLoopDirective(getCurrentDirective()) && "Expected loop-based directive."
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(getCurrentDirective()) && \"Expected loop-based directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 368, __PRETTY_FUNCTION__))
;
369 return !getTopOfStack().LoopStart;
370 }
371 /// Marks (or clears) declaration as possibly loop counter.
372 void resetPossibleLoopCounter(const Decl *D = nullptr) {
373 getTopOfStack().PossiblyLoopCounter =
374 D ? D->getCanonicalDecl() : D;
375 }
376 /// Gets the possible loop counter decl.
377 const Decl *getPossiblyLoopCunter() const {
378 return getTopOfStack().PossiblyLoopCounter;
379 }
380 /// Start new OpenMP region stack in new non-capturing function.
381 void pushFunction() {
382 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 383, __PRETTY_FUNCTION__))
383 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 383, __PRETTY_FUNCTION__))
;
384 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
385 assert(!isa<CapturingScopeInfo>(CurFnScope))((!isa<CapturingScopeInfo>(CurFnScope)) ? static_cast<
void> (0) : __assert_fail ("!isa<CapturingScopeInfo>(CurFnScope)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 385, __PRETTY_FUNCTION__))
;
386 CurrentNonCapturingFunctionScope = CurFnScope;
387 }
388 /// Pop region stack for non-capturing function.
389 void popFunction(const FunctionScopeInfo *OldFSI) {
390 assert(!IgnoredStackElements &&((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 391, __PRETTY_FUNCTION__))
391 "cannot change stack while ignoring elements")((!IgnoredStackElements && "cannot change stack while ignoring elements"
) ? static_cast<void> (0) : __assert_fail ("!IgnoredStackElements && \"cannot change stack while ignoring elements\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 391, __PRETTY_FUNCTION__))
;
392 if (!Stack.empty() && Stack.back().second == OldFSI) {
393 assert(Stack.back().first.empty())((Stack.back().first.empty()) ? static_cast<void> (0) :
__assert_fail ("Stack.back().first.empty()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 393, __PRETTY_FUNCTION__))
;
394 Stack.pop_back();
395 }
396 CurrentNonCapturingFunctionScope = nullptr;
397 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
398 if (!isa<CapturingScopeInfo>(FSI)) {
399 CurrentNonCapturingFunctionScope = FSI;
400 break;
401 }
402 }
403 }
404
405 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
406 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
407 }
408 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
409 getCriticalWithHint(const DeclarationNameInfo &Name) const {
410 auto I = Criticals.find(Name.getAsString());
411 if (I != Criticals.end())
412 return I->second;
413 return std::make_pair(nullptr, llvm::APSInt());
414 }
415 /// If 'aligned' declaration for given variable \a D was not seen yet,
416 /// add it and return NULL; otherwise return previous occurrence's expression
417 /// for diagnostics.
418 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
419
420 /// Register specified variable as loop control variable.
421 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
422 /// Check if the specified variable is a loop control variable for
423 /// current region.
424 /// \return The index of the loop control variable in the list of associated
425 /// for-loops (from outer to inner).
426 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
427 /// Check if the specified variable is a loop control variable for
428 /// parent region.
429 /// \return The index of the loop control variable in the list of associated
430 /// for-loops (from outer to inner).
431 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
432 /// Get the loop control variable for the I-th loop (or nullptr) in
433 /// parent directive.
434 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
435
436 /// Adds explicit data sharing attribute to the specified declaration.
437 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
438 DeclRefExpr *PrivateCopy = nullptr);
439
440 /// Adds additional information for the reduction items with the reduction id
441 /// represented as an operator.
442 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
443 BinaryOperatorKind BOK);
444 /// Adds additional information for the reduction items with the reduction id
445 /// represented as reduction identifier.
446 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
447 const Expr *ReductionRef);
448 /// Returns the location and reduction operation from the innermost parent
449 /// region for the given \p D.
450 const DSAVarData
451 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
452 BinaryOperatorKind &BOK,
453 Expr *&TaskgroupDescriptor) const;
454 /// Returns the location and reduction operation from the innermost parent
455 /// region for the given \p D.
456 const DSAVarData
457 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
458 const Expr *&ReductionRef,
459 Expr *&TaskgroupDescriptor) const;
460 /// Return reduction reference expression for the current taskgroup.
461 Expr *getTaskgroupReductionRef() const {
462 assert(getTopOfStack().Directive == OMPD_taskgroup &&((getTopOfStack().Directive == OMPD_taskgroup && "taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"getTopOfStack().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 464, __PRETTY_FUNCTION__))
463 "taskgroup reference expression requested for non taskgroup "((getTopOfStack().Directive == OMPD_taskgroup && "taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"getTopOfStack().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 464, __PRETTY_FUNCTION__))
464 "directive.")((getTopOfStack().Directive == OMPD_taskgroup && "taskgroup reference expression requested for non taskgroup "
"directive.") ? static_cast<void> (0) : __assert_fail (
"getTopOfStack().Directive == OMPD_taskgroup && \"taskgroup reference expression requested for non taskgroup \" \"directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 464, __PRETTY_FUNCTION__))
;
465 return getTopOfStack().TaskgroupReductionRef;
466 }
467 /// Checks if the given \p VD declaration is actually a taskgroup reduction
468 /// descriptor variable at the \p Level of OpenMP regions.
469 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
470 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
471 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
472 ->getDecl() == VD;
473 }
474
475 /// Returns data sharing attributes from top of the stack for the
476 /// specified declaration.
477 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
478 /// Returns data-sharing attributes for the specified declaration.
479 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
480 /// Checks if the specified variables has data-sharing attributes which
481 /// match specified \a CPred predicate in any directive which matches \a DPred
482 /// predicate.
483 const DSAVarData
484 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
485 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
486 bool FromParent) const;
487 /// Checks if the specified variables has data-sharing attributes which
488 /// match specified \a CPred predicate in any innermost directive which
489 /// matches \a DPred predicate.
490 const DSAVarData
491 hasInnermostDSA(ValueDecl *D,
492 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
493 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
494 bool FromParent) const;
495 /// Checks if the specified variables has explicit data-sharing
496 /// attributes which match specified \a CPred predicate at the specified
497 /// OpenMP region.
498 bool hasExplicitDSA(const ValueDecl *D,
499 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
500 unsigned Level, bool NotLastprivate = false) const;
501
502 /// Returns true if the directive at level \Level matches in the
503 /// specified \a DPred predicate.
504 bool hasExplicitDirective(
505 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
506 unsigned Level) const;
507
508 /// Finds a directive which matches specified \a DPred predicate.
509 bool hasDirective(
510 const llvm::function_ref<bool(
511 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
512 DPred,
513 bool FromParent) const;
514
515 /// Returns currently analyzed directive.
516 OpenMPDirectiveKind getCurrentDirective() const {
517 const SharingMapTy *Top = getTopOfStackOrNull();
518 return Top ? Top->Directive : OMPD_unknown;
519 }
520 /// Returns directive kind at specified level.
521 OpenMPDirectiveKind getDirective(unsigned Level) const {
522 assert(!isStackEmpty() && "No directive at specified level.")((!isStackEmpty() && "No directive at specified level."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"No directive at specified level.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 522, __PRETTY_FUNCTION__))
;
523 return getStackElemAtLevel(Level).Directive;
524 }
525 /// Returns the capture region at the specified level.
526 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
527 unsigned OpenMPCaptureLevel) const {
528 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
529 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
530 return CaptureRegions[OpenMPCaptureLevel];
531 }
532 /// Returns parent directive.
533 OpenMPDirectiveKind getParentDirective() const {
534 const SharingMapTy *Parent = getSecondOnStackOrNull();
535 return Parent ? Parent->Directive : OMPD_unknown;
536 }
537
538 /// Add requires decl to internal vector
539 void addRequiresDecl(OMPRequiresDecl *RD) {
540 RequiresDecls.push_back(RD);
541 }
542
543 /// Checks if the defined 'requires' directive has specified type of clause.
544 template <typename ClauseType>
545 bool hasRequiresDeclWithClause() {
546 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
547 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
548 return isa<ClauseType>(C);
549 });
550 });
551 }
552
553 /// Checks for a duplicate clause amongst previously declared requires
554 /// directives
555 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
556 bool IsDuplicate = false;
557 for (OMPClause *CNew : ClauseList) {
558 for (const OMPRequiresDecl *D : RequiresDecls) {
559 for (const OMPClause *CPrev : D->clauselists()) {
560 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
561 SemaRef.Diag(CNew->getBeginLoc(),
562 diag::err_omp_requires_clause_redeclaration)
563 << getOpenMPClauseName(CNew->getClauseKind());
564 SemaRef.Diag(CPrev->getBeginLoc(),
565 diag::note_omp_requires_previous_clause)
566 << getOpenMPClauseName(CPrev->getClauseKind());
567 IsDuplicate = true;
568 }
569 }
570 }
571 }
572 return IsDuplicate;
573 }
574
575 /// Add location of previously encountered target to internal vector
576 void addTargetDirLocation(SourceLocation LocStart) {
577 TargetLocations.push_back(LocStart);
578 }
579
580 // Return previously encountered target region locations.
581 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
582 return TargetLocations;
583 }
584
585 /// Set default data sharing attribute to none.
586 void setDefaultDSANone(SourceLocation Loc) {
587 getTopOfStack().DefaultAttr = DSA_none;
588 getTopOfStack().DefaultAttrLoc = Loc;
589 }
590 /// Set default data sharing attribute to shared.
591 void setDefaultDSAShared(SourceLocation Loc) {
592 getTopOfStack().DefaultAttr = DSA_shared;
593 getTopOfStack().DefaultAttrLoc = Loc;
594 }
595 /// Set default data mapping attribute to 'tofrom:scalar'.
596 void setDefaultDMAToFromScalar(SourceLocation Loc) {
597 getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
598 getTopOfStack().DefaultMapAttrLoc = Loc;
599 }
600
601 DefaultDataSharingAttributes getDefaultDSA() const {
602 return isStackEmpty() ? DSA_unspecified
603 : getTopOfStack().DefaultAttr;
604 }
605 SourceLocation getDefaultDSALocation() const {
606 return isStackEmpty() ? SourceLocation()
607 : getTopOfStack().DefaultAttrLoc;
608 }
609 DefaultMapAttributes getDefaultDMA() const {
610 return isStackEmpty() ? DMA_unspecified
611 : getTopOfStack().DefaultMapAttr;
612 }
613 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
614 return getStackElemAtLevel(Level).DefaultMapAttr;
615 }
616 SourceLocation getDefaultDMALocation() const {
617 return isStackEmpty() ? SourceLocation()
618 : getTopOfStack().DefaultMapAttrLoc;
619 }
620
621 /// Checks if the specified variable is a threadprivate.
622 bool isThreadPrivate(VarDecl *D) {
623 const DSAVarData DVar = getTopDSA(D, false);
624 return isOpenMPThreadPrivate(DVar.CKind);
625 }
626
627 /// Marks current region as ordered (it has an 'ordered' clause).
628 void setOrderedRegion(bool IsOrdered, const Expr *Param,
629 OMPOrderedClause *Clause) {
630 if (IsOrdered)
631 getTopOfStack().OrderedRegion.emplace(Param, Clause);
632 else
633 getTopOfStack().OrderedRegion.reset();
634 }
635 /// Returns true, if region is ordered (has associated 'ordered' clause),
636 /// false - otherwise.
637 bool isOrderedRegion() const {
638 if (const SharingMapTy *Top = getTopOfStackOrNull())
639 return Top->OrderedRegion.hasValue();
640 return false;
641 }
642 /// Returns optional parameter for the ordered region.
643 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
644 if (const SharingMapTy *Top = getTopOfStackOrNull())
645 if (Top->OrderedRegion.hasValue())
646 return Top->OrderedRegion.getValue();
647 return std::make_pair(nullptr, nullptr);
648 }
649 /// Returns true, if parent region is ordered (has associated
650 /// 'ordered' clause), false - otherwise.
651 bool isParentOrderedRegion() const {
652 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
653 return Parent->OrderedRegion.hasValue();
654 return false;
655 }
656 /// Returns optional parameter for the ordered region.
657 std::pair<const Expr *, OMPOrderedClause *>
658 getParentOrderedRegionParam() const {
659 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
660 if (Parent->OrderedRegion.hasValue())
661 return Parent->OrderedRegion.getValue();
662 return std::make_pair(nullptr, nullptr);
663 }
664 /// Marks current region as nowait (it has a 'nowait' clause).
665 void setNowaitRegion(bool IsNowait = true) {
666 getTopOfStack().NowaitRegion = IsNowait;
667 }
668 /// Returns true, if parent region is nowait (has associated
669 /// 'nowait' clause), false - otherwise.
670 bool isParentNowaitRegion() const {
671 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
672 return Parent->NowaitRegion;
673 return false;
674 }
675 /// Marks parent region as cancel region.
676 void setParentCancelRegion(bool Cancel = true) {
677 if (SharingMapTy *Parent = getSecondOnStackOrNull())
678 Parent->CancelRegion |= Cancel;
679 }
680 /// Return true if current region has inner cancel construct.
681 bool isCancelRegion() const {
682 const SharingMapTy *Top = getTopOfStackOrNull();
683 return Top ? Top->CancelRegion : false;
684 }
685
686 /// Set collapse value for the region.
687 void setAssociatedLoops(unsigned Val) {
688 getTopOfStack().AssociatedLoops = Val;
689 if (Val > 1)
690 getTopOfStack().HasMutipleLoops = true;
691 }
692 /// Return collapse value for region.
693 unsigned getAssociatedLoops() const {
694 const SharingMapTy *Top = getTopOfStackOrNull();
695 return Top ? Top->AssociatedLoops : 0;
696 }
697 /// Returns true if the construct is associated with multiple loops.
698 bool hasMutipleLoops() const {
699 const SharingMapTy *Top = getTopOfStackOrNull();
700 return Top ? Top->HasMutipleLoops : false;
701 }
702
703 /// Marks current target region as one with closely nested teams
704 /// region.
705 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
706 if (SharingMapTy *Parent = getSecondOnStackOrNull())
707 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
708 }
709 /// Returns true, if current region has closely nested teams region.
710 bool hasInnerTeamsRegion() const {
711 return getInnerTeamsRegionLoc().isValid();
712 }
713 /// Returns location of the nested teams region (if any).
714 SourceLocation getInnerTeamsRegionLoc() const {
715 const SharingMapTy *Top = getTopOfStackOrNull();
716 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
717 }
718
719 Scope *getCurScope() const {
720 const SharingMapTy *Top = getTopOfStackOrNull();
721 return Top ? Top->CurScope : nullptr;
722 }
723 SourceLocation getConstructLoc() const {
724 const SharingMapTy *Top = getTopOfStackOrNull();
725 return Top ? Top->ConstructLoc : SourceLocation();
726 }
727
728 /// Do the check specified in \a Check to all component lists and return true
729 /// if any issue is found.
730 bool checkMappableExprComponentListsForDecl(
731 const ValueDecl *VD, bool CurrentRegionOnly,
732 const llvm::function_ref<
733 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
734 OpenMPClauseKind)>
735 Check) const {
736 if (isStackEmpty())
737 return false;
738 auto SI = begin();
739 auto SE = end();
740
741 if (SI == SE)
742 return false;
743
744 if (CurrentRegionOnly)
745 SE = std::next(SI);
746 else
747 std::advance(SI, 1);
748
749 for (; SI != SE; ++SI) {
750 auto MI = SI->MappedExprComponents.find(VD);
751 if (MI != SI->MappedExprComponents.end())
752 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
753 MI->second.Components)
754 if (Check(L, MI->second.Kind))
755 return true;
756 }
757 return false;
758 }
759
760 /// Do the check specified in \a Check to all component lists at a given level
761 /// and return true if any issue is found.
762 bool checkMappableExprComponentListsForDeclAtLevel(
763 const ValueDecl *VD, unsigned Level,
764 const llvm::function_ref<
765 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
766 OpenMPClauseKind)>
767 Check) const {
768 if (getStackSize() <= Level)
769 return false;
770
771 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
772 auto MI = StackElem.MappedExprComponents.find(VD);
773 if (MI != StackElem.MappedExprComponents.end())
774 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
775 MI->second.Components)
776 if (Check(L, MI->second.Kind))
777 return true;
778 return false;
779 }
780
781 /// Create a new mappable expression component list associated with a given
782 /// declaration and initialize it with the provided list of components.
783 void addMappableExpressionComponents(
784 const ValueDecl *VD,
785 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
786 OpenMPClauseKind WhereFoundClauseKind) {
787 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
788 // Create new entry and append the new components there.
789 MEC.Components.resize(MEC.Components.size() + 1);
790 MEC.Components.back().append(Components.begin(), Components.end());
791 MEC.Kind = WhereFoundClauseKind;
792 }
793
794 unsigned getNestingLevel() const {
795 assert(!isStackEmpty())((!isStackEmpty()) ? static_cast<void> (0) : __assert_fail
("!isStackEmpty()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 795, __PRETTY_FUNCTION__))
;
796 return getStackSize() - 1;
797 }
798 void addDoacrossDependClause(OMPDependClause *C,
799 const OperatorOffsetTy &OpsOffs) {
800 SharingMapTy *Parent = getSecondOnStackOrNull();
801 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive))((Parent && isOpenMPWorksharingDirective(Parent->Directive
)) ? static_cast<void> (0) : __assert_fail ("Parent && isOpenMPWorksharingDirective(Parent->Directive)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 801, __PRETTY_FUNCTION__))
;
802 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
803 }
804 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
805 getDoacrossDependClauses() const {
806 const SharingMapTy &StackElem = getTopOfStack();
807 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
808 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
809 return llvm::make_range(Ref.begin(), Ref.end());
810 }
811 return llvm::make_range(StackElem.DoacrossDepends.end(),
812 StackElem.DoacrossDepends.end());
813 }
814
815 // Store types of classes which have been explicitly mapped
816 void addMappedClassesQualTypes(QualType QT) {
817 SharingMapTy &StackElem = getTopOfStack();
818 StackElem.MappedClassesQualTypes.insert(QT);
819 }
820
821 // Return set of mapped classes types
822 bool isClassPreviouslyMapped(QualType QT) const {
823 const SharingMapTy &StackElem = getTopOfStack();
824 return StackElem.MappedClassesQualTypes.count(QT) != 0;
825 }
826
827 /// Adds global declare target to the parent target region.
828 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
829 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(((*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->
getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && "Expected declare target link global."
) ? static_cast<void> (0) : __assert_fail ("*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && \"Expected declare target link global.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 831, __PRETTY_FUNCTION__))
830 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&((*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->
getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && "Expected declare target link global."
) ? static_cast<void> (0) : __assert_fail ("*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && \"Expected declare target link global.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 831, __PRETTY_FUNCTION__))
831 "Expected declare target link global.")((*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->
getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && "Expected declare target link global."
) ? static_cast<void> (0) : __assert_fail ("*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && \"Expected declare target link global.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 831, __PRETTY_FUNCTION__))
;
832 for (auto &Elem : *this) {
833 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
834 Elem.DeclareTargetLinkVarDecls.push_back(E);
835 return;
836 }
837 }
838 }
839
840 /// Returns the list of globals with declare target link if current directive
841 /// is target.
842 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
843 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&((isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
"Expected target executable directive.") ? static_cast<void
> (0) : __assert_fail ("isOpenMPTargetExecutionDirective(getCurrentDirective()) && \"Expected target executable directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 844, __PRETTY_FUNCTION__))
844 "Expected target executable directive.")((isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
"Expected target executable directive.") ? static_cast<void
> (0) : __assert_fail ("isOpenMPTargetExecutionDirective(getCurrentDirective()) && \"Expected target executable directive.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 844, __PRETTY_FUNCTION__))
;
845 return getTopOfStack().DeclareTargetLinkVarDecls;
846 }
847};
848
849bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
850 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
851}
852
853bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
854 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
855 DKind == OMPD_unknown;
856}
857
858} // namespace
859
860static const Expr *getExprAsWritten(const Expr *E) {
861 if (const auto *FE = dyn_cast<FullExpr>(E))
862 E = FE->getSubExpr();
863
864 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
865 E = MTE->GetTemporaryExpr();
866
867 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
868 E = Binder->getSubExpr();
869
870 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
871 E = ICE->getSubExprAsWritten();
872 return E->IgnoreParens();
873}
874
875static Expr *getExprAsWritten(Expr *E) {
876 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
877}
878
879static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
880 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
881 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
882 D = ME->getMemberDecl();
883 const auto *VD = dyn_cast<VarDecl>(D);
884 const auto *FD = dyn_cast<FieldDecl>(D);
885 if (VD != nullptr) {
886 VD = VD->getCanonicalDecl();
887 D = VD;
888 } else {
889 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 889, __PRETTY_FUNCTION__))
;
890 FD = FD->getCanonicalDecl();
891 D = FD;
892 }
893 return D;
894}
895
896static ValueDecl *getCanonicalDecl(ValueDecl *D) {
897 return const_cast<ValueDecl *>(
898 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
899}
900
901DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
902 ValueDecl *D) const {
903 D = getCanonicalDecl(D);
904 auto *VD = dyn_cast<VarDecl>(D);
905 const auto *FD = dyn_cast<FieldDecl>(D);
906 DSAVarData DVar;
907 if (Iter == end()) {
908 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
909 // in a region but not in construct]
910 // File-scope or namespace-scope variables referenced in called routines
911 // in the region are shared unless they appear in a threadprivate
912 // directive.
913 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
914 DVar.CKind = OMPC_shared;
915
916 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
917 // in a region but not in construct]
918 // Variables with static storage duration that are declared in called
919 // routines in the region are shared.
920 if (VD && VD->hasGlobalStorage())
921 DVar.CKind = OMPC_shared;
922
923 // Non-static data members are shared by default.
924 if (FD)
925 DVar.CKind = OMPC_shared;
926
927 return DVar;
928 }
929
930 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
931 // in a Construct, C/C++, predetermined, p.1]
932 // Variables with automatic storage duration that are declared in a scope
933 // inside the construct are private.
934 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
935 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
936 DVar.CKind = OMPC_private;
937 return DVar;
938 }
939
940 DVar.DKind = Iter->Directive;
941 // Explicitly specified attributes and local variables with predetermined
942 // attributes.
943 if (Iter->SharingMap.count(D)) {
944 const DSAInfo &Data = Iter->SharingMap.lookup(D);
945 DVar.RefExpr = Data.RefExpr.getPointer();
946 DVar.PrivateCopy = Data.PrivateCopy;
947 DVar.CKind = Data.Attributes;
948 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
949 return DVar;
950 }
951
952 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
953 // in a Construct, C/C++, implicitly determined, p.1]
954 // In a parallel or task construct, the data-sharing attributes of these
955 // variables are determined by the default clause, if present.
956 switch (Iter->DefaultAttr) {
957 case DSA_shared:
958 DVar.CKind = OMPC_shared;
959 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
960 return DVar;
961 case DSA_none:
962 return DVar;
963 case DSA_unspecified:
964 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
965 // in a Construct, implicitly determined, p.2]
966 // In a parallel construct, if no default clause is present, these
967 // variables are shared.
968 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
969 if ((isOpenMPParallelDirective(DVar.DKind) &&
970 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
971 isOpenMPTeamsDirective(DVar.DKind)) {
972 DVar.CKind = OMPC_shared;
973 return DVar;
974 }
975
976 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
977 // in a Construct, implicitly determined, p.4]
978 // In a task construct, if no default clause is present, a variable that in
979 // the enclosing context is determined to be shared by all implicit tasks
980 // bound to the current team is shared.
981 if (isOpenMPTaskingDirective(DVar.DKind)) {
982 DSAVarData DVarTemp;
983 const_iterator I = Iter, E = end();
984 do {
985 ++I;
986 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
987 // Referenced in a Construct, implicitly determined, p.6]
988 // In a task construct, if no default clause is present, a variable
989 // whose data-sharing attribute is not determined by the rules above is
990 // firstprivate.
991 DVarTemp = getDSA(I, D);
992 if (DVarTemp.CKind != OMPC_shared) {
993 DVar.RefExpr = nullptr;
994 DVar.CKind = OMPC_firstprivate;
995 return DVar;
996 }
997 } while (I != E && !isImplicitTaskingRegion(I->Directive));
998 DVar.CKind =
999 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1000 return DVar;
1001 }
1002 }
1003 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1004 // in a Construct, implicitly determined, p.3]
1005 // For constructs other than task, if no default clause is present, these
1006 // variables inherit their data-sharing attributes from the enclosing
1007 // context.
1008 return getDSA(++Iter, D);
1009}
1010
1011const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1012 const Expr *NewDE) {
1013 assert(!isStackEmpty() && "Data sharing attributes stack is empty")((!isStackEmpty() && "Data sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1013, __PRETTY_FUNCTION__))
;
1014 D = getCanonicalDecl(D);
1015 SharingMapTy &StackElem = getTopOfStack();
1016 auto It = StackElem.AlignedMap.find(D);
1017 if (It == StackElem.AlignedMap.end()) {
1018 assert(NewDE && "Unexpected nullptr expr to be added into aligned map")((NewDE && "Unexpected nullptr expr to be added into aligned map"
) ? static_cast<void> (0) : __assert_fail ("NewDE && \"Unexpected nullptr expr to be added into aligned map\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1018, __PRETTY_FUNCTION__))
;
1019 StackElem.AlignedMap[D] = NewDE;
1020 return nullptr;
1021 }
1022 assert(It->second && "Unexpected nullptr expr in the aligned map")((It->second && "Unexpected nullptr expr in the aligned map"
) ? static_cast<void> (0) : __assert_fail ("It->second && \"Unexpected nullptr expr in the aligned map\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1022, __PRETTY_FUNCTION__))
;
1023 return It->second;
1024}
1025
1026void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1027 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1027, __PRETTY_FUNCTION__))
;
1028 D = getCanonicalDecl(D);
1029 SharingMapTy &StackElem = getTopOfStack();
1030 StackElem.LCVMap.try_emplace(
1031 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1032}
1033
1034const DSAStackTy::LCDeclInfo
1035DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1036 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1036, __PRETTY_FUNCTION__))
;
16
'?' condition is true
1037 D = getCanonicalDecl(D);
1038 const SharingMapTy &StackElem = getTopOfStack();
1039 auto It = StackElem.LCVMap.find(D);
1040 if (It != StackElem.LCVMap.end())
17
Assuming the condition is true
18
Taking true branch
1041 return It->second;
19
Value assigned to field 'first', which participates in a condition later
1042 return {0, nullptr};
1043}
1044
1045const DSAStackTy::LCDeclInfo
1046DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1047 const SharingMapTy *Parent = getSecondOnStackOrNull();
1048 assert(Parent && "Data-sharing attributes stack is empty")((Parent && "Data-sharing attributes stack is empty")
? static_cast<void> (0) : __assert_fail ("Parent && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1048, __PRETTY_FUNCTION__))
;
1049 D = getCanonicalDecl(D);
1050 auto It = Parent->LCVMap.find(D);
1051 if (It != Parent->LCVMap.end())
1052 return It->second;
1053 return {0, nullptr};
1054}
1055
1056const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1057 const SharingMapTy *Parent = getSecondOnStackOrNull();
1058 assert(Parent && "Data-sharing attributes stack is empty")((Parent && "Data-sharing attributes stack is empty")
? static_cast<void> (0) : __assert_fail ("Parent && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1058, __PRETTY_FUNCTION__))
;
1059 if (Parent->LCVMap.size() < I)
1060 return nullptr;
1061 for (const auto &Pair : Parent->LCVMap)
1062 if (Pair.second.first == I)
1063 return Pair.first;
1064 return nullptr;
1065}
1066
1067void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1068 DeclRefExpr *PrivateCopy) {
1069 D = getCanonicalDecl(D);
1070 if (A == OMPC_threadprivate) {
1071 DSAInfo &Data = Threadprivates[D];
1072 Data.Attributes = A;
1073 Data.RefExpr.setPointer(E);
1074 Data.PrivateCopy = nullptr;
1075 } else {
1076 DSAInfo &Data = getTopOfStack().SharingMap[D];
1077 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1080, __PRETTY_FUNCTION__))
1078 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1080, __PRETTY_FUNCTION__))
1079 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1080, __PRETTY_FUNCTION__))
1080 (isLoopControlVariable(D).first && A == OMPC_private))((Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
(A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate
) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate
) || (isLoopControlVariable(D).first && A == OMPC_private
)) ? static_cast<void> (0) : __assert_fail ("Data.Attributes == OMPC_unknown || (A == Data.Attributes) || (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || (isLoopControlVariable(D).first && A == OMPC_private)"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1080, __PRETTY_FUNCTION__))
;
1081 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1082 Data.RefExpr.setInt(/*IntVal=*/true);
1083 return;
1084 }
1085 const bool IsLastprivate =
1086 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1087 Data.Attributes = A;
1088 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1089 Data.PrivateCopy = PrivateCopy;
1090 if (PrivateCopy) {
1091 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1092 Data.Attributes = A;
1093 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1094 Data.PrivateCopy = nullptr;
1095 }
1096 }
1097}
1098
1099/// Build a variable declaration for OpenMP loop iteration variable.
1100static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
1101 StringRef Name, const AttrVec *Attrs = nullptr,
1102 DeclRefExpr *OrigRef = nullptr) {
1103 DeclContext *DC = SemaRef.CurContext;
1104 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1105 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1106 auto *Decl =
1107 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1108 if (Attrs) {
1109 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1110 I != E; ++I)
1111 Decl->addAttr(*I);
1112 }
1113 Decl->setImplicit();
1114 if (OrigRef) {
1115 Decl->addAttr(
1116 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1117 }
1118 return Decl;
1119}
1120
1121static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1122 SourceLocation Loc,
1123 bool RefersToCapture = false) {
1124 D->setReferenced();
1125 D->markUsed(S.Context);
1126 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1127 SourceLocation(), D, RefersToCapture, Loc, Ty,
1128 VK_LValue);
1129}
1130
1131void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1132 BinaryOperatorKind BOK) {
1133 D = getCanonicalDecl(D);
1134 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1134, __PRETTY_FUNCTION__))
;
1135 assert(((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1137, __PRETTY_FUNCTION__))
1136 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1137, __PRETTY_FUNCTION__))
1137 "Additional reduction info may be specified only for reduction items.")((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1137, __PRETTY_FUNCTION__))
;
1138 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1139 assert(ReductionData.ReductionRange.isInvalid() &&((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1142, __PRETTY_FUNCTION__))
1140 getTopOfStack().Directive == OMPD_taskgroup &&((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1142, __PRETTY_FUNCTION__))
1141 "Additional reduction info may be specified only once for reduction "((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1142, __PRETTY_FUNCTION__))
1142 "items.")((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1142, __PRETTY_FUNCTION__))
;
1143 ReductionData.set(BOK, SR);
1144 Expr *&TaskgroupReductionRef =
1145 getTopOfStack().TaskgroupReductionRef;
1146 if (!TaskgroupReductionRef) {
1147 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1148 SemaRef.Context.VoidPtrTy, ".task_red.");
1149 TaskgroupReductionRef =
1150 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1151 }
1152}
1153
1154void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1155 const Expr *ReductionRef) {
1156 D = getCanonicalDecl(D);
1157 assert(!isStackEmpty() && "Data-sharing attributes stack is empty")((!isStackEmpty() && "Data-sharing attributes stack is empty"
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1157, __PRETTY_FUNCTION__))
;
1158 assert(((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1160, __PRETTY_FUNCTION__))
1159 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1160, __PRETTY_FUNCTION__))
1160 "Additional reduction info may be specified only for reduction items.")((getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
"Additional reduction info may be specified only for reduction items."
) ? static_cast<void> (0) : __assert_fail ("getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && \"Additional reduction info may be specified only for reduction items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1160, __PRETTY_FUNCTION__))
;
1161 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1162 assert(ReductionData.ReductionRange.isInvalid() &&((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1165, __PRETTY_FUNCTION__))
1163 getTopOfStack().Directive == OMPD_taskgroup &&((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1165, __PRETTY_FUNCTION__))
1164 "Additional reduction info may be specified only once for reduction "((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1165, __PRETTY_FUNCTION__))
1165 "items.")((ReductionData.ReductionRange.isInvalid() && getTopOfStack
().Directive == OMPD_taskgroup && "Additional reduction info may be specified only once for reduction "
"items.") ? static_cast<void> (0) : __assert_fail ("ReductionData.ReductionRange.isInvalid() && getTopOfStack().Directive == OMPD_taskgroup && \"Additional reduction info may be specified only once for reduction \" \"items.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1165, __PRETTY_FUNCTION__))
;
1166 ReductionData.set(ReductionRef, SR);
1167 Expr *&TaskgroupReductionRef =
1168 getTopOfStack().TaskgroupReductionRef;
1169 if (!TaskgroupReductionRef) {
1170 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1171 SemaRef.Context.VoidPtrTy, ".task_red.");
1172 TaskgroupReductionRef =
1173 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1174 }
1175}
1176
1177const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1178 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1179 Expr *&TaskgroupDescriptor) const {
1180 D = getCanonicalDecl(D);
1181 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.")((!isStackEmpty() && "Data-sharing attributes stack is empty."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1181, __PRETTY_FUNCTION__))
;
1182 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1183 const DSAInfo &Data = I->SharingMap.lookup(D);
1184 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1185 continue;
1186 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1187 if (!ReductionData.ReductionOp ||
1188 ReductionData.ReductionOp.is<const Expr *>())
1189 return DSAVarData();
1190 SR = ReductionData.ReductionRange;
1191 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1192 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1194, __PRETTY_FUNCTION__))
1193 "expression for the descriptor is not "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1194, __PRETTY_FUNCTION__))
1194 "set.")((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1194, __PRETTY_FUNCTION__))
;
1195 TaskgroupDescriptor = I->TaskgroupReductionRef;
1196 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1197 Data.PrivateCopy, I->DefaultAttrLoc);
1198 }
1199 return DSAVarData();
1200}
1201
1202const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1203 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1204 Expr *&TaskgroupDescriptor) const {
1205 D = getCanonicalDecl(D);
1206 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.")((!isStackEmpty() && "Data-sharing attributes stack is empty."
) ? static_cast<void> (0) : __assert_fail ("!isStackEmpty() && \"Data-sharing attributes stack is empty.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1206, __PRETTY_FUNCTION__))
;
1207 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1208 const DSAInfo &Data = I->SharingMap.lookup(D);
1209 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1210 continue;
1211 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1212 if (!ReductionData.ReductionOp ||
1213 !ReductionData.ReductionOp.is<const Expr *>())
1214 return DSAVarData();
1215 SR = ReductionData.ReductionRange;
1216 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1217 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1219, __PRETTY_FUNCTION__))
1218 "expression for the descriptor is not "((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1219, __PRETTY_FUNCTION__))
1219 "set.")((I->TaskgroupReductionRef && "taskgroup reduction reference "
"expression for the descriptor is not " "set.") ? static_cast
<void> (0) : __assert_fail ("I->TaskgroupReductionRef && \"taskgroup reduction reference \" \"expression for the descriptor is not \" \"set.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1219, __PRETTY_FUNCTION__))
;
1220 TaskgroupDescriptor = I->TaskgroupReductionRef;
1221 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1222 Data.PrivateCopy, I->DefaultAttrLoc);
1223 }
1224 return DSAVarData();
1225}
1226
1227bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1228 D = D->getCanonicalDecl();
1229 for (const_iterator E = end(); I != E; ++I) {
1230 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1231 isOpenMPTargetExecutionDirective(I->Directive)) {
1232 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1233 Scope *CurScope = getCurScope();
1234 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1235 CurScope = CurScope->getParent();
1236 return CurScope != TopScope;
1237 }
1238 }
1239 return false;
1240}
1241
1242static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1243 bool AcceptIfMutable = true,
1244 bool *IsClassType = nullptr) {
1245 ASTContext &Context = SemaRef.getASTContext();
1246 Type = Type.getNonReferenceType().getCanonicalType();
1247 bool IsConstant = Type.isConstant(Context);
1248 Type = Context.getBaseElementType(Type);
1249 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1250 ? Type->getAsCXXRecordDecl()
1251 : nullptr;
1252 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1253 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1254 RD = CTD->getTemplatedDecl();
1255 if (IsClassType)
1256 *IsClassType = RD;
1257 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1258 RD->hasDefinition() && RD->hasMutableFields());
1259}
1260
1261static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1262 QualType Type, OpenMPClauseKind CKind,
1263 SourceLocation ELoc,
1264 bool AcceptIfMutable = true,
1265 bool ListItemNotVar = false) {
1266 ASTContext &Context = SemaRef.getASTContext();
1267 bool IsClassType;
1268 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1269 unsigned Diag = ListItemNotVar
1270 ? diag::err_omp_const_list_item
1271 : IsClassType ? diag::err_omp_const_not_mutable_variable
1272 : diag::err_omp_const_variable;
1273 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1274 if (!ListItemNotVar && D) {
1275 const VarDecl *VD = dyn_cast<VarDecl>(D);
1276 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1277 VarDecl::DeclarationOnly;
1278 SemaRef.Diag(D->getLocation(),
1279 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1280 << D;
1281 }
1282 return true;
1283 }
1284 return false;
1285}
1286
1287const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1288 bool FromParent) {
1289 D = getCanonicalDecl(D);
1290 DSAVarData DVar;
1291
1292 auto *VD = dyn_cast<VarDecl>(D);
1293 auto TI = Threadprivates.find(D);
1294 if (TI != Threadprivates.end()) {
1295 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1296 DVar.CKind = OMPC_threadprivate;
1297 return DVar;
1298 }
1299 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1300 DVar.RefExpr = buildDeclRefExpr(
1301 SemaRef, VD, D->getType().getNonReferenceType(),
1302 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1303 DVar.CKind = OMPC_threadprivate;
1304 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1305 return DVar;
1306 }
1307 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1308 // in a Construct, C/C++, predetermined, p.1]
1309 // Variables appearing in threadprivate directives are threadprivate.
1310 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1311 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1312 SemaRef.getLangOpts().OpenMPUseTLS &&
1313 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1314 (VD && VD->getStorageClass() == SC_Register &&
1315 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1316 DVar.RefExpr = buildDeclRefExpr(
1317 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1318 DVar.CKind = OMPC_threadprivate;
1319 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1320 return DVar;
1321 }
1322 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1323 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1324 !isLoopControlVariable(D).first) {
1325 const_iterator IterTarget =
1326 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1327 return isOpenMPTargetExecutionDirective(Data.Directive);
1328 });
1329 if (IterTarget != end()) {
1330 const_iterator ParentIterTarget = IterTarget + 1;
1331 for (const_iterator Iter = begin();
1332 Iter != ParentIterTarget; ++Iter) {
1333 if (isOpenMPLocal(VD, Iter)) {
1334 DVar.RefExpr =
1335 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1336 D->getLocation());
1337 DVar.CKind = OMPC_threadprivate;
1338 return DVar;
1339 }
1340 }
1341 if (!isClauseParsingMode() || IterTarget != begin()) {
1342 auto DSAIter = IterTarget->SharingMap.find(D);
1343 if (DSAIter != IterTarget->SharingMap.end() &&
1344 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1345 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1346 DVar.CKind = OMPC_threadprivate;
1347 return DVar;
1348 }
1349 const_iterator End = end();
1350 if (!SemaRef.isOpenMPCapturedByRef(
1351 D, std::distance(ParentIterTarget, End),
1352 /*OpenMPCaptureLevel=*/0)) {
1353 DVar.RefExpr =
1354 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1355 IterTarget->ConstructLoc);
1356 DVar.CKind = OMPC_threadprivate;
1357 return DVar;
1358 }
1359 }
1360 }
1361 }
1362
1363 if (isStackEmpty())
1364 // Not in OpenMP execution region and top scope was already checked.
1365 return DVar;
1366
1367 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1368 // in a Construct, C/C++, predetermined, p.4]
1369 // Static data members are shared.
1370 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1371 // in a Construct, C/C++, predetermined, p.7]
1372 // Variables with static storage duration that are declared in a scope
1373 // inside the construct are shared.
1374 if (VD && VD->isStaticDataMember()) {
1375 // Check for explicitly specified attributes.
1376 const_iterator I = begin();
1377 const_iterator EndI = end();
1378 if (FromParent && I != EndI)
1379 ++I;
1380 auto It = I->SharingMap.find(D);
1381 if (It != I->SharingMap.end()) {
1382 const DSAInfo &Data = It->getSecond();
1383 DVar.RefExpr = Data.RefExpr.getPointer();
1384 DVar.PrivateCopy = Data.PrivateCopy;
1385 DVar.CKind = Data.Attributes;
1386 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1387 DVar.DKind = I->Directive;
1388 return DVar;
1389 }
1390
1391 DVar.CKind = OMPC_shared;
1392 return DVar;
1393 }
1394
1395 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1396 // The predetermined shared attribute for const-qualified types having no
1397 // mutable members was removed after OpenMP 3.1.
1398 if (SemaRef.LangOpts.OpenMP <= 31) {
1399 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1400 // in a Construct, C/C++, predetermined, p.6]
1401 // Variables with const qualified type having no mutable member are
1402 // shared.
1403 if (isConstNotMutableType(SemaRef, D->getType())) {
1404 // Variables with const-qualified type having no mutable member may be
1405 // listed in a firstprivate clause, even if they are static data members.
1406 DSAVarData DVarTemp = hasInnermostDSA(
1407 D,
1408 [](OpenMPClauseKind C) {
1409 return C == OMPC_firstprivate || C == OMPC_shared;
1410 },
1411 MatchesAlways, FromParent);
1412 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1413 return DVarTemp;
1414
1415 DVar.CKind = OMPC_shared;
1416 return DVar;
1417 }
1418 }
1419
1420 // Explicitly specified attributes and local variables with predetermined
1421 // attributes.
1422 const_iterator I = begin();
1423 const_iterator EndI = end();
1424 if (FromParent && I != EndI)
1425 ++I;
1426 auto It = I->SharingMap.find(D);
1427 if (It != I->SharingMap.end()) {
1428 const DSAInfo &Data = It->getSecond();
1429 DVar.RefExpr = Data.RefExpr.getPointer();
1430 DVar.PrivateCopy = Data.PrivateCopy;
1431 DVar.CKind = Data.Attributes;
1432 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1433 DVar.DKind = I->Directive;
1434 }
1435
1436 return DVar;
1437}
1438
1439const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1440 bool FromParent) const {
1441 if (isStackEmpty()) {
1442 const_iterator I;
1443 return getDSA(I, D);
1444 }
1445 D = getCanonicalDecl(D);
1446 const_iterator StartI = begin();
1447 const_iterator EndI = end();
1448 if (FromParent && StartI != EndI)
1449 ++StartI;
1450 return getDSA(StartI, D);
1451}
1452
1453const DSAStackTy::DSAVarData
1454DSAStackTy::hasDSA(ValueDecl *D,
1455 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1456 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1457 bool FromParent) const {
1458 if (isStackEmpty())
1459 return {};
1460 D = getCanonicalDecl(D);
1461 const_iterator I = begin();
1462 const_iterator EndI = end();
1463 if (FromParent && I != EndI)
1464 ++I;
1465 for (; I != EndI; ++I) {
1466 if (!DPred(I->Directive) &&
1467 !isImplicitOrExplicitTaskingRegion(I->Directive))
1468 continue;
1469 const_iterator NewI = I;
1470 DSAVarData DVar = getDSA(NewI, D);
1471 if (I == NewI && CPred(DVar.CKind))
1472 return DVar;
1473 }
1474 return {};
1475}
1476
1477const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1478 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1479 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1480 bool FromParent) const {
1481 if (isStackEmpty())
1482 return {};
1483 D = getCanonicalDecl(D);
1484 const_iterator StartI = begin();
1485 const_iterator EndI = end();
1486 if (FromParent && StartI != EndI)
1487 ++StartI;
1488 if (StartI == EndI || !DPred(StartI->Directive))
1489 return {};
1490 const_iterator NewI = StartI;
1491 DSAVarData DVar = getDSA(NewI, D);
1492 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1493}
1494
1495bool DSAStackTy::hasExplicitDSA(
1496 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1497 unsigned Level, bool NotLastprivate) const {
1498 if (getStackSize() <= Level)
1499 return false;
1500 D = getCanonicalDecl(D);
1501 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1502 auto I = StackElem.SharingMap.find(D);
1503 if (I != StackElem.SharingMap.end() &&
1504 I->getSecond().RefExpr.getPointer() &&
1505 CPred(I->getSecond().Attributes) &&
1506 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1507 return true;
1508 // Check predetermined rules for the loop control variables.
1509 auto LI = StackElem.LCVMap.find(D);
1510 if (LI != StackElem.LCVMap.end())
1511 return CPred(OMPC_private);
1512 return false;
1513}
1514
1515bool DSAStackTy::hasExplicitDirective(
1516 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1517 unsigned Level) const {
1518 if (getStackSize() <= Level)
1519 return false;
1520 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1521 return DPred(StackElem.Directive);
1522}
1523
1524bool DSAStackTy::hasDirective(
1525 const llvm::function_ref<bool(OpenMPDirectiveKind,
1526 const DeclarationNameInfo &, SourceLocation)>
1527 DPred,
1528 bool FromParent) const {
1529 // We look only in the enclosing region.
1530 size_t Skip = FromParent ? 2 : 1;
1531 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1532 I != E; ++I) {
1533 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1534 return true;
1535 }
1536 return false;
1537}
1538
1539void Sema::InitDataSharingAttributesStack() {
1540 VarDataSharingAttributesStack = new DSAStackTy(*this);
1541}
1542
1543#define DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1544
1545void Sema::pushOpenMPFunctionRegion() {
1546 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->pushFunction();
1547}
1548
1549void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1550 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->popFunction(OldFSI);
1551}
1552
1553static bool isOpenMPDeviceDelayedContext(Sema &S) {
1554 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&((S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1555, __PRETTY_FUNCTION__))
1555 "Expected OpenMP device compilation.")((S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1555, __PRETTY_FUNCTION__))
;
1556 return !S.isInOpenMPTargetExecutionDirective() &&
1557 !S.isInOpenMPDeclareTargetContext();
1558}
1559
1560namespace {
1561/// Status of the function emission on the host/device.
1562enum class FunctionEmissionStatus {
1563 Emitted,
1564 Discarded,
1565 Unknown,
1566};
1567} // anonymous namespace
1568
1569Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1570 unsigned DiagID) {
1571 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&((LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("LangOpts.OpenMP && LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1572, __PRETTY_FUNCTION__))
1572 "Expected OpenMP device compilation.")((LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("LangOpts.OpenMP && LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1572, __PRETTY_FUNCTION__))
;
1573 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
1574 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1575 switch (FES) {
1576 case FunctionEmissionStatus::Emitted:
1577 Kind = DeviceDiagBuilder::K_Immediate;
1578 break;
1579 case FunctionEmissionStatus::Unknown:
1580 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1581 : DeviceDiagBuilder::K_Immediate;
1582 break;
1583 case FunctionEmissionStatus::TemplateDiscarded:
1584 case FunctionEmissionStatus::OMPDiscarded:
1585 Kind = DeviceDiagBuilder::K_Nop;
1586 break;
1587 case FunctionEmissionStatus::CUDADiscarded:
1588 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation")::llvm::llvm_unreachable_internal("CUDADiscarded unexpected in OpenMP device compilation"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1588)
;
1589 break;
1590 }
1591
1592 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1593}
1594
1595Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1596 unsigned DiagID) {
1597 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&((LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
"Expected OpenMP host compilation.") ? static_cast<void>
(0) : __assert_fail ("LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && \"Expected OpenMP host compilation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1598, __PRETTY_FUNCTION__))
1598 "Expected OpenMP host compilation.")((LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
"Expected OpenMP host compilation.") ? static_cast<void>
(0) : __assert_fail ("LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && \"Expected OpenMP host compilation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1598, __PRETTY_FUNCTION__))
;
1599 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
1600 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1601 switch (FES) {
1602 case FunctionEmissionStatus::Emitted:
1603 Kind = DeviceDiagBuilder::K_Immediate;
1604 break;
1605 case FunctionEmissionStatus::Unknown:
1606 Kind = DeviceDiagBuilder::K_Deferred;
1607 break;
1608 case FunctionEmissionStatus::TemplateDiscarded:
1609 case FunctionEmissionStatus::OMPDiscarded:
1610 case FunctionEmissionStatus::CUDADiscarded:
1611 Kind = DeviceDiagBuilder::K_Nop;
1612 break;
1613 }
1614
1615 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1616}
1617
1618void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1619 bool CheckForDelayedContext) {
1620 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&((LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("LangOpts.OpenMP && LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1621, __PRETTY_FUNCTION__))
1621 "Expected OpenMP device compilation.")((LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
"Expected OpenMP device compilation.") ? static_cast<void
> (0) : __assert_fail ("LangOpts.OpenMP && LangOpts.OpenMPIsDevice && \"Expected OpenMP device compilation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1621, __PRETTY_FUNCTION__))
;
1622 assert(Callee && "Callee may not be null.")((Callee && "Callee may not be null.") ? static_cast<
void> (0) : __assert_fail ("Callee && \"Callee may not be null.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1622, __PRETTY_FUNCTION__))
;
1623 Callee = Callee->getMostRecentDecl();
1624 FunctionDecl *Caller = getCurFunctionDecl();
1625
1626 // host only function are not available on the device.
1627 if (Caller) {
1628 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1629 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1630 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&((CallerS != FunctionEmissionStatus::CUDADiscarded &&
CalleeS != FunctionEmissionStatus::CUDADiscarded && "CUDADiscarded unexpected in OpenMP device function check"
) ? static_cast<void> (0) : __assert_fail ("CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded && \"CUDADiscarded unexpected in OpenMP device function check\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1632, __PRETTY_FUNCTION__))
1631 CalleeS != FunctionEmissionStatus::CUDADiscarded &&((CallerS != FunctionEmissionStatus::CUDADiscarded &&
CalleeS != FunctionEmissionStatus::CUDADiscarded && "CUDADiscarded unexpected in OpenMP device function check"
) ? static_cast<void> (0) : __assert_fail ("CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded && \"CUDADiscarded unexpected in OpenMP device function check\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1632, __PRETTY_FUNCTION__))
1632 "CUDADiscarded unexpected in OpenMP device function check")((CallerS != FunctionEmissionStatus::CUDADiscarded &&
CalleeS != FunctionEmissionStatus::CUDADiscarded && "CUDADiscarded unexpected in OpenMP device function check"
) ? static_cast<void> (0) : __assert_fail ("CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded && \"CUDADiscarded unexpected in OpenMP device function check\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1632, __PRETTY_FUNCTION__))
;
1633 if ((CallerS == FunctionEmissionStatus::Emitted ||
1634 (!isOpenMPDeviceDelayedContext(*this) &&
1635 CallerS == FunctionEmissionStatus::Unknown)) &&
1636 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1637 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1638 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1639 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1640 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1641 diag::note_omp_marked_device_type_here)
1642 << HostDevTy;
1643 return;
1644 }
1645 }
1646 // If the caller is known-emitted, mark the callee as known-emitted.
1647 // Otherwise, mark the call in our call graph so we can traverse it later.
1648 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1649 (!Caller && !CheckForDelayedContext) ||
1650 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1651 markKnownEmitted(*this, Caller, Callee, Loc,
1652 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
1653 return CheckForDelayedContext &&
1654 S.getEmissionStatus(FD) ==
1655 FunctionEmissionStatus::Emitted;
1656 });
1657 else if (Caller)
1658 DeviceCallGraph[Caller].insert({Callee, Loc});
1659}
1660
1661void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1662 bool CheckCaller) {
1663 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&((LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
"Expected OpenMP host compilation.") ? static_cast<void>
(0) : __assert_fail ("LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && \"Expected OpenMP host compilation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1664, __PRETTY_FUNCTION__))
1664 "Expected OpenMP host compilation.")((LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
"Expected OpenMP host compilation.") ? static_cast<void>
(0) : __assert_fail ("LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && \"Expected OpenMP host compilation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1664, __PRETTY_FUNCTION__))
;
1665 assert(Callee && "Callee may not be null.")((Callee && "Callee may not be null.") ? static_cast<
void> (0) : __assert_fail ("Callee && \"Callee may not be null.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1665, __PRETTY_FUNCTION__))
;
1666 Callee = Callee->getMostRecentDecl();
1667 FunctionDecl *Caller = getCurFunctionDecl();
1668
1669 // device only function are not available on the host.
1670 if (Caller) {
1671 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1672 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1673 assert((((LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded
&& CalleeS != FunctionEmissionStatus::CUDADiscarded)
) && "CUDADiscarded unexpected in OpenMP host function check"
) ? static_cast<void> (0) : __assert_fail ("(LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded)) && \"CUDADiscarded unexpected in OpenMP host function check\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1676, __PRETTY_FUNCTION__))
1674 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&(((LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded
&& CalleeS != FunctionEmissionStatus::CUDADiscarded)
) && "CUDADiscarded unexpected in OpenMP host function check"
) ? static_cast<void> (0) : __assert_fail ("(LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded)) && \"CUDADiscarded unexpected in OpenMP host function check\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1676, __PRETTY_FUNCTION__))
1675 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&(((LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded
&& CalleeS != FunctionEmissionStatus::CUDADiscarded)
) && "CUDADiscarded unexpected in OpenMP host function check"
) ? static_cast<void> (0) : __assert_fail ("(LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded)) && \"CUDADiscarded unexpected in OpenMP host function check\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1676, __PRETTY_FUNCTION__))
1676 "CUDADiscarded unexpected in OpenMP host function check")(((LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded
&& CalleeS != FunctionEmissionStatus::CUDADiscarded)
) && "CUDADiscarded unexpected in OpenMP host function check"
) ? static_cast<void> (0) : __assert_fail ("(LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded && CalleeS != FunctionEmissionStatus::CUDADiscarded)) && \"CUDADiscarded unexpected in OpenMP host function check\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1676, __PRETTY_FUNCTION__))
;
1677 if (CallerS == FunctionEmissionStatus::Emitted &&
1678 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1679 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1680 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1681 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1682 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1683 diag::note_omp_marked_device_type_here)
1684 << NoHostDevTy;
1685 return;
1686 }
1687 }
1688 // If the caller is known-emitted, mark the callee as known-emitted.
1689 // Otherwise, mark the call in our call graph so we can traverse it later.
1690 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1691 if ((!CheckCaller && !Caller) ||
1692 (Caller &&
1693 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1694 markKnownEmitted(
1695 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1696 return CheckCaller &&
1697 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1698 });
1699 else if (Caller)
1700 DeviceCallGraph[Caller].insert({Callee, Loc});
1701 }
1702}
1703
1704void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1705 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&((getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice
&& "OpenMP device compilation mode is expected.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"OpenMP device compilation mode is expected.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1706, __PRETTY_FUNCTION__))
1706 "OpenMP device compilation mode is expected.")((getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice
&& "OpenMP device compilation mode is expected.") ? static_cast
<void> (0) : __assert_fail ("getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && \"OpenMP device compilation mode is expected.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1706, __PRETTY_FUNCTION__))
;
1707 QualType Ty = E->getType();
1708 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1709 ((Ty->isFloat128Type() ||
1710 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1711 !Context.getTargetInfo().hasFloat128Type()) ||
1712 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1713 !Context.getTargetInfo().hasInt128Type()))
1714 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1715 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1716 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
1717}
1718
1719bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1720 unsigned OpenMPCaptureLevel) const {
1721 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1721, __PRETTY_FUNCTION__))
;
1722
1723 ASTContext &Ctx = getASTContext();
1724 bool IsByRef = true;
1725
1726 // Find the directive that is associated with the provided scope.
1727 D = cast<ValueDecl>(D->getCanonicalDecl());
1728 QualType Ty = D->getType();
1729
1730 bool IsVariableUsedInMapClause = false;
1731 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1732 // This table summarizes how a given variable should be passed to the device
1733 // given its type and the clauses where it appears. This table is based on
1734 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1735 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1736 //
1737 // =========================================================================
1738 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1739 // | |(tofrom:scalar)| | pvt | | | |
1740 // =========================================================================
1741 // | scl | | | | - | | bycopy|
1742 // | scl | | - | x | - | - | bycopy|
1743 // | scl | | x | - | - | - | null |
1744 // | scl | x | | | - | | byref |
1745 // | scl | x | - | x | - | - | bycopy|
1746 // | scl | x | x | - | - | - | null |
1747 // | scl | | - | - | - | x | byref |
1748 // | scl | x | - | - | - | x | byref |
1749 //
1750 // | agg | n.a. | | | - | | byref |
1751 // | agg | n.a. | - | x | - | - | byref |
1752 // | agg | n.a. | x | - | - | - | null |
1753 // | agg | n.a. | - | - | - | x | byref |
1754 // | agg | n.a. | - | - | - | x[] | byref |
1755 //
1756 // | ptr | n.a. | | | - | | bycopy|
1757 // | ptr | n.a. | - | x | - | - | bycopy|
1758 // | ptr | n.a. | x | - | - | - | null |
1759 // | ptr | n.a. | - | - | - | x | byref |
1760 // | ptr | n.a. | - | - | - | x[] | bycopy|
1761 // | ptr | n.a. | - | - | x | | bycopy|
1762 // | ptr | n.a. | - | - | x | x | bycopy|
1763 // | ptr | n.a. | - | - | x | x[] | bycopy|
1764 // =========================================================================
1765 // Legend:
1766 // scl - scalar
1767 // ptr - pointer
1768 // agg - aggregate
1769 // x - applies
1770 // - - invalid in this combination
1771 // [] - mapped with an array section
1772 // byref - should be mapped by reference
1773 // byval - should be mapped by value
1774 // null - initialize a local variable to null on the device
1775 //
1776 // Observations:
1777 // - All scalar declarations that show up in a map clause have to be passed
1778 // by reference, because they may have been mapped in the enclosing data
1779 // environment.
1780 // - If the scalar value does not fit the size of uintptr, it has to be
1781 // passed by reference, regardless the result in the table above.
1782 // - For pointers mapped by value that have either an implicit map or an
1783 // array section, the runtime library may pass the NULL value to the
1784 // device instead of the value passed to it by the compiler.
1785
1786 if (Ty->isReferenceType())
1787 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1788
1789 // Locate map clauses and see if the variable being captured is referred to
1790 // in any of those clauses. Here we only care about variables, not fields,
1791 // because fields are part of aggregates.
1792 bool IsVariableAssociatedWithSection = false;
1793
1794 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDeclAtLevel(
1795 D, Level,
1796 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1797 OMPClauseMappableExprCommon::MappableExprComponentListRef
1798 MapExprComponents,
1799 OpenMPClauseKind WhereFoundClauseKind) {
1800 // Only the map clause information influences how a variable is
1801 // captured. E.g. is_device_ptr does not require changing the default
1802 // behavior.
1803 if (WhereFoundClauseKind != OMPC_map)
1804 return false;
1805
1806 auto EI = MapExprComponents.rbegin();
1807 auto EE = MapExprComponents.rend();
1808
1809 assert(EI != EE && "Invalid map expression!")((EI != EE && "Invalid map expression!") ? static_cast
<void> (0) : __assert_fail ("EI != EE && \"Invalid map expression!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1809, __PRETTY_FUNCTION__))
;
1810
1811 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1812 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1813
1814 ++EI;
1815 if (EI == EE)
1816 return false;
1817
1818 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1819 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1820 isa<MemberExpr>(EI->getAssociatedExpression())) {
1821 IsVariableAssociatedWithSection = true;
1822 // There is nothing more we need to know about this variable.
1823 return true;
1824 }
1825
1826 // Keep looking for more map info.
1827 return false;
1828 });
1829
1830 if (IsVariableUsedInMapClause) {
1831 // If variable is identified in a map clause it is always captured by
1832 // reference except if it is a pointer that is dereferenced somehow.
1833 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1834 } else {
1835 // By default, all the data that has a scalar type is mapped by copy
1836 // (except for reduction variables).
1837 IsByRef =
1838 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceCaptureByReferenceInTargetExecutable() &&
1839 !Ty->isAnyPointerType()) ||
1840 !Ty->isScalarType() ||
1841 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1842 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
1843 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1844 }
1845 }
1846
1847 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1848 IsByRef =
1849 ((IsVariableUsedInMapClause &&
1850 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1851 OMPD_target) ||
1852 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
1853 D,
1854 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1855 Level, /*NotLastprivate=*/true)) &&
1856 // If the variable is artificial and must be captured by value - try to
1857 // capture by value.
1858 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1859 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1860 }
1861
1862 // When passing data by copy, we need to make sure it fits the uintptr size
1863 // and alignment, because the runtime library only deals with uintptr types.
1864 // If it does not fit the uintptr size, we need to pass the data by reference
1865 // instead.
1866 if (!IsByRef &&
1867 (Ctx.getTypeSizeInChars(Ty) >
1868 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1869 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1870 IsByRef = true;
1871 }
1872
1873 return IsByRef;
1874}
1875
1876unsigned Sema::getOpenMPNestingLevel() const {
1877 assert(getLangOpts().OpenMP)((getLangOpts().OpenMP) ? static_cast<void> (0) : __assert_fail
("getLangOpts().OpenMP", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1877, __PRETTY_FUNCTION__))
;
1878 return DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getNestingLevel();
1879}
1880
1881bool Sema::isInOpenMPTargetExecutionDirective() const {
1882 return (isOpenMPTargetExecutionDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
1883 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode()) ||
1884 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDirective(
1885 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1886 SourceLocation) -> bool {
1887 return isOpenMPTargetExecutionDirective(K);
1888 },
1889 false);
1890}
1891
1892VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1893 unsigned StopAt) {
1894 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1894, __PRETTY_FUNCTION__))
;
6
Assuming field 'OpenMP' is not equal to 0
7
'?' condition is true
1895 D = getCanonicalDecl(D);
1896
1897 // If we want to determine whether the variable should be captured from the
1898 // perspective of the current capturing scope, and we've already left all the
1899 // capturing scopes of the top directive on the stack, check from the
1900 // perspective of its parent directive (if any) instead.
1901 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1902 *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, CheckScopeInfo
7.1
'CheckScopeInfo' is false
&& DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isBodyComplete());
1903
1904 // If we are attempting to capture a global variable in a directive with
1905 // 'target' we return true so that this global is also mapped to the device.
1906 //
1907 auto *VD = dyn_cast<VarDecl>(D);
8
Assuming 'D' is not a 'VarDecl'
1908 if (VD
8.1
'VD' is null
&& !VD->hasLocalStorage() &&
1909 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1910 if (isInOpenMPDeclareTargetContext()) {
1911 // Try to mark variable as declare target if it is used in capturing
1912 // regions.
1913 if (LangOpts.OpenMP <= 45 &&
1914 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1915 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
1916 return nullptr;
1917 } else if (isInOpenMPTargetExecutionDirective()) {
1918 // If the declaration is enclosed in a 'declare target' directive,
1919 // then it should not be captured.
1920 //
1921 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1922 return nullptr;
1923 return VD;
1924 }
1925 }
1926
1927 if (CheckScopeInfo
8.2
'CheckScopeInfo' is false
) {
9
Taking false branch
1928 bool OpenMPFound = false;
1929 for (unsigned I = StopAt + 1; I > 0; --I) {
1930 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1931 if(!isa<CapturingScopeInfo>(FSI))
1932 return nullptr;
1933 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1934 if (RSI->CapRegionKind == CR_OpenMP) {
1935 OpenMPFound = true;
1936 break;
1937 }
1938 }
1939 if (!OpenMPFound)
1940 return nullptr;
1941 }
1942
1943 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() != OMPD_unknown
&&
10
Assuming the condition is true
1944 (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode()
||
11
Calling 'DSAStackTy::isClauseParsingMode'
14
Returning from 'DSAStackTy::isClauseParsingMode'
1945 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentDirective() != OMPD_unknown)) {
1946 auto &&Info = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D)
;
15
Calling 'DSAStackTy::isLoopControlVariable'
20
Returning from 'DSAStackTy::isLoopControlVariable'
1947 if (Info.first ||
21
Assuming field 'first' is 0
1948 (VD
21.1
'VD' is null
&& VD->hasLocalStorage() &&
1949 isImplicitOrExplicitTaskingRegion(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) ||
1950 (VD
21.2
'VD' is null
&& DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceVarCapturing()))
1951 return VD ? VD : Info.second;
1952 DSAStackTy::DSAVarData DVarPrivate =
1953 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode());
1954 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
22
Assuming field 'CKind' is equal to OMPC_unknown
1955 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1956 // Threadprivate variables must not be captured.
1957 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
23
Assuming the condition is false
24
Taking false branch
1958 return nullptr;
1959 // The variable is not private or it is the variable in the directive with
1960 // default(none) clause and not used in any clause.
1961 DVarPrivate = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDSA(D, isOpenMPPrivate,
25
Null pointer value stored to 'DVarPrivate.PrivateCopy'
1962 [](OpenMPDirectiveKind) { return true; },
1963 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode())
;
1964 if (DVarPrivate.CKind
25.1
Field 'CKind' is not equal to OMPC_unknown
!= OMPC_unknown ||
1965 (VD && DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() == DSA_none))
1966 return VD
25.2
'VD' is null
? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
26
'?' condition is false
27
Called C++ object pointer is null
1967 }
1968 return nullptr;
1969}
1970
1971void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1972 unsigned Level) const {
1973 SmallVector<OpenMPDirectiveKind, 4> Regions;
1974 getOpenMPCaptureRegions(Regions, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(Level));
1975 FunctionScopesIndex -= Regions.size();
1976}
1977
1978void Sema::startOpenMPLoop() {
1979 assert(LangOpts.OpenMP && "OpenMP must be enabled.")((LangOpts.OpenMP && "OpenMP must be enabled.") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP must be enabled.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1979, __PRETTY_FUNCTION__))
;
1980 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
1981 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopInit();
1982}
1983
1984void Sema::startOpenMPCXXRangeFor() {
1985 assert(LangOpts.OpenMP && "OpenMP must be enabled.")((LangOpts.OpenMP && "OpenMP must be enabled.") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP must be enabled.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1985, __PRETTY_FUNCTION__))
;
1986 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
1987 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->resetPossibleLoopCounter();
1988 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopStart();
1989 }
1990}
1991
1992bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
1993 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 1993, __PRETTY_FUNCTION__))
;
1994 if (isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
1995 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops() > 0 &&
1996 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopStarted()) {
1997 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->resetPossibleLoopCounter(D);
1998 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopStart();
1999 return true;
2000 }
2001 if ((DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2002 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isLoopControlVariable(D).first) &&
2003 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2004 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2005 !isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
2006 return true;
2007 }
2008 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2009 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2010 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceVarCapturing() &&
2011 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2012 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2013 return true;
2014 }
2015 return DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(
2016 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
2017 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isClauseParsingMode() &&
2018 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getClauseParsingMode() == OMPC_private) ||
2019 // Consider taskgroup reduction descriptor variable a private to avoid
2020 // possible capture in the region.
2021 (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(
2022 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2023 Level) &&
2024 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isTaskgroupReductionRef(D, Level));
2025}
2026
2027void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2028 unsigned Level) {
2029 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2029, __PRETTY_FUNCTION__))
;
2030 D = getCanonicalDecl(D);
2031 OpenMPClauseKind OMPC = OMPC_unknown;
2032 for (unsigned I = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getNestingLevel() + 1; I > Level; --I) {
2033 const unsigned NewLevel = I - 1;
2034 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDSA(D,
2035 [&OMPC](const OpenMPClauseKind K) {
2036 if (isOpenMPPrivate(K)) {
2037 OMPC = K;
2038 return true;
2039 }
2040 return false;
2041 },
2042 NewLevel))
2043 break;
2044 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDeclAtLevel(
2045 D, NewLevel,
2046 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2047 OpenMPClauseKind) { return true; })) {
2048 OMPC = OMPC_map;
2049 break;
2050 }
2051 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2052 NewLevel)) {
2053 OMPC = OMPC_map;
2054 if (D->getType()->isScalarType() &&
2055 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDMAAtLevel(NewLevel) !=
2056 DefaultMapAttributes::DMA_tofrom_scalar)
2057 OMPC = OMPC_firstprivate;
2058 break;
2059 }
2060 }
2061 if (OMPC != OMPC_unknown)
2062 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2063}
2064
2065bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2066 unsigned Level) const {
2067 assert(LangOpts.OpenMP && "OpenMP is not allowed")((LangOpts.OpenMP && "OpenMP is not allowed") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"OpenMP is not allowed\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2067, __PRETTY_FUNCTION__))
;
2068 // Return true if the current level is no longer enclosed in a target region.
2069
2070 const auto *VD = dyn_cast<VarDecl>(D);
2071 return VD && !VD->hasLocalStorage() &&
2072 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2073 Level);
2074}
2075
2076void Sema::DestroyDataSharingAttributesStack() { delete DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
; }
2077
2078void Sema::finalizeOpenMPDelayedAnalysis() {
2079 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.")((LangOpts.OpenMP && "Expected OpenMP compilation mode."
) ? static_cast<void> (0) : __assert_fail ("LangOpts.OpenMP && \"Expected OpenMP compilation mode.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2079, __PRETTY_FUNCTION__))
;
2080 // Diagnose implicit declare target functions and their callees.
2081 for (const auto &CallerCallees : DeviceCallGraph) {
2082 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2083 OMPDeclareTargetDeclAttr::getDeviceType(
2084 CallerCallees.getFirst()->getMostRecentDecl());
2085 // Ignore host functions during device analyzis.
2086 if (LangOpts.OpenMPIsDevice && DevTy &&
2087 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2088 continue;
2089 // Ignore nohost functions during host analyzis.
2090 if (!LangOpts.OpenMPIsDevice && DevTy &&
2091 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2092 continue;
2093 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2094 &Callee : CallerCallees.getSecond()) {
2095 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2096 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2097 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2098 if (LangOpts.OpenMPIsDevice && DevTy &&
2099 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2100 // Diagnose host function called during device codegen.
2101 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2102 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2103 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2104 << HostDevTy << 0;
2105 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2106 diag::note_omp_marked_device_type_here)
2107 << HostDevTy;
2108 continue;
2109 }
2110 if (!LangOpts.OpenMPIsDevice && DevTy &&
2111 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2112 // Diagnose nohost function called during host codegen.
2113 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2114 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2115 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2116 << NoHostDevTy << 1;
2117 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2118 diag::note_omp_marked_device_type_here)
2119 << NoHostDevTy;
2120 continue;
2121 }
2122 }
2123 }
2124}
2125
2126void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2127 const DeclarationNameInfo &DirName,
2128 Scope *CurScope, SourceLocation Loc) {
2129 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->push(DKind, DirName, CurScope, Loc);
2130 PushExpressionEvaluationContext(
2131 ExpressionEvaluationContext::PotentiallyEvaluated);
2132}
2133
2134void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2135 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setClauseParsingMode(K);
2136}
2137
2138void Sema::EndOpenMPClause() {
2139 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setClauseParsingMode(/*K=*/OMPC_unknown);
2140}
2141
2142static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2143 ArrayRef<OMPClause *> Clauses);
2144
2145void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
2146 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2147 // A variable of class type (or array thereof) that appears in a lastprivate
2148 // clause requires an accessible, unambiguous default constructor for the
2149 // class type, unless the list item is also specified in a firstprivate
2150 // clause.
2151 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2152 for (OMPClause *C : D->clauses()) {
2153 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2154 SmallVector<Expr *, 8> PrivateCopies;
2155 for (Expr *DE : Clause->varlists()) {
2156 if (DE->isValueDependent() || DE->isTypeDependent()) {
2157 PrivateCopies.push_back(nullptr);
2158 continue;
2159 }
2160 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
2161 auto *VD = cast<VarDecl>(DRE->getDecl());
2162 QualType Type = VD->getType().getNonReferenceType();
2163 const DSAStackTy::DSAVarData DVar =
2164 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(VD, /*FromParent=*/false);
2165 if (DVar.CKind == OMPC_lastprivate) {
2166 // Generate helper private variable and initialize it with the
2167 // default value. The address of the original variable is replaced
2168 // by the address of the new private variable in CodeGen. This new
2169 // variable is not added to IdResolver, so the code in the OpenMP
2170 // region uses original variable for proper diagnostics.
2171 VarDecl *VDPrivate = buildVarDecl(
2172 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
2173 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
2174 ActOnUninitializedDecl(VDPrivate);
2175 if (VDPrivate->isInvalidDecl()) {
2176 PrivateCopies.push_back(nullptr);
2177 continue;
2178 }
2179 PrivateCopies.push_back(buildDeclRefExpr(
2180 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
2181 } else {
2182 // The variable is also a firstprivate, so initialization sequence
2183 // for private copy is generated already.
2184 PrivateCopies.push_back(nullptr);
2185 }
2186 }
2187 Clause->setPrivateCopies(PrivateCopies);
2188 }
2189 }
2190 // Check allocate clauses.
2191 if (!CurContext->isDependentContext())
2192 checkAllocateClauses(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D->clauses());
2193 }
2194
2195 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->pop();
2196 DiscardCleanupsInEvaluationContext();
2197 PopExpressionEvaluationContext();
2198}
2199
2200static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2201 Expr *NumIterations, Sema &SemaRef,
2202 Scope *S, DSAStackTy *Stack);
2203
2204namespace {
2205
2206class VarDeclFilterCCC final : public CorrectionCandidateCallback {
2207private:
2208 Sema &SemaRef;
2209
2210public:
2211 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
2212 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2213 NamedDecl *ND = Candidate.getCorrectionDecl();
2214 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
2215 return VD->hasGlobalStorage() &&
2216 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2217 SemaRef.getCurScope());
2218 }
2219 return false;
2220 }
2221
2222 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2223 return std::make_unique<VarDeclFilterCCC>(*this);
2224 }
2225
2226};
2227
2228class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
2229private:
2230 Sema &SemaRef;
2231
2232public:
2233 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2234 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2235 NamedDecl *ND = Candidate.getCorrectionDecl();
2236 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2237 isa<FunctionDecl>(ND))) {
2238 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2239 SemaRef.getCurScope());
2240 }
2241 return false;
2242 }
2243
2244 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2245 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
2246 }
2247};
2248
2249} // namespace
2250
2251ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2252 CXXScopeSpec &ScopeSpec,
2253 const DeclarationNameInfo &Id,
2254 OpenMPDirectiveKind Kind) {
2255 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2256 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2257
2258 if (Lookup.isAmbiguous())
2259 return ExprError();
2260
2261 VarDecl *VD;
2262 if (!Lookup.isSingleResult()) {
2263 VarDeclFilterCCC CCC(*this);
2264 if (TypoCorrection Corrected =
2265 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2266 CTK_ErrorRecovery)) {
2267 diagnoseTypo(Corrected,
2268 PDiag(Lookup.empty()
2269 ? diag::err_undeclared_var_use_suggest
2270 : diag::err_omp_expected_var_arg_suggest)
2271 << Id.getName());
2272 VD = Corrected.getCorrectionDeclAs<VarDecl>();
2273 } else {
2274 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2275 : diag::err_omp_expected_var_arg)
2276 << Id.getName();
2277 return ExprError();
2278 }
2279 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2280 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2281 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2282 return ExprError();
2283 }
2284 Lookup.suppressDiagnostics();
2285
2286 // OpenMP [2.9.2, Syntax, C/C++]
2287 // Variables must be file-scope, namespace-scope, or static block-scope.
2288 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
2289 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
2290 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
2291 bool IsDecl =
2292 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2293 Diag(VD->getLocation(),
2294 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2295 << VD;
2296 return ExprError();
2297 }
2298
2299 VarDecl *CanonicalVD = VD->getCanonicalDecl();
2300 NamedDecl *ND = CanonicalVD;
2301 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2302 // A threadprivate directive for file-scope variables must appear outside
2303 // any definition or declaration.
2304 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2305 !getCurLexicalContext()->isTranslationUnit()) {
2306 Diag(Id.getLoc(), diag::err_omp_var_scope)
2307 << getOpenMPDirectiveName(Kind) << VD;
2308 bool IsDecl =
2309 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2310 Diag(VD->getLocation(),
2311 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2312 << VD;
2313 return ExprError();
2314 }
2315 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2316 // A threadprivate directive for static class member variables must appear
2317 // in the class definition, in the same scope in which the member
2318 // variables are declared.
2319 if (CanonicalVD->isStaticDataMember() &&
2320 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2321 Diag(Id.getLoc(), diag::err_omp_var_scope)
2322 << getOpenMPDirectiveName(Kind) << VD;
2323 bool IsDecl =
2324 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2325 Diag(VD->getLocation(),
2326 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2327 << VD;
2328 return ExprError();
2329 }
2330 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2331 // A threadprivate directive for namespace-scope variables must appear
2332 // outside any definition or declaration other than the namespace
2333 // definition itself.
2334 if (CanonicalVD->getDeclContext()->isNamespace() &&
2335 (!getCurLexicalContext()->isFileContext() ||
2336 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2337 Diag(Id.getLoc(), diag::err_omp_var_scope)
2338 << getOpenMPDirectiveName(Kind) << VD;
2339 bool IsDecl =
2340 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2341 Diag(VD->getLocation(),
2342 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2343 << VD;
2344 return ExprError();
2345 }
2346 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2347 // A threadprivate directive for static block-scope variables must appear
2348 // in the scope of the variable and not in a nested scope.
2349 if (CanonicalVD->isLocalVarDecl() && CurScope &&
2350 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
2351 Diag(Id.getLoc(), diag::err_omp_var_scope)
2352 << getOpenMPDirectiveName(Kind) << VD;
2353 bool IsDecl =
2354 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2355 Diag(VD->getLocation(),
2356 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2357 << VD;
2358 return ExprError();
2359 }
2360
2361 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2362 // A threadprivate directive must lexically precede all references to any
2363 // of the variables in its list.
2364 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2365 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
2366 Diag(Id.getLoc(), diag::err_omp_var_used)
2367 << getOpenMPDirectiveName(Kind) << VD;
2368 return ExprError();
2369 }
2370
2371 QualType ExprType = VD->getType().getNonReferenceType();
2372 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2373 SourceLocation(), VD,
2374 /*RefersToEnclosingVariableOrCapture=*/false,
2375 Id.getLoc(), ExprType, VK_LValue);
2376}
2377
2378Sema::DeclGroupPtrTy
2379Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2380 ArrayRef<Expr *> VarList) {
2381 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
2382 CurContext->addDecl(D);
2383 return DeclGroupPtrTy::make(DeclGroupRef(D));
2384 }
2385 return nullptr;
2386}
2387
2388namespace {
2389class LocalVarRefChecker final
2390 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
2391 Sema &SemaRef;
2392
2393public:
2394 bool VisitDeclRefExpr(const DeclRefExpr *E) {
2395 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2396 if (VD->hasLocalStorage()) {
2397 SemaRef.Diag(E->getBeginLoc(),
2398 diag::err_omp_local_var_in_threadprivate_init)
2399 << E->getSourceRange();
2400 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2401 << VD << VD->getSourceRange();
2402 return true;
2403 }
2404 }
2405 return false;
2406 }
2407 bool VisitStmt(const Stmt *S) {
2408 for (const Stmt *Child : S->children()) {
2409 if (Child && Visit(Child))
2410 return true;
2411 }
2412 return false;
2413 }
2414 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2415};
2416} // namespace
2417
2418OMPThreadPrivateDecl *
2419Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2420 SmallVector<Expr *, 8> Vars;
2421 for (Expr *RefExpr : VarList) {
2422 auto *DE = cast<DeclRefExpr>(RefExpr);
2423 auto *VD = cast<VarDecl>(DE->getDecl());
2424 SourceLocation ILoc = DE->getExprLoc();
2425
2426 // Mark variable as used.
2427 VD->setReferenced();
2428 VD->markUsed(Context);
2429
2430 QualType QType = VD->getType();
2431 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2432 // It will be analyzed later.
2433 Vars.push_back(DE);
2434 continue;
2435 }
2436
2437 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2438 // A threadprivate variable must not have an incomplete type.
2439 if (RequireCompleteType(ILoc, VD->getType(),
2440 diag::err_omp_threadprivate_incomplete_type)) {
2441 continue;
2442 }
2443
2444 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2445 // A threadprivate variable must not have a reference type.
2446 if (VD->getType()->isReferenceType()) {
2447 Diag(ILoc, diag::err_omp_ref_type_arg)
2448 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2449 bool IsDecl =
2450 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2451 Diag(VD->getLocation(),
2452 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2453 << VD;
2454 continue;
2455 }
2456
2457 // Check if this is a TLS variable. If TLS is not being supported, produce
2458 // the corresponding diagnostic.
2459 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2460 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2461 getLangOpts().OpenMPUseTLS &&
2462 getASTContext().getTargetInfo().isTLSSupported())) ||
2463 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2464 !VD->isLocalVarDecl())) {
2465 Diag(ILoc, diag::err_omp_var_thread_local)
2466 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
2467 bool IsDecl =
2468 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2469 Diag(VD->getLocation(),
2470 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2471 << VD;
2472 continue;
2473 }
2474
2475 // Check if initial value of threadprivate variable reference variable with
2476 // local storage (it is not supported by runtime).
2477 if (const Expr *Init = VD->getAnyInitializer()) {
2478 LocalVarRefChecker Checker(*this);
2479 if (Checker.Visit(Init))
2480 continue;
2481 }
2482
2483 Vars.push_back(RefExpr);
2484 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(VD, DE, OMPC_threadprivate);
2485 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2486 Context, SourceRange(Loc, Loc)));
2487 if (ASTMutationListener *ML = Context.getASTMutationListener())
2488 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
2489 }
2490 OMPThreadPrivateDecl *D = nullptr;
2491 if (!Vars.empty()) {
2492 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2493 Vars);
2494 D->setAccess(AS_public);
2495 }
2496 return D;
2497}
2498
2499static OMPAllocateDeclAttr::AllocatorTypeTy
2500getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2501 if (!Allocator)
2502 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2503 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2504 Allocator->isInstantiationDependent() ||
2505 Allocator->containsUnexpandedParameterPack())
2506 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2507 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2508 const Expr *AE = Allocator->IgnoreParenImpCasts();
2509 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2510 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2511 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2512 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
2513 llvm::FoldingSetNodeID AEId, DAEId;
2514 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2515 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2516 if (AEId == DAEId) {
2517 AllocatorKindRes = AllocatorKind;
2518 break;
2519 }
2520 }
2521 return AllocatorKindRes;
2522}
2523
2524static bool checkPreviousOMPAllocateAttribute(
2525 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2526 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2527 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2528 return false;
2529 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2530 Expr *PrevAllocator = A->getAllocator();
2531 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2532 getAllocatorKind(S, Stack, PrevAllocator);
2533 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2534 if (AllocatorsMatch &&
2535 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2536 Allocator && PrevAllocator) {
2537 const Expr *AE = Allocator->IgnoreParenImpCasts();
2538 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2539 llvm::FoldingSetNodeID AEId, PAEId;
2540 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2541 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2542 AllocatorsMatch = AEId == PAEId;
2543 }
2544 if (!AllocatorsMatch) {
2545 SmallString<256> AllocatorBuffer;
2546 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2547 if (Allocator)
2548 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2549 SmallString<256> PrevAllocatorBuffer;
2550 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2551 if (PrevAllocator)
2552 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2553 S.getPrintingPolicy());
2554
2555 SourceLocation AllocatorLoc =
2556 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2557 SourceRange AllocatorRange =
2558 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2559 SourceLocation PrevAllocatorLoc =
2560 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2561 SourceRange PrevAllocatorRange =
2562 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2563 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2564 << (Allocator ? 1 : 0) << AllocatorStream.str()
2565 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2566 << AllocatorRange;
2567 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2568 << PrevAllocatorRange;
2569 return true;
2570 }
2571 return false;
2572}
2573
2574static void
2575applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2576 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2577 Expr *Allocator, SourceRange SR) {
2578 if (VD->hasAttr<OMPAllocateDeclAttr>())
2579 return;
2580 if (Allocator &&
2581 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2582 Allocator->isInstantiationDependent() ||
2583 Allocator->containsUnexpandedParameterPack()))
2584 return;
2585 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2586 Allocator, SR);
2587 VD->addAttr(A);
2588 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2589 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2590}
2591
2592Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2593 SourceLocation Loc, ArrayRef<Expr *> VarList,
2594 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2595 assert(Clauses.size() <= 1 && "Expected at most one clause.")((Clauses.size() <= 1 && "Expected at most one clause."
) ? static_cast<void> (0) : __assert_fail ("Clauses.size() <= 1 && \"Expected at most one clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 2595, __PRETTY_FUNCTION__))
;
2596 Expr *Allocator = nullptr;
2597 if (Clauses.empty()) {
2598 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2599 // allocate directives that appear in a target region must specify an
2600 // allocator clause unless a requires directive with the dynamic_allocators
2601 // clause is present in the same compilation unit.
2602 if (LangOpts.OpenMPIsDevice &&
2603 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
2604 targetDiag(Loc, diag::err_expected_allocator_clause);
2605 } else {
2606 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
2607 }
2608 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2609 getAllocatorKind(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, Allocator);
2610 SmallVector<Expr *, 8> Vars;
2611 for (Expr *RefExpr : VarList) {
2612 auto *DE = cast<DeclRefExpr>(RefExpr);
2613 auto *VD = cast<VarDecl>(DE->getDecl());
2614
2615 // Check if this is a TLS variable or global register.
2616 if (VD->getTLSKind() != VarDecl::TLS_None ||
2617 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2618 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2619 !VD->isLocalVarDecl()))
2620 continue;
2621
2622 // If the used several times in the allocate directive, the same allocator
2623 // must be used.
2624 if (checkPreviousOMPAllocateAttribute(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, RefExpr, VD,
2625 AllocatorKind, Allocator))
2626 continue;
2627
2628 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2629 // If a list item has a static storage type, the allocator expression in the
2630 // allocator clause must be a constant expression that evaluates to one of
2631 // the predefined memory allocator values.
2632 if (Allocator && VD->hasGlobalStorage()) {
2633 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
2634 Diag(Allocator->getExprLoc(),
2635 diag::err_omp_expected_predefined_allocator)
2636 << Allocator->getSourceRange();
2637 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2638 VarDecl::DeclarationOnly;
2639 Diag(VD->getLocation(),
2640 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2641 << VD;
2642 continue;
2643 }
2644 }
2645
2646 Vars.push_back(RefExpr);
2647 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2648 DE->getSourceRange());
2649 }
2650 if (Vars.empty())
2651 return nullptr;
2652 if (!Owner)
2653 Owner = getCurLexicalContext();
2654 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
2655 D->setAccess(AS_public);
2656 Owner->addDecl(D);
2657 return DeclGroupPtrTy::make(DeclGroupRef(D));
2658}
2659
2660Sema::DeclGroupPtrTy
2661Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2662 ArrayRef<OMPClause *> ClauseList) {
2663 OMPRequiresDecl *D = nullptr;
2664 if (!CurContext->isFileContext()) {
2665 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2666 } else {
2667 D = CheckOMPRequiresDecl(Loc, ClauseList);
2668 if (D) {
2669 CurContext->addDecl(D);
2670 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addRequiresDecl(D);
2671 }
2672 }
2673 return DeclGroupPtrTy::make(DeclGroupRef(D));
2674}
2675
2676OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2677 ArrayRef<OMPClause *> ClauseList) {
2678 /// For target specific clauses, the requires directive cannot be
2679 /// specified after the handling of any of the target regions in the
2680 /// current compilation unit.
2681 ArrayRef<SourceLocation> TargetLocations =
2682 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getEncounteredTargetLocs();
2683 if (!TargetLocations.empty()) {
2684 for (const OMPClause *CNew : ClauseList) {
2685 // Check if any of the requires clauses affect target regions.
2686 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2687 isa<OMPUnifiedAddressClause>(CNew) ||
2688 isa<OMPReverseOffloadClause>(CNew) ||
2689 isa<OMPDynamicAllocatorsClause>(CNew)) {
2690 Diag(Loc, diag::err_omp_target_before_requires)
2691 << getOpenMPClauseName(CNew->getClauseKind());
2692 for (SourceLocation TargetLoc : TargetLocations) {
2693 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2694 }
2695 }
2696 }
2697 }
2698
2699 if (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasDuplicateRequiresClause(ClauseList))
2700 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2701 ClauseList);
2702 return nullptr;
2703}
2704
2705static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2706 const ValueDecl *D,
2707 const DSAStackTy::DSAVarData &DVar,
2708 bool IsLoopIterVar = false) {
2709 if (DVar.RefExpr) {
2710 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2711 << getOpenMPClauseName(DVar.CKind);
2712 return;
2713 }
2714 enum {
2715 PDSA_StaticMemberShared,
2716 PDSA_StaticLocalVarShared,
2717 PDSA_LoopIterVarPrivate,
2718 PDSA_LoopIterVarLinear,
2719 PDSA_LoopIterVarLastprivate,
2720 PDSA_ConstVarShared,
2721 PDSA_GlobalVarShared,
2722 PDSA_TaskVarFirstprivate,
2723 PDSA_LocalVarPrivate,
2724 PDSA_Implicit
2725 } Reason = PDSA_Implicit;
2726 bool ReportHint = false;
2727 auto ReportLoc = D->getLocation();
2728 auto *VD = dyn_cast<VarDecl>(D);
2729 if (IsLoopIterVar) {
2730 if (DVar.CKind == OMPC_private)
2731 Reason = PDSA_LoopIterVarPrivate;
2732 else if (DVar.CKind == OMPC_lastprivate)
2733 Reason = PDSA_LoopIterVarLastprivate;
2734 else
2735 Reason = PDSA_LoopIterVarLinear;
2736 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2737 DVar.CKind == OMPC_firstprivate) {
2738 Reason = PDSA_TaskVarFirstprivate;
2739 ReportLoc = DVar.ImplicitDSALoc;
2740 } else if (VD && VD->isStaticLocal())
2741 Reason = PDSA_StaticLocalVarShared;
2742 else if (VD && VD->isStaticDataMember())
2743 Reason = PDSA_StaticMemberShared;
2744 else if (VD && VD->isFileVarDecl())
2745 Reason = PDSA_GlobalVarShared;
2746 else if (D->getType().isConstant(SemaRef.getASTContext()))
2747 Reason = PDSA_ConstVarShared;
2748 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
2749 ReportHint = true;
2750 Reason = PDSA_LocalVarPrivate;
2751 }
2752 if (Reason != PDSA_Implicit) {
2753 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
2754 << Reason << ReportHint
2755 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2756 } else if (DVar.ImplicitDSALoc.isValid()) {
2757 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2758 << getOpenMPClauseName(DVar.CKind);
2759 }
2760}
2761
2762namespace {
2763class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
2764 DSAStackTy *Stack;
2765 Sema &SemaRef;
2766 bool ErrorFound = false;
2767 CapturedStmt *CS = nullptr;
2768 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2769 llvm::SmallVector<Expr *, 4> ImplicitMap;
2770 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2771 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
2772
2773 void VisitSubCaptures(OMPExecutableDirective *S) {
2774 // Check implicitly captured variables.
2775 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2776 return;
2777 visitSubCaptures(S->getInnermostCapturedStmt());
2778 }
2779
2780public:
2781 void VisitDeclRefExpr(DeclRefExpr *E) {
2782 if (E->isTypeDependent() || E->isValueDependent() ||
2783 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2784 return;
2785 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2786 // Check the datasharing rules for the expressions in the clauses.
2787 if (!CS) {
2788 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2789 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2790 Visit(CED->getInit());
2791 return;
2792 }
2793 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2794 // Do not analyze internal variables and do not enclose them into
2795 // implicit clauses.
2796 return;
2797 VD = VD->getCanonicalDecl();
2798 // Skip internally declared variables.
2799 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
2800 return;
2801
2802 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
2803 // Check if the variable has explicit DSA set and stop analysis if it so.
2804 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
2805 return;
2806
2807 // Skip internally declared static variables.
2808 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2809 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2810 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
2811 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2812 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
2813 return;
2814
2815 SourceLocation ELoc = E->getExprLoc();
2816 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2817 // The default(none) clause requires that each variable that is referenced
2818 // in the construct, and does not have a predetermined data-sharing
2819 // attribute, must have its data-sharing attribute explicitly determined
2820 // by being listed in a data-sharing attribute clause.
2821 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
2822 isImplicitOrExplicitTaskingRegion(DKind) &&
2823 VarsWithInheritedDSA.count(VD) == 0) {
2824 VarsWithInheritedDSA[VD] = E;
2825 return;
2826 }
2827
2828 if (isOpenMPTargetExecutionDirective(DKind) &&
2829 !Stack->isLoopControlVariable(VD).first) {
2830 if (!Stack->checkMappableExprComponentListsForDecl(
2831 VD, /*CurrentRegionOnly=*/true,
2832 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2833 StackComponents,
2834 OpenMPClauseKind) {
2835 // Variable is used if it has been marked as an array, array
2836 // section or the variable iself.
2837 return StackComponents.size() == 1 ||
2838 std::all_of(
2839 std::next(StackComponents.rbegin()),
2840 StackComponents.rend(),
2841 [](const OMPClauseMappableExprCommon::
2842 MappableComponent &MC) {
2843 return MC.getAssociatedDeclaration() ==
2844 nullptr &&
2845 (isa<OMPArraySectionExpr>(
2846 MC.getAssociatedExpression()) ||
2847 isa<ArraySubscriptExpr>(
2848 MC.getAssociatedExpression()));
2849 });
2850 })) {
2851 bool IsFirstprivate = false;
2852 // By default lambdas are captured as firstprivates.
2853 if (const auto *RD =
2854 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
2855 IsFirstprivate = RD->isLambda();
2856 IsFirstprivate =
2857 IsFirstprivate ||
2858 (VD->getType().getNonReferenceType()->isScalarType() &&
2859 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
2860 if (IsFirstprivate)
2861 ImplicitFirstprivate.emplace_back(E);
2862 else
2863 ImplicitMap.emplace_back(E);
2864 return;
2865 }
2866 }
2867
2868 // OpenMP [2.9.3.6, Restrictions, p.2]
2869 // A list item that appears in a reduction clause of the innermost
2870 // enclosing worksharing or parallel construct may not be accessed in an
2871 // explicit task.
2872 DVar = Stack->hasInnermostDSA(
2873 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2874 [](OpenMPDirectiveKind K) {
2875 return isOpenMPParallelDirective(K) ||
2876 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2877 },
2878 /*FromParent=*/true);
2879 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2880 ErrorFound = true;
2881 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2882 reportOriginalDsa(SemaRef, Stack, VD, DVar);
2883 return;
2884 }
2885
2886 // Define implicit data-sharing attributes for task.
2887 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
2888 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2889 !Stack->isLoopControlVariable(VD).first) {
2890 ImplicitFirstprivate.push_back(E);
2891 return;
2892 }
2893
2894 // Store implicitly used globals with declare target link for parent
2895 // target.
2896 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2897 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2898 Stack->addToParentTargetRegionLinkGlobals(E);
2899 return;
2900 }
2901 }
2902 }
2903 void VisitMemberExpr(MemberExpr *E) {
2904 if (E->isTypeDependent() || E->isValueDependent() ||
2905 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2906 return;
2907 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2908 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2909 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2910 if (!FD)
2911 return;
2912 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
2913 // Check if the variable has explicit DSA set and stop analysis if it
2914 // so.
2915 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2916 return;
2917
2918 if (isOpenMPTargetExecutionDirective(DKind) &&
2919 !Stack->isLoopControlVariable(FD).first &&
2920 !Stack->checkMappableExprComponentListsForDecl(
2921 FD, /*CurrentRegionOnly=*/true,
2922 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2923 StackComponents,
2924 OpenMPClauseKind) {
2925 return isa<CXXThisExpr>(
2926 cast<MemberExpr>(
2927 StackComponents.back().getAssociatedExpression())
2928 ->getBase()
2929 ->IgnoreParens());
2930 })) {
2931 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2932 // A bit-field cannot appear in a map clause.
2933 //
2934 if (FD->isBitField())
2935 return;
2936
2937 // Check to see if the member expression is referencing a class that
2938 // has already been explicitly mapped
2939 if (Stack->isClassPreviouslyMapped(TE->getType()))
2940 return;
2941
2942 ImplicitMap.emplace_back(E);
2943 return;
2944 }
2945
2946 SourceLocation ELoc = E->getExprLoc();
2947 // OpenMP [2.9.3.6, Restrictions, p.2]
2948 // A list item that appears in a reduction clause of the innermost
2949 // enclosing worksharing or parallel construct may not be accessed in
2950 // an explicit task.
2951 DVar = Stack->hasInnermostDSA(
2952 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2953 [](OpenMPDirectiveKind K) {
2954 return isOpenMPParallelDirective(K) ||
2955 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2956 },
2957 /*FromParent=*/true);
2958 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2959 ErrorFound = true;
2960 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2961 reportOriginalDsa(SemaRef, Stack, FD, DVar);
2962 return;
2963 }
2964
2965 // Define implicit data-sharing attributes for task.
2966 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
2967 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2968 !Stack->isLoopControlVariable(FD).first) {
2969 // Check if there is a captured expression for the current field in the
2970 // region. Do not mark it as firstprivate unless there is no captured
2971 // expression.
2972 // TODO: try to make it firstprivate.
2973 if (DVar.CKind != OMPC_unknown)
2974 ImplicitFirstprivate.push_back(E);
2975 }
2976 return;
2977 }
2978 if (isOpenMPTargetExecutionDirective(DKind)) {
2979 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2980 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2981 /*NoDiagnose=*/true))
2982 return;
2983 const auto *VD = cast<ValueDecl>(
2984 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2985 if (!Stack->checkMappableExprComponentListsForDecl(
2986 VD, /*CurrentRegionOnly=*/true,
2987 [&CurComponents](
2988 OMPClauseMappableExprCommon::MappableExprComponentListRef
2989 StackComponents,
2990 OpenMPClauseKind) {
2991 auto CCI = CurComponents.rbegin();
2992 auto CCE = CurComponents.rend();
2993 for (const auto &SC : llvm::reverse(StackComponents)) {
2994 // Do both expressions have the same kind?
2995 if (CCI->getAssociatedExpression()->getStmtClass() !=
2996 SC.getAssociatedExpression()->getStmtClass())
2997 if (!(isa<OMPArraySectionExpr>(
2998 SC.getAssociatedExpression()) &&
2999 isa<ArraySubscriptExpr>(
3000 CCI->getAssociatedExpression())))
3001 return false;
3002
3003 const Decl *CCD = CCI->getAssociatedDeclaration();
3004 const Decl *SCD = SC.getAssociatedDeclaration();
3005 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3006 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3007 if (SCD != CCD)
3008 return false;
3009 std::advance(CCI, 1);
3010 if (CCI == CCE)
3011 break;
3012 }
3013 return true;
3014 })) {
3015 Visit(E->getBase());
3016 }
3017 } else {
3018 Visit(E->getBase());
3019 }
3020 }
3021 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
3022 for (OMPClause *C : S->clauses()) {
3023 // Skip analysis of arguments of implicitly defined firstprivate clause
3024 // for task|target directives.
3025 // Skip analysis of arguments of implicitly defined map clause for target
3026 // directives.
3027 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3028 C->isImplicit())) {
3029 for (Stmt *CC : C->children()) {
3030 if (CC)
3031 Visit(CC);
3032 }
3033 }
3034 }
3035 // Check implicitly captured variables.
3036 VisitSubCaptures(S);
3037 }
3038 void VisitStmt(Stmt *S) {
3039 for (Stmt *C : S->children()) {
3040 if (C) {
3041 // Check implicitly captured variables in the task-based directives to
3042 // check if they must be firstprivatized.
3043 Visit(C);
3044 }
3045 }
3046 }
3047
3048 void visitSubCaptures(CapturedStmt *S) {
3049 for (const CapturedStmt::Capture &Cap : S->captures()) {
3050 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3051 continue;
3052 VarDecl *VD = Cap.getCapturedVar();
3053 // Do not try to map the variable if it or its sub-component was mapped
3054 // already.
3055 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3056 Stack->checkMappableExprComponentListsForDecl(
3057 VD, /*CurrentRegionOnly=*/true,
3058 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3059 OpenMPClauseKind) { return true; }))
3060 continue;
3061 DeclRefExpr *DRE = buildDeclRefExpr(
3062 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3063 Cap.getLocation(), /*RefersToCapture=*/true);
3064 Visit(DRE);
3065 }
3066 }
3067 bool isErrorFound() const { return ErrorFound; }
3068 ArrayRef<Expr *> getImplicitFirstprivate() const {
3069 return ImplicitFirstprivate;
3070 }
3071 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
3072 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
3073 return VarsWithInheritedDSA;
3074 }
3075
3076 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
3077 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3078 // Process declare target link variables for the target directives.
3079 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3080 for (DeclRefExpr *E : Stack->getLinkGlobals())
3081 Visit(E);
3082 }
3083 }
3084};
3085} // namespace
3086
3087void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
3088 switch (DKind) {
3089 case OMPD_parallel:
3090 case OMPD_parallel_for:
3091 case OMPD_parallel_for_simd:
3092 case OMPD_parallel_sections:
3093 case OMPD_teams:
3094 case OMPD_teams_distribute:
3095 case OMPD_teams_distribute_simd: {
3096 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3097 QualType KmpInt32PtrTy =
3098 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3099 Sema::CapturedParamNameType Params[] = {
3100 std::make_pair(".global_tid.", KmpInt32PtrTy),
3101 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3102 std::make_pair(StringRef(), QualType()) // __context with shared vars
3103 };
3104 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3105 Params);
3106 break;
3107 }
3108 case OMPD_target_teams:
3109 case OMPD_target_parallel:
3110 case OMPD_target_parallel_for:
3111 case OMPD_target_parallel_for_simd:
3112 case OMPD_target_teams_distribute:
3113 case OMPD_target_teams_distribute_simd: {
3114 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3115 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3116 QualType KmpInt32PtrTy =
3117 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3118 QualType Args[] = {VoidPtrTy};
3119 FunctionProtoType::ExtProtoInfo EPI;
3120 EPI.Variadic = true;
3121 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3122 Sema::CapturedParamNameType Params[] = {
3123 std::make_pair(".global_tid.", KmpInt32Ty),
3124 std::make_pair(".part_id.", KmpInt32PtrTy),
3125 std::make_pair(".privates.", VoidPtrTy),
3126 std::make_pair(
3127 ".copy_fn.",
3128 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3129 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3130 std::make_pair(StringRef(), QualType()) // __context with shared vars
3131 };
3132 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3133 Params, /*OpenMPCaptureLevel=*/0);
3134 // Mark this captured region as inlined, because we don't use outlined
3135 // function directly.
3136 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3137 AlwaysInlineAttr::CreateImplicit(
3138 Context, {}, AttributeCommonInfo::AS_Keyword,
3139 AlwaysInlineAttr::Keyword_forceinline));
3140 Sema::CapturedParamNameType ParamsTarget[] = {
3141 std::make_pair(StringRef(), QualType()) // __context with shared vars
3142 };
3143 // Start a captured region for 'target' with no implicit parameters.
3144 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3145 ParamsTarget, /*OpenMPCaptureLevel=*/1);
3146 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
3147 std::make_pair(".global_tid.", KmpInt32PtrTy),
3148 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3149 std::make_pair(StringRef(), QualType()) // __context with shared vars
3150 };
3151 // Start a captured region for 'teams' or 'parallel'. Both regions have
3152 // the same implicit parameters.
3153 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3154 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
3155 break;
3156 }
3157 case OMPD_target:
3158 case OMPD_target_simd: {
3159 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3160 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3161 QualType KmpInt32PtrTy =
3162 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3163 QualType Args[] = {VoidPtrTy};
3164 FunctionProtoType::ExtProtoInfo EPI;
3165 EPI.Variadic = true;
3166 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3167 Sema::CapturedParamNameType Params[] = {
3168 std::make_pair(".global_tid.", KmpInt32Ty),
3169 std::make_pair(".part_id.", KmpInt32PtrTy),
3170 std::make_pair(".privates.", VoidPtrTy),
3171 std::make_pair(
3172 ".copy_fn.",
3173 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3174 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3175 std::make_pair(StringRef(), QualType()) // __context with shared vars
3176 };
3177 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3178 Params, /*OpenMPCaptureLevel=*/0);
3179 // Mark this captured region as inlined, because we don't use outlined
3180 // function directly.
3181 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3182 AlwaysInlineAttr::CreateImplicit(
3183 Context, {}, AttributeCommonInfo::AS_Keyword,
3184 AlwaysInlineAttr::Keyword_forceinline));
3185 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3186 std::make_pair(StringRef(), QualType()),
3187 /*OpenMPCaptureLevel=*/1);
3188 break;
3189 }
3190 case OMPD_simd:
3191 case OMPD_for:
3192 case OMPD_for_simd:
3193 case OMPD_sections:
3194 case OMPD_section:
3195 case OMPD_single:
3196 case OMPD_master:
3197 case OMPD_critical:
3198 case OMPD_taskgroup:
3199 case OMPD_distribute:
3200 case OMPD_distribute_simd:
3201 case OMPD_ordered:
3202 case OMPD_atomic:
3203 case OMPD_target_data: {
3204 Sema::CapturedParamNameType Params[] = {
3205 std::make_pair(StringRef(), QualType()) // __context with shared vars
3206 };
3207 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3208 Params);
3209 break;
3210 }
3211 case OMPD_task: {
3212 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3213 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3214 QualType KmpInt32PtrTy =
3215 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3216 QualType Args[] = {VoidPtrTy};
3217 FunctionProtoType::ExtProtoInfo EPI;
3218 EPI.Variadic = true;
3219 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3220 Sema::CapturedParamNameType Params[] = {
3221 std::make_pair(".global_tid.", KmpInt32Ty),
3222 std::make_pair(".part_id.", KmpInt32PtrTy),
3223 std::make_pair(".privates.", VoidPtrTy),
3224 std::make_pair(
3225 ".copy_fn.",
3226 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3227 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3228 std::make_pair(StringRef(), QualType()) // __context with shared vars
3229 };
3230 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3231 Params);
3232 // Mark this captured region as inlined, because we don't use outlined
3233 // function directly.
3234 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3235 AlwaysInlineAttr::CreateImplicit(
3236 Context, {}, AttributeCommonInfo::AS_Keyword,
3237 AlwaysInlineAttr::Keyword_forceinline));
3238 break;
3239 }
3240 case OMPD_taskloop:
3241 case OMPD_taskloop_simd:
3242 case OMPD_master_taskloop: {
3243 QualType KmpInt32Ty =
3244 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3245 .withConst();
3246 QualType KmpUInt64Ty =
3247 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3248 .withConst();
3249 QualType KmpInt64Ty =
3250 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3251 .withConst();
3252 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3253 QualType KmpInt32PtrTy =
3254 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3255 QualType Args[] = {VoidPtrTy};
3256 FunctionProtoType::ExtProtoInfo EPI;
3257 EPI.Variadic = true;
3258 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3259 Sema::CapturedParamNameType Params[] = {
3260 std::make_pair(".global_tid.", KmpInt32Ty),
3261 std::make_pair(".part_id.", KmpInt32PtrTy),
3262 std::make_pair(".privates.", VoidPtrTy),
3263 std::make_pair(
3264 ".copy_fn.",
3265 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3266 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3267 std::make_pair(".lb.", KmpUInt64Ty),
3268 std::make_pair(".ub.", KmpUInt64Ty),
3269 std::make_pair(".st.", KmpInt64Ty),
3270 std::make_pair(".liter.", KmpInt32Ty),
3271 std::make_pair(".reductions.", VoidPtrTy),
3272 std::make_pair(StringRef(), QualType()) // __context with shared vars
3273 };
3274 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3275 Params);
3276 // Mark this captured region as inlined, because we don't use outlined
3277 // function directly.
3278 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3279 AlwaysInlineAttr::CreateImplicit(
3280 Context, {}, AttributeCommonInfo::AS_Keyword,
3281 AlwaysInlineAttr::Keyword_forceinline));
3282 break;
3283 }
3284 case OMPD_parallel_master_taskloop: {
3285 QualType KmpInt32Ty =
3286 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3287 .withConst();
3288 QualType KmpUInt64Ty =
3289 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3290 .withConst();
3291 QualType KmpInt64Ty =
3292 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3293 .withConst();
3294 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3295 QualType KmpInt32PtrTy =
3296 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3297 Sema::CapturedParamNameType ParamsParallel[] = {
3298 std::make_pair(".global_tid.", KmpInt32PtrTy),
3299 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3300 std::make_pair(StringRef(), QualType()) // __context with shared vars
3301 };
3302 // Start a captured region for 'parallel'.
3303 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3304 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3305 QualType Args[] = {VoidPtrTy};
3306 FunctionProtoType::ExtProtoInfo EPI;
3307 EPI.Variadic = true;
3308 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3309 Sema::CapturedParamNameType Params[] = {
3310 std::make_pair(".global_tid.", KmpInt32Ty),
3311 std::make_pair(".part_id.", KmpInt32PtrTy),
3312 std::make_pair(".privates.", VoidPtrTy),
3313 std::make_pair(
3314 ".copy_fn.",
3315 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3316 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3317 std::make_pair(".lb.", KmpUInt64Ty),
3318 std::make_pair(".ub.", KmpUInt64Ty),
3319 std::make_pair(".st.", KmpInt64Ty),
3320 std::make_pair(".liter.", KmpInt32Ty),
3321 std::make_pair(".reductions.", VoidPtrTy),
3322 std::make_pair(StringRef(), QualType()) // __context with shared vars
3323 };
3324 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3325 Params, /*OpenMPCaptureLevel=*/2);
3326 // Mark this captured region as inlined, because we don't use outlined
3327 // function directly.
3328 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3329 AlwaysInlineAttr::CreateImplicit(
3330 Context, {}, AttributeCommonInfo::AS_Keyword,
3331 AlwaysInlineAttr::Keyword_forceinline));
3332 break;
3333 }
3334 case OMPD_distribute_parallel_for_simd:
3335 case OMPD_distribute_parallel_for: {
3336 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3337 QualType KmpInt32PtrTy =
3338 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3339 Sema::CapturedParamNameType Params[] = {
3340 std::make_pair(".global_tid.", KmpInt32PtrTy),
3341 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3342 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3343 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3344 std::make_pair(StringRef(), QualType()) // __context with shared vars
3345 };
3346 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3347 Params);
3348 break;
3349 }
3350 case OMPD_target_teams_distribute_parallel_for:
3351 case OMPD_target_teams_distribute_parallel_for_simd: {
3352 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3353 QualType KmpInt32PtrTy =
3354 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3355 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3356
3357 QualType Args[] = {VoidPtrTy};
3358 FunctionProtoType::ExtProtoInfo EPI;
3359 EPI.Variadic = true;
3360 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3361 Sema::CapturedParamNameType Params[] = {
3362 std::make_pair(".global_tid.", KmpInt32Ty),
3363 std::make_pair(".part_id.", KmpInt32PtrTy),
3364 std::make_pair(".privates.", VoidPtrTy),
3365 std::make_pair(
3366 ".copy_fn.",
3367 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3368 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3369 std::make_pair(StringRef(), QualType()) // __context with shared vars
3370 };
3371 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3372 Params, /*OpenMPCaptureLevel=*/0);
3373 // Mark this captured region as inlined, because we don't use outlined
3374 // function directly.
3375 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3376 AlwaysInlineAttr::CreateImplicit(
3377 Context, {}, AttributeCommonInfo::AS_Keyword,
3378 AlwaysInlineAttr::Keyword_forceinline));
3379 Sema::CapturedParamNameType ParamsTarget[] = {
3380 std::make_pair(StringRef(), QualType()) // __context with shared vars
3381 };
3382 // Start a captured region for 'target' with no implicit parameters.
3383 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3384 ParamsTarget, /*OpenMPCaptureLevel=*/1);
3385
3386 Sema::CapturedParamNameType ParamsTeams[] = {
3387 std::make_pair(".global_tid.", KmpInt32PtrTy),
3388 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3389 std::make_pair(StringRef(), QualType()) // __context with shared vars
3390 };
3391 // Start a captured region for 'target' with no implicit parameters.
3392 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3393 ParamsTeams, /*OpenMPCaptureLevel=*/2);
3394
3395 Sema::CapturedParamNameType ParamsParallel[] = {
3396 std::make_pair(".global_tid.", KmpInt32PtrTy),
3397 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3398 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3399 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3400 std::make_pair(StringRef(), QualType()) // __context with shared vars
3401 };
3402 // Start a captured region for 'teams' or 'parallel'. Both regions have
3403 // the same implicit parameters.
3404 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3405 ParamsParallel, /*OpenMPCaptureLevel=*/3);
3406 break;
3407 }
3408
3409 case OMPD_teams_distribute_parallel_for:
3410 case OMPD_teams_distribute_parallel_for_simd: {
3411 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3412 QualType KmpInt32PtrTy =
3413 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3414
3415 Sema::CapturedParamNameType ParamsTeams[] = {
3416 std::make_pair(".global_tid.", KmpInt32PtrTy),
3417 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3418 std::make_pair(StringRef(), QualType()) // __context with shared vars
3419 };
3420 // Start a captured region for 'target' with no implicit parameters.
3421 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3422 ParamsTeams, /*OpenMPCaptureLevel=*/0);
3423
3424 Sema::CapturedParamNameType ParamsParallel[] = {
3425 std::make_pair(".global_tid.", KmpInt32PtrTy),
3426 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3427 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3428 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
3429 std::make_pair(StringRef(), QualType()) // __context with shared vars
3430 };
3431 // Start a captured region for 'teams' or 'parallel'. Both regions have
3432 // the same implicit parameters.
3433 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3434 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3435 break;
3436 }
3437 case OMPD_target_update:
3438 case OMPD_target_enter_data:
3439 case OMPD_target_exit_data: {
3440 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3441 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3442 QualType KmpInt32PtrTy =
3443 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3444 QualType Args[] = {VoidPtrTy};
3445 FunctionProtoType::ExtProtoInfo EPI;
3446 EPI.Variadic = true;
3447 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3448 Sema::CapturedParamNameType Params[] = {
3449 std::make_pair(".global_tid.", KmpInt32Ty),
3450 std::make_pair(".part_id.", KmpInt32PtrTy),
3451 std::make_pair(".privates.", VoidPtrTy),
3452 std::make_pair(
3453 ".copy_fn.",
3454 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3455 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3456 std::make_pair(StringRef(), QualType()) // __context with shared vars
3457 };
3458 ActOnCapturedRegionStart(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc(), CurScope, CR_OpenMP,
3459 Params);
3460 // Mark this captured region as inlined, because we don't use outlined
3461 // function directly.
3462 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3463 AlwaysInlineAttr::CreateImplicit(
3464 Context, {}, AttributeCommonInfo::AS_Keyword,
3465 AlwaysInlineAttr::Keyword_forceinline));
3466 break;
3467 }
3468 case OMPD_threadprivate:
3469 case OMPD_allocate:
3470 case OMPD_taskyield:
3471 case OMPD_barrier:
3472 case OMPD_taskwait:
3473 case OMPD_cancellation_point:
3474 case OMPD_cancel:
3475 case OMPD_flush:
3476 case OMPD_declare_reduction:
3477 case OMPD_declare_mapper:
3478 case OMPD_declare_simd:
3479 case OMPD_declare_target:
3480 case OMPD_end_declare_target:
3481 case OMPD_requires:
3482 case OMPD_declare_variant:
3483 llvm_unreachable("OpenMP Directive is not allowed")::llvm::llvm_unreachable_internal("OpenMP Directive is not allowed"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3483)
;
3484 case OMPD_unknown:
3485 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3485)
;
3486 }
3487}
3488
3489int Sema::getNumberOfConstructScopes(unsigned Level) const {
3490 return getOpenMPCaptureLevels(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDirective(Level));
3491}
3492
3493int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3494 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3495 getOpenMPCaptureRegions(CaptureRegions, DKind);
3496 return CaptureRegions.size();
3497}
3498
3499static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
3500 Expr *CaptureExpr, bool WithInit,
3501 bool AsExpression) {
3502 assert(CaptureExpr)((CaptureExpr) ? static_cast<void> (0) : __assert_fail (
"CaptureExpr", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 3502, __PRETTY_FUNCTION__))
;
3503 ASTContext &C = S.getASTContext();
3504 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
3505 QualType Ty = Init->getType();
3506 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
3507 if (S.getLangOpts().CPlusPlus) {
3508 Ty = C.getLValueReferenceType(Ty);
3509 } else {
3510 Ty = C.getPointerType(Ty);
3511 ExprResult Res =
3512 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3513 if (!Res.isUsable())
3514 return nullptr;
3515 Init = Res.get();
3516 }
3517 WithInit = true;
3518 }
3519 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
3520 CaptureExpr->getBeginLoc());
3521 if (!WithInit)
3522 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
3523 S.CurContext->addHiddenDecl(CED);
3524 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
3525 return CED;
3526}
3527
3528static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3529 bool WithInit) {
3530 OMPCapturedExprDecl *CD;
3531 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
5
Calling 'Sema::isOpenMPCapturedDecl'
3532 CD = cast<OMPCapturedExprDecl>(VD);
3533 else
3534 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3535 /*AsExpression=*/false);
3536 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3537 CaptureExpr->getExprLoc());
3538}
3539
3540static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
3541 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
3542 if (!Ref) {
3543 OMPCapturedExprDecl *CD = buildCaptureDecl(
3544 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3545 /*WithInit=*/true, /*AsExpression=*/true);
3546 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3547 CaptureExpr->getExprLoc());
3548 }
3549 ExprResult Res = Ref;
3550 if (!S.getLangOpts().CPlusPlus &&
3551 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
3552 Ref->getType()->isPointerType()) {
3553 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
3554 if (!Res.isUsable())
3555 return ExprError();
3556 }
3557 return S.DefaultLvalueConversion(Res.get());
3558}
3559
3560namespace {
3561// OpenMP directives parsed in this section are represented as a
3562// CapturedStatement with an associated statement. If a syntax error
3563// is detected during the parsing of the associated statement, the
3564// compiler must abort processing and close the CapturedStatement.
3565//
3566// Combined directives such as 'target parallel' have more than one
3567// nested CapturedStatements. This RAII ensures that we unwind out
3568// of all the nested CapturedStatements when an error is found.
3569class CaptureRegionUnwinderRAII {
3570private:
3571 Sema &S;
3572 bool &ErrorFound;
3573 OpenMPDirectiveKind DKind = OMPD_unknown;
3574
3575public:
3576 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3577 OpenMPDirectiveKind DKind)
3578 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3579 ~CaptureRegionUnwinderRAII() {
3580 if (ErrorFound) {
3581 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3582 while (--ThisCaptureLevel >= 0)
3583 S.ActOnCapturedRegionError();
3584 }
3585 }
3586};
3587} // namespace
3588
3589void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3590 // Capture variables captured by reference in lambdas for target-based
3591 // directives.
3592 if (!CurContext->isDependentContext() &&
3593 (isOpenMPTargetExecutionDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) ||
3594 isOpenMPTargetDataManagementDirective(
3595 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))) {
3596 QualType Type = V->getType();
3597 if (const auto *RD = Type.getCanonicalType()
3598 .getNonReferenceType()
3599 ->getAsCXXRecordDecl()) {
3600 bool SavedForceCaptureByReferenceInTargetExecutable =
3601 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isForceCaptureByReferenceInTargetExecutable();
3602 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceCaptureByReferenceInTargetExecutable(
3603 /*V=*/true);
3604 if (RD->isLambda()) {
3605 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3606 FieldDecl *ThisCapture;
3607 RD->getCaptureFields(Captures, ThisCapture);
3608 for (const LambdaCapture &LC : RD->captures()) {
3609 if (LC.getCaptureKind() == LCK_ByRef) {
3610 VarDecl *VD = LC.getCapturedVar();
3611 DeclContext *VDC = VD->getDeclContext();
3612 if (!VDC->Encloses(CurContext))
3613 continue;
3614 MarkVariableReferenced(LC.getLocation(), VD);
3615 } else if (LC.getCaptureKind() == LCK_This) {
3616 QualType ThisTy = getCurrentThisType();
3617 if (!ThisTy.isNull() &&
3618 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3619 CheckCXXThisCapture(LC.getLocation());
3620 }
3621 }
3622 }
3623 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceCaptureByReferenceInTargetExecutable(
3624 SavedForceCaptureByReferenceInTargetExecutable);
3625 }
3626 }
3627}
3628
3629StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3630 ArrayRef<OMPClause *> Clauses) {
3631 bool ErrorFound = false;
3632 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3633 *this, ErrorFound, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
3634 if (!S.isUsable()) {
3635 ErrorFound = true;
3636 return StmtError();
3637 }
3638
3639 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3640 getOpenMPCaptureRegions(CaptureRegions, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
3641 OMPOrderedClause *OC = nullptr;
3642 OMPScheduleClause *SC = nullptr;
3643 SmallVector<const OMPLinearClause *, 4> LCs;
3644 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
3645 // This is required for proper codegen.
3646 for (OMPClause *Clause : Clauses) {
3647 if (isOpenMPTaskingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
3648 Clause->getClauseKind() == OMPC_in_reduction) {
3649 // Capture taskgroup task_reduction descriptors inside the tasking regions
3650 // with the corresponding in_reduction items.
3651 auto *IRC = cast<OMPInReductionClause>(Clause);
3652 for (Expr *E : IRC->taskgroup_descriptors())
3653 if (E)
3654 MarkDeclarationsReferencedInExpr(E);
3655 }
3656 if (isOpenMPPrivate(Clause->getClauseKind()) ||
3657 Clause->getClauseKind() == OMPC_copyprivate ||
3658 (getLangOpts().OpenMPUseTLS &&
3659 getASTContext().getTargetInfo().isTLSSupported() &&
3660 Clause->getClauseKind() == OMPC_copyin)) {
3661 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
3662 // Mark all variables in private list clauses as used in inner region.
3663 for (Stmt *VarRef : Clause->children()) {
3664 if (auto *E = cast_or_null<Expr>(VarRef)) {
3665 MarkDeclarationsReferencedInExpr(E);
3666 }
3667 }
3668 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setForceVarCapturing(/*V=*/false);
3669 } else if (CaptureRegions.size() > 1 ||
3670 CaptureRegions.back() != OMPD_unknown) {
3671 if (auto *C = OMPClauseWithPreInit::get(Clause))
3672 PICs.push_back(C);
3673 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
3674 if (Expr *E = C->getPostUpdateExpr())
3675 MarkDeclarationsReferencedInExpr(E);
3676 }
3677 }
3678 if (Clause->getClauseKind() == OMPC_schedule)
3679 SC = cast<OMPScheduleClause>(Clause);
3680 else if (Clause->getClauseKind() == OMPC_ordered)
3681 OC = cast<OMPOrderedClause>(Clause);
3682 else if (Clause->getClauseKind() == OMPC_linear)
3683 LCs.push_back(cast<OMPLinearClause>(Clause));
3684 }
3685 // OpenMP, 2.7.1 Loop Construct, Restrictions
3686 // The nonmonotonic modifier cannot be specified if an ordered clause is
3687 // specified.
3688 if (SC &&
3689 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3690 SC->getSecondScheduleModifier() ==
3691 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3692 OC) {
3693 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3694 ? SC->getFirstScheduleModifierLoc()
3695 : SC->getSecondScheduleModifierLoc(),
3696 diag::err_omp_schedule_nonmonotonic_ordered)
3697 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
3698 ErrorFound = true;
3699 }
3700 if (!LCs.empty() && OC && OC->getNumForLoops()) {
3701 for (const OMPLinearClause *C : LCs) {
3702 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
3703 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
3704 }
3705 ErrorFound = true;
3706 }
3707 if (isOpenMPWorksharingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
3708 isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) && OC &&
3709 OC->getNumForLoops()) {
3710 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
3711 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
3712 ErrorFound = true;
3713 }
3714 if (ErrorFound) {
3715 return StmtError();
3716 }
3717 StmtResult SR = S;
3718 unsigned CompletedRegions = 0;
3719 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
3720 // Mark all variables in private list clauses as used in inner region.
3721 // Required for proper codegen of combined directives.
3722 // TODO: add processing for other clauses.
3723 if (ThisCaptureRegion != OMPD_unknown) {
3724 for (const clang::OMPClauseWithPreInit *C : PICs) {
3725 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3726 // Find the particular capture region for the clause if the
3727 // directive is a combined one with multiple capture regions.
3728 // If the directive is not a combined one, the capture region
3729 // associated with the clause is OMPD_unknown and is generated
3730 // only once.
3731 if (CaptureRegion == ThisCaptureRegion ||
3732 CaptureRegion == OMPD_unknown) {
3733 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
3734 for (Decl *D : DS->decls())
3735 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3736 }
3737 }
3738 }
3739 }
3740 if (++CompletedRegions == CaptureRegions.size())
3741 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setBodyComplete();
3742 SR = ActOnCapturedRegionEnd(SR.get());
3743 }
3744 return SR;
3745}
3746
3747static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3748 OpenMPDirectiveKind CancelRegion,
3749 SourceLocation StartLoc) {
3750 // CancelRegion is only needed for cancel and cancellation_point.
3751 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3752 return false;
3753
3754 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3755 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3756 return false;
3757
3758 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3759 << getOpenMPDirectiveName(CancelRegion);
3760 return true;
3761}
3762
3763static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
3764 OpenMPDirectiveKind CurrentRegion,
3765 const DeclarationNameInfo &CurrentName,
3766 OpenMPDirectiveKind CancelRegion,
3767 SourceLocation StartLoc) {
3768 if (Stack->getCurScope()) {
3769 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3770 OpenMPDirectiveKind OffendingRegion = ParentRegion;
3771 bool NestingProhibited = false;
3772 bool CloseNesting = true;
3773 bool OrphanSeen = false;
3774 enum {
3775 NoRecommend,
3776 ShouldBeInParallelRegion,
3777 ShouldBeInOrderedRegion,
3778 ShouldBeInTargetRegion,
3779 ShouldBeInTeamsRegion
3780 } Recommend = NoRecommend;
3781 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
3782 // OpenMP [2.16, Nesting of Regions]
3783 // OpenMP constructs may not be nested inside a simd region.
3784 // OpenMP [2.8.1,simd Construct, Restrictions]
3785 // An ordered construct with the simd clause is the only OpenMP
3786 // construct that can appear in the simd region.
3787 // Allowing a SIMD construct nested in another SIMD construct is an
3788 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3789 // message.
3790 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3791 ? diag::err_omp_prohibited_region_simd
3792 : diag::warn_omp_nesting_simd);
3793 return CurrentRegion != OMPD_simd;
3794 }
3795 if (ParentRegion == OMPD_atomic) {
3796 // OpenMP [2.16, Nesting of Regions]
3797 // OpenMP constructs may not be nested inside an atomic region.
3798 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3799 return true;
3800 }
3801 if (CurrentRegion == OMPD_section) {
3802 // OpenMP [2.7.2, sections Construct, Restrictions]
3803 // Orphaned section directives are prohibited. That is, the section
3804 // directives must appear within the sections construct and must not be
3805 // encountered elsewhere in the sections region.
3806 if (ParentRegion != OMPD_sections &&
3807 ParentRegion != OMPD_parallel_sections) {
3808 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3809 << (ParentRegion != OMPD_unknown)
3810 << getOpenMPDirectiveName(ParentRegion);
3811 return true;
3812 }
3813 return false;
3814 }
3815 // Allow some constructs (except teams and cancellation constructs) to be
3816 // orphaned (they could be used in functions, called from OpenMP regions
3817 // with the required preconditions).
3818 if (ParentRegion == OMPD_unknown &&
3819 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3820 CurrentRegion != OMPD_cancellation_point &&
3821 CurrentRegion != OMPD_cancel)
3822 return false;
3823 if (CurrentRegion == OMPD_cancellation_point ||
3824 CurrentRegion == OMPD_cancel) {
3825 // OpenMP [2.16, Nesting of Regions]
3826 // A cancellation point construct for which construct-type-clause is
3827 // taskgroup must be nested inside a task construct. A cancellation
3828 // point construct for which construct-type-clause is not taskgroup must
3829 // be closely nested inside an OpenMP construct that matches the type
3830 // specified in construct-type-clause.
3831 // A cancel construct for which construct-type-clause is taskgroup must be
3832 // nested inside a task construct. A cancel construct for which
3833 // construct-type-clause is not taskgroup must be closely nested inside an
3834 // OpenMP construct that matches the type specified in
3835 // construct-type-clause.
3836 NestingProhibited =
3837 !((CancelRegion == OMPD_parallel &&
3838 (ParentRegion == OMPD_parallel ||
3839 ParentRegion == OMPD_target_parallel)) ||
3840 (CancelRegion == OMPD_for &&
3841 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
3842 ParentRegion == OMPD_target_parallel_for ||
3843 ParentRegion == OMPD_distribute_parallel_for ||
3844 ParentRegion == OMPD_teams_distribute_parallel_for ||
3845 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
3846 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3847 (CancelRegion == OMPD_sections &&
3848 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3849 ParentRegion == OMPD_parallel_sections)));
3850 OrphanSeen = ParentRegion == OMPD_unknown;
3851 } else if (CurrentRegion == OMPD_master) {
3852 // OpenMP [2.16, Nesting of Regions]
3853 // A master region may not be closely nested inside a worksharing,
3854 // atomic, or explicit task region.
3855 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3856 isOpenMPTaskingDirective(ParentRegion);
3857 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3858 // OpenMP [2.16, Nesting of Regions]
3859 // A critical region may not be nested (closely or otherwise) inside a
3860 // critical region with the same name. Note that this restriction is not
3861 // sufficient to prevent deadlock.
3862 SourceLocation PreviousCriticalLoc;
3863 bool DeadLock = Stack->hasDirective(
3864 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3865 const DeclarationNameInfo &DNI,
3866 SourceLocation Loc) {
3867 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3868 PreviousCriticalLoc = Loc;
3869 return true;
3870 }
3871 return false;
3872 },
3873 false /* skip top directive */);
3874 if (DeadLock) {
3875 SemaRef.Diag(StartLoc,
3876 diag::err_omp_prohibited_region_critical_same_name)
3877 << CurrentName.getName();
3878 if (PreviousCriticalLoc.isValid())
3879 SemaRef.Diag(PreviousCriticalLoc,
3880 diag::note_omp_previous_critical_region);
3881 return true;
3882 }
3883 } else if (CurrentRegion == OMPD_barrier) {
3884 // OpenMP [2.16, Nesting of Regions]
3885 // A barrier region may not be closely nested inside a worksharing,
3886 // explicit task, critical, ordered, atomic, or master region.
3887 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3888 isOpenMPTaskingDirective(ParentRegion) ||
3889 ParentRegion == OMPD_master ||
3890 ParentRegion == OMPD_critical ||
3891 ParentRegion == OMPD_ordered;
3892 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
3893 !isOpenMPParallelDirective(CurrentRegion) &&
3894 !isOpenMPTeamsDirective(CurrentRegion)) {
3895 // OpenMP [2.16, Nesting of Regions]
3896 // A worksharing region may not be closely nested inside a worksharing,
3897 // explicit task, critical, ordered, atomic, or master region.
3898 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3899 isOpenMPTaskingDirective(ParentRegion) ||
3900 ParentRegion == OMPD_master ||
3901 ParentRegion == OMPD_critical ||
3902 ParentRegion == OMPD_ordered;
3903 Recommend = ShouldBeInParallelRegion;
3904 } else if (CurrentRegion == OMPD_ordered) {
3905 // OpenMP [2.16, Nesting of Regions]
3906 // An ordered region may not be closely nested inside a critical,
3907 // atomic, or explicit task region.
3908 // An ordered region must be closely nested inside a loop region (or
3909 // parallel loop region) with an ordered clause.
3910 // OpenMP [2.8.1,simd Construct, Restrictions]
3911 // An ordered construct with the simd clause is the only OpenMP construct
3912 // that can appear in the simd region.
3913 NestingProhibited = ParentRegion == OMPD_critical ||
3914 isOpenMPTaskingDirective(ParentRegion) ||
3915 !(isOpenMPSimdDirective(ParentRegion) ||
3916 Stack->isParentOrderedRegion());
3917 Recommend = ShouldBeInOrderedRegion;
3918 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
3919 // OpenMP [2.16, Nesting of Regions]
3920 // If specified, a teams construct must be contained within a target
3921 // construct.
3922 NestingProhibited =
3923 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
3924 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
3925 ParentRegion != OMPD_target);
3926 OrphanSeen = ParentRegion == OMPD_unknown;
3927 Recommend = ShouldBeInTargetRegion;
3928 }
3929 if (!NestingProhibited &&
3930 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3931 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3932 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
3933 // OpenMP [2.16, Nesting of Regions]
3934 // distribute, parallel, parallel sections, parallel workshare, and the
3935 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3936 // constructs that can be closely nested in the teams region.
3937 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3938 !isOpenMPDistributeDirective(CurrentRegion);
3939 Recommend = ShouldBeInParallelRegion;
3940 }
3941 if (!NestingProhibited &&
3942 isOpenMPNestingDistributeDirective(CurrentRegion)) {
3943 // OpenMP 4.5 [2.17 Nesting of Regions]
3944 // The region associated with the distribute construct must be strictly
3945 // nested inside a teams region
3946 NestingProhibited =
3947 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
3948 Recommend = ShouldBeInTeamsRegion;
3949 }
3950 if (!NestingProhibited &&
3951 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3952 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3953 // OpenMP 4.5 [2.17 Nesting of Regions]
3954 // If a target, target update, target data, target enter data, or
3955 // target exit data construct is encountered during execution of a
3956 // target region, the behavior is unspecified.
3957 NestingProhibited = Stack->hasDirective(
3958 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
3959 SourceLocation) {
3960 if (isOpenMPTargetExecutionDirective(K)) {
3961 OffendingRegion = K;
3962 return true;
3963 }
3964 return false;
3965 },
3966 false /* don't skip top directive */);
3967 CloseNesting = false;
3968 }
3969 if (NestingProhibited) {
3970 if (OrphanSeen) {
3971 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3972 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3973 } else {
3974 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3975 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3976 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3977 }
3978 return true;
3979 }
3980 }
3981 return false;
3982}
3983
3984static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3985 ArrayRef<OMPClause *> Clauses,
3986 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3987 bool ErrorFound = false;
3988 unsigned NamedModifiersNumber = 0;
3989 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3990 OMPD_unknown + 1);
3991 SmallVector<SourceLocation, 4> NameModifierLoc;
3992 for (const OMPClause *C : Clauses) {
3993 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3994 // At most one if clause without a directive-name-modifier can appear on
3995 // the directive.
3996 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3997 if (FoundNameModifiers[CurNM]) {
3998 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
3999 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4000 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4001 ErrorFound = true;
4002 } else if (CurNM != OMPD_unknown) {
4003 NameModifierLoc.push_back(IC->getNameModifierLoc());
4004 ++NamedModifiersNumber;
4005 }
4006 FoundNameModifiers[CurNM] = IC;
4007 if (CurNM == OMPD_unknown)
4008 continue;
4009 // Check if the specified name modifier is allowed for the current
4010 // directive.
4011 // At most one if clause with the particular directive-name-modifier can
4012 // appear on the directive.
4013 bool MatchFound = false;
4014 for (auto NM : AllowedNameModifiers) {
4015 if (CurNM == NM) {
4016 MatchFound = true;
4017 break;
4018 }
4019 }
4020 if (!MatchFound) {
4021 S.Diag(IC->getNameModifierLoc(),
4022 diag::err_omp_wrong_if_directive_name_modifier)
4023 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4024 ErrorFound = true;
4025 }
4026 }
4027 }
4028 // If any if clause on the directive includes a directive-name-modifier then
4029 // all if clauses on the directive must include a directive-name-modifier.
4030 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4031 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
4032 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
4033 diag::err_omp_no_more_if_clause);
4034 } else {
4035 std::string Values;
4036 std::string Sep(", ");
4037 unsigned AllowedCnt = 0;
4038 unsigned TotalAllowedNum =
4039 AllowedNameModifiers.size() - NamedModifiersNumber;
4040 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4041 ++Cnt) {
4042 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4043 if (!FoundNameModifiers[NM]) {
4044 Values += "'";
4045 Values += getOpenMPDirectiveName(NM);
4046 Values += "'";
4047 if (AllowedCnt + 2 == TotalAllowedNum)
4048 Values += " or ";
4049 else if (AllowedCnt + 1 != TotalAllowedNum)
4050 Values += Sep;
4051 ++AllowedCnt;
4052 }
4053 }
4054 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
4055 diag::err_omp_unnamed_if_clause)
4056 << (TotalAllowedNum > 1) << Values;
4057 }
4058 for (SourceLocation Loc : NameModifierLoc) {
4059 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4060 }
4061 ErrorFound = true;
4062 }
4063 return ErrorFound;
4064}
4065
4066static std::pair<ValueDecl *, bool>
4067getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
4068 SourceRange &ERange, bool AllowArraySection = false) {
4069 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4070 RefExpr->containsUnexpandedParameterPack())
4071 return std::make_pair(nullptr, true);
4072
4073 // OpenMP [3.1, C/C++]
4074 // A list item is a variable name.
4075 // OpenMP [2.9.3.3, Restrictions, p.1]
4076 // A variable that is part of another variable (as an array or
4077 // structure element) cannot appear in a private clause.
4078 RefExpr = RefExpr->IgnoreParens();
4079 enum {
4080 NoArrayExpr = -1,
4081 ArraySubscript = 0,
4082 OMPArraySection = 1
4083 } IsArrayExpr = NoArrayExpr;
4084 if (AllowArraySection) {
4085 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4086 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4087 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4088 Base = TempASE->getBase()->IgnoreParenImpCasts();
4089 RefExpr = Base;
4090 IsArrayExpr = ArraySubscript;
4091 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4092 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4093 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4094 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4095 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4096 Base = TempASE->getBase()->IgnoreParenImpCasts();
4097 RefExpr = Base;
4098 IsArrayExpr = OMPArraySection;
4099 }
4100 }
4101 ELoc = RefExpr->getExprLoc();
4102 ERange = RefExpr->getSourceRange();
4103 RefExpr = RefExpr->IgnoreParenImpCasts();
4104 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4105 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4106 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4107 (S.getCurrentThisType().isNull() || !ME ||
4108 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4109 !isa<FieldDecl>(ME->getMemberDecl()))) {
4110 if (IsArrayExpr != NoArrayExpr) {
4111 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4112 << ERange;
4113 } else {
4114 S.Diag(ELoc,
4115 AllowArraySection
4116 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4117 : diag::err_omp_expected_var_name_member_expr)
4118 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4119 }
4120 return std::make_pair(nullptr, false);
4121 }
4122 return std::make_pair(
4123 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4124}
4125
4126static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
4127 ArrayRef<OMPClause *> Clauses) {
4128 assert(!S.CurContext->isDependentContext() &&((!S.CurContext->isDependentContext() && "Expected non-dependent context."
) ? static_cast<void> (0) : __assert_fail ("!S.CurContext->isDependentContext() && \"Expected non-dependent context.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4129, __PRETTY_FUNCTION__))
4129 "Expected non-dependent context.")((!S.CurContext->isDependentContext() && "Expected non-dependent context."
) ? static_cast<void> (0) : __assert_fail ("!S.CurContext->isDependentContext() && \"Expected non-dependent context.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4129, __PRETTY_FUNCTION__))
;
4130 auto AllocateRange =
4131 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
4132 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4133 DeclToCopy;
4134 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4135 return isOpenMPPrivate(C->getClauseKind());
4136 });
4137 for (OMPClause *Cl : PrivateRange) {
4138 MutableArrayRef<Expr *>::iterator I, It, Et;
4139 if (Cl->getClauseKind() == OMPC_private) {
4140 auto *PC = cast<OMPPrivateClause>(Cl);
4141 I = PC->private_copies().begin();
4142 It = PC->varlist_begin();
4143 Et = PC->varlist_end();
4144 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4145 auto *PC = cast<OMPFirstprivateClause>(Cl);
4146 I = PC->private_copies().begin();
4147 It = PC->varlist_begin();
4148 Et = PC->varlist_end();
4149 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4150 auto *PC = cast<OMPLastprivateClause>(Cl);
4151 I = PC->private_copies().begin();
4152 It = PC->varlist_begin();
4153 Et = PC->varlist_end();
4154 } else if (Cl->getClauseKind() == OMPC_linear) {
4155 auto *PC = cast<OMPLinearClause>(Cl);
4156 I = PC->privates().begin();
4157 It = PC->varlist_begin();
4158 Et = PC->varlist_end();
4159 } else if (Cl->getClauseKind() == OMPC_reduction) {
4160 auto *PC = cast<OMPReductionClause>(Cl);
4161 I = PC->privates().begin();
4162 It = PC->varlist_begin();
4163 Et = PC->varlist_end();
4164 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4165 auto *PC = cast<OMPTaskReductionClause>(Cl);
4166 I = PC->privates().begin();
4167 It = PC->varlist_begin();
4168 Et = PC->varlist_end();
4169 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4170 auto *PC = cast<OMPInReductionClause>(Cl);
4171 I = PC->privates().begin();
4172 It = PC->varlist_begin();
4173 Et = PC->varlist_end();
4174 } else {
4175 llvm_unreachable("Expected private clause.")::llvm::llvm_unreachable_internal("Expected private clause.",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4175)
;
4176 }
4177 for (Expr *E : llvm::make_range(It, Et)) {
4178 if (!*I) {
4179 ++I;
4180 continue;
4181 }
4182 SourceLocation ELoc;
4183 SourceRange ERange;
4184 Expr *SimpleRefExpr = E;
4185 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4186 /*AllowArraySection=*/true);
4187 DeclToCopy.try_emplace(Res.first,
4188 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4189 ++I;
4190 }
4191 }
4192 for (OMPClause *C : AllocateRange) {
4193 auto *AC = cast<OMPAllocateClause>(C);
4194 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4195 getAllocatorKind(S, Stack, AC->getAllocator());
4196 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4197 // For task, taskloop or target directives, allocation requests to memory
4198 // allocators with the trait access set to thread result in unspecified
4199 // behavior.
4200 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4201 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4202 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4203 S.Diag(AC->getAllocator()->getExprLoc(),
4204 diag::warn_omp_allocate_thread_on_task_target_directive)
4205 << getOpenMPDirectiveName(Stack->getCurrentDirective());
4206 }
4207 for (Expr *E : AC->varlists()) {
4208 SourceLocation ELoc;
4209 SourceRange ERange;
4210 Expr *SimpleRefExpr = E;
4211 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4212 ValueDecl *VD = Res.first;
4213 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4214 if (!isOpenMPPrivate(Data.CKind)) {
4215 S.Diag(E->getExprLoc(),
4216 diag::err_omp_expected_private_copy_for_allocate);
4217 continue;
4218 }
4219 VarDecl *PrivateVD = DeclToCopy[VD];
4220 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4221 AllocatorKind, AC->getAllocator()))
4222 continue;
4223 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4224 E->getSourceRange());
4225 }
4226 }
4227}
4228
4229StmtResult Sema::ActOnOpenMPExecutableDirective(
4230 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4231 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4232 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
4233 StmtResult Res = StmtError();
4234 // First check CancelRegion which is then used in checkNestingOfRegions.
4235 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4236 checkNestingOfRegions(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, Kind, DirName, CancelRegion,
4237 StartLoc))
4238 return StmtError();
4239
4240 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
4241 VarsWithInheritedDSAType VarsWithInheritedDSA;
4242 bool ErrorFound = false;
4243 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
4244 if (AStmt && !CurContext->isDependentContext()) {
4245 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4245, __PRETTY_FUNCTION__))
;
4246
4247 // Check default data sharing attributes for referenced variables.
4248 DSAAttrChecker DSAChecker(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, *this, cast<CapturedStmt>(AStmt));
4249 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4250 Stmt *S = AStmt;
4251 while (--ThisCaptureLevel >= 0)
4252 S = cast<CapturedStmt>(S)->getCapturedStmt();
4253 DSAChecker.Visit(S);
4254 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4255 !isOpenMPTaskingDirective(Kind)) {
4256 // Visit subcaptures to generate implicit clauses for captured vars.
4257 auto *CS = cast<CapturedStmt>(AStmt);
4258 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4259 getOpenMPCaptureRegions(CaptureRegions, Kind);
4260 // Ignore outer tasking regions for target directives.
4261 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4262 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4263 DSAChecker.visitSubCaptures(CS);
4264 }
4265 if (DSAChecker.isErrorFound())
4266 return StmtError();
4267 // Generate list of implicitly defined firstprivate variables.
4268 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
4269
4270 SmallVector<Expr *, 4> ImplicitFirstprivates(
4271 DSAChecker.getImplicitFirstprivate().begin(),
4272 DSAChecker.getImplicitFirstprivate().end());
4273 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
4274 DSAChecker.getImplicitMap().end());
4275 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
4276 for (OMPClause *C : Clauses) {
4277 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
4278 for (Expr *E : IRC->taskgroup_descriptors())
4279 if (E)
4280 ImplicitFirstprivates.emplace_back(E);
4281 }
4282 }
4283 if (!ImplicitFirstprivates.empty()) {
4284 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
4285 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4286 SourceLocation())) {
4287 ClausesWithImplicit.push_back(Implicit);
4288 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
4289 ImplicitFirstprivates.size();
4290 } else {
4291 ErrorFound = true;
4292 }
4293 }
4294 if (!ImplicitMaps.empty()) {
4295 CXXScopeSpec MapperIdScopeSpec;
4296 DeclarationNameInfo MapperId;
4297 if (OMPClause *Implicit = ActOnOpenMPMapClause(
4298 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
4299 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
4300 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
4301 ClausesWithImplicit.emplace_back(Implicit);
4302 ErrorFound |=
4303 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
4304 } else {
4305 ErrorFound = true;
4306 }
4307 }
4308 }
4309
4310 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
4311 switch (Kind) {
4312 case OMPD_parallel:
4313 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4314 EndLoc);
4315 AllowedNameModifiers.push_back(OMPD_parallel);
4316 break;
4317 case OMPD_simd:
4318 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4319 VarsWithInheritedDSA);
4320 break;
4321 case OMPD_for:
4322 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4323 VarsWithInheritedDSA);
4324 break;
4325 case OMPD_for_simd:
4326 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4327 EndLoc, VarsWithInheritedDSA);
4328 break;
4329 case OMPD_sections:
4330 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4331 EndLoc);
4332 break;
4333 case OMPD_section:
4334 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp section' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp section' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4335, __PRETTY_FUNCTION__))
4335 "No clauses are allowed for 'omp section' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp section' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp section' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4335, __PRETTY_FUNCTION__))
;
4336 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4337 break;
4338 case OMPD_single:
4339 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4340 EndLoc);
4341 break;
4342 case OMPD_master:
4343 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp master' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp master' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4344, __PRETTY_FUNCTION__))
4344 "No clauses are allowed for 'omp master' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp master' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp master' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4344, __PRETTY_FUNCTION__))
;
4345 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4346 break;
4347 case OMPD_critical:
4348 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4349 StartLoc, EndLoc);
4350 break;
4351 case OMPD_parallel_for:
4352 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4353 EndLoc, VarsWithInheritedDSA);
4354 AllowedNameModifiers.push_back(OMPD_parallel);
4355 break;
4356 case OMPD_parallel_for_simd:
4357 Res = ActOnOpenMPParallelForSimdDirective(
4358 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4359 AllowedNameModifiers.push_back(OMPD_parallel);
4360 break;
4361 case OMPD_parallel_sections:
4362 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4363 StartLoc, EndLoc);
4364 AllowedNameModifiers.push_back(OMPD_parallel);
4365 break;
4366 case OMPD_task:
4367 Res =
4368 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4369 AllowedNameModifiers.push_back(OMPD_task);
4370 break;
4371 case OMPD_taskyield:
4372 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4373, __PRETTY_FUNCTION__))
4373 "No clauses are allowed for 'omp taskyield' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4373, __PRETTY_FUNCTION__))
;
4374 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4375, __PRETTY_FUNCTION__))
4375 "No associated statement allowed for 'omp taskyield' directive")((AStmt == nullptr && "No associated statement allowed for 'omp taskyield' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskyield' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4375, __PRETTY_FUNCTION__))
;
4376 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4377 break;
4378 case OMPD_barrier:
4379 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4380, __PRETTY_FUNCTION__))
4380 "No clauses are allowed for 'omp barrier' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4380, __PRETTY_FUNCTION__))
;
4381 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4382, __PRETTY_FUNCTION__))
4382 "No associated statement allowed for 'omp barrier' directive")((AStmt == nullptr && "No associated statement allowed for 'omp barrier' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp barrier' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4382, __PRETTY_FUNCTION__))
;
4383 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4384 break;
4385 case OMPD_taskwait:
4386 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4387, __PRETTY_FUNCTION__))
4387 "No clauses are allowed for 'omp taskwait' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4387, __PRETTY_FUNCTION__))
;
4388 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4389, __PRETTY_FUNCTION__))
4389 "No associated statement allowed for 'omp taskwait' directive")((AStmt == nullptr && "No associated statement allowed for 'omp taskwait' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp taskwait' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4389, __PRETTY_FUNCTION__))
;
4390 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4391 break;
4392 case OMPD_taskgroup:
4393 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4394 EndLoc);
4395 break;
4396 case OMPD_flush:
4397 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp flush' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp flush' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4398, __PRETTY_FUNCTION__))
4398 "No associated statement allowed for 'omp flush' directive")((AStmt == nullptr && "No associated statement allowed for 'omp flush' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp flush' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4398, __PRETTY_FUNCTION__))
;
4399 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4400 break;
4401 case OMPD_ordered:
4402 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4403 EndLoc);
4404 break;
4405 case OMPD_atomic:
4406 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4407 EndLoc);
4408 break;
4409 case OMPD_teams:
4410 Res =
4411 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4412 break;
4413 case OMPD_target:
4414 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4415 EndLoc);
4416 AllowedNameModifiers.push_back(OMPD_target);
4417 break;
4418 case OMPD_target_parallel:
4419 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4420 StartLoc, EndLoc);
4421 AllowedNameModifiers.push_back(OMPD_target);
4422 AllowedNameModifiers.push_back(OMPD_parallel);
4423 break;
4424 case OMPD_target_parallel_for:
4425 Res = ActOnOpenMPTargetParallelForDirective(
4426 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4427 AllowedNameModifiers.push_back(OMPD_target);
4428 AllowedNameModifiers.push_back(OMPD_parallel);
4429 break;
4430 case OMPD_cancellation_point:
4431 assert(ClausesWithImplicit.empty() &&((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp cancellation point' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4432, __PRETTY_FUNCTION__))
4432 "No clauses are allowed for 'omp cancellation point' directive")((ClausesWithImplicit.empty() && "No clauses are allowed for 'omp cancellation point' directive"
) ? static_cast<void> (0) : __assert_fail ("ClausesWithImplicit.empty() && \"No clauses are allowed for 'omp cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4432, __PRETTY_FUNCTION__))
;
4433 assert(AStmt == nullptr && "No associated statement allowed for 'omp "((AStmt == nullptr && "No associated statement allowed for 'omp "
"cancellation point' directive") ? static_cast<void> (
0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp \" \"cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4434, __PRETTY_FUNCTION__))
4434 "cancellation point' directive")((AStmt == nullptr && "No associated statement allowed for 'omp "
"cancellation point' directive") ? static_cast<void> (
0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp \" \"cancellation point' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4434, __PRETTY_FUNCTION__))
;
4435 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4436 break;
4437 case OMPD_cancel:
4438 assert(AStmt == nullptr &&((AStmt == nullptr && "No associated statement allowed for 'omp cancel' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp cancel' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4439, __PRETTY_FUNCTION__))
4439 "No associated statement allowed for 'omp cancel' directive")((AStmt == nullptr && "No associated statement allowed for 'omp cancel' directive"
) ? static_cast<void> (0) : __assert_fail ("AStmt == nullptr && \"No associated statement allowed for 'omp cancel' directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4439, __PRETTY_FUNCTION__))
;
4440 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4441 CancelRegion);
4442 AllowedNameModifiers.push_back(OMPD_cancel);
4443 break;
4444 case OMPD_target_data:
4445 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4446 EndLoc);
4447 AllowedNameModifiers.push_back(OMPD_target_data);
4448 break;
4449 case OMPD_target_enter_data:
4450 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
4451 EndLoc, AStmt);
4452 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4453 break;
4454 case OMPD_target_exit_data:
4455 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
4456 EndLoc, AStmt);
4457 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4458 break;
4459 case OMPD_taskloop:
4460 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4461 EndLoc, VarsWithInheritedDSA);
4462 AllowedNameModifiers.push_back(OMPD_taskloop);
4463 break;
4464 case OMPD_taskloop_simd:
4465 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4466 EndLoc, VarsWithInheritedDSA);
4467 AllowedNameModifiers.push_back(OMPD_taskloop);
4468 break;
4469 case OMPD_master_taskloop:
4470 Res = ActOnOpenMPMasterTaskLoopDirective(
4471 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4472 AllowedNameModifiers.push_back(OMPD_taskloop);
4473 break;
4474 case OMPD_parallel_master_taskloop:
4475 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4476 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4477 AllowedNameModifiers.push_back(OMPD_taskloop);
4478 AllowedNameModifiers.push_back(OMPD_parallel);
4479 break;
4480 case OMPD_distribute:
4481 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4482 EndLoc, VarsWithInheritedDSA);
4483 break;
4484 case OMPD_target_update:
4485 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4486 EndLoc, AStmt);
4487 AllowedNameModifiers.push_back(OMPD_target_update);
4488 break;
4489 case OMPD_distribute_parallel_for:
4490 Res = ActOnOpenMPDistributeParallelForDirective(
4491 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4492 AllowedNameModifiers.push_back(OMPD_parallel);
4493 break;
4494 case OMPD_distribute_parallel_for_simd:
4495 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4496 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4497 AllowedNameModifiers.push_back(OMPD_parallel);
4498 break;
4499 case OMPD_distribute_simd:
4500 Res = ActOnOpenMPDistributeSimdDirective(
4501 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4502 break;
4503 case OMPD_target_parallel_for_simd:
4504 Res = ActOnOpenMPTargetParallelForSimdDirective(
4505 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4506 AllowedNameModifiers.push_back(OMPD_target);
4507 AllowedNameModifiers.push_back(OMPD_parallel);
4508 break;
4509 case OMPD_target_simd:
4510 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4511 EndLoc, VarsWithInheritedDSA);
4512 AllowedNameModifiers.push_back(OMPD_target);
4513 break;
4514 case OMPD_teams_distribute:
4515 Res = ActOnOpenMPTeamsDistributeDirective(
4516 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4517 break;
4518 case OMPD_teams_distribute_simd:
4519 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4520 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4521 break;
4522 case OMPD_teams_distribute_parallel_for_simd:
4523 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4524 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4525 AllowedNameModifiers.push_back(OMPD_parallel);
4526 break;
4527 case OMPD_teams_distribute_parallel_for:
4528 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4529 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4530 AllowedNameModifiers.push_back(OMPD_parallel);
4531 break;
4532 case OMPD_target_teams:
4533 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4534 EndLoc);
4535 AllowedNameModifiers.push_back(OMPD_target);
4536 break;
4537 case OMPD_target_teams_distribute:
4538 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4539 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4540 AllowedNameModifiers.push_back(OMPD_target);
4541 break;
4542 case OMPD_target_teams_distribute_parallel_for:
4543 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4544 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4545 AllowedNameModifiers.push_back(OMPD_target);
4546 AllowedNameModifiers.push_back(OMPD_parallel);
4547 break;
4548 case OMPD_target_teams_distribute_parallel_for_simd:
4549 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4550 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4551 AllowedNameModifiers.push_back(OMPD_target);
4552 AllowedNameModifiers.push_back(OMPD_parallel);
4553 break;
4554 case OMPD_target_teams_distribute_simd:
4555 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4556 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4557 AllowedNameModifiers.push_back(OMPD_target);
4558 break;
4559 case OMPD_declare_target:
4560 case OMPD_end_declare_target:
4561 case OMPD_threadprivate:
4562 case OMPD_allocate:
4563 case OMPD_declare_reduction:
4564 case OMPD_declare_mapper:
4565 case OMPD_declare_simd:
4566 case OMPD_requires:
4567 case OMPD_declare_variant:
4568 llvm_unreachable("OpenMP Directive is not allowed")::llvm::llvm_unreachable_internal("OpenMP Directive is not allowed"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4568)
;
4569 case OMPD_unknown:
4570 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4570)
;
4571 }
4572
4573 ErrorFound = Res.isInvalid() || ErrorFound;
4574
4575 // Check variables in the clauses if default(none) was specified.
4576 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSA() == DSA_none) {
4577 DSAAttrChecker DSAChecker(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, *this, nullptr);
4578 for (OMPClause *C : Clauses) {
4579 switch (C->getClauseKind()) {
4580 case OMPC_num_threads:
4581 case OMPC_dist_schedule:
4582 // Do not analyse if no parent teams directive.
4583 if (isOpenMPTeamsDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
4584 break;
4585 continue;
4586 case OMPC_if:
4587 if (isOpenMPTeamsDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()) &&
4588 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4589 break;
4590 continue;
4591 case OMPC_schedule:
4592 break;
4593 case OMPC_grainsize:
4594 // Do not analyze if no parent parallel directive.
4595 if (isOpenMPParallelDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
4596 break;
4597 continue;
4598 case OMPC_num_tasks:
4599 // Do not analyze if no parent parallel directive.
4600 if (isOpenMPParallelDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective()))
4601 break;
4602 continue;
4603 case OMPC_ordered:
4604 case OMPC_device:
4605 case OMPC_num_teams:
4606 case OMPC_thread_limit:
4607 case OMPC_priority:
4608 case OMPC_hint:
4609 case OMPC_collapse:
4610 case OMPC_safelen:
4611 case OMPC_simdlen:
4612 case OMPC_final:
4613 case OMPC_default:
4614 case OMPC_proc_bind:
4615 case OMPC_private:
4616 case OMPC_firstprivate:
4617 case OMPC_lastprivate:
4618 case OMPC_shared:
4619 case OMPC_reduction:
4620 case OMPC_task_reduction:
4621 case OMPC_in_reduction:
4622 case OMPC_linear:
4623 case OMPC_aligned:
4624 case OMPC_copyin:
4625 case OMPC_copyprivate:
4626 case OMPC_nowait:
4627 case OMPC_untied:
4628 case OMPC_mergeable:
4629 case OMPC_allocate:
4630 case OMPC_read:
4631 case OMPC_write:
4632 case OMPC_update:
4633 case OMPC_capture:
4634 case OMPC_seq_cst:
4635 case OMPC_depend:
4636 case OMPC_threads:
4637 case OMPC_simd:
4638 case OMPC_map:
4639 case OMPC_nogroup:
4640 case OMPC_defaultmap:
4641 case OMPC_to:
4642 case OMPC_from:
4643 case OMPC_use_device_ptr:
4644 case OMPC_is_device_ptr:
4645 continue;
4646 case OMPC_allocator:
4647 case OMPC_flush:
4648 case OMPC_threadprivate:
4649 case OMPC_uniform:
4650 case OMPC_unknown:
4651 case OMPC_unified_address:
4652 case OMPC_unified_shared_memory:
4653 case OMPC_reverse_offload:
4654 case OMPC_dynamic_allocators:
4655 case OMPC_atomic_default_mem_order:
4656 case OMPC_device_type:
4657 case OMPC_match:
4658 llvm_unreachable("Unexpected clause")::llvm::llvm_unreachable_internal("Unexpected clause", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4658)
;
4659 }
4660 for (Stmt *CC : C->children()) {
4661 if (CC)
4662 DSAChecker.Visit(CC);
4663 }
4664 }
4665 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4666 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4667 }
4668 for (const auto &P : VarsWithInheritedDSA) {
4669 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4670 continue;
4671 ErrorFound = true;
4672 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4673 << P.first << P.second->getSourceRange();
4674 Diag(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
4675 }
4676
4677 if (!AllowedNameModifiers.empty())
4678 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4679 ErrorFound;
4680
4681 if (ErrorFound)
4682 return StmtError();
4683
4684 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4685 Res.getAs<OMPExecutableDirective>()
4686 ->getStructuredBlock()
4687 ->setIsOMPStructuredBlock(true);
4688 }
4689
4690 if (!CurContext->isDependentContext() &&
4691 isOpenMPTargetExecutionDirective(Kind) &&
4692 !(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4693 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4694 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4695 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4696 // Register target to DSA Stack.
4697 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addTargetDirLocation(StartLoc);
4698 }
4699
4700 return Res;
4701}
4702
4703Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4704 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
4705 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
4706 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4707 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
4708 assert(Aligneds.size() == Alignments.size())((Aligneds.size() == Alignments.size()) ? static_cast<void
> (0) : __assert_fail ("Aligneds.size() == Alignments.size()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4708, __PRETTY_FUNCTION__))
;
4709 assert(Linears.size() == LinModifiers.size())((Linears.size() == LinModifiers.size()) ? static_cast<void
> (0) : __assert_fail ("Linears.size() == LinModifiers.size()"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4709, __PRETTY_FUNCTION__))
;
4710 assert(Linears.size() == Steps.size())((Linears.size() == Steps.size()) ? static_cast<void> (
0) : __assert_fail ("Linears.size() == Steps.size()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 4710, __PRETTY_FUNCTION__))
;
4711 if (!DG || DG.get().isNull())
4712 return DeclGroupPtrTy();
4713
4714 const int SimdId = 0;
4715 if (!DG.get().isSingleDecl()) {
4716 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4717 << SimdId;
4718 return DG;
4719 }
4720 Decl *ADecl = DG.get().getSingleDecl();
4721 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4722 ADecl = FTD->getTemplatedDecl();
4723
4724 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4725 if (!FD) {
4726 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
4727 return DeclGroupPtrTy();
4728 }
4729
4730 // OpenMP [2.8.2, declare simd construct, Description]
4731 // The parameter of the simdlen clause must be a constant positive integer
4732 // expression.
4733 ExprResult SL;
4734 if (Simdlen)
4735 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
4736 // OpenMP [2.8.2, declare simd construct, Description]
4737 // The special this pointer can be used as if was one of the arguments to the
4738 // function in any of the linear, aligned, or uniform clauses.
4739 // The uniform clause declares one or more arguments to have an invariant
4740 // value for all concurrent invocations of the function in the execution of a
4741 // single SIMD loop.
4742 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4743 const Expr *UniformedLinearThis = nullptr;
4744 for (const Expr *E : Uniforms) {
4745 E = E->IgnoreParenImpCasts();
4746 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4747 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
4748 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4749 FD->getParamDecl(PVD->getFunctionScopeIndex())
4750 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
4751 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
4752 continue;
4753 }
4754 if (isa<CXXThisExpr>(E)) {
4755 UniformedLinearThis = E;
4756 continue;
4757 }
4758 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4759 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4760 }
4761 // OpenMP [2.8.2, declare simd construct, Description]
4762 // The aligned clause declares that the object to which each list item points
4763 // is aligned to the number of bytes expressed in the optional parameter of
4764 // the aligned clause.
4765 // The special this pointer can be used as if was one of the arguments to the
4766 // function in any of the linear, aligned, or uniform clauses.
4767 // The type of list items appearing in the aligned clause must be array,
4768 // pointer, reference to array, or reference to pointer.
4769 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4770 const Expr *AlignedThis = nullptr;
4771 for (const Expr *E : Aligneds) {
4772 E = E->IgnoreParenImpCasts();
4773 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4774 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4775 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4776 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4777 FD->getParamDecl(PVD->getFunctionScopeIndex())
4778 ->getCanonicalDecl() == CanonPVD) {
4779 // OpenMP [2.8.1, simd construct, Restrictions]
4780 // A list-item cannot appear in more than one aligned clause.
4781 if (AlignedArgs.count(CanonPVD) > 0) {
4782 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4783 << 1 << E->getSourceRange();
4784 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4785 diag::note_omp_explicit_dsa)
4786 << getOpenMPClauseName(OMPC_aligned);
4787 continue;
4788 }
4789 AlignedArgs[CanonPVD] = E;
4790 QualType QTy = PVD->getType()
4791 .getNonReferenceType()
4792 .getUnqualifiedType()
4793 .getCanonicalType();
4794 const Type *Ty = QTy.getTypePtrOrNull();
4795 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4796 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4797 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4798 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4799 }
4800 continue;
4801 }
4802 }
4803 if (isa<CXXThisExpr>(E)) {
4804 if (AlignedThis) {
4805 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4806 << 2 << E->getSourceRange();
4807 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4808 << getOpenMPClauseName(OMPC_aligned);
4809 }
4810 AlignedThis = E;
4811 continue;
4812 }
4813 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4814 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4815 }
4816 // The optional parameter of the aligned clause, alignment, must be a constant
4817 // positive integer expression. If no optional parameter is specified,
4818 // implementation-defined default alignments for SIMD instructions on the
4819 // target platforms are assumed.
4820 SmallVector<const Expr *, 4> NewAligns;
4821 for (Expr *E : Alignments) {
4822 ExprResult Align;
4823 if (E)
4824 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4825 NewAligns.push_back(Align.get());
4826 }
4827 // OpenMP [2.8.2, declare simd construct, Description]
4828 // The linear clause declares one or more list items to be private to a SIMD
4829 // lane and to have a linear relationship with respect to the iteration space
4830 // of a loop.
4831 // The special this pointer can be used as if was one of the arguments to the
4832 // function in any of the linear, aligned, or uniform clauses.
4833 // When a linear-step expression is specified in a linear clause it must be
4834 // either a constant integer expression or an integer-typed parameter that is
4835 // specified in a uniform clause on the directive.
4836 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
4837 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4838 auto MI = LinModifiers.begin();
4839 for (const Expr *E : Linears) {
4840 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4841 ++MI;
4842 E = E->IgnoreParenImpCasts();
4843 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4844 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4845 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4846 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4847 FD->getParamDecl(PVD->getFunctionScopeIndex())
4848 ->getCanonicalDecl() == CanonPVD) {
4849 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4850 // A list-item cannot appear in more than one linear clause.
4851 if (LinearArgs.count(CanonPVD) > 0) {
4852 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4853 << getOpenMPClauseName(OMPC_linear)
4854 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4855 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4856 diag::note_omp_explicit_dsa)
4857 << getOpenMPClauseName(OMPC_linear);
4858 continue;
4859 }
4860 // Each argument can appear in at most one uniform or linear clause.
4861 if (UniformedArgs.count(CanonPVD) > 0) {
4862 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4863 << getOpenMPClauseName(OMPC_linear)
4864 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4865 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4866 diag::note_omp_explicit_dsa)
4867 << getOpenMPClauseName(OMPC_uniform);
4868 continue;
4869 }
4870 LinearArgs[CanonPVD] = E;
4871 if (E->isValueDependent() || E->isTypeDependent() ||
4872 E->isInstantiationDependent() ||
4873 E->containsUnexpandedParameterPack())
4874 continue;
4875 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4876 PVD->getOriginalType());
4877 continue;
4878 }
4879 }
4880 if (isa<CXXThisExpr>(E)) {
4881 if (UniformedLinearThis) {
4882 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4883 << getOpenMPClauseName(OMPC_linear)
4884 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4885 << E->getSourceRange();
4886 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4887 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4888 : OMPC_linear);
4889 continue;
4890 }
4891 UniformedLinearThis = E;
4892 if (E->isValueDependent() || E->isTypeDependent() ||
4893 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4894 continue;
4895 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4896 E->getType());
4897 continue;
4898 }
4899 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4900 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4901 }
4902 Expr *Step = nullptr;
4903 Expr *NewStep = nullptr;
4904 SmallVector<Expr *, 4> NewSteps;
4905 for (Expr *E : Steps) {
4906 // Skip the same step expression, it was checked already.
4907 if (Step == E || !E) {
4908 NewSteps.push_back(E ? NewStep : nullptr);
4909 continue;
4910 }
4911 Step = E;
4912 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4913 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4914 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
4915 if (UniformedArgs.count(CanonPVD) == 0) {
4916 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4917 << Step->getSourceRange();
4918 } else if (E->isValueDependent() || E->isTypeDependent() ||
4919 E->isInstantiationDependent() ||
4920 E->containsUnexpandedParameterPack() ||
4921 CanonPVD->getType()->hasIntegerRepresentation()) {
4922 NewSteps.push_back(Step);
4923 } else {
4924 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4925 << Step->getSourceRange();
4926 }
4927 continue;
4928 }
4929 NewStep = Step;
4930 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4931 !Step->isInstantiationDependent() &&
4932 !Step->containsUnexpandedParameterPack()) {
4933 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4934 .get();
4935 if (NewStep)
4936 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4937 }
4938 NewSteps.push_back(NewStep);
4939 }
4940 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4941 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
4942 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
4943 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4944 const_cast<Expr **>(Linears.data()), Linears.size(),
4945 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4946 NewSteps.data(), NewSteps.size(), SR);
4947 ADecl->addAttr(NewAttr);
4948 return DG;
4949}
4950
4951Optional<std::pair<FunctionDecl *, Expr *>>
4952Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
4953 Expr *VariantRef, SourceRange SR) {
4954 if (!DG || DG.get().isNull())
4955 return None;
4956
4957 const int VariantId = 1;
4958 // Must be applied only to single decl.
4959 if (!DG.get().isSingleDecl()) {
4960 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4961 << VariantId << SR;
4962 return None;
4963 }
4964 Decl *ADecl = DG.get().getSingleDecl();
4965 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4966 ADecl = FTD->getTemplatedDecl();
4967
4968 // Decl must be a function.
4969 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4970 if (!FD) {
4971 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
4972 << VariantId << SR;
4973 return None;
4974 }
4975
4976 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
4977 return FD->hasAttrs() &&
4978 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
4979 FD->hasAttr<TargetAttr>());
4980 };
4981 // OpenMP is not compatible with CPU-specific attributes.
4982 if (HasMultiVersionAttributes(FD)) {
4983 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
4984 << SR;
4985 return None;
4986 }
4987
4988 // Allow #pragma omp declare variant only if the function is not used.
4989 if (FD->isUsed(false))
4990 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
4991 << FD->getLocation();
4992
4993 // Check if the function was emitted already.
4994 const FunctionDecl *Definition;
4995 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
4996 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
4997 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
4998 << FD->getLocation();
4999
5000 // The VariantRef must point to function.
5001 if (!VariantRef) {
5002 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
5003 return None;
5004 }
5005
5006 // Do not check templates, wait until instantiation.
5007 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5008 VariantRef->containsUnexpandedParameterPack() ||
5009 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5010 return std::make_pair(FD, VariantRef);
5011
5012 // Convert VariantRef expression to the type of the original function to
5013 // resolve possible conflicts.
5014 ExprResult VariantRefCast;
5015 if (LangOpts.CPlusPlus) {
5016 QualType FnPtrType;
5017 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5018 if (Method && !Method->isStatic()) {
5019 const Type *ClassType =
5020 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5021 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5022 ExprResult ER;
5023 {
5024 // Build adrr_of unary op to correctly handle type checks for member
5025 // functions.
5026 Sema::TentativeAnalysisScope Trap(*this);
5027 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5028 VariantRef);
5029 }
5030 if (!ER.isUsable()) {
5031 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5032 << VariantId << VariantRef->getSourceRange();
5033 return None;
5034 }
5035 VariantRef = ER.get();
5036 } else {
5037 FnPtrType = Context.getPointerType(FD->getType());
5038 }
5039 ImplicitConversionSequence ICS =
5040 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5041 /*SuppressUserConversions=*/false,
5042 /*AllowExplicit=*/false,
5043 /*InOverloadResolution=*/false,
5044 /*CStyle=*/false,
5045 /*AllowObjCWritebackConversion=*/false);
5046 if (ICS.isFailure()) {
5047 Diag(VariantRef->getExprLoc(),
5048 diag::err_omp_declare_variant_incompat_types)
5049 << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
5050 return None;
5051 }
5052 VariantRefCast = PerformImplicitConversion(
5053 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5054 if (!VariantRefCast.isUsable())
5055 return None;
5056 // Drop previously built artificial addr_of unary op for member functions.
5057 if (Method && !Method->isStatic()) {
5058 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5059 if (auto *UO = dyn_cast<UnaryOperator>(
5060 PossibleAddrOfVariantRef->IgnoreImplicit()))
5061 VariantRefCast = UO->getSubExpr();
5062 }
5063 } else {
5064 VariantRefCast = VariantRef;
5065 }
5066
5067 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5068 if (!ER.isUsable() ||
5069 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5070 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5071 << VariantId << VariantRef->getSourceRange();
5072 return None;
5073 }
5074
5075 // The VariantRef must point to function.
5076 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5077 if (!DRE) {
5078 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5079 << VariantId << VariantRef->getSourceRange();
5080 return None;
5081 }
5082 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5083 if (!NewFD) {
5084 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5085 << VariantId << VariantRef->getSourceRange();
5086 return None;
5087 }
5088
5089 // Check if variant function is not marked with declare variant directive.
5090 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5091 Diag(VariantRef->getExprLoc(),
5092 diag::warn_omp_declare_variant_marked_as_declare_variant)
5093 << VariantRef->getSourceRange();
5094 SourceRange SR =
5095 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5096 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
5097 return None;
5098 }
5099
5100 enum DoesntSupport {
5101 VirtFuncs = 1,
5102 Constructors = 3,
5103 Destructors = 4,
5104 DeletedFuncs = 5,
5105 DefaultedFuncs = 6,
5106 ConstexprFuncs = 7,
5107 ConstevalFuncs = 8,
5108 };
5109 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5110 if (CXXFD->isVirtual()) {
5111 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5112 << VirtFuncs;
5113 return None;
5114 }
5115
5116 if (isa<CXXConstructorDecl>(FD)) {
5117 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5118 << Constructors;
5119 return None;
5120 }
5121
5122 if (isa<CXXDestructorDecl>(FD)) {
5123 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5124 << Destructors;
5125 return None;
5126 }
5127 }
5128
5129 if (FD->isDeleted()) {
5130 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5131 << DeletedFuncs;
5132 return None;
5133 }
5134
5135 if (FD->isDefaulted()) {
5136 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5137 << DefaultedFuncs;
5138 return None;
5139 }
5140
5141 if (FD->isConstexpr()) {
5142 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5143 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
5144 return None;
5145 }
5146
5147 // Check general compatibility.
5148 if (areMultiversionVariantFunctionsCompatible(
5149 FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
5150 PartialDiagnosticAt(
5151 SR.getBegin(),
5152 PDiag(diag::note_omp_declare_variant_specified_here) << SR),
5153 PartialDiagnosticAt(
5154 VariantRef->getExprLoc(),
5155 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5156 PartialDiagnosticAt(VariantRef->getExprLoc(),
5157 PDiag(diag::err_omp_declare_variant_diff)
5158 << FD->getLocation()),
5159 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5160 /*CLinkageMayDiffer=*/true))
5161 return None;
5162 return std::make_pair(FD, cast<Expr>(DRE));
5163}
5164
5165void Sema::ActOnOpenMPDeclareVariantDirective(
5166 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
5167 const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
5168 if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
5169 Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
5170 return;
5171 Expr *Score = nullptr;
5172 OMPDeclareVariantAttr::ScoreType ST = OMPDeclareVariantAttr::ScoreUnknown;
5173 if (Data.CtxScore.isUsable()) {
5174 ST = OMPDeclareVariantAttr::ScoreSpecified;
5175 Score = Data.CtxScore.get();
5176 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5177 !Score->isInstantiationDependent() &&
5178 !Score->containsUnexpandedParameterPack()) {
5179 llvm::APSInt Result;
5180 ExprResult ICE = VerifyIntegerConstantExpression(Score, &Result);
5181 if (ICE.isInvalid())
5182 return;
5183 }
5184 }
5185 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5186 Context, VariantRef, Score, Data.CtxSet, ST, Data.Ctx,
5187 Data.ImplVendors.begin(), Data.ImplVendors.size(), SR);
5188 FD->addAttr(NewAttr);
5189}
5190
5191void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5192 FunctionDecl *Func,
5193 bool MightBeOdrUse) {
5194 assert(LangOpts.OpenMP && "Expected OpenMP mode.")((LangOpts.OpenMP && "Expected OpenMP mode.") ? static_cast
<void> (0) : __assert_fail ("LangOpts.OpenMP && \"Expected OpenMP mode.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5194, __PRETTY_FUNCTION__))
;
5195
5196 if (!Func->isDependentContext() && Func->hasAttrs()) {
5197 for (OMPDeclareVariantAttr *A :
5198 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5199 // TODO: add checks for active OpenMP context where possible.
5200 Expr *VariantRef = A->getVariantFuncRef();
5201 auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
5202 auto *F = cast<FunctionDecl>(DRE->getDecl());
5203 if (!F->isDefined() && F->isTemplateInstantiation())
5204 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5205 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5206 }
5207 }
5208}
5209
5210StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5211 Stmt *AStmt,
5212 SourceLocation StartLoc,
5213 SourceLocation EndLoc) {
5214 if (!AStmt)
5215 return StmtError();
5216
5217 auto *CS = cast<CapturedStmt>(AStmt);
5218 // 1.2.2 OpenMP Language Terminology
5219 // Structured block - An executable statement with a single entry at the
5220 // top and a single exit at the bottom.
5221 // The point of exit cannot be a branch out of the structured block.
5222 // longjmp() and throw() must not violate the entry/exit criteria.
5223 CS->getCapturedDecl()->setNothrow();
5224
5225 setFunctionHasBranchProtectedScope();
5226
5227 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5228 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
5229}
5230
5231namespace {
5232/// Iteration space of a single for loop.
5233struct LoopIterationSpace final {
5234 /// True if the condition operator is the strict compare operator (<, > or
5235 /// !=).
5236 bool IsStrictCompare = false;
5237 /// Condition of the loop.
5238 Expr *PreCond = nullptr;
5239 /// This expression calculates the number of iterations in the loop.
5240 /// It is always possible to calculate it before starting the loop.
5241 Expr *NumIterations = nullptr;
5242 /// The loop counter variable.
5243 Expr *CounterVar = nullptr;
5244 /// Private loop counter variable.
5245 Expr *PrivateCounterVar = nullptr;
5246 /// This is initializer for the initial value of #CounterVar.
5247 Expr *CounterInit = nullptr;
5248 /// This is step for the #CounterVar used to generate its update:
5249 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5250 Expr *CounterStep = nullptr;
5251 /// Should step be subtracted?
5252 bool Subtract = false;
5253 /// Source range of the loop init.
5254 SourceRange InitSrcRange;
5255 /// Source range of the loop condition.
5256 SourceRange CondSrcRange;
5257 /// Source range of the loop increment.
5258 SourceRange IncSrcRange;
5259 /// Minimum value that can have the loop control variable. Used to support
5260 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5261 /// since only such variables can be used in non-loop invariant expressions.
5262 Expr *MinValue = nullptr;
5263 /// Maximum value that can have the loop control variable. Used to support
5264 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5265 /// since only such variables can be used in non-loop invariant expressions.
5266 Expr *MaxValue = nullptr;
5267 /// true, if the lower bound depends on the outer loop control var.
5268 bool IsNonRectangularLB = false;
5269 /// true, if the upper bound depends on the outer loop control var.
5270 bool IsNonRectangularUB = false;
5271 /// Index of the loop this loop depends on and forms non-rectangular loop
5272 /// nest.
5273 unsigned LoopDependentIdx = 0;
5274 /// Final condition for the non-rectangular loop nest support. It is used to
5275 /// check that the number of iterations for this particular counter must be
5276 /// finished.
5277 Expr *FinalCondition = nullptr;
5278};
5279
5280/// Helper class for checking canonical form of the OpenMP loops and
5281/// extracting iteration space of each loop in the loop nest, that will be used
5282/// for IR generation.
5283class OpenMPIterationSpaceChecker {
5284 /// Reference to Sema.
5285 Sema &SemaRef;
5286 /// Data-sharing stack.
5287 DSAStackTy &Stack;
5288 /// A location for diagnostics (when there is no some better location).
5289 SourceLocation DefaultLoc;
5290 /// A location for diagnostics (when increment is not compatible).
5291 SourceLocation ConditionLoc;
5292 /// A source location for referring to loop init later.
5293 SourceRange InitSrcRange;
5294 /// A source location for referring to condition later.
5295 SourceRange ConditionSrcRange;
5296 /// A source location for referring to increment later.
5297 SourceRange IncrementSrcRange;
5298 /// Loop variable.
5299 ValueDecl *LCDecl = nullptr;
5300 /// Reference to loop variable.
5301 Expr *LCRef = nullptr;
5302 /// Lower bound (initializer for the var).
5303 Expr *LB = nullptr;
5304 /// Upper bound.
5305 Expr *UB = nullptr;
5306 /// Loop step (increment).
5307 Expr *Step = nullptr;
5308 /// This flag is true when condition is one of:
5309 /// Var < UB
5310 /// Var <= UB
5311 /// UB > Var
5312 /// UB >= Var
5313 /// This will have no value when the condition is !=
5314 llvm::Optional<bool> TestIsLessOp;
5315 /// This flag is true when condition is strict ( < or > ).
5316 bool TestIsStrictOp = false;
5317 /// This flag is true when step is subtracted on each iteration.
5318 bool SubtractStep = false;
5319 /// The outer loop counter this loop depends on (if any).
5320 const ValueDecl *DepDecl = nullptr;
5321 /// Contains number of loop (starts from 1) on which loop counter init
5322 /// expression of this loop depends on.
5323 Optional<unsigned> InitDependOnLC;
5324 /// Contains number of loop (starts from 1) on which loop counter condition
5325 /// expression of this loop depends on.
5326 Optional<unsigned> CondDependOnLC;
5327 /// Checks if the provide statement depends on the loop counter.
5328 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
5329 /// Original condition required for checking of the exit condition for
5330 /// non-rectangular loop.
5331 Expr *Condition = nullptr;
5332
5333public:
5334 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5335 SourceLocation DefaultLoc)
5336 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5337 ConditionLoc(DefaultLoc) {}
5338 /// Check init-expr for canonical loop form and save loop counter
5339 /// variable - #Var and its initialization value - #LB.
5340 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
5341 /// Check test-expr for canonical form, save upper-bound (#UB), flags
5342 /// for less/greater and for strict/non-strict comparison.
5343 bool checkAndSetCond(Expr *S);
5344 /// Check incr-expr for canonical loop form and return true if it
5345 /// does not conform, otherwise save loop step (#Step).
5346 bool checkAndSetInc(Expr *S);
5347 /// Return the loop counter variable.
5348 ValueDecl *getLoopDecl() const { return LCDecl; }
5349 /// Return the reference expression to loop counter variable.
5350 Expr *getLoopDeclRefExpr() const { return LCRef; }
5351 /// Source range of the loop init.
5352 SourceRange getInitSrcRange() const { return InitSrcRange; }
5353 /// Source range of the loop condition.
5354 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
5355 /// Source range of the loop increment.
5356 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
5357 /// True if the step should be subtracted.
5358 bool shouldSubtractStep() const { return SubtractStep; }
5359 /// True, if the compare operator is strict (<, > or !=).
5360 bool isStrictTestOp() const { return TestIsStrictOp; }
5361 /// Build the expression to calculate the number of iterations.
5362 Expr *buildNumIterations(
5363 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
5364 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5365 /// Build the precondition expression for the loops.
5366 Expr *
5367 buildPreCond(Scope *S, Expr *Cond,
5368 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5369 /// Build reference expression to the counter be used for codegen.
5370 DeclRefExpr *
5371 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5372 DSAStackTy &DSA) const;
5373 /// Build reference expression to the private counter be used for
5374 /// codegen.
5375 Expr *buildPrivateCounterVar() const;
5376 /// Build initialization of the counter be used for codegen.
5377 Expr *buildCounterInit() const;
5378 /// Build step of the counter be used for codegen.
5379 Expr *buildCounterStep() const;
5380 /// Build loop data with counter value for depend clauses in ordered
5381 /// directives.
5382 Expr *
5383 buildOrderedLoopData(Scope *S, Expr *Counter,
5384 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5385 SourceLocation Loc, Expr *Inc = nullptr,
5386 OverloadedOperatorKind OOK = OO_Amp);
5387 /// Builds the minimum value for the loop counter.
5388 std::pair<Expr *, Expr *> buildMinMaxValues(
5389 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5390 /// Builds final condition for the non-rectangular loops.
5391 Expr *buildFinalCondition(Scope *S) const;
5392 /// Return true if any expression is dependent.
5393 bool dependent() const;
5394 /// Returns true if the initializer forms non-rectangular loop.
5395 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5396 /// Returns true if the condition forms non-rectangular loop.
5397 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5398 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5399 unsigned getLoopDependentIdx() const {
5400 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5401 }
5402
5403private:
5404 /// Check the right-hand side of an assignment in the increment
5405 /// expression.
5406 bool checkAndSetIncRHS(Expr *RHS);
5407 /// Helper to set loop counter variable and its initializer.
5408 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5409 bool EmitDiags);
5410 /// Helper to set upper bound.
5411 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5412 SourceRange SR, SourceLocation SL);
5413 /// Helper to set loop increment.
5414 bool setStep(Expr *NewStep, bool Subtract);
5415};
5416
5417bool OpenMPIterationSpaceChecker::dependent() const {
5418 if (!LCDecl) {
5419 assert(!LB && !UB && !Step)((!LB && !UB && !Step) ? static_cast<void>
(0) : __assert_fail ("!LB && !UB && !Step", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5419, __PRETTY_FUNCTION__))
;
5420 return false;
5421 }
5422 return LCDecl->getType()->isDependentType() ||
5423 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5424 (Step && Step->isValueDependent());
5425}
5426
5427bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
5428 Expr *NewLCRefExpr,
5429 Expr *NewLB, bool EmitDiags) {
5430 // State consistency checking to ensure correct usage.
5431 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&((LCDecl == nullptr && LB == nullptr && LCRef
== nullptr && UB == nullptr && Step == nullptr
&& !TestIsLessOp && !TestIsStrictOp) ? static_cast
<void> (0) : __assert_fail ("LCDecl == nullptr && LB == nullptr && LCRef == nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5432, __PRETTY_FUNCTION__))
5432 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp)((LCDecl == nullptr && LB == nullptr && LCRef
== nullptr && UB == nullptr && Step == nullptr
&& !TestIsLessOp && !TestIsStrictOp) ? static_cast
<void> (0) : __assert_fail ("LCDecl == nullptr && LB == nullptr && LCRef == nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5432, __PRETTY_FUNCTION__))
;
5433 if (!NewLCDecl || !NewLB)
5434 return true;
5435 LCDecl = getCanonicalDecl(NewLCDecl);
5436 LCRef = NewLCRefExpr;
5437 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5438 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
5439 if ((Ctor->isCopyOrMoveConstructor() ||
5440 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5441 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
5442 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
5443 LB = NewLB;
5444 if (EmitDiags)
5445 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
5446 return false;
5447}
5448
5449bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5450 llvm::Optional<bool> LessOp,
5451 bool StrictOp, SourceRange SR,
5452 SourceLocation SL) {
5453 // State consistency checking to ensure correct usage.
5454 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&((LCDecl != nullptr && LB != nullptr && UB ==
nullptr && Step == nullptr && !TestIsLessOp &&
!TestIsStrictOp) ? static_cast<void> (0) : __assert_fail
("LCDecl != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5455, __PRETTY_FUNCTION__))
5455 Step == nullptr && !TestIsLessOp && !TestIsStrictOp)((LCDecl != nullptr && LB != nullptr && UB ==
nullptr && Step == nullptr && !TestIsLessOp &&
!TestIsStrictOp) ? static_cast<void> (0) : __assert_fail
("LCDecl != nullptr && LB != nullptr && UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5455, __PRETTY_FUNCTION__))
;
5456 if (!NewUB)
5457 return true;
5458 UB = NewUB;
5459 if (LessOp)
5460 TestIsLessOp = LessOp;
5461 TestIsStrictOp = StrictOp;
5462 ConditionSrcRange = SR;
5463 ConditionLoc = SL;
5464 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
5465 return false;
5466}
5467
5468bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
5469 // State consistency checking to ensure correct usage.
5470 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr)((LCDecl != nullptr && LB != nullptr && Step ==
nullptr) ? static_cast<void> (0) : __assert_fail ("LCDecl != nullptr && LB != nullptr && Step == nullptr"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5470, __PRETTY_FUNCTION__))
;
5471 if (!NewStep)
5472 return true;
5473 if (!NewStep->isValueDependent()) {
5474 // Check that the step is integer expression.
5475 SourceLocation StepLoc = NewStep->getBeginLoc();
5476 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5477 StepLoc, getExprAsWritten(NewStep));
5478 if (Val.isInvalid())
5479 return true;
5480 NewStep = Val.get();
5481
5482 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5483 // If test-expr is of form var relational-op b and relational-op is < or
5484 // <= then incr-expr must cause var to increase on each iteration of the
5485 // loop. If test-expr is of form var relational-op b and relational-op is
5486 // > or >= then incr-expr must cause var to decrease on each iteration of
5487 // the loop.
5488 // If test-expr is of form b relational-op var and relational-op is < or
5489 // <= then incr-expr must cause var to decrease on each iteration of the
5490 // loop. If test-expr is of form b relational-op var and relational-op is
5491 // > or >= then incr-expr must cause var to increase on each iteration of
5492 // the loop.
5493 llvm::APSInt Result;
5494 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5495 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5496 bool IsConstNeg =
5497 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
5498 bool IsConstPos =
5499 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
5500 bool IsConstZero = IsConstant && !Result.getBoolValue();
5501
5502 // != with increment is treated as <; != with decrement is treated as >
5503 if (!TestIsLessOp.hasValue())
5504 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
5505 if (UB && (IsConstZero ||
5506 (TestIsLessOp.getValue() ?
5507 (IsConstNeg || (IsUnsigned && Subtract)) :
5508 (IsConstPos || (IsUnsigned && !Subtract))))) {
5509 SemaRef.Diag(NewStep->getExprLoc(),
5510 diag::err_omp_loop_incr_not_compatible)
5511 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
5512 SemaRef.Diag(ConditionLoc,
5513 diag::note_omp_loop_cond_requres_compatible_incr)
5514 << TestIsLessOp.getValue() << ConditionSrcRange;
5515 return true;
5516 }
5517 if (TestIsLessOp.getValue() == Subtract) {
5518 NewStep =
5519 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5520 .get();
5521 Subtract = !Subtract;
5522 }
5523 }
5524
5525 Step = NewStep;
5526 SubtractStep = Subtract;
5527 return false;
5528}
5529
5530namespace {
5531/// Checker for the non-rectangular loops. Checks if the initializer or
5532/// condition expression references loop counter variable.
5533class LoopCounterRefChecker final
5534 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5535 Sema &SemaRef;
5536 DSAStackTy &Stack;
5537 const ValueDecl *CurLCDecl = nullptr;
5538 const ValueDecl *DepDecl = nullptr;
5539 const ValueDecl *PrevDepDecl = nullptr;
5540 bool IsInitializer = true;
5541 unsigned BaseLoopId = 0;
5542 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5543 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5544 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5545 << (IsInitializer ? 0 : 1);
5546 return false;
5547 }
5548 const auto &&Data = Stack.isLoopControlVariable(VD);
5549 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5550 // The type of the loop iterator on which we depend may not have a random
5551 // access iterator type.
5552 if (Data.first && VD->getType()->isRecordType()) {
5553 SmallString<128> Name;
5554 llvm::raw_svector_ostream OS(Name);
5555 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5556 /*Qualified=*/true);
5557 SemaRef.Diag(E->getExprLoc(),
5558 diag::err_omp_wrong_dependency_iterator_type)
5559 << OS.str();
5560 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5561 return false;
5562 }
5563 if (Data.first &&
5564 (DepDecl || (PrevDepDecl &&
5565 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5566 if (!DepDecl && PrevDepDecl)
5567 DepDecl = PrevDepDecl;
5568 SmallString<128> Name;
5569 llvm::raw_svector_ostream OS(Name);
5570 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5571 /*Qualified=*/true);
5572 SemaRef.Diag(E->getExprLoc(),
5573 diag::err_omp_invariant_or_linear_dependency)
5574 << OS.str();
5575 return false;
5576 }
5577 if (Data.first) {
5578 DepDecl = VD;
5579 BaseLoopId = Data.first;
5580 }
5581 return Data.first;
5582 }
5583
5584public:
5585 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5586 const ValueDecl *VD = E->getDecl();
5587 if (isa<VarDecl>(VD))
5588 return checkDecl(E, VD);
5589 return false;
5590 }
5591 bool VisitMemberExpr(const MemberExpr *E) {
5592 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5593 const ValueDecl *VD = E->getMemberDecl();
5594 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5595 return checkDecl(E, VD);
5596 }
5597 return false;
5598 }
5599 bool VisitStmt(const Stmt *S) {
5600 bool Res = false;
5601 for (const Stmt *Child : S->children())
5602 Res = (Child && Visit(Child)) || Res;
5603 return Res;
5604 }
5605 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
5606 const ValueDecl *CurLCDecl, bool IsInitializer,
5607 const ValueDecl *PrevDepDecl = nullptr)
5608 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
5609 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5610 unsigned getBaseLoopId() const {
5611 assert(CurLCDecl && "Expected loop dependency.")((CurLCDecl && "Expected loop dependency.") ? static_cast
<void> (0) : __assert_fail ("CurLCDecl && \"Expected loop dependency.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5611, __PRETTY_FUNCTION__))
;
5612 return BaseLoopId;
5613 }
5614 const ValueDecl *getDepDecl() const {
5615 assert(CurLCDecl && "Expected loop dependency.")((CurLCDecl && "Expected loop dependency.") ? static_cast
<void> (0) : __assert_fail ("CurLCDecl && \"Expected loop dependency.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 5615, __PRETTY_FUNCTION__))
;
5616 return DepDecl;
5617 }
5618};
5619} // namespace
5620
5621Optional<unsigned>
5622OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5623 bool IsInitializer) {
5624 // Check for the non-rectangular loops.
5625 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5626 DepDecl);
5627 if (LoopStmtChecker.Visit(S)) {
5628 DepDecl = LoopStmtChecker.getDepDecl();
5629 return LoopStmtChecker.getBaseLoopId();
5630 }
5631 return llvm::None;
5632}
5633
5634bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
5635 // Check init-expr for canonical loop form and save loop counter
5636 // variable - #Var and its initialization value - #LB.
5637 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5638 // var = lb
5639 // integer-type var = lb
5640 // random-access-iterator-type var = lb
5641 // pointer-type var = lb
5642 //
5643 if (!S) {
5644 if (EmitDiags) {
5645 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5646 }
5647 return true;
5648 }
5649 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5650 if (!ExprTemp->cleanupsHaveSideEffects())
5651 S = ExprTemp->getSubExpr();
5652
5653 InitSrcRange = S->getSourceRange();
5654 if (Expr *E = dyn_cast<Expr>(S))
5655 S = E->IgnoreParens();
5656 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
5657 if (BO->getOpcode() == BO_Assign) {
5658 Expr *LHS = BO->getLHS()->IgnoreParens();
5659 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5660 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5661 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
5662 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5663 EmitDiags);
5664 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
5665 }
5666 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5667 if (ME->isArrow() &&
5668 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5669 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5670 EmitDiags);
5671 }
5672 }
5673 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
5674 if (DS->isSingleDecl()) {
5675 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
5676 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
5677 // Accept non-canonical init form here but emit ext. warning.
5678 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
5679 SemaRef.Diag(S->getBeginLoc(),
5680 diag::ext_omp_loop_not_canonical_init)
5681 << S->getSourceRange();
5682 return setLCDeclAndLB(
5683 Var,
5684 buildDeclRefExpr(SemaRef, Var,
5685 Var->getType().getNonReferenceType(),
5686 DS->getBeginLoc()),
5687 Var->getInit(), EmitDiags);
5688 }
5689 }
5690 }
5691 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
5692 if (CE->getOperator() == OO_Equal) {
5693 Expr *LHS = CE->getArg(0);
5694 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5695 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5696 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
5697 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5698 EmitDiags);
5699 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
5700 }
5701 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5702 if (ME->isArrow() &&
5703 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5704 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5705 EmitDiags);
5706 }
5707 }
5708 }
5709
5710 if (dependent() || SemaRef.CurContext->isDependentContext())
5711 return false;
5712 if (EmitDiags) {
5713 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
5714 << S->getSourceRange();
5715 }
5716 return true;
5717}
5718
5719/// Ignore parenthesizes, implicit casts, copy constructor and return the
5720/// variable (which may be the loop variable) if possible.
5721static const ValueDecl *getInitLCDecl(const Expr *E) {
5722 if (!E)
5723 return nullptr;
5724 E = getExprAsWritten(E);
5725 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
5726 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
5727 if ((Ctor->isCopyOrMoveConstructor() ||
5728 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5729 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
5730 E = CE->getArg(0)->IgnoreParenImpCasts();
5731 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5732 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
5733 return getCanonicalDecl(VD);
5734 }
5735 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
5736 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5737 return getCanonicalDecl(ME->getMemberDecl());
5738 return nullptr;
5739}
5740
5741bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
5742 // Check test-expr for canonical form, save upper-bound UB, flags for
5743 // less/greater and for strict/non-strict comparison.
5744 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
5745 // var relational-op b
5746 // b relational-op var
5747 //
5748 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
5749 if (!S) {
5750 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
5751 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
5752 return true;
5753 }
5754 Condition = S;
5755 S = getExprAsWritten(S);
5756 SourceLocation CondLoc = S->getBeginLoc();
5757 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
5758 if (BO->isRelationalOp()) {
5759 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5760 return setUB(BO->getRHS(),
5761 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
5762 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5763 BO->getSourceRange(), BO->getOperatorLoc());
5764 if (getInitLCDecl(BO->getRHS()) == LCDecl)
5765 return setUB(BO->getLHS(),
5766 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
5767 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5768 BO->getSourceRange(), BO->getOperatorLoc());
5769 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
5770 return setUB(
5771 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
5772 /*LessOp=*/llvm::None,
5773 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
5774 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
5775 if (CE->getNumArgs() == 2) {
5776 auto Op = CE->getOperator();
5777 switch (Op) {
5778 case OO_Greater:
5779 case OO_GreaterEqual:
5780 case OO_Less:
5781 case OO_LessEqual:
5782 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5783 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
5784 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5785 CE->getOperatorLoc());
5786 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
5787 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
5788 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5789 CE->getOperatorLoc());
5790 break;
5791 case OO_ExclaimEqual:
5792 if (IneqCondIsCanonical)
5793 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
5794 : CE->getArg(0),
5795 /*LessOp=*/llvm::None,
5796 /*StrictOp=*/true, CE->getSourceRange(),
5797 CE->getOperatorLoc());
5798 break;
5799 default:
5800 break;
5801 }
5802 }
5803 }
5804 if (dependent() || SemaRef.CurContext->isDependentContext())
5805 return false;
5806 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
5807 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
5808 return true;
5809}
5810
5811bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
5812 // RHS of canonical loop form increment can be:
5813 // var + incr
5814 // incr + var
5815 // var - incr
5816 //
5817 RHS = RHS->IgnoreParenImpCasts();
5818 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
5819 if (BO->isAdditiveOp()) {
5820 bool IsAdd = BO->getOpcode() == BO_Add;
5821 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5822 return setStep(BO->getRHS(), !IsAdd);
5823 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5824 return setStep(BO->getLHS(), /*Subtract=*/false);
5825 }
5826 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
5827 bool IsAdd = CE->getOperator() == OO_Plus;
5828 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
5829 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5830 return setStep(CE->getArg(1), !IsAdd);
5831 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5832 return setStep(CE->getArg(0), /*Subtract=*/false);
5833 }
5834 }
5835 if (dependent() || SemaRef.CurContext->isDependentContext())
5836 return false;
5837 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
5838 << RHS->getSourceRange() << LCDecl;
5839 return true;
5840}
5841
5842bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
5843 // Check incr-expr for canonical loop form and return true if it
5844 // does not conform.
5845 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5846 // ++var
5847 // var++
5848 // --var
5849 // var--
5850 // var += incr
5851 // var -= incr
5852 // var = var + incr
5853 // var = incr + var
5854 // var = var - incr
5855 //
5856 if (!S) {
5857 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
5858 return true;
5859 }
5860 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5861 if (!ExprTemp->cleanupsHaveSideEffects())
5862 S = ExprTemp->getSubExpr();
5863
5864 IncrementSrcRange = S->getSourceRange();
5865 S = S->IgnoreParens();
5866 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
5867 if (UO->isIncrementDecrementOp() &&
5868 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5869 return setStep(SemaRef
5870 .ActOnIntegerConstant(UO->getBeginLoc(),
5871 (UO->isDecrementOp() ? -1 : 1))
5872 .get(),
5873 /*Subtract=*/false);
5874 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
5875 switch (BO->getOpcode()) {
5876 case BO_AddAssign:
5877 case BO_SubAssign:
5878 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5879 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
5880 break;
5881 case BO_Assign:
5882 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5883 return checkAndSetIncRHS(BO->getRHS());
5884 break;
5885 default:
5886 break;
5887 }
5888 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
5889 switch (CE->getOperator()) {
5890 case OO_PlusPlus:
5891 case OO_MinusMinus:
5892 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5893 return setStep(SemaRef
5894 .ActOnIntegerConstant(
5895 CE->getBeginLoc(),
5896 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5897 .get(),
5898 /*Subtract=*/false);
5899 break;
5900 case OO_PlusEqual:
5901 case OO_MinusEqual:
5902 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5903 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
5904 break;
5905 case OO_Equal:
5906 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5907 return checkAndSetIncRHS(CE->getArg(1));
5908 break;
5909 default:
5910 break;
5911 }
5912 }
5913 if (dependent() || SemaRef.CurContext->isDependentContext())
5914 return false;
5915 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
5916 << S->getSourceRange() << LCDecl;
5917 return true;
5918}
5919
5920static ExprResult
5921tryBuildCapture(Sema &SemaRef, Expr *Capture,
5922 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5923 if (SemaRef.CurContext->isDependentContext())
5924 return ExprResult(Capture);
5925 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5926 return SemaRef.PerformImplicitConversion(
5927 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5928 /*AllowExplicit=*/true);
5929 auto I = Captures.find(Capture);
5930 if (I != Captures.end())
5931 return buildCapture(SemaRef, Capture, I->second);
5932 DeclRefExpr *Ref = nullptr;
5933 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
5934 Captures[Capture] = Ref;
5935 return Res;
5936}
5937
5938/// Build the expression to calculate the number of iterations.
5939Expr *OpenMPIterationSpaceChecker::buildNumIterations(
5940 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
5941 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
5942 ExprResult Diff;
5943 QualType VarType = LCDecl->getType().getNonReferenceType();
5944 if (VarType->isIntegerType() || VarType->isPointerType() ||
5945 SemaRef.getLangOpts().CPlusPlus) {
5946 Expr *LBVal = LB;
5947 Expr *UBVal = UB;
5948 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
5949 // max(LB(MinVal), LB(MaxVal))
5950 if (InitDependOnLC) {
5951 const LoopIterationSpace &IS =
5952 ResultIterSpaces[ResultIterSpaces.size() - 1 -
5953 InitDependOnLC.getValueOr(
5954 CondDependOnLC.getValueOr(0))];
5955 if (!IS.MinValue || !IS.MaxValue)
5956 return nullptr;
5957 // OuterVar = Min
5958 ExprResult MinValue =
5959 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
5960 if (!MinValue.isUsable())
5961 return nullptr;
5962
5963 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5964 IS.CounterVar, MinValue.get());
5965 if (!LBMinVal.isUsable())
5966 return nullptr;
5967 // OuterVar = Min, LBVal
5968 LBMinVal =
5969 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
5970 if (!LBMinVal.isUsable())
5971 return nullptr;
5972 // (OuterVar = Min, LBVal)
5973 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
5974 if (!LBMinVal.isUsable())
5975 return nullptr;
5976
5977 // OuterVar = Max
5978 ExprResult MaxValue =
5979 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
5980 if (!MaxValue.isUsable())
5981 return nullptr;
5982
5983 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5984 IS.CounterVar, MaxValue.get());
5985 if (!LBMaxVal.isUsable())
5986 return nullptr;
5987 // OuterVar = Max, LBVal
5988 LBMaxVal =
5989 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
5990 if (!LBMaxVal.isUsable())
5991 return nullptr;
5992 // (OuterVar = Max, LBVal)
5993 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
5994 if (!LBMaxVal.isUsable())
5995 return nullptr;
5996
5997 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
5998 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
5999 if (!LBMin || !LBMax)
6000 return nullptr;
6001 // LB(MinVal) < LB(MaxVal)
6002 ExprResult MinLessMaxRes =
6003 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6004 if (!MinLessMaxRes.isUsable())
6005 return nullptr;
6006 Expr *MinLessMax =
6007 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6008 if (!MinLessMax)
6009 return nullptr;
6010 if (TestIsLessOp.getValue()) {
6011 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6012 // LB(MaxVal))
6013 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6014 MinLessMax, LBMin, LBMax);
6015 if (!MinLB.isUsable())
6016 return nullptr;
6017 LBVal = MinLB.get();
6018 } else {
6019 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6020 // LB(MaxVal))
6021 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6022 MinLessMax, LBMax, LBMin);
6023 if (!MaxLB.isUsable())
6024 return nullptr;
6025 LBVal = MaxLB.get();
6026 }
6027 }
6028 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6029 // min(UB(MinVal), UB(MaxVal))
6030 if (CondDependOnLC) {
6031 const LoopIterationSpace &IS =
6032 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6033 InitDependOnLC.getValueOr(
6034 CondDependOnLC.getValueOr(0))];
6035 if (!IS.MinValue || !IS.MaxValue)
6036 return nullptr;
6037 // OuterVar = Min
6038 ExprResult MinValue =
6039 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6040 if (!MinValue.isUsable())
6041 return nullptr;
6042
6043 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6044 IS.CounterVar, MinValue.get());
6045 if (!UBMinVal.isUsable())
6046 return nullptr;
6047 // OuterVar = Min, UBVal
6048 UBMinVal =
6049 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6050 if (!UBMinVal.isUsable())
6051 return nullptr;
6052 // (OuterVar = Min, UBVal)
6053 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6054 if (!UBMinVal.isUsable())
6055 return nullptr;
6056
6057 // OuterVar = Max
6058 ExprResult MaxValue =
6059 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6060 if (!MaxValue.isUsable())
6061 return nullptr;
6062
6063 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6064 IS.CounterVar, MaxValue.get());
6065 if (!UBMaxVal.isUsable())
6066 return nullptr;
6067 // OuterVar = Max, UBVal
6068 UBMaxVal =
6069 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6070 if (!UBMaxVal.isUsable())
6071 return nullptr;
6072 // (OuterVar = Max, UBVal)
6073 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6074 if (!UBMaxVal.isUsable())
6075 return nullptr;
6076
6077 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6078 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6079 if (!UBMin || !UBMax)
6080 return nullptr;
6081 // UB(MinVal) > UB(MaxVal)
6082 ExprResult MinGreaterMaxRes =
6083 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6084 if (!MinGreaterMaxRes.isUsable())
6085 return nullptr;
6086 Expr *MinGreaterMax =
6087 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6088 if (!MinGreaterMax)
6089 return nullptr;
6090 if (TestIsLessOp.getValue()) {
6091 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6092 // UB(MaxVal))
6093 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6094 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6095 if (!MaxUB.isUsable())
6096 return nullptr;
6097 UBVal = MaxUB.get();
6098 } else {
6099 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6100 // UB(MaxVal))
6101 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6102 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6103 if (!MinUB.isUsable())
6104 return nullptr;
6105 UBVal = MinUB.get();
6106 }
6107 }
6108 // Upper - Lower
6109 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6110 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
6111 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6112 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
6113 if (!Upper || !Lower)
6114 return nullptr;
6115
6116 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6117
6118 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6119 // BuildBinOp already emitted error, this one is to point user to upper
6120 // and lower bound, and to tell what is passed to 'operator-'.
6121 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6122 << Upper->getSourceRange() << Lower->getSourceRange();
6123 return nullptr;
6124 }
6125 }
6126
6127 if (!Diff.isUsable())
6128 return nullptr;
6129
6130 // Upper - Lower [- 1]
6131 if (TestIsStrictOp)
6132 Diff = SemaRef.BuildBinOp(
6133 S, DefaultLoc, BO_Sub, Diff.get(),
6134 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6135 if (!Diff.isUsable())
6136 return nullptr;
6137
6138 // Upper - Lower [- 1] + Step
6139 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6140 if (!NewStep.isUsable())
6141 return nullptr;
6142 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
6143 if (!Diff.isUsable())
6144 return nullptr;
6145
6146 // Parentheses (for dumping/debugging purposes only).
6147 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6148 if (!Diff.isUsable())
6149 return nullptr;
6150
6151 // (Upper - Lower [- 1] + Step) / Step
6152 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6153 if (!Diff.isUsable())
6154 return nullptr;
6155
6156 // OpenMP runtime requires 32-bit or 64-bit loop variables.
6157 QualType Type = Diff.get()->getType();
6158 ASTContext &C = SemaRef.Context;
6159 bool UseVarType = VarType->hasIntegerRepresentation() &&
6160 C.getTypeSize(Type) > C.getTypeSize(VarType);
6161 if (!Type->isIntegerType() || UseVarType) {
6162 unsigned NewSize =
6163 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6164 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6165 : Type->hasSignedIntegerRepresentation();
6166 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
6167 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6168 Diff = SemaRef.PerformImplicitConversion(
6169 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6170 if (!Diff.isUsable())
6171 return nullptr;
6172 }
6173 }
6174 if (LimitedType) {
6175 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6176 if (NewSize != C.getTypeSize(Type)) {
6177 if (NewSize < C.getTypeSize(Type)) {
6178 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-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6178, __PRETTY_FUNCTION__))
;
6179 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6180 << InitSrcRange << ConditionSrcRange;
6181 }
6182 QualType NewType = C.getIntTypeForBitwidth(
6183 NewSize, Type->hasSignedIntegerRepresentation() ||
6184 C.getTypeSize(Type) < NewSize);
6185 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6186 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6187 Sema::AA_Converting, true);
6188 if (!Diff.isUsable())
6189 return nullptr;
6190 }
6191 }
6192 }
6193
6194 return Diff.get();
6195}
6196
6197std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6198 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6199 // Do not build for iterators, they cannot be used in non-rectangular loop
6200 // nests.
6201 if (LCDecl->getType()->isRecordType())
6202 return std::make_pair(nullptr, nullptr);
6203 // If we subtract, the min is in the condition, otherwise the min is in the
6204 // init value.
6205 Expr *MinExpr = nullptr;
6206 Expr *MaxExpr = nullptr;
6207 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6208 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6209 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6210 : CondDependOnLC.hasValue();
6211 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6212 : InitDependOnLC.hasValue();
6213 Expr *Lower =
6214 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6215 Expr *Upper =
6216 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6217 if (!Upper || !Lower)
6218 return std::make_pair(nullptr, nullptr);
6219
6220 if (TestIsLessOp.getValue())
6221 MinExpr = Lower;
6222 else
6223 MaxExpr = Upper;
6224
6225 // Build minimum/maximum value based on number of iterations.
6226 ExprResult Diff;
6227 QualType VarType = LCDecl->getType().getNonReferenceType();
6228
6229 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6230 if (!Diff.isUsable())
6231 return std::make_pair(nullptr, nullptr);
6232
6233 // Upper - Lower [- 1]
6234 if (TestIsStrictOp)
6235 Diff = SemaRef.BuildBinOp(
6236 S, DefaultLoc, BO_Sub, Diff.get(),
6237 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6238 if (!Diff.isUsable())
6239 return std::make_pair(nullptr, nullptr);
6240
6241 // Upper - Lower [- 1] + Step
6242 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6243 if (!NewStep.isUsable())
6244 return std::make_pair(nullptr, nullptr);
6245
6246 // Parentheses (for dumping/debugging purposes only).
6247 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6248 if (!Diff.isUsable())
6249 return std::make_pair(nullptr, nullptr);
6250
6251 // (Upper - Lower [- 1]) / Step
6252 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6253 if (!Diff.isUsable())
6254 return std::make_pair(nullptr, nullptr);
6255
6256 // ((Upper - Lower [- 1]) / Step) * Step
6257 // Parentheses (for dumping/debugging purposes only).
6258 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6259 if (!Diff.isUsable())
6260 return std::make_pair(nullptr, nullptr);
6261
6262 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6263 if (!Diff.isUsable())
6264 return std::make_pair(nullptr, nullptr);
6265
6266 // Convert to the original type or ptrdiff_t, if original type is pointer.
6267 if (!VarType->isAnyPointerType() &&
6268 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6269 Diff = SemaRef.PerformImplicitConversion(
6270 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6271 } else if (VarType->isAnyPointerType() &&
6272 !SemaRef.Context.hasSameType(
6273 Diff.get()->getType(),
6274 SemaRef.Context.getUnsignedPointerDiffType())) {
6275 Diff = SemaRef.PerformImplicitConversion(
6276 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6277 Sema::AA_Converting, /*AllowExplicit=*/true);
6278 }
6279 if (!Diff.isUsable())
6280 return std::make_pair(nullptr, nullptr);
6281
6282 // Parentheses (for dumping/debugging purposes only).
6283 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6284 if (!Diff.isUsable())
6285 return std::make_pair(nullptr, nullptr);
6286
6287 if (TestIsLessOp.getValue()) {
6288 // MinExpr = Lower;
6289 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6290 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6291 if (!Diff.isUsable())
6292 return std::make_pair(nullptr, nullptr);
6293 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6294 if (!Diff.isUsable())
6295 return std::make_pair(nullptr, nullptr);
6296 MaxExpr = Diff.get();
6297 } else {
6298 // MaxExpr = Upper;
6299 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6300 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6301 if (!Diff.isUsable())
6302 return std::make_pair(nullptr, nullptr);
6303 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6304 if (!Diff.isUsable())
6305 return std::make_pair(nullptr, nullptr);
6306 MinExpr = Diff.get();
6307 }
6308
6309 return std::make_pair(MinExpr, MaxExpr);
6310}
6311
6312Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6313 if (InitDependOnLC || CondDependOnLC)
6314 return Condition;
6315 return nullptr;
6316}
6317
6318Expr *OpenMPIterationSpaceChecker::buildPreCond(
6319 Scope *S, Expr *Cond,
6320 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6321 // Do not build a precondition when the condition/initialization is dependent
6322 // to prevent pessimistic early loop exit.
6323 // TODO: this can be improved by calculating min/max values but not sure that
6324 // it will be very effective.
6325 if (CondDependOnLC || InitDependOnLC)
6326 return SemaRef.PerformImplicitConversion(
6327 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6328 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6329 /*AllowExplicit=*/true).get();
6330
6331 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
6332 Sema::TentativeAnalysisScope Trap(SemaRef);
6333
6334 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6335 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
6336 if (!NewLB.isUsable() || !NewUB.isUsable())
6337 return nullptr;
6338
6339 ExprResult CondExpr =
6340 SemaRef.BuildBinOp(S, DefaultLoc,
6341 TestIsLessOp.getValue() ?
6342 (TestIsStrictOp ? BO_LT : BO_LE) :
6343 (TestIsStrictOp ? BO_GT : BO_GE),
6344 NewLB.get(), NewUB.get());
6345 if (CondExpr.isUsable()) {
6346 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6347 SemaRef.Context.BoolTy))
6348 CondExpr = SemaRef.PerformImplicitConversion(
6349 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6350 /*AllowExplicit=*/true);
6351 }
6352
6353 // Otherwise use original loop condition and evaluate it in runtime.
6354 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6355}
6356
6357/// Build reference expression to the counter be used for codegen.
6358DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
6359 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6360 DSAStackTy &DSA) const {
6361 auto *VD = dyn_cast<VarDecl>(LCDecl);
6362 if (!VD) {
6363 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6364 DeclRefExpr *Ref = buildDeclRefExpr(
6365 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
6366 const DSAStackTy::DSAVarData Data =
6367 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
6368 // If the loop control decl is explicitly marked as private, do not mark it
6369 // as captured again.
6370 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6371 Captures.insert(std::make_pair(LCRef, Ref));
6372 return Ref;
6373 }
6374 return cast<DeclRefExpr>(LCRef);
6375}
6376
6377Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
6378 if (LCDecl && !LCDecl->isInvalidDecl()) {
6379 QualType Type = LCDecl->getType().getNonReferenceType();
6380 VarDecl *PrivateVar = buildVarDecl(
6381 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6382 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6383 isa<VarDecl>(LCDecl)
6384 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6385 : nullptr);
6386 if (PrivateVar->isInvalidDecl())
6387 return nullptr;
6388 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6389 }
6390 return nullptr;
6391}
6392
6393/// Build initialization of the counter to be used for codegen.
6394Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
6395
6396/// Build step of the counter be used for codegen.
6397Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
6398
6399Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6400 Scope *S, Expr *Counter,
6401 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6402 Expr *Inc, OverloadedOperatorKind OOK) {
6403 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6404 if (!Cnt)
6405 return nullptr;
6406 if (Inc) {
6407 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-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6408, __PRETTY_FUNCTION__))
6408 "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-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6408, __PRETTY_FUNCTION__))
;
6409 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6410 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6411 if (!Cnt)
6412 return nullptr;
6413 }
6414 ExprResult Diff;
6415 QualType VarType = LCDecl->getType().getNonReferenceType();
6416 if (VarType->isIntegerType() || VarType->isPointerType() ||
6417 SemaRef.getLangOpts().CPlusPlus) {
6418 // Upper - Lower
6419 Expr *Upper = TestIsLessOp.getValue()
6420 ? Cnt
6421 : tryBuildCapture(SemaRef, UB, Captures).get();
6422 Expr *Lower = TestIsLessOp.getValue()
6423 ? tryBuildCapture(SemaRef, LB, Captures).get()
6424 : Cnt;
6425 if (!Upper || !Lower)
6426 return nullptr;
6427
6428 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6429
6430 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6431 // BuildBinOp already emitted error, this one is to point user to upper
6432 // and lower bound, and to tell what is passed to 'operator-'.
6433 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6434 << Upper->getSourceRange() << Lower->getSourceRange();
6435 return nullptr;
6436 }
6437 }
6438
6439 if (!Diff.isUsable())
6440 return nullptr;
6441
6442 // Parentheses (for dumping/debugging purposes only).
6443 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6444 if (!Diff.isUsable())
6445 return nullptr;
6446
6447 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6448 if (!NewStep.isUsable())
6449 return nullptr;
6450 // (Upper - Lower) / Step
6451 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6452 if (!Diff.isUsable())
6453 return nullptr;
6454
6455 return Diff.get();
6456}
6457} // namespace
6458
6459void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6460 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-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6460, __PRETTY_FUNCTION__))
;
6461 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-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6461, __PRETTY_FUNCTION__))
;
6462 unsigned AssociatedLoops = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops();
6463 if (AssociatedLoops > 0 &&
6464 isOpenMPLoopDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
6465 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->loopStart();
6466 OpenMPIterationSpaceChecker ISC(*this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, ForLoc);
6467 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6468 if (ValueDecl *D = ISC.getLoopDecl()) {
6469 auto *VD = dyn_cast<VarDecl>(D);
6470 DeclRefExpr *PrivateRef = nullptr;
6471 if (!VD) {
6472 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
6473 VD = Private;
6474 } else {
6475 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6476 /*WithInit=*/false);
6477 VD = cast<VarDecl>(PrivateRef->getDecl());
6478 }
6479 }
6480 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addLoopControlVariable(D, VD);
6481 const Decl *LD = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getPossiblyLoopCunter();
6482 if (LD != D->getCanonicalDecl()) {
6483 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->resetPossibleLoopCounter();
6484 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6485 MarkDeclarationsReferencedInExpr(
6486 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6487 Var->getType().getNonLValueExprType(Context),
6488 ForLoc, /*RefersToCapture=*/true));
6489 }
6490 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
6491 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6492 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6493 // associated for-loop of a simd construct with just one associated
6494 // for-loop may be listed in a linear clause with a constant-linear-step
6495 // that is the increment of the associated for-loop. The loop iteration
6496 // variable(s) in the associated for-loop(s) of a for or parallel for
6497 // construct may be listed in a private or lastprivate clause.
6498 DSAStackTy::DSAVarData DVar =
6499 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
6500 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6501 // is declared in the loop and it is predetermined as a private.
6502 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6503 OpenMPClauseKind PredeterminedCKind =
6504 isOpenMPSimdDirective(DKind)
6505 ? (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6506 : OMPC_private;
6507 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6508 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6509 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6510 DVar.CKind != OMPC_private))) ||
6511 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
6512 DKind == OMPD_master_taskloop ||
6513 DKind == OMPD_parallel_master_taskloop ||
6514 isOpenMPDistributeDirective(DKind)) &&
6515 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6516 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6517 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6518 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6519 << getOpenMPClauseName(DVar.CKind)
6520 << getOpenMPDirectiveName(DKind)
6521 << getOpenMPClauseName(PredeterminedCKind);
6522 if (DVar.RefExpr == nullptr)
6523 DVar.CKind = PredeterminedCKind;
6524 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar,
6525 /*IsLoopIterVar=*/true);
6526 } else if (LoopDeclRefExpr) {
6527 // Make the loop iteration variable private (for worksharing
6528 // constructs), linear (for simd directives with the only one
6529 // associated loop) or lastprivate (for simd directives with several
6530 // collapsed or ordered loops).
6531 if (DVar.CKind == OMPC_unknown)
6532 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6533 PrivateRef);
6534 }
6535 }
6536 }
6537 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setAssociatedLoops(AssociatedLoops - 1);
6538 }
6539}
6540
6541/// Called on a for stmt to check and extract its iteration space
6542/// for further processing (such as collapsing).
6543static bool checkOpenMPIterationSpace(
6544 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6545 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
6546 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6547 Expr *OrderedLoopCountExpr,
6548 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
6549 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
6550 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
6551 // OpenMP [2.9.1, Canonical Loop Form]
6552 // for (init-expr; test-expr; incr-expr) structured-block
6553 // for (range-decl: range-expr) structured-block
6554 auto *For = dyn_cast_or_null<ForStmt>(S);
6555 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6556 // Ranged for is supported only in OpenMP 5.0.
6557 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
6558 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
6559 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
6560 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
6561 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
6562 if (TotalNestedLoopCount > 1) {
6563 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6564 SemaRef.Diag(DSA.getConstructLoc(),
6565 diag::note_omp_collapse_ordered_expr)
6566 << 2 << CollapseLoopCountExpr->getSourceRange()
6567 << OrderedLoopCountExpr->getSourceRange();
6568 else if (CollapseLoopCountExpr)
6569 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6570 diag::note_omp_collapse_ordered_expr)
6571 << 0 << CollapseLoopCountExpr->getSourceRange();
6572 else
6573 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6574 diag::note_omp_collapse_ordered_expr)
6575 << 1 << OrderedLoopCountExpr->getSourceRange();
6576 }
6577 return true;
6578 }
6579 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&((((For && For->getBody()) || (CXXFor && CXXFor
->getBody())) && "No loop body.") ? static_cast<
void> (0) : __assert_fail ("((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && \"No loop body.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6580, __PRETTY_FUNCTION__))
6580 "No loop body.")((((For && For->getBody()) || (CXXFor && CXXFor
->getBody())) && "No loop body.") ? static_cast<
void> (0) : __assert_fail ("((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && \"No loop body.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6580, __PRETTY_FUNCTION__))
;
6581
6582 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6583 For ? For->getForLoc() : CXXFor->getForLoc());
6584
6585 // Check init.
6586 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
6587 if (ISC.checkAndSetInit(Init))
6588 return true;
6589
6590 bool HasErrors = false;
6591
6592 // Check loop variable's type.
6593 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
6594 // OpenMP [2.6, Canonical Loop Form]
6595 // Var is one of the following:
6596 // A variable of signed or unsigned integer type.
6597 // For C++, a variable of a random access iterator type.
6598 // For C, a variable of a pointer type.
6599 QualType VarType = LCDecl->getType().getNonReferenceType();
6600 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6601 !VarType->isPointerType() &&
6602 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
6603 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
6604 << SemaRef.getLangOpts().CPlusPlus;
6605 HasErrors = true;
6606 }
6607
6608 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6609 // a Construct
6610 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6611 // parallel for construct is (are) private.
6612 // The loop iteration variable in the associated for-loop of a simd
6613 // construct with just one associated for-loop is linear with a
6614 // constant-linear-step that is the increment of the associated for-loop.
6615 // Exclude loop var from the list of variables with implicitly defined data
6616 // sharing attributes.
6617 VarsWithImplicitDSA.erase(LCDecl);
6618
6619 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars")((isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"
) ? static_cast<void> (0) : __assert_fail ("isOpenMPLoopDirective(DKind) && \"DSA for non-loop vars\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6619, __PRETTY_FUNCTION__))
;
6620
6621 // Check test-expr.
6622 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
6623
6624 // Check incr-expr.
6625 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
6626 }
6627
6628 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
6629 return HasErrors;
6630
6631 // Build the loop's iteration space representation.
6632 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
6633 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
6634 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
6635 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
6636 (isOpenMPWorksharingDirective(DKind) ||
6637 isOpenMPTaskLoopDirective(DKind) ||
6638 isOpenMPDistributeDirective(DKind)),
6639 Captures);
6640 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
6641 ISC.buildCounterVar(Captures, DSA);
6642 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
6643 ISC.buildPrivateCounterVar();
6644 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
6645 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
6646 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
6647 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
6648 ISC.getConditionSrcRange();
6649 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
6650 ISC.getIncrementSrcRange();
6651 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
6652 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
6653 ISC.isStrictTestOp();
6654 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
6655 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
6656 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
6657 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
6658 ISC.buildFinalCondition(DSA.getCurScope());
6659 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
6660 ISC.doesInitDependOnLC();
6661 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
6662 ISC.doesCondDependOnLC();
6663 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
6664 ISC.getLoopDependentIdx();
6665
6666 HasErrors |=
6667 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
6668 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
6669 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
6670 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
6671 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
6672 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
6673 if (!HasErrors && DSA.isOrderedRegion()) {
6674 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
6675 if (CurrentNestedLoopCount <
6676 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
6677 DSA.getOrderedRegionParam().second->setLoopNumIterations(
6678 CurrentNestedLoopCount,
6679 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
6680 DSA.getOrderedRegionParam().second->setLoopCounter(
6681 CurrentNestedLoopCount,
6682 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
6683 }
6684 }
6685 for (auto &Pair : DSA.getDoacrossDependClauses()) {
6686 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
6687 // Erroneous case - clause has some problems.
6688 continue;
6689 }
6690 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
6691 Pair.second.size() <= CurrentNestedLoopCount) {
6692 // Erroneous case - clause has some problems.
6693 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
6694 continue;
6695 }
6696 Expr *CntValue;
6697 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
6698 CntValue = ISC.buildOrderedLoopData(
6699 DSA.getCurScope(),
6700 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
6701 Pair.first->getDependencyLoc());
6702 else
6703 CntValue = ISC.buildOrderedLoopData(
6704 DSA.getCurScope(),
6705 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
6706 Pair.first->getDependencyLoc(),
6707 Pair.second[CurrentNestedLoopCount].first,
6708 Pair.second[CurrentNestedLoopCount].second);
6709 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
6710 }
6711 }
6712
6713 return HasErrors;
6714}
6715
6716/// Build 'VarRef = Start.
6717static ExprResult
6718buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
6719 ExprResult Start, bool IsNonRectangularLB,
6720 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
6721 // Build 'VarRef = Start.
6722 ExprResult NewStart = IsNonRectangularLB
6723 ? Start.get()
6724 : tryBuildCapture(SemaRef, Start.get(), Captures);
6725 if (!NewStart.isUsable())
6726 return ExprError();
6727 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
6728 VarRef.get()->getType())) {
6729 NewStart = SemaRef.PerformImplicitConversion(
6730 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
6731 /*AllowExplicit=*/true);
6732 if (!NewStart.isUsable())
6733 return ExprError();
6734 }
6735
6736 ExprResult Init =
6737 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6738 return Init;
6739}
6740
6741/// Build 'VarRef = Start + Iter * Step'.
6742static ExprResult buildCounterUpdate(
6743 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
6744 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
6745 bool IsNonRectangularLB,
6746 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
6747 // Add parentheses (for debugging purposes only).
6748 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
6749 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
6750 !Step.isUsable())
6751 return ExprError();
6752
6753 ExprResult NewStep = Step;
6754 if (Captures)
6755 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
6756 if (NewStep.isInvalid())
6757 return ExprError();
6758 ExprResult Update =
6759 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
6760 if (!Update.isUsable())
6761 return ExprError();
6762
6763 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
6764 // 'VarRef = Start (+|-) Iter * Step'.
6765 if (!Start.isUsable())
6766 return ExprError();
6767 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
6768 if (!NewStart.isUsable())
6769 return ExprError();
6770 if (Captures && !IsNonRectangularLB)
6771 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
6772 if (NewStart.isInvalid())
6773 return ExprError();
6774
6775 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
6776 ExprResult SavedUpdate = Update;
6777 ExprResult UpdateVal;
6778 if (VarRef.get()->getType()->isOverloadableType() ||
6779 NewStart.get()->getType()->isOverloadableType() ||
6780 Update.get()->getType()->isOverloadableType()) {
6781 Sema::TentativeAnalysisScope Trap(SemaRef);
6782
6783 Update =
6784 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6785 if (Update.isUsable()) {
6786 UpdateVal =
6787 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
6788 VarRef.get(), SavedUpdate.get());
6789 if (UpdateVal.isUsable()) {
6790 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
6791 UpdateVal.get());
6792 }
6793 }
6794 }
6795
6796 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
6797 if (!Update.isUsable() || !UpdateVal.isUsable()) {
6798 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
6799 NewStart.get(), SavedUpdate.get());
6800 if (!Update.isUsable())
6801 return ExprError();
6802
6803 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
6804 VarRef.get()->getType())) {
6805 Update = SemaRef.PerformImplicitConversion(
6806 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
6807 if (!Update.isUsable())
6808 return ExprError();
6809 }
6810
6811 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
6812 }
6813 return Update;
6814}
6815
6816/// Convert integer expression \a E to make it have at least \a Bits
6817/// bits.
6818static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
6819 if (E == nullptr)
6820 return ExprError();
6821 ASTContext &C = SemaRef.Context;
6822 QualType OldType = E->getType();
6823 unsigned HasBits = C.getTypeSize(OldType);
6824 if (HasBits >= Bits)
6825 return ExprResult(E);
6826 // OK to convert to signed, because new type has more bits than old.
6827 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
6828 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
6829 true);
6830}
6831
6832/// Check if the given expression \a E is a constant integer that fits
6833/// into \a Bits bits.
6834static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
6835 if (E == nullptr)
6836 return false;
6837 llvm::APSInt Result;
6838 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
6839 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
6840 return false;
6841}
6842
6843/// Build preinits statement for the given declarations.
6844static Stmt *buildPreInits(ASTContext &Context,
6845 MutableArrayRef<Decl *> PreInits) {
6846 if (!PreInits.empty()) {
6847 return new (Context) DeclStmt(
6848 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
6849 SourceLocation(), SourceLocation());
6850 }
6851 return nullptr;
6852}
6853
6854/// Build preinits statement for the given declarations.
6855static Stmt *
6856buildPreInits(ASTContext &Context,
6857 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
6858 if (!Captures.empty()) {
6859 SmallVector<Decl *, 16> PreInits;
6860 for (const auto &Pair : Captures)
6861 PreInits.push_back(Pair.second->getDecl());
6862 return buildPreInits(Context, PreInits);
6863 }
6864 return nullptr;
6865}
6866
6867/// Build postupdate expression for the given list of postupdates expressions.
6868static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
6869 Expr *PostUpdate = nullptr;
6870 if (!PostUpdates.empty()) {
6871 for (Expr *E : PostUpdates) {
6872 Expr *ConvE = S.BuildCStyleCastExpr(
6873 E->getExprLoc(),
6874 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
6875 E->getExprLoc(), E)
6876 .get();
6877 PostUpdate = PostUpdate
6878 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
6879 PostUpdate, ConvE)
6880 .get()
6881 : ConvE;
6882 }
6883 }
6884 return PostUpdate;
6885}
6886
6887/// Called on a for stmt to check itself and nested loops (if any).
6888/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
6889/// number of collapsed loops otherwise.
6890static unsigned
6891checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
6892 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
6893 DSAStackTy &DSA,
6894 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
6895 OMPLoopDirective::HelperExprs &Built) {
6896 unsigned NestedLoopCount = 1;
6897 if (CollapseLoopCountExpr) {
6898 // Found 'collapse' clause - calculate collapse number.
6899 Expr::EvalResult Result;
6900 if (!CollapseLoopCountExpr->isValueDependent() &&
6901 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
6902 NestedLoopCount = Result.Val.getInt().getLimitedValue();
6903 } else {
6904 Built.clear(/*Size=*/1);
6905 return 1;
6906 }
6907 }
6908 unsigned OrderedLoopCount = 1;
6909 if (OrderedLoopCountExpr) {
6910 // Found 'ordered' clause - calculate collapse number.
6911 Expr::EvalResult EVResult;
6912 if (!OrderedLoopCountExpr->isValueDependent() &&
6913 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
6914 SemaRef.getASTContext())) {
6915 llvm::APSInt Result = EVResult.Val.getInt();
6916 if (Result.getLimitedValue() < NestedLoopCount) {
6917 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6918 diag::err_omp_wrong_ordered_loop_count)
6919 << OrderedLoopCountExpr->getSourceRange();
6920 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6921 diag::note_collapse_loop_count)
6922 << CollapseLoopCountExpr->getSourceRange();
6923 }
6924 OrderedLoopCount = Result.getLimitedValue();
6925 } else {
6926 Built.clear(/*Size=*/1);
6927 return 1;
6928 }
6929 }
6930 // This is helper routine for loop directives (e.g., 'for', 'simd',
6931 // 'for simd', etc.).
6932 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
6933 SmallVector<LoopIterationSpace, 4> IterSpaces(
6934 std::max(OrderedLoopCount, NestedLoopCount));
6935 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
6936 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
6937 if (checkOpenMPIterationSpace(
6938 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6939 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
6940 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
6941 return 0;
6942 // Move on to the next nested for loop, or to the loop body.
6943 // OpenMP [2.8.1, simd construct, Restrictions]
6944 // All loops associated with the construct must be perfectly nested; that
6945 // is, there must be no intervening code nor any OpenMP directive between
6946 // any two loops.
6947 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
6948 CurStmt = For->getBody();
6949 } else {
6950 assert(isa<CXXForRangeStmt>(CurStmt) &&((isa<CXXForRangeStmt>(CurStmt) && "Expected canonical for or range-based for loops."
) ? static_cast<void> (0) : __assert_fail ("isa<CXXForRangeStmt>(CurStmt) && \"Expected canonical for or range-based for loops.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6951, __PRETTY_FUNCTION__))
6951 "Expected canonical for or range-based for loops.")((isa<CXXForRangeStmt>(CurStmt) && "Expected canonical for or range-based for loops."
) ? static_cast<void> (0) : __assert_fail ("isa<CXXForRangeStmt>(CurStmt) && \"Expected canonical for or range-based for loops.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6951, __PRETTY_FUNCTION__))
;
6952 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
6953 }
6954 CurStmt = CurStmt->IgnoreContainers();
6955 }
6956 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
6957 if (checkOpenMPIterationSpace(
6958 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6959 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
6960 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
6961 return 0;
6962 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
6963 // Handle initialization of captured loop iterator variables.
6964 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
6965 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
6966 Captures[DRE] = DRE;
6967 }
6968 }
6969 // Move on to the next nested for loop, or to the loop body.
6970 // OpenMP [2.8.1, simd construct, Restrictions]
6971 // All loops associated with the construct must be perfectly nested; that
6972 // is, there must be no intervening code nor any OpenMP directive between
6973 // any two loops.
6974 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
6975 CurStmt = For->getBody();
6976 } else {
6977 assert(isa<CXXForRangeStmt>(CurStmt) &&((isa<CXXForRangeStmt>(CurStmt) && "Expected canonical for or range-based for loops."
) ? static_cast<void> (0) : __assert_fail ("isa<CXXForRangeStmt>(CurStmt) && \"Expected canonical for or range-based for loops.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6978, __PRETTY_FUNCTION__))
6978 "Expected canonical for or range-based for loops.")((isa<CXXForRangeStmt>(CurStmt) && "Expected canonical for or range-based for loops."
) ? static_cast<void> (0) : __assert_fail ("isa<CXXForRangeStmt>(CurStmt) && \"Expected canonical for or range-based for loops.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 6978, __PRETTY_FUNCTION__))
;
6979 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
6980 }
6981 CurStmt = CurStmt->IgnoreContainers();
6982 }
6983
6984 Built.clear(/* size */ NestedLoopCount);
6985
6986 if (SemaRef.CurContext->isDependentContext())
6987 return NestedLoopCount;
6988
6989 // An example of what is generated for the following code:
6990 //
6991 // #pragma omp simd collapse(2) ordered(2)
6992 // for (i = 0; i < NI; ++i)
6993 // for (k = 0; k < NK; ++k)
6994 // for (j = J0; j < NJ; j+=2) {
6995 // <loop body>
6996 // }
6997 //
6998 // We generate the code below.
6999 // Note: the loop body may be outlined in CodeGen.
7000 // Note: some counters may be C++ classes, operator- is used to find number of
7001 // iterations and operator+= to calculate counter value.
7002 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7003 // or i64 is currently supported).
7004 //
7005 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7006 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7007 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7008 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7009 // // similar updates for vars in clauses (e.g. 'linear')
7010 // <loop body (using local i and j)>
7011 // }
7012 // i = NI; // assign final values of counters
7013 // j = NJ;
7014 //
7015
7016 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7017 // the iteration counts of the collapsed for loops.
7018 // Precondition tests if there is at least one iteration (all conditions are
7019 // true).
7020 auto PreCond = ExprResult(IterSpaces[0].PreCond);
7021 Expr *N0 = IterSpaces[0].NumIterations;
7022 ExprResult LastIteration32 =
7023 widenIterationCount(/*Bits=*/32,
7024 SemaRef
7025 .PerformImplicitConversion(
7026 N0->IgnoreImpCasts(), N0->getType(),
7027 Sema::AA_Converting, /*AllowExplicit=*/true)
7028 .get(),
7029 SemaRef);
7030 ExprResult LastIteration64 = widenIterationCount(
7031 /*Bits=*/64,
7032 SemaRef
7033 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7034 Sema::AA_Converting,
7035 /*AllowExplicit=*/true)
7036 .get(),
7037 SemaRef);
7038
7039 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7040 return NestedLoopCount;
7041
7042 ASTContext &C = SemaRef.Context;
7043 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7044
7045 Scope *CurScope = DSA.getCurScope();
7046 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
7047 if (PreCond.isUsable()) {
7048 PreCond =
7049 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7050 PreCond.get(), IterSpaces[Cnt].PreCond);
7051 }
7052 Expr *N = IterSpaces[Cnt].NumIterations;
7053 SourceLocation Loc = N->getExprLoc();
7054 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7055 if (LastIteration32.isUsable())
7056 LastIteration32 = SemaRef.BuildBinOp(
7057 CurScope, Loc, BO_Mul, LastIteration32.get(),
7058 SemaRef
7059 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7060 Sema::AA_Converting,
7061 /*AllowExplicit=*/true)
7062 .get());
7063 if (LastIteration64.isUsable())
7064 LastIteration64 = SemaRef.BuildBinOp(
7065 CurScope, Loc, BO_Mul, LastIteration64.get(),
7066 SemaRef
7067 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7068 Sema::AA_Converting,
7069 /*AllowExplicit=*/true)
7070 .get());
7071 }
7072
7073 // Choose either the 32-bit or 64-bit version.
7074 ExprResult LastIteration = LastIteration64;
7075 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7076 (LastIteration32.isUsable() &&
7077 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7078 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7079 fitsInto(
7080 /*Bits=*/32,
7081 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7082 LastIteration64.get(), SemaRef))))
7083 LastIteration = LastIteration32;
7084 QualType VType = LastIteration.get()->getType();
7085 QualType RealVType = VType;
7086 QualType StrideVType = VType;
7087 if (isOpenMPTaskLoopDirective(DKind)) {
7088 VType =
7089 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7090 StrideVType =
7091 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7092 }
7093
7094 if (!LastIteration.isUsable())
7095 return 0;
7096
7097 // Save the number of iterations.
7098 ExprResult NumIterations = LastIteration;
7099 {
7100 LastIteration = SemaRef.BuildBinOp(
7101 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7102 LastIteration.get(),
7103 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7104 if (!LastIteration.isUsable())
7105 return 0;
7106 }
7107
7108 // Calculate the last iteration number beforehand instead of doing this on
7109 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7110 llvm::APSInt Result;
7111 bool IsConstant =
7112 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7113 ExprResult CalcLastIteration;
7114 if (!IsConstant) {
7115 ExprResult SaveRef =
7116 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
7117 LastIteration = SaveRef;
7118
7119 // Prepare SaveRef + 1.
7120 NumIterations = SemaRef.BuildBinOp(
7121 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
7122 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7123 if (!NumIterations.isUsable())
7124 return 0;
7125 }
7126
7127 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7128
7129 // Build variables passed into runtime, necessary for worksharing directives.
7130 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
7131 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7132 isOpenMPDistributeDirective(DKind)) {
7133 // Lower bound variable, initialized with zero.
7134 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7135 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
7136 SemaRef.AddInitializerToDecl(LBDecl,
7137 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7138 /*DirectInit*/ false);
7139
7140 // Upper bound variable, initialized with last iteration number.
7141 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7142 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
7143 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
7144 /*DirectInit*/ false);
7145
7146 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7147 // This will be used to implement clause 'lastprivate'.
7148 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
7149 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7150 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
7151 SemaRef.AddInitializerToDecl(ILDecl,
7152 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7153 /*DirectInit*/ false);
7154
7155 // Stride variable returned by runtime (we initialize it to 1 by default).
7156 VarDecl *STDecl =
7157 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7158 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
7159 SemaRef.AddInitializerToDecl(STDecl,
7160 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7161 /*DirectInit*/ false);
7162
7163 // Build expression: UB = min(UB, LastIteration)
7164 // It is necessary for CodeGen of directives with static scheduling.
7165 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7166 UB.get(), LastIteration.get());
7167 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7168 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7169 LastIteration.get(), UB.get());
7170 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7171 CondOp.get());
7172 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
7173
7174 // If we have a combined directive that combines 'distribute', 'for' or
7175 // 'simd' we need to be able to access the bounds of the schedule of the
7176 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7177 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7178 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7179 // Lower bound variable, initialized with zero.
7180 VarDecl *CombLBDecl =
7181 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7182 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7183 SemaRef.AddInitializerToDecl(
7184 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7185 /*DirectInit*/ false);
7186
7187 // Upper bound variable, initialized with last iteration number.
7188 VarDecl *CombUBDecl =
7189 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7190 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7191 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7192 /*DirectInit*/ false);
7193
7194 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7195 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7196 ExprResult CombCondOp =
7197 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7198 LastIteration.get(), CombUB.get());
7199 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7200 CombCondOp.get());
7201 CombEUB =
7202 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
7203
7204 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
7205 // We expect to have at least 2 more parameters than the 'parallel'
7206 // directive does - the lower and upper bounds of the previous schedule.
7207 assert(CD->getNumParams() >= 4 &&((CD->getNumParams() >= 4 && "Unexpected number of parameters in loop combined directive"
) ? static_cast<void> (0) : __assert_fail ("CD->getNumParams() >= 4 && \"Unexpected number of parameters in loop combined directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7208, __PRETTY_FUNCTION__))
7208 "Unexpected number of parameters in loop combined directive")((CD->getNumParams() >= 4 && "Unexpected number of parameters in loop combined directive"
) ? static_cast<void> (0) : __assert_fail ("CD->getNumParams() >= 4 && \"Unexpected number of parameters in loop combined directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7208, __PRETTY_FUNCTION__))
;
7209
7210 // Set the proper type for the bounds given what we learned from the
7211 // enclosed loops.
7212 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7213 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
7214
7215 // Previous lower and upper bounds are obtained from the region
7216 // parameters.
7217 PrevLB =
7218 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7219 PrevUB =
7220 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7221 }
7222 }
7223
7224 // Build the iteration variable and its initialization before loop.
7225 ExprResult IV;
7226 ExprResult Init, CombInit;
7227 {
7228 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7229 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
7230 Expr *RHS =
7231 (isOpenMPWorksharingDirective(DKind) ||
7232 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7233 ? LB.get()
7234 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7235 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
7236 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
7237
7238 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7239 Expr *CombRHS =
7240 (isOpenMPWorksharingDirective(DKind) ||
7241 isOpenMPTaskLoopDirective(DKind) ||
7242 isOpenMPDistributeDirective(DKind))
7243 ? CombLB.get()
7244 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7245 CombInit =
7246 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
7247 CombInit =
7248 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
7249 }
7250 }
7251
7252 bool UseStrictCompare =
7253 RealVType->hasUnsignedIntegerRepresentation() &&
7254 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7255 return LIS.IsStrictCompare;
7256 });
7257 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7258 // unsigned IV)) for worksharing loops.
7259 SourceLocation CondLoc = AStmt->getBeginLoc();
7260 Expr *BoundUB = UB.get();
7261 if (UseStrictCompare) {
7262 BoundUB =
7263 SemaRef
7264 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7265 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7266 .get();
7267 BoundUB =
7268 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7269 }
7270 ExprResult Cond =
7271 (isOpenMPWorksharingDirective(DKind) ||
7272 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7273 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7274 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7275 BoundUB)
7276 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7277 NumIterations.get());
7278 ExprResult CombDistCond;
7279 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7280 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7281 NumIterations.get());
7282 }
7283
7284 ExprResult CombCond;
7285 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7286 Expr *BoundCombUB = CombUB.get();
7287 if (UseStrictCompare) {
7288 BoundCombUB =
7289 SemaRef
7290 .BuildBinOp(
7291 CurScope, CondLoc, BO_Add, BoundCombUB,
7292 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7293 .get();
7294 BoundCombUB =
7295 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7296 .get();
7297 }
7298 CombCond =
7299 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7300 IV.get(), BoundCombUB);
7301 }
7302 // Loop increment (IV = IV + 1)
7303 SourceLocation IncLoc = AStmt->getBeginLoc();
7304 ExprResult Inc =
7305 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7306 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7307 if (!Inc.isUsable())
7308 return 0;
7309 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
7310 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
7311 if (!Inc.isUsable())
7312 return 0;
7313
7314 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7315 // Used for directives with static scheduling.
7316 // In combined construct, add combined version that use CombLB and CombUB
7317 // base variables for the update
7318 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
7319 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7320 isOpenMPDistributeDirective(DKind)) {
7321 // LB + ST
7322 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7323 if (!NextLB.isUsable())
7324 return 0;
7325 // LB = LB + ST
7326 NextLB =
7327 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
7328 NextLB =
7329 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
7330 if (!NextLB.isUsable())
7331 return 0;
7332 // UB + ST
7333 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7334 if (!NextUB.isUsable())
7335 return 0;
7336 // UB = UB + ST
7337 NextUB =
7338 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
7339 NextUB =
7340 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
7341 if (!NextUB.isUsable())
7342 return 0;
7343 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7344 CombNextLB =
7345 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7346 if (!NextLB.isUsable())
7347 return 0;
7348 // LB = LB + ST
7349 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7350 CombNextLB.get());
7351 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7352 /*DiscardedValue*/ false);
7353 if (!CombNextLB.isUsable())
7354 return 0;
7355 // UB + ST
7356 CombNextUB =
7357 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7358 if (!CombNextUB.isUsable())
7359 return 0;
7360 // UB = UB + ST
7361 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7362 CombNextUB.get());
7363 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7364 /*DiscardedValue*/ false);
7365 if (!CombNextUB.isUsable())
7366 return 0;
7367 }
7368 }
7369
7370 // Create increment expression for distribute loop when combined in a same
7371 // directive with for as IV = IV + ST; ensure upper bound expression based
7372 // on PrevUB instead of NumIterations - used to implement 'for' when found
7373 // in combination with 'distribute', like in 'distribute parallel for'
7374 SourceLocation DistIncLoc = AStmt->getBeginLoc();
7375 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
7376 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7377 DistCond = SemaRef.BuildBinOp(
7378 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
7379 assert(DistCond.isUsable() && "distribute cond expr was not built")((DistCond.isUsable() && "distribute cond expr was not built"
) ? static_cast<void> (0) : __assert_fail ("DistCond.isUsable() && \"distribute cond expr was not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7379, __PRETTY_FUNCTION__))
;
7380
7381 DistInc =
7382 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7383 assert(DistInc.isUsable() && "distribute inc expr was not built")((DistInc.isUsable() && "distribute inc expr was not built"
) ? static_cast<void> (0) : __assert_fail ("DistInc.isUsable() && \"distribute inc expr was not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7383, __PRETTY_FUNCTION__))
;
7384 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7385 DistInc.get());
7386 DistInc =
7387 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
7388 assert(DistInc.isUsable() && "distribute inc expr was not built")((DistInc.isUsable() && "distribute inc expr was not built"
) ? static_cast<void> (0) : __assert_fail ("DistInc.isUsable() && \"distribute inc expr was not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7388, __PRETTY_FUNCTION__))
;
7389
7390 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7391 // construct
7392 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
7393 ExprResult IsUBGreater =
7394 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7395 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7396 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7397 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7398 CondOp.get());
7399 PrevEUB =
7400 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
7401
7402 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7403 // parallel for is in combination with a distribute directive with
7404 // schedule(static, 1)
7405 Expr *BoundPrevUB = PrevUB.get();
7406 if (UseStrictCompare) {
7407 BoundPrevUB =
7408 SemaRef
7409 .BuildBinOp(
7410 CurScope, CondLoc, BO_Add, BoundPrevUB,
7411 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7412 .get();
7413 BoundPrevUB =
7414 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7415 .get();
7416 }
7417 ParForInDistCond =
7418 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7419 IV.get(), BoundPrevUB);
7420 }
7421
7422 // Build updates and final values of the loop counters.
7423 bool HasErrors = false;
7424 Built.Counters.resize(NestedLoopCount);
7425 Built.Inits.resize(NestedLoopCount);
7426 Built.Updates.resize(NestedLoopCount);
7427 Built.Finals.resize(NestedLoopCount);
7428 Built.DependentCounters.resize(NestedLoopCount);
7429 Built.DependentInits.resize(NestedLoopCount);
7430 Built.FinalsConditions.resize(NestedLoopCount);
7431 {
7432 // We implement the following algorithm for obtaining the
7433 // original loop iteration variable values based on the
7434 // value of the collapsed loop iteration variable IV.
7435 //
7436 // Let n+1 be the number of collapsed loops in the nest.
7437 // Iteration variables (I0, I1, .... In)
7438 // Iteration counts (N0, N1, ... Nn)
7439 //
7440 // Acc = IV;
7441 //
7442 // To compute Ik for loop k, 0 <= k <= n, generate:
7443 // Prod = N(k+1) * N(k+2) * ... * Nn;
7444 // Ik = Acc / Prod;
7445 // Acc -= Ik * Prod;
7446 //
7447 ExprResult Acc = IV;
7448 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
7449 LoopIterationSpace &IS = IterSpaces[Cnt];
7450 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
7451 ExprResult Iter;
7452
7453 // Compute prod
7454 ExprResult Prod =
7455 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7456 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7457 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7458 IterSpaces[K].NumIterations);
7459
7460 // Iter = Acc / Prod
7461 // If there is at least one more inner loop to avoid
7462 // multiplication by 1.
7463 if (Cnt + 1 < NestedLoopCount)
7464 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7465 Acc.get(), Prod.get());
7466 else
7467 Iter = Acc;
7468 if (!Iter.isUsable()) {
7469 HasErrors = true;
7470 break;
7471 }
7472
7473 // Update Acc:
7474 // Acc -= Iter * Prod
7475 // Check if there is at least one more inner loop to avoid
7476 // multiplication by 1.
7477 if (Cnt + 1 < NestedLoopCount)
7478 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7479 Iter.get(), Prod.get());
7480 else
7481 Prod = Iter;
7482 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7483 Acc.get(), Prod.get());
7484
7485 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
7486 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
7487 DeclRefExpr *CounterVar = buildDeclRefExpr(
7488 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7489 /*RefersToCapture=*/true);
7490 ExprResult Init =
7491 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7492 IS.CounterInit, IS.IsNonRectangularLB, Captures);
7493 if (!Init.isUsable()) {
7494 HasErrors = true;
7495 break;
7496 }
7497 ExprResult Update = buildCounterUpdate(
7498 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
7499 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
7500 if (!Update.isUsable()) {
7501 HasErrors = true;
7502 break;
7503 }
7504
7505 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
7506 ExprResult Final =
7507 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7508 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7509 IS.Subtract, IS.IsNonRectangularLB, &Captures);
7510 if (!Final.isUsable()) {
7511 HasErrors = true;
7512 break;
7513 }
7514
7515 if (!Update.isUsable() || !Final.isUsable()) {
7516 HasErrors = true;
7517 break;
7518 }
7519 // Save results
7520 Built.Counters[Cnt] = IS.CounterVar;
7521 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
7522 Built.Inits[Cnt] = Init.get();
7523 Built.Updates[Cnt] = Update.get();
7524 Built.Finals[Cnt] = Final.get();
7525 Built.DependentCounters[Cnt] = nullptr;
7526 Built.DependentInits[Cnt] = nullptr;
7527 Built.FinalsConditions[Cnt] = nullptr;
7528 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
7529 Built.DependentCounters[Cnt] =
7530 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7531 Built.DependentInits[Cnt] =
7532 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7533 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7534 }
7535 }
7536 }
7537
7538 if (HasErrors)
7539 return 0;
7540
7541 // Save results
7542 Built.IterationVarRef = IV.get();
7543 Built.LastIteration = LastIteration.get();
7544 Built.NumIterations = NumIterations.get();
7545 Built.CalcLastIteration = SemaRef
7546 .ActOnFinishFullExpr(CalcLastIteration.get(),
7547 /*DiscardedValue=*/false)
7548 .get();
7549 Built.PreCond = PreCond.get();
7550 Built.PreInits = buildPreInits(C, Captures);
7551 Built.Cond = Cond.get();
7552 Built.Init = Init.get();
7553 Built.Inc = Inc.get();
7554 Built.LB = LB.get();
7555 Built.UB = UB.get();
7556 Built.IL = IL.get();
7557 Built.ST = ST.get();
7558 Built.EUB = EUB.get();
7559 Built.NLB = NextLB.get();
7560 Built.NUB = NextUB.get();
7561 Built.PrevLB = PrevLB.get();
7562 Built.PrevUB = PrevUB.get();
7563 Built.DistInc = DistInc.get();
7564 Built.PrevEUB = PrevEUB.get();
7565 Built.DistCombinedFields.LB = CombLB.get();
7566 Built.DistCombinedFields.UB = CombUB.get();
7567 Built.DistCombinedFields.EUB = CombEUB.get();
7568 Built.DistCombinedFields.Init = CombInit.get();
7569 Built.DistCombinedFields.Cond = CombCond.get();
7570 Built.DistCombinedFields.NLB = CombNextLB.get();
7571 Built.DistCombinedFields.NUB = CombNextUB.get();
7572 Built.DistCombinedFields.DistCond = CombDistCond.get();
7573 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
7574
7575 return NestedLoopCount;
7576}
7577
7578static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
7579 auto CollapseClauses =
7580 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7581 if (CollapseClauses.begin() != CollapseClauses.end())
7582 return (*CollapseClauses.begin())->getNumForLoops();
7583 return nullptr;
7584}
7585
7586static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
7587 auto OrderedClauses =
7588 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7589 if (OrderedClauses.begin() != OrderedClauses.end())
7590 return (*OrderedClauses.begin())->getNumForLoops();
7591 return nullptr;
7592}
7593
7594static bool checkSimdlenSafelenSpecified(Sema &S,
7595 const ArrayRef<OMPClause *> Clauses) {
7596 const OMPSafelenClause *Safelen = nullptr;
7597 const OMPSimdlenClause *Simdlen = nullptr;
7598
7599 for (const OMPClause *Clause : Clauses) {
7600 if (Clause->getClauseKind() == OMPC_safelen)
7601 Safelen = cast<OMPSafelenClause>(Clause);
7602 else if (Clause->getClauseKind() == OMPC_simdlen)
7603 Simdlen = cast<OMPSimdlenClause>(Clause);
7604 if (Safelen && Simdlen)
7605 break;
7606 }
7607
7608 if (Simdlen && Safelen) {
7609 const Expr *SimdlenLength = Simdlen->getSimdlen();
7610 const Expr *SafelenLength = Safelen->getSafelen();
7611 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7612 SimdlenLength->isInstantiationDependent() ||
7613 SimdlenLength->containsUnexpandedParameterPack())
7614 return false;
7615 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7616 SafelenLength->isInstantiationDependent() ||
7617 SafelenLength->containsUnexpandedParameterPack())
7618 return false;
7619 Expr::EvalResult SimdlenResult, SafelenResult;
7620 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
7621 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
7622 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
7623 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
7624 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
7625 // If both simdlen and safelen clauses are specified, the value of the
7626 // simdlen parameter must be less than or equal to the value of the safelen
7627 // parameter.
7628 if (SimdlenRes > SafelenRes) {
7629 S.Diag(SimdlenLength->getExprLoc(),
7630 diag::err_omp_wrong_simdlen_safelen_values)
7631 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
7632 return true;
7633 }
7634 }
7635 return false;
7636}
7637
7638StmtResult
7639Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7640 SourceLocation StartLoc, SourceLocation EndLoc,
7641 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7642 if (!AStmt)
7643 return StmtError();
7644
7645 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7645, __PRETTY_FUNCTION__))
;
7646 OMPLoopDirective::HelperExprs B;
7647 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7648 // define the nested loops number.
7649 unsigned NestedLoopCount = checkOpenMPLoop(
7650 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7651 AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
7652 if (NestedLoopCount == 0)
7653 return StmtError();
7654
7655 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp simd loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7656, __PRETTY_FUNCTION__))
7656 "omp simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp simd loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7656, __PRETTY_FUNCTION__))
;
7657
7658 if (!CurContext->isDependentContext()) {
7659 // Finalize the clauses that need pre-built expressions for CodeGen.
7660 for (OMPClause *C : Clauses) {
7661 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7662 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7663 B.NumIterations, *this, CurScope,
7664 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
7665 return StmtError();
7666 }
7667 }
7668
7669 if (checkSimdlenSafelenSpecified(*this, Clauses))
7670 return StmtError();
7671
7672 setFunctionHasBranchProtectedScope();
7673 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7674 Clauses, AStmt, B);
7675}
7676
7677StmtResult
7678Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7679 SourceLocation StartLoc, SourceLocation EndLoc,
7680 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7681 if (!AStmt)
7682 return StmtError();
7683
7684 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7684, __PRETTY_FUNCTION__))
;
7685 OMPLoopDirective::HelperExprs B;
7686 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7687 // define the nested loops number.
7688 unsigned NestedLoopCount = checkOpenMPLoop(
7689 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7690 AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
7691 if (NestedLoopCount == 0)
7692 return StmtError();
7693
7694 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7695, __PRETTY_FUNCTION__))
7695 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7695, __PRETTY_FUNCTION__))
;
7696
7697 if (!CurContext->isDependentContext()) {
7698 // Finalize the clauses that need pre-built expressions for CodeGen.
7699 for (OMPClause *C : Clauses) {
7700 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7701 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7702 B.NumIterations, *this, CurScope,
7703 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
7704 return StmtError();
7705 }
7706 }
7707
7708 setFunctionHasBranchProtectedScope();
7709 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7710 Clauses, AStmt, B, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
7711}
7712
7713StmtResult Sema::ActOnOpenMPForSimdDirective(
7714 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7715 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7716 if (!AStmt)
7717 return StmtError();
7718
7719 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7719, __PRETTY_FUNCTION__))
;
7720 OMPLoopDirective::HelperExprs B;
7721 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7722 // define the nested loops number.
7723 unsigned NestedLoopCount =
7724 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
7725 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
7726 VarsWithImplicitDSA, B);
7727 if (NestedLoopCount == 0)
7728 return StmtError();
7729
7730 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for simd loop exprs were not built") ? static_cast<void
> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7731, __PRETTY_FUNCTION__))
7731 "omp for simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for simd loop exprs were not built") ? static_cast<void
> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7731, __PRETTY_FUNCTION__))
;
7732
7733 if (!CurContext->isDependentContext()) {
7734 // Finalize the clauses that need pre-built expressions for CodeGen.
7735 for (OMPClause *C : Clauses) {
7736 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7737 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7738 B.NumIterations, *this, CurScope,
7739 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
7740 return StmtError();
7741 }
7742 }
7743
7744 if (checkSimdlenSafelenSpecified(*this, Clauses))
7745 return StmtError();
7746
7747 setFunctionHasBranchProtectedScope();
7748 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7749 Clauses, AStmt, B);
7750}
7751
7752StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7753 Stmt *AStmt,
7754 SourceLocation StartLoc,
7755 SourceLocation EndLoc) {
7756 if (!AStmt)
7757 return StmtError();
7758
7759 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7759, __PRETTY_FUNCTION__))
;
7760 auto BaseStmt = AStmt;
7761 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
7762 BaseStmt = CS->getCapturedStmt();
7763 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
7764 auto S = C->children();
7765 if (S.begin() == S.end())
7766 return StmtError();
7767 // All associated statements must be '#pragma omp section' except for
7768 // the first one.
7769 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
7770 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7771 if (SectionStmt)
7772 Diag(SectionStmt->getBeginLoc(),
7773 diag::err_omp_sections_substmt_not_section);
7774 return StmtError();
7775 }
7776 cast<OMPSectionDirective>(SectionStmt)
7777 ->setHasCancel(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
7778 }
7779 } else {
7780 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
7781 return StmtError();
7782 }
7783
7784 setFunctionHasBranchProtectedScope();
7785
7786 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7787 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
7788}
7789
7790StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
7791 SourceLocation StartLoc,
7792 SourceLocation EndLoc) {
7793 if (!AStmt)
7794 return StmtError();
7795
7796 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7796, __PRETTY_FUNCTION__))
;
7797
7798 setFunctionHasBranchProtectedScope();
7799 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentCancelRegion(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
7800
7801 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
7802 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
7803}
7804
7805StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7806 Stmt *AStmt,
7807 SourceLocation StartLoc,
7808 SourceLocation EndLoc) {
7809 if (!AStmt)
7810 return StmtError();
7811
7812 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7812, __PRETTY_FUNCTION__))
;
7813
7814 setFunctionHasBranchProtectedScope();
7815
7816 // OpenMP [2.7.3, single Construct, Restrictions]
7817 // The copyprivate clause must not be used with the nowait clause.
7818 const OMPClause *Nowait = nullptr;
7819 const OMPClause *Copyprivate = nullptr;
7820 for (const OMPClause *Clause : Clauses) {
7821 if (Clause->getClauseKind() == OMPC_nowait)
7822 Nowait = Clause;
7823 else if (Clause->getClauseKind() == OMPC_copyprivate)
7824 Copyprivate = Clause;
7825 if (Copyprivate && Nowait) {
7826 Diag(Copyprivate->getBeginLoc(),
7827 diag::err_omp_single_copyprivate_with_nowait);
7828 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
7829 return StmtError();
7830 }
7831 }
7832
7833 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7834}
7835
7836StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
7837 SourceLocation StartLoc,
7838 SourceLocation EndLoc) {
7839 if (!AStmt)
7840 return StmtError();
7841
7842 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7842, __PRETTY_FUNCTION__))
;
7843
7844 setFunctionHasBranchProtectedScope();
7845
7846 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
7847}
7848
7849StmtResult Sema::ActOnOpenMPCriticalDirective(
7850 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
7851 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
7852 if (!AStmt)
7853 return StmtError();
7854
7855 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7855, __PRETTY_FUNCTION__))
;
7856
7857 bool ErrorFound = false;
7858 llvm::APSInt Hint;
7859 SourceLocation HintLoc;
7860 bool DependentHint = false;
7861 for (const OMPClause *C : Clauses) {
7862 if (C->getClauseKind() == OMPC_hint) {
7863 if (!DirName.getName()) {
7864 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
7865 ErrorFound = true;
7866 }
7867 Expr *E = cast<OMPHintClause>(C)->getHint();
7868 if (E->isTypeDependent() || E->isValueDependent() ||
7869 E->isInstantiationDependent()) {
7870 DependentHint = true;
7871 } else {
7872 Hint = E->EvaluateKnownConstInt(Context);
7873 HintLoc = C->getBeginLoc();
7874 }
7875 }
7876 }
7877 if (ErrorFound)
7878 return StmtError();
7879 const auto Pair = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCriticalWithHint(DirName);
7880 if (Pair.first && DirName.getName() && !DependentHint) {
7881 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
7882 Diag(StartLoc, diag::err_omp_critical_with_hint);
7883 if (HintLoc.isValid())
7884 Diag(HintLoc, diag::note_omp_critical_hint_here)
7885 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
7886 else
7887 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
7888 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
7889 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
7890 << 1
7891 << C->getHint()->EvaluateKnownConstInt(Context).toString(
7892 /*Radix=*/10, /*Signed=*/false);
7893 } else {
7894 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
7895 }
7896 }
7897 }
7898
7899 setFunctionHasBranchProtectedScope();
7900
7901 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
7902 Clauses, AStmt);
7903 if (!Pair.first && DirName.getName() && !DependentHint)
7904 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addCriticalWithHint(Dir, Hint);
7905 return Dir;
7906}
7907
7908StmtResult Sema::ActOnOpenMPParallelForDirective(
7909 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7910 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7911 if (!AStmt)
7912 return StmtError();
7913
7914 auto *CS = cast<CapturedStmt>(AStmt);
7915 // 1.2.2 OpenMP Language Terminology
7916 // Structured block - An executable statement with a single entry at the
7917 // top and a single exit at the bottom.
7918 // The point of exit cannot be a branch out of the structured block.
7919 // longjmp() and throw() must not violate the entry/exit criteria.
7920 CS->getCapturedDecl()->setNothrow();
7921
7922 OMPLoopDirective::HelperExprs B;
7923 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7924 // define the nested loops number.
7925 unsigned NestedLoopCount =
7926 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
7927 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
7928 VarsWithImplicitDSA, B);
7929 if (NestedLoopCount == 0)
7930 return StmtError();
7931
7932 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp parallel for loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7933, __PRETTY_FUNCTION__))
7933 "omp parallel for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp parallel for loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 7933, __PRETTY_FUNCTION__))
;
7934
7935 if (!CurContext->isDependentContext()) {
7936 // Finalize the clauses that need pre-built expressions for CodeGen.
7937 for (OMPClause *C : Clauses) {
7938 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7939 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7940 B.NumIterations, *this, CurScope,
7941 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
7942 return StmtError();
7943 }
7944 }
7945
7946 setFunctionHasBranchProtectedScope();
7947 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
7948 NestedLoopCount, Clauses, AStmt, B,
7949 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
7950}
7951
7952StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
7953 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7954 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7955 if (!AStmt)
7956 return StmtError();
7957
7958 auto *CS = cast<CapturedStmt>(AStmt);
7959 // 1.2.2 OpenMP Language Terminology
7960 // Structured block - An executable statement with a single entry at the
7961 // top and a single exit at the bottom.
7962 // The point of exit cannot be a branch out of the structured block.
7963 // longjmp() and throw() must not violate the entry/exit criteria.
7964 CS->getCapturedDecl()->setNothrow();
7965
7966 OMPLoopDirective::HelperExprs B;
7967 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7968 // define the nested loops number.
7969 unsigned NestedLoopCount =
7970 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
7971 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
7972 VarsWithImplicitDSA, B);
7973 if (NestedLoopCount == 0)
7974 return StmtError();
7975
7976 if (!CurContext->isDependentContext()) {
7977 // Finalize the clauses that need pre-built expressions for CodeGen.
7978 for (OMPClause *C : Clauses) {
7979 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7980 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7981 B.NumIterations, *this, CurScope,
7982 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
7983 return StmtError();
7984 }
7985 }
7986
7987 if (checkSimdlenSafelenSpecified(*this, Clauses))
7988 return StmtError();
7989
7990 setFunctionHasBranchProtectedScope();
7991 return OMPParallelForSimdDirective::Create(
7992 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7993}
7994
7995StmtResult
7996Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7997 Stmt *AStmt, SourceLocation StartLoc,
7998 SourceLocation EndLoc) {
7999 if (!AStmt)
8000 return StmtError();
8001
8002 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8002, __PRETTY_FUNCTION__))
;
8003 auto BaseStmt = AStmt;
8004 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
8005 BaseStmt = CS->getCapturedStmt();
8006 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
8007 auto S = C->children();
8008 if (S.begin() == S.end())
8009 return StmtError();
8010 // All associated statements must be '#pragma omp section' except for
8011 // the first one.
8012 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
8013 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8014 if (SectionStmt)
8015 Diag(SectionStmt->getBeginLoc(),
8016 diag::err_omp_parallel_sections_substmt_not_section);
8017 return StmtError();
8018 }
8019 cast<OMPSectionDirective>(SectionStmt)
8020 ->setHasCancel(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
8021 }
8022 } else {
8023 Diag(AStmt->getBeginLoc(),
8024 diag::err_omp_parallel_sections_not_compound_stmt);
8025 return StmtError();
8026 }
8027
8028 setFunctionHasBranchProtectedScope();
8029
8030 return OMPParallelSectionsDirective::Create(
8031 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
8032}
8033
8034StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8035 Stmt *AStmt, SourceLocation StartLoc,
8036 SourceLocation EndLoc) {
8037 if (!AStmt)
8038 return StmtError();
8039
8040 auto *CS = cast<CapturedStmt>(AStmt);
8041 // 1.2.2 OpenMP Language Terminology
8042 // Structured block - An executable statement with a single entry at the
8043 // top and a single exit at the bottom.
8044 // The point of exit cannot be a branch out of the structured block.
8045 // longjmp() and throw() must not violate the entry/exit criteria.
8046 CS->getCapturedDecl()->setNothrow();
8047
8048 setFunctionHasBranchProtectedScope();
8049
8050 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8051 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
8052}
8053
8054StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8055 SourceLocation EndLoc) {
8056 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8057}
8058
8059StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8060 SourceLocation EndLoc) {
8061 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8062}
8063
8064StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8065 SourceLocation EndLoc) {
8066 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8067}
8068
8069StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8070 Stmt *AStmt,
8071 SourceLocation StartLoc,
8072 SourceLocation EndLoc) {
8073 if (!AStmt)
8074 return StmtError();
8075
8076 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8076, __PRETTY_FUNCTION__))
;
8077
8078 setFunctionHasBranchProtectedScope();
8079
8080 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
8081 AStmt,
8082 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTaskgroupReductionRef());
8083}
8084
8085StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8086 SourceLocation StartLoc,
8087 SourceLocation EndLoc) {
8088 assert(Clauses.size() <= 1 && "Extra clauses in flush directive")((Clauses.size() <= 1 && "Extra clauses in flush directive"
) ? static_cast<void> (0) : __assert_fail ("Clauses.size() <= 1 && \"Extra clauses in flush directive\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8088, __PRETTY_FUNCTION__))
;
8089 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8090}
8091
8092StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8093 Stmt *AStmt,
8094 SourceLocation StartLoc,
8095 SourceLocation EndLoc) {
8096 const OMPClause *DependFound = nullptr;
8097 const OMPClause *DependSourceClause = nullptr;
8098 const OMPClause *DependSinkClause = nullptr;
8099 bool ErrorFound = false;
8100 const OMPThreadsClause *TC = nullptr;
8101 const OMPSIMDClause *SC = nullptr;
8102 for (const OMPClause *C : Clauses) {
8103 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8104 DependFound = C;
8105 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8106 if (DependSourceClause) {
8107 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
8108 << getOpenMPDirectiveName(OMPD_ordered)
8109 << getOpenMPClauseName(OMPC_depend) << 2;
8110 ErrorFound = true;
8111 } else {
8112 DependSourceClause = C;
8113 }
8114 if (DependSinkClause) {
8115 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
8116 << 0;
8117 ErrorFound = true;
8118 }
8119 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8120 if (DependSourceClause) {
8121 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
8122 << 1;
8123 ErrorFound = true;
8124 }
8125 DependSinkClause = C;
8126 }
8127 } else if (C->getClauseKind() == OMPC_threads) {
8128 TC = cast<OMPThreadsClause>(C);
8129 } else if (C->getClauseKind() == OMPC_simd) {
8130 SC = cast<OMPSIMDClause>(C);
8131 }
8132 }
8133 if (!ErrorFound && !SC &&
8134 isOpenMPSimdDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentDirective())) {
8135 // OpenMP [2.8.1,simd Construct, Restrictions]
8136 // An ordered construct with the simd clause is the only OpenMP construct
8137 // that can appear in the simd region.
8138 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
8139 ErrorFound = true;
8140 } else if (DependFound && (TC || SC)) {
8141 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
8142 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8143 ErrorFound = true;
8144 } else if (DependFound && !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first) {
8145 Diag(DependFound->getBeginLoc(),
8146 diag::err_omp_ordered_directive_without_param);
8147 ErrorFound = true;
8148 } else if (TC || Clauses.empty()) {
8149 if (const Expr *Param = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first) {
8150 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
8151 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8152 << (TC != nullptr);
8153 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
8154 ErrorFound = true;
8155 }
8156 }
8157 if ((!AStmt && !DependFound) || ErrorFound)
8158 return StmtError();
8159
8160 if (AStmt) {
8161 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8161, __PRETTY_FUNCTION__))
;
8162
8163 setFunctionHasBranchProtectedScope();
8164 }
8165
8166 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8167}
8168
8169namespace {
8170/// Helper class for checking expression in 'omp atomic [update]'
8171/// construct.
8172class OpenMPAtomicUpdateChecker {
8173 /// Error results for atomic update expressions.
8174 enum ExprAnalysisErrorCode {
8175 /// A statement is not an expression statement.
8176 NotAnExpression,
8177 /// Expression is not builtin binary or unary operation.
8178 NotABinaryOrUnaryExpression,
8179 /// Unary operation is not post-/pre- increment/decrement operation.
8180 NotAnUnaryIncDecExpression,
8181 /// An expression is not of scalar type.
8182 NotAScalarType,
8183 /// A binary operation is not an assignment operation.
8184 NotAnAssignmentOp,
8185 /// RHS part of the binary operation is not a binary expression.
8186 NotABinaryExpression,
8187 /// RHS part is not additive/multiplicative/shift/biwise binary
8188 /// expression.
8189 NotABinaryOperator,
8190 /// RHS binary operation does not have reference to the updated LHS
8191 /// part.
8192 NotAnUpdateExpression,
8193 /// No errors is found.
8194 NoError
8195 };
8196 /// Reference to Sema.
8197 Sema &SemaRef;
8198 /// A location for note diagnostics (when error is found).
8199 SourceLocation NoteLoc;
8200 /// 'x' lvalue part of the source atomic expression.
8201 Expr *X;
8202 /// 'expr' rvalue part of the source atomic expression.
8203 Expr *E;
8204 /// Helper expression of the form
8205 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8206 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8207 Expr *UpdateExpr;
8208 /// Is 'x' a LHS in a RHS part of full update expression. It is
8209 /// important for non-associative operations.
8210 bool IsXLHSInRHSPart;
8211 BinaryOperatorKind Op;
8212 SourceLocation OpLoc;
8213 /// true if the source expression is a postfix unary operation, false
8214 /// if it is a prefix unary operation.
8215 bool IsPostfixUpdate;
8216
8217public:
8218 OpenMPAtomicUpdateChecker(Sema &SemaRef)
8219 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
8220 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
8221 /// Check specified statement that it is suitable for 'atomic update'
8222 /// constructs and extract 'x', 'expr' and Operation from the original
8223 /// expression. If DiagId and NoteId == 0, then only check is performed
8224 /// without error notification.
8225 /// \param DiagId Diagnostic which should be emitted if error is found.
8226 /// \param NoteId Diagnostic note for the main error message.
8227 /// \return true if statement is not an update expression, false otherwise.
8228 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
8229 /// Return the 'x' lvalue part of the source atomic expression.
8230 Expr *getX() const { return X; }
8231 /// Return the 'expr' rvalue part of the source atomic expression.
8232 Expr *getExpr() const { return E; }
8233 /// Return the update expression used in calculation of the updated
8234 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8235 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8236 Expr *getUpdateExpr() const { return UpdateExpr; }
8237 /// Return true if 'x' is LHS in RHS part of full update expression,
8238 /// false otherwise.
8239 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8240
8241 /// true if the source expression is a postfix unary operation, false
8242 /// if it is a prefix unary operation.
8243 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8244
8245private:
8246 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8247 unsigned NoteId = 0);
8248};
8249} // namespace
8250
8251bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8252 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8253 ExprAnalysisErrorCode ErrorFound = NoError;
8254 SourceLocation ErrorLoc, NoteLoc;
8255 SourceRange ErrorRange, NoteRange;
8256 // Allowed constructs are:
8257 // x = x binop expr;
8258 // x = expr binop x;
8259 if (AtomicBinOp->getOpcode() == BO_Assign) {
8260 X = AtomicBinOp->getLHS();
8261 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
8262 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8263 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8264 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8265 AtomicInnerBinOp->isBitwiseOp()) {
8266 Op = AtomicInnerBinOp->getOpcode();
8267 OpLoc = AtomicInnerBinOp->getOperatorLoc();
8268 Expr *LHS = AtomicInnerBinOp->getLHS();
8269 Expr *RHS = AtomicInnerBinOp->getRHS();
8270 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8271 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8272 /*Canonical=*/true);
8273 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8274 /*Canonical=*/true);
8275 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8276 /*Canonical=*/true);
8277 if (XId == LHSId) {
8278 E = RHS;
8279 IsXLHSInRHSPart = true;
8280 } else if (XId == RHSId) {
8281 E = LHS;
8282 IsXLHSInRHSPart = false;
8283 } else {
8284 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8285 ErrorRange = AtomicInnerBinOp->getSourceRange();
8286 NoteLoc = X->getExprLoc();
8287 NoteRange = X->getSourceRange();
8288 ErrorFound = NotAnUpdateExpression;
8289 }
8290 } else {
8291 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8292 ErrorRange = AtomicInnerBinOp->getSourceRange();
8293 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8294 NoteRange = SourceRange(NoteLoc, NoteLoc);
8295 ErrorFound = NotABinaryOperator;
8296 }
8297 } else {
8298 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8299 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8300 ErrorFound = NotABinaryExpression;
8301 }
8302 } else {
8303 ErrorLoc = AtomicBinOp->getExprLoc();
8304 ErrorRange = AtomicBinOp->getSourceRange();
8305 NoteLoc = AtomicBinOp->getOperatorLoc();
8306 NoteRange = SourceRange(NoteLoc, NoteLoc);
8307 ErrorFound = NotAnAssignmentOp;
8308 }
8309 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
8310 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8311 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8312 return true;
8313 }
8314 if (SemaRef.CurContext->isDependentContext())
8315 E = X = UpdateExpr = nullptr;
8316 return ErrorFound != NoError;
8317}
8318
8319bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8320 unsigned NoteId) {
8321 ExprAnalysisErrorCode ErrorFound = NoError;
8322 SourceLocation ErrorLoc, NoteLoc;
8323 SourceRange ErrorRange, NoteRange;
8324 // Allowed constructs are:
8325 // x++;
8326 // x--;
8327 // ++x;
8328 // --x;
8329 // x binop= expr;
8330 // x = x binop expr;
8331 // x = expr binop x;
8332 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8333 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8334 if (AtomicBody->getType()->isScalarType() ||
8335 AtomicBody->isInstantiationDependent()) {
8336 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
8337 AtomicBody->IgnoreParenImpCasts())) {
8338 // Check for Compound Assignment Operation
8339 Op = BinaryOperator::getOpForCompoundAssignment(
8340 AtomicCompAssignOp->getOpcode());
8341 OpLoc = AtomicCompAssignOp->getOperatorLoc();
8342 E = AtomicCompAssignOp->getRHS();
8343 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
8344 IsXLHSInRHSPart = true;
8345 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8346 AtomicBody->IgnoreParenImpCasts())) {
8347 // Check for Binary Operation
8348 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
8349 return true;
8350 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
8351 AtomicBody->IgnoreParenImpCasts())) {
8352 // Check for Unary Operation
8353 if (AtomicUnaryOp->isIncrementDecrementOp()) {
8354 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
8355 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8356 OpLoc = AtomicUnaryOp->getOperatorLoc();
8357 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
8358 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8359 IsXLHSInRHSPart = true;
8360 } else {
8361 ErrorFound = NotAnUnaryIncDecExpression;
8362 ErrorLoc = AtomicUnaryOp->getExprLoc();
8363 ErrorRange = AtomicUnaryOp->getSourceRange();
8364 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8365 NoteRange = SourceRange(NoteLoc, NoteLoc);
8366 }
8367 } else if (!AtomicBody->isInstantiationDependent()) {
8368 ErrorFound = NotABinaryOrUnaryExpression;
8369 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8370 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8371 }
8372 } else {
8373 ErrorFound = NotAScalarType;
8374 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
8375 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8376 }
8377 } else {
8378 ErrorFound = NotAnExpression;
8379 NoteLoc = ErrorLoc = S->getBeginLoc();
8380 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8381 }
8382 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
8383 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8384 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8385 return true;
8386 }
8387 if (SemaRef.CurContext->isDependentContext())
8388 E = X = UpdateExpr = nullptr;
8389 if (ErrorFound == NoError && E && X) {
8390 // Build an update expression of form 'OpaqueValueExpr(x) binop
8391 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8392 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8393 auto *OVEX = new (SemaRef.getASTContext())
8394 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8395 auto *OVEExpr = new (SemaRef.getASTContext())
8396 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
8397 ExprResult Update =
8398 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8399 IsXLHSInRHSPart ? OVEExpr : OVEX);
8400 if (Update.isInvalid())
8401 return true;
8402 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8403 Sema::AA_Casting);
8404 if (Update.isInvalid())
8405 return true;
8406 UpdateExpr = Update.get();
8407 }
8408 return ErrorFound != NoError;
8409}
8410
8411StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8412 Stmt *AStmt,
8413 SourceLocation StartLoc,
8414 SourceLocation EndLoc) {
8415 if (!AStmt)
8416 return StmtError();
8417
8418 auto *CS = cast<CapturedStmt>(AStmt);
8419 // 1.2.2 OpenMP Language Terminology
8420 // Structured block - An executable statement with a single entry at the
8421 // top and a single exit at the bottom.
8422 // The point of exit cannot be a branch out of the structured block.
8423 // longjmp() and throw() must not violate the entry/exit criteria.
8424 OpenMPClauseKind AtomicKind = OMPC_unknown;
8425 SourceLocation AtomicKindLoc;
8426 for (const OMPClause *C : Clauses) {
8427 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
8428 C->getClauseKind() == OMPC_update ||
8429 C->getClauseKind() == OMPC_capture) {
8430 if (AtomicKind != OMPC_unknown) {
8431 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
8432 << SourceRange(C->getBeginLoc(), C->getEndLoc());
8433 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8434 << getOpenMPClauseName(AtomicKind);
8435 } else {
8436 AtomicKind = C->getClauseKind();
8437 AtomicKindLoc = C->getBeginLoc();
8438 }
8439 }
8440 }
8441
8442 Stmt *Body = CS->getCapturedStmt();
8443 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8444 Body = EWC->getSubExpr();
8445
8446 Expr *X = nullptr;
8447 Expr *V = nullptr;
8448 Expr *E = nullptr;
8449 Expr *UE = nullptr;
8450 bool IsXLHSInRHSPart = false;
8451 bool IsPostfixUpdate = false;
8452 // OpenMP [2.12.6, atomic Construct]
8453 // In the next expressions:
8454 // * x and v (as applicable) are both l-value expressions with scalar type.
8455 // * During the execution of an atomic region, multiple syntactic
8456 // occurrences of x must designate the same storage location.
8457 // * Neither of v and expr (as applicable) may access the storage location
8458 // designated by x.
8459 // * Neither of x and expr (as applicable) may access the storage location
8460 // designated by v.
8461 // * expr is an expression with scalar type.
8462 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8463 // * binop, binop=, ++, and -- are not overloaded operators.
8464 // * The expression x binop expr must be numerically equivalent to x binop
8465 // (expr). This requirement is satisfied if the operators in expr have
8466 // precedence greater than binop, or by using parentheses around expr or
8467 // subexpressions of expr.
8468 // * The expression expr binop x must be numerically equivalent to (expr)
8469 // binop x. This requirement is satisfied if the operators in expr have
8470 // precedence equal to or greater than binop, or by using parentheses around
8471 // expr or subexpressions of expr.
8472 // * For forms that allow multiple occurrences of x, the number of times
8473 // that x is evaluated is unspecified.
8474 if (AtomicKind == OMPC_read) {
8475 enum {
8476 NotAnExpression,
8477 NotAnAssignmentOp,
8478 NotAScalarType,
8479 NotAnLValue,
8480 NoError
8481 } ErrorFound = NoError;
8482 SourceLocation ErrorLoc, NoteLoc;
8483 SourceRange ErrorRange, NoteRange;
8484 // If clause is read:
8485 // v = x;
8486 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8487 const auto *AtomicBinOp =
8488 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8489 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8490 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8491 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8492 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8493 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8494 if (!X->isLValue() || !V->isLValue()) {
8495 const Expr *NotLValueExpr = X->isLValue() ? V : X;
8496 ErrorFound = NotAnLValue;
8497 ErrorLoc = AtomicBinOp->getExprLoc();
8498 ErrorRange = AtomicBinOp->getSourceRange();
8499 NoteLoc = NotLValueExpr->getExprLoc();
8500 NoteRange = NotLValueExpr->getSourceRange();
8501 }
8502 } else if (!X->isInstantiationDependent() ||
8503 !V->isInstantiationDependent()) {
8504 const Expr *NotScalarExpr =
8505 (X->isInstantiationDependent() || X->getType()->isScalarType())
8506 ? V
8507 : X;
8508 ErrorFound = NotAScalarType;
8509 ErrorLoc = AtomicBinOp->getExprLoc();
8510 ErrorRange = AtomicBinOp->getSourceRange();
8511 NoteLoc = NotScalarExpr->getExprLoc();
8512 NoteRange = NotScalarExpr->getSourceRange();
8513 }
8514 } else if (!AtomicBody->isInstantiationDependent()) {
8515 ErrorFound = NotAnAssignmentOp;
8516 ErrorLoc = AtomicBody->getExprLoc();
8517 ErrorRange = AtomicBody->getSourceRange();
8518 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8519 : AtomicBody->getExprLoc();
8520 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8521 : AtomicBody->getSourceRange();
8522 }
8523 } else {
8524 ErrorFound = NotAnExpression;
8525 NoteLoc = ErrorLoc = Body->getBeginLoc();
8526 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8527 }
8528 if (ErrorFound != NoError) {
8529 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8530 << ErrorRange;
8531 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8532 << NoteRange;
8533 return StmtError();
8534 }
8535 if (CurContext->isDependentContext())
8536 V = X = nullptr;
8537 } else if (AtomicKind == OMPC_write) {
8538 enum {
8539 NotAnExpression,
8540 NotAnAssignmentOp,
8541 NotAScalarType,
8542 NotAnLValue,
8543 NoError
8544 } ErrorFound = NoError;
8545 SourceLocation ErrorLoc, NoteLoc;
8546 SourceRange ErrorRange, NoteRange;
8547 // If clause is write:
8548 // x = expr;
8549 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8550 const auto *AtomicBinOp =
8551 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8552 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8553 X = AtomicBinOp->getLHS();
8554 E = AtomicBinOp->getRHS();
8555 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8556 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8557 if (!X->isLValue()) {
8558 ErrorFound = NotAnLValue;
8559 ErrorLoc = AtomicBinOp->getExprLoc();
8560 ErrorRange = AtomicBinOp->getSourceRange();
8561 NoteLoc = X->getExprLoc();
8562 NoteRange = X->getSourceRange();
8563 }
8564 } else if (!X->isInstantiationDependent() ||
8565 !E->isInstantiationDependent()) {
8566 const Expr *NotScalarExpr =
8567 (X->isInstantiationDependent() || X->getType()->isScalarType())
8568 ? E
8569 : X;
8570 ErrorFound = NotAScalarType;
8571 ErrorLoc = AtomicBinOp->getExprLoc();
8572 ErrorRange = AtomicBinOp->getSourceRange();
8573 NoteLoc = NotScalarExpr->getExprLoc();
8574 NoteRange = NotScalarExpr->getSourceRange();
8575 }
8576 } else if (!AtomicBody->isInstantiationDependent()) {
8577 ErrorFound = NotAnAssignmentOp;
8578 ErrorLoc = AtomicBody->getExprLoc();
8579 ErrorRange = AtomicBody->getSourceRange();
8580 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8581 : AtomicBody->getExprLoc();
8582 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8583 : AtomicBody->getSourceRange();
8584 }
8585 } else {
8586 ErrorFound = NotAnExpression;
8587 NoteLoc = ErrorLoc = Body->getBeginLoc();
8588 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8589 }
8590 if (ErrorFound != NoError) {
8591 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8592 << ErrorRange;
8593 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8594 << NoteRange;
8595 return StmtError();
8596 }
8597 if (CurContext->isDependentContext())
8598 E = X = nullptr;
8599 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
8600 // If clause is update:
8601 // x++;
8602 // x--;
8603 // ++x;
8604 // --x;
8605 // x binop= expr;
8606 // x = x binop expr;
8607 // x = expr binop x;
8608 OpenMPAtomicUpdateChecker Checker(*this);
8609 if (Checker.checkStatement(
8610 Body, (AtomicKind == OMPC_update)
8611 ? diag::err_omp_atomic_update_not_expression_statement
8612 : diag::err_omp_atomic_not_expression_statement,
8613 diag::note_omp_atomic_update))
8614 return StmtError();
8615 if (!CurContext->isDependentContext()) {
8616 E = Checker.getExpr();
8617 X = Checker.getX();
8618 UE = Checker.getUpdateExpr();
8619 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8620 }
8621 } else if (AtomicKind == OMPC_capture) {
8622 enum {
8623 NotAnAssignmentOp,
8624 NotACompoundStatement,
8625 NotTwoSubstatements,
8626 NotASpecificExpression,
8627 NoError
8628 } ErrorFound = NoError;
8629 SourceLocation ErrorLoc, NoteLoc;
8630 SourceRange ErrorRange, NoteRange;
8631 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8632 // If clause is a capture:
8633 // v = x++;
8634 // v = x--;
8635 // v = ++x;
8636 // v = --x;
8637 // v = x binop= expr;
8638 // v = x = x binop expr;
8639 // v = x = expr binop x;
8640 const auto *AtomicBinOp =
8641 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8642 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8643 V = AtomicBinOp->getLHS();
8644 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8645 OpenMPAtomicUpdateChecker Checker(*this);
8646 if (Checker.checkStatement(
8647 Body, diag::err_omp_atomic_capture_not_expression_statement,
8648 diag::note_omp_atomic_update))
8649 return StmtError();
8650 E = Checker.getExpr();
8651 X = Checker.getX();
8652 UE = Checker.getUpdateExpr();
8653 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8654 IsPostfixUpdate = Checker.isPostfixUpdate();
8655 } else if (!AtomicBody->isInstantiationDependent()) {
8656 ErrorLoc = AtomicBody->getExprLoc();
8657 ErrorRange = AtomicBody->getSourceRange();
8658 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8659 : AtomicBody->getExprLoc();
8660 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8661 : AtomicBody->getSourceRange();
8662 ErrorFound = NotAnAssignmentOp;
8663 }
8664 if (ErrorFound != NoError) {
8665 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
8666 << ErrorRange;
8667 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8668 return StmtError();
8669 }
8670 if (CurContext->isDependentContext())
8671 UE = V = E = X = nullptr;
8672 } else {
8673 // If clause is a capture:
8674 // { v = x; x = expr; }
8675 // { v = x; x++; }
8676 // { v = x; x--; }
8677 // { v = x; ++x; }
8678 // { v = x; --x; }
8679 // { v = x; x binop= expr; }
8680 // { v = x; x = x binop expr; }
8681 // { v = x; x = expr binop x; }
8682 // { x++; v = x; }
8683 // { x--; v = x; }
8684 // { ++x; v = x; }
8685 // { --x; v = x; }
8686 // { x binop= expr; v = x; }
8687 // { x = x binop expr; v = x; }
8688 // { x = expr binop x; v = x; }
8689 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
8690 // Check that this is { expr1; expr2; }
8691 if (CS->size() == 2) {
8692 Stmt *First = CS->body_front();
8693 Stmt *Second = CS->body_back();
8694 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
8695 First = EWC->getSubExpr()->IgnoreParenImpCasts();
8696 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
8697 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
8698 // Need to find what subexpression is 'v' and what is 'x'.
8699 OpenMPAtomicUpdateChecker Checker(*this);
8700 bool IsUpdateExprFound = !Checker.checkStatement(Second);
8701 BinaryOperator *BinOp = nullptr;
8702 if (IsUpdateExprFound) {
8703 BinOp = dyn_cast<BinaryOperator>(First);
8704 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8705 }
8706 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8707 // { v = x; x++; }
8708 // { v = x; x--; }
8709 // { v = x; ++x; }
8710 // { v = x; --x; }
8711 // { v = x; x binop= expr; }
8712 // { v = x; x = x binop expr; }
8713 // { v = x; x = expr binop x; }
8714 // Check that the first expression has form v = x.
8715 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
8716 llvm::FoldingSetNodeID XId, PossibleXId;
8717 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8718 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8719 IsUpdateExprFound = XId == PossibleXId;
8720 if (IsUpdateExprFound) {
8721 V = BinOp->getLHS();
8722 X = Checker.getX();
8723 E = Checker.getExpr();
8724 UE = Checker.getUpdateExpr();
8725 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8726 IsPostfixUpdate = true;
8727 }
8728 }
8729 if (!IsUpdateExprFound) {
8730 IsUpdateExprFound = !Checker.checkStatement(First);
8731 BinOp = nullptr;
8732 if (IsUpdateExprFound) {
8733 BinOp = dyn_cast<BinaryOperator>(Second);
8734 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8735 }
8736 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8737 // { x++; v = x; }
8738 // { x--; v = x; }
8739 // { ++x; v = x; }
8740 // { --x; v = x; }
8741 // { x binop= expr; v = x; }
8742 // { x = x binop expr; v = x; }
8743 // { x = expr binop x; v = x; }
8744 // Check that the second expression has form v = x.
8745 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
8746 llvm::FoldingSetNodeID XId, PossibleXId;
8747 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8748 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8749 IsUpdateExprFound = XId == PossibleXId;
8750 if (IsUpdateExprFound) {
8751 V = BinOp->getLHS();
8752 X = Checker.getX();
8753 E = Checker.getExpr();
8754 UE = Checker.getUpdateExpr();
8755 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8756 IsPostfixUpdate = false;
8757 }
8758 }
8759 }
8760 if (!IsUpdateExprFound) {
8761 // { v = x; x = expr; }
8762 auto *FirstExpr = dyn_cast<Expr>(First);
8763 auto *SecondExpr = dyn_cast<Expr>(Second);
8764 if (!FirstExpr || !SecondExpr ||
8765 !(FirstExpr->isInstantiationDependent() ||
8766 SecondExpr->isInstantiationDependent())) {
8767 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
8768 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
8769 ErrorFound = NotAnAssignmentOp;
8770 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
8771 : First->getBeginLoc();
8772 NoteRange = ErrorRange = FirstBinOp
8773 ? FirstBinOp->getSourceRange()
8774 : SourceRange(ErrorLoc, ErrorLoc);
8775 } else {
8776 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
8777 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
8778 ErrorFound = NotAnAssignmentOp;
8779 NoteLoc = ErrorLoc = SecondBinOp
8780 ? SecondBinOp->getOperatorLoc()
8781 : Second->getBeginLoc();
8782 NoteRange = ErrorRange =
8783 SecondBinOp ? SecondBinOp->getSourceRange()
8784 : SourceRange(ErrorLoc, ErrorLoc);
8785 } else {
8786 Expr *PossibleXRHSInFirst =
8787 FirstBinOp->getRHS()->IgnoreParenImpCasts();
8788 Expr *PossibleXLHSInSecond =
8789 SecondBinOp->getLHS()->IgnoreParenImpCasts();
8790 llvm::FoldingSetNodeID X1Id, X2Id;
8791 PossibleXRHSInFirst->Profile(X1Id, Context,
8792 /*Canonical=*/true);
8793 PossibleXLHSInSecond->Profile(X2Id, Context,
8794 /*Canonical=*/true);
8795 IsUpdateExprFound = X1Id == X2Id;
8796 if (IsUpdateExprFound) {
8797 V = FirstBinOp->getLHS();
8798 X = SecondBinOp->getLHS();
8799 E = SecondBinOp->getRHS();
8800 UE = nullptr;
8801 IsXLHSInRHSPart = false;
8802 IsPostfixUpdate = true;
8803 } else {
8804 ErrorFound = NotASpecificExpression;
8805 ErrorLoc = FirstBinOp->getExprLoc();
8806 ErrorRange = FirstBinOp->getSourceRange();
8807 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
8808 NoteRange = SecondBinOp->getRHS()->getSourceRange();
8809 }
8810 }
8811 }
8812 }
8813 }
8814 } else {
8815 NoteLoc = ErrorLoc = Body->getBeginLoc();
8816 NoteRange = ErrorRange =
8817 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
8818 ErrorFound = NotTwoSubstatements;
8819 }
8820 } else {
8821 NoteLoc = ErrorLoc = Body->getBeginLoc();
8822 NoteRange = ErrorRange =
8823 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
8824 ErrorFound = NotACompoundStatement;
8825 }
8826 if (ErrorFound != NoError) {
8827 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
8828 << ErrorRange;
8829 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8830 return StmtError();
8831 }
8832 if (CurContext->isDependentContext())
8833 UE = V = E = X = nullptr;
8834 }
8835 }
8836
8837 setFunctionHasBranchProtectedScope();
8838
8839 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8840 X, V, E, UE, IsXLHSInRHSPart,
8841 IsPostfixUpdate);
8842}
8843
8844StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8845 Stmt *AStmt,
8846 SourceLocation StartLoc,
8847 SourceLocation EndLoc) {
8848 if (!AStmt)
8849 return StmtError();
8850
8851 auto *CS = cast<CapturedStmt>(AStmt);
8852 // 1.2.2 OpenMP Language Terminology
8853 // Structured block - An executable statement with a single entry at the
8854 // top and a single exit at the bottom.
8855 // The point of exit cannot be a branch out of the structured block.
8856 // longjmp() and throw() must not violate the entry/exit criteria.
8857 CS->getCapturedDecl()->setNothrow();
8858 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
8859 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8860 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8861 // 1.2.2 OpenMP Language Terminology
8862 // Structured block - An executable statement with a single entry at the
8863 // top and a single exit at the bottom.
8864 // The point of exit cannot be a branch out of the structured block.
8865 // longjmp() and throw() must not violate the entry/exit criteria.
8866 CS->getCapturedDecl()->setNothrow();
8867 }
8868
8869 // OpenMP [2.16, Nesting of Regions]
8870 // If specified, a teams construct must be contained within a target
8871 // construct. That target construct must contain no statements or directives
8872 // outside of the teams construct.
8873 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasInnerTeamsRegion()) {
8874 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
8875 bool OMPTeamsFound = true;
8876 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
8877 auto I = CS->body_begin();
8878 while (I != CS->body_end()) {
8879 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
8880 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
8881 OMPTeamsFound) {
8882
8883 OMPTeamsFound = false;
8884 break;
8885 }
8886 ++I;
8887 }
8888 assert(I != CS->body_end() && "Not found statement")((I != CS->body_end() && "Not found statement") ? static_cast
<void> (0) : __assert_fail ("I != CS->body_end() && \"Not found statement\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8888, __PRETTY_FUNCTION__))
;
8889 S = *I;
8890 } else {
8891 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
8892 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
8893 }
8894 if (!OMPTeamsFound) {
8895 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
8896 Diag(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getInnerTeamsRegionLoc(),
8897 diag::note_omp_nested_teams_construct_here);
8898 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
8899 << isa<OMPExecutableDirective>(S);
8900 return StmtError();
8901 }
8902 }
8903
8904 setFunctionHasBranchProtectedScope();
8905
8906 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8907}
8908
8909StmtResult
8910Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8911 Stmt *AStmt, SourceLocation StartLoc,
8912 SourceLocation EndLoc) {
8913 if (!AStmt)
8914 return StmtError();
8915
8916 auto *CS = cast<CapturedStmt>(AStmt);
8917 // 1.2.2 OpenMP Language Terminology
8918 // Structured block - An executable statement with a single entry at the
8919 // top and a single exit at the bottom.
8920 // The point of exit cannot be a branch out of the structured block.
8921 // longjmp() and throw() must not violate the entry/exit criteria.
8922 CS->getCapturedDecl()->setNothrow();
8923 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
8924 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8925 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8926 // 1.2.2 OpenMP Language Terminology
8927 // Structured block - An executable statement with a single entry at the
8928 // top and a single exit at the bottom.
8929 // The point of exit cannot be a branch out of the structured block.
8930 // longjmp() and throw() must not violate the entry/exit criteria.
8931 CS->getCapturedDecl()->setNothrow();
8932 }
8933
8934 setFunctionHasBranchProtectedScope();
8935
8936 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8937 AStmt);
8938}
8939
8940StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
8941 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8942 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8943 if (!AStmt)
8944 return StmtError();
8945
8946 auto *CS = cast<CapturedStmt>(AStmt);
8947 // 1.2.2 OpenMP Language Terminology
8948 // Structured block - An executable statement with a single entry at the
8949 // top and a single exit at the bottom.
8950 // The point of exit cannot be a branch out of the structured block.
8951 // longjmp() and throw() must not violate the entry/exit criteria.
8952 CS->getCapturedDecl()->setNothrow();
8953 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8954 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8955 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8956 // 1.2.2 OpenMP Language Terminology
8957 // Structured block - An executable statement with a single entry at the
8958 // top and a single exit at the bottom.
8959 // The point of exit cannot be a branch out of the structured block.
8960 // longjmp() and throw() must not violate the entry/exit criteria.
8961 CS->getCapturedDecl()->setNothrow();
8962 }
8963
8964 OMPLoopDirective::HelperExprs B;
8965 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8966 // define the nested loops number.
8967 unsigned NestedLoopCount =
8968 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
8969 getOrderedNumberExpr(Clauses), CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
8970 VarsWithImplicitDSA, B);
8971 if (NestedLoopCount == 0)
8972 return StmtError();
8973
8974 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8975, __PRETTY_FUNCTION__))
8975 "omp target parallel for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 8975, __PRETTY_FUNCTION__))
;
8976
8977 if (!CurContext->isDependentContext()) {
8978 // Finalize the clauses that need pre-built expressions for CodeGen.
8979 for (OMPClause *C : Clauses) {
8980 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8981 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8982 B.NumIterations, *this, CurScope,
8983 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
8984 return StmtError();
8985 }
8986 }
8987
8988 setFunctionHasBranchProtectedScope();
8989 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
8990 NestedLoopCount, Clauses, AStmt,
8991 B, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
8992}
8993
8994/// Check for existence of a map clause in the list of clauses.
8995static bool hasClauses(ArrayRef<OMPClause *> Clauses,
8996 const OpenMPClauseKind K) {
8997 return llvm::any_of(
8998 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
8999}
9000
9001template <typename... Params>
9002static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9003 const Params... ClauseTypes) {
9004 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
9005}
9006
9007StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9008 Stmt *AStmt,
9009 SourceLocation StartLoc,
9010 SourceLocation EndLoc) {
9011 if (!AStmt)
9012 return StmtError();
9013
9014 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9014, __PRETTY_FUNCTION__))
;
9015
9016 // OpenMP [2.10.1, Restrictions, p. 97]
9017 // At least one map clause must appear on the directive.
9018 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9019 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9020 << "'map' or 'use_device_ptr'"
9021 << getOpenMPDirectiveName(OMPD_target_data);
9022 return StmtError();
9023 }
9024
9025 setFunctionHasBranchProtectedScope();
9026
9027 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9028 AStmt);
9029}
9030
9031StmtResult
9032Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9033 SourceLocation StartLoc,
9034 SourceLocation EndLoc, Stmt *AStmt) {
9035 if (!AStmt)
9036 return StmtError();
9037
9038 auto *CS = cast<CapturedStmt>(AStmt);
9039 // 1.2.2 OpenMP Language Terminology
9040 // Structured block - An executable statement with a single entry at the
9041 // top and a single exit at the bottom.
9042 // The point of exit cannot be a branch out of the structured block.
9043 // longjmp() and throw() must not violate the entry/exit criteria.
9044 CS->getCapturedDecl()->setNothrow();
9045 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9046 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9047 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9048 // 1.2.2 OpenMP Language Terminology
9049 // Structured block - An executable statement with a single entry at the
9050 // top and a single exit at the bottom.
9051 // The point of exit cannot be a branch out of the structured block.
9052 // longjmp() and throw() must not violate the entry/exit criteria.
9053 CS->getCapturedDecl()->setNothrow();
9054 }
9055
9056 // OpenMP [2.10.2, Restrictions, p. 99]
9057 // At least one map clause must appear on the directive.
9058 if (!hasClauses(Clauses, OMPC_map)) {
9059 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9060 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
9061 return StmtError();
9062 }
9063
9064 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9065 AStmt);
9066}
9067
9068StmtResult
9069Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9070 SourceLocation StartLoc,
9071 SourceLocation EndLoc, Stmt *AStmt) {
9072 if (!AStmt)
9073 return StmtError();
9074
9075 auto *CS = cast<CapturedStmt>(AStmt);
9076 // 1.2.2 OpenMP Language Terminology
9077 // Structured block - An executable statement with a single entry at the
9078 // top and a single exit at the bottom.
9079 // The point of exit cannot be a branch out of the structured block.
9080 // longjmp() and throw() must not violate the entry/exit criteria.
9081 CS->getCapturedDecl()->setNothrow();
9082 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9083 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9084 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9085 // 1.2.2 OpenMP Language Terminology
9086 // Structured block - An executable statement with a single entry at the
9087 // top and a single exit at the bottom.
9088 // The point of exit cannot be a branch out of the structured block.
9089 // longjmp() and throw() must not violate the entry/exit criteria.
9090 CS->getCapturedDecl()->setNothrow();
9091 }
9092
9093 // OpenMP [2.10.3, Restrictions, p. 102]
9094 // At least one map clause must appear on the directive.
9095 if (!hasClauses(Clauses, OMPC_map)) {
9096 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9097 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
9098 return StmtError();
9099 }
9100
9101 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9102 AStmt);
9103}
9104
9105StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9106 SourceLocation StartLoc,
9107 SourceLocation EndLoc,
9108 Stmt *AStmt) {
9109 if (!AStmt)
9110 return StmtError();
9111
9112 auto *CS = cast<CapturedStmt>(AStmt);
9113 // 1.2.2 OpenMP Language Terminology
9114 // Structured block - An executable statement with a single entry at the
9115 // top and a single exit at the bottom.
9116 // The point of exit cannot be a branch out of the structured block.
9117 // longjmp() and throw() must not violate the entry/exit criteria.
9118 CS->getCapturedDecl()->setNothrow();
9119 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9120 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9121 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9122 // 1.2.2 OpenMP Language Terminology
9123 // Structured block - An executable statement with a single entry at the
9124 // top and a single exit at the bottom.
9125 // The point of exit cannot be a branch out of the structured block.
9126 // longjmp() and throw() must not violate the entry/exit criteria.
9127 CS->getCapturedDecl()->setNothrow();
9128 }
9129
9130 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
9131 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9132 return StmtError();
9133 }
9134 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9135 AStmt);
9136}
9137
9138StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9139 Stmt *AStmt, SourceLocation StartLoc,
9140 SourceLocation EndLoc) {
9141 if (!AStmt)
9142 return StmtError();
9143
9144 auto *CS = cast<CapturedStmt>(AStmt);
9145 // 1.2.2 OpenMP Language Terminology
9146 // Structured block - An executable statement with a single entry at the
9147 // top and a single exit at the bottom.
9148 // The point of exit cannot be a branch out of the structured block.
9149 // longjmp() and throw() must not violate the entry/exit criteria.
9150 CS->getCapturedDecl()->setNothrow();
9151
9152 setFunctionHasBranchProtectedScope();
9153
9154 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentTeamsRegionLoc(StartLoc);
9155
9156 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9157}
9158
9159StmtResult
9160Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9161 SourceLocation EndLoc,
9162 OpenMPDirectiveKind CancelRegion) {
9163 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentNowaitRegion()) {
9164 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9165 return StmtError();
9166 }
9167 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentOrderedRegion()) {
9168 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9169 return StmtError();
9170 }
9171 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9172 CancelRegion);
9173}
9174
9175StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9176 SourceLocation StartLoc,
9177 SourceLocation EndLoc,
9178 OpenMPDirectiveKind CancelRegion) {
9179 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentNowaitRegion()) {
9180 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9181 return StmtError();
9182 }
9183 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentOrderedRegion()) {
9184 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9185 return StmtError();
9186 }
9187 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentCancelRegion(/*Cancel=*/true);
9188 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9189 CancelRegion);
9190}
9191
9192static bool checkGrainsizeNumTasksClauses(Sema &S,
9193 ArrayRef<OMPClause *> Clauses) {
9194 const OMPClause *PrevClause = nullptr;
9195 bool ErrorFound = false;
9196 for (const OMPClause *C : Clauses) {
9197 if (C->getClauseKind() == OMPC_grainsize ||
9198 C->getClauseKind() == OMPC_num_tasks) {
9199 if (!PrevClause)
9200 PrevClause = C;
9201 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
9202 S.Diag(C->getBeginLoc(),
9203 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9204 << getOpenMPClauseName(C->getClauseKind())
9205 << getOpenMPClauseName(PrevClause->getClauseKind());
9206 S.Diag(PrevClause->getBeginLoc(),
9207 diag::note_omp_previous_grainsize_num_tasks)
9208 << getOpenMPClauseName(PrevClause->getClauseKind());
9209 ErrorFound = true;
9210 }
9211 }
9212 }
9213 return ErrorFound;
9214}
9215
9216static bool checkReductionClauseWithNogroup(Sema &S,
9217 ArrayRef<OMPClause *> Clauses) {
9218 const OMPClause *ReductionClause = nullptr;
9219 const OMPClause *NogroupClause = nullptr;
9220 for (const OMPClause *C : Clauses) {
9221 if (C->getClauseKind() == OMPC_reduction) {
9222 ReductionClause = C;
9223 if (NogroupClause)
9224 break;
9225 continue;
9226 }
9227 if (C->getClauseKind() == OMPC_nogroup) {
9228 NogroupClause = C;
9229 if (ReductionClause)
9230 break;
9231 continue;
9232 }
9233 }
9234 if (ReductionClause && NogroupClause) {
9235 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9236 << SourceRange(NogroupClause->getBeginLoc(),
9237 NogroupClause->getEndLoc());
9238 return true;
9239 }
9240 return false;
9241}
9242
9243StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9244 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9245 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9246 if (!AStmt)
9247 return StmtError();
9248
9249 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9249, __PRETTY_FUNCTION__))
;
9250 OMPLoopDirective::HelperExprs B;
9251 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9252 // define the nested loops number.
9253 unsigned NestedLoopCount =
9254 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
9255 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9256 VarsWithImplicitDSA, B);
9257 if (NestedLoopCount == 0)
9258 return StmtError();
9259
9260 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9261, __PRETTY_FUNCTION__))
9261 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9261, __PRETTY_FUNCTION__))
;
9262
9263 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9264 // The grainsize clause and num_tasks clause are mutually exclusive and may
9265 // not appear on the same taskloop directive.
9266 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9267 return StmtError();
9268 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9269 // If a reduction clause is present on the taskloop directive, the nogroup
9270 // clause must not be specified.
9271 if (checkReductionClauseWithNogroup(*this, Clauses))
9272 return StmtError();
9273
9274 setFunctionHasBranchProtectedScope();
9275 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9276 NestedLoopCount, Clauses, AStmt, B);
9277}
9278
9279StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9280 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9281 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9282 if (!AStmt)
9283 return StmtError();
9284
9285 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9285, __PRETTY_FUNCTION__))
;
9286 OMPLoopDirective::HelperExprs B;
9287 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9288 // define the nested loops number.
9289 unsigned NestedLoopCount =
9290 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
9291 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9292 VarsWithImplicitDSA, B);
9293 if (NestedLoopCount == 0)
9294 return StmtError();
9295
9296 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9297, __PRETTY_FUNCTION__))
9297 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9297, __PRETTY_FUNCTION__))
;
9298
9299 if (!CurContext->isDependentContext()) {
9300 // Finalize the clauses that need pre-built expressions for CodeGen.
9301 for (OMPClause *C : Clauses) {
9302 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9303 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9304 B.NumIterations, *this, CurScope,
9305 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
9306 return StmtError();
9307 }
9308 }
9309
9310 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9311 // The grainsize clause and num_tasks clause are mutually exclusive and may
9312 // not appear on the same taskloop directive.
9313 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9314 return StmtError();
9315 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9316 // If a reduction clause is present on the taskloop directive, the nogroup
9317 // clause must not be specified.
9318 if (checkReductionClauseWithNogroup(*this, Clauses))
9319 return StmtError();
9320 if (checkSimdlenSafelenSpecified(*this, Clauses))
9321 return StmtError();
9322
9323 setFunctionHasBranchProtectedScope();
9324 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9325 NestedLoopCount, Clauses, AStmt, B);
9326}
9327
9328StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9329 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9330 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9331 if (!AStmt)
9332 return StmtError();
9333
9334 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9334, __PRETTY_FUNCTION__))
;
9335 OMPLoopDirective::HelperExprs B;
9336 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9337 // define the nested loops number.
9338 unsigned NestedLoopCount =
9339 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9340 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9341 VarsWithImplicitDSA, B);
9342 if (NestedLoopCount == 0)
9343 return StmtError();
9344
9345 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9346, __PRETTY_FUNCTION__))
9346 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9346, __PRETTY_FUNCTION__))
;
9347
9348 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9349 // The grainsize clause and num_tasks clause are mutually exclusive and may
9350 // not appear on the same taskloop directive.
9351 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9352 return StmtError();
9353 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9354 // If a reduction clause is present on the taskloop directive, the nogroup
9355 // clause must not be specified.
9356 if (checkReductionClauseWithNogroup(*this, Clauses))
9357 return StmtError();
9358
9359 setFunctionHasBranchProtectedScope();
9360 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9361 NestedLoopCount, Clauses, AStmt, B);
9362}
9363
9364StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9365 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9366 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9367 if (!AStmt)
9368 return StmtError();
9369
9370 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9370, __PRETTY_FUNCTION__))
;
9371 auto *CS = cast<CapturedStmt>(AStmt);
9372 // 1.2.2 OpenMP Language Terminology
9373 // Structured block - An executable statement with a single entry at the
9374 // top and a single exit at the bottom.
9375 // The point of exit cannot be a branch out of the structured block.
9376 // longjmp() and throw() must not violate the entry/exit criteria.
9377 CS->getCapturedDecl()->setNothrow();
9378 for (int ThisCaptureLevel =
9379 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9380 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9381 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9382 // 1.2.2 OpenMP Language Terminology
9383 // Structured block - An executable statement with a single entry at the
9384 // top and a single exit at the bottom.
9385 // The point of exit cannot be a branch out of the structured block.
9386 // longjmp() and throw() must not violate the entry/exit criteria.
9387 CS->getCapturedDecl()->setNothrow();
9388 }
9389
9390 OMPLoopDirective::HelperExprs B;
9391 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9392 // define the nested loops number.
9393 unsigned NestedLoopCount = checkOpenMPLoop(
9394 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9395 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9396 VarsWithImplicitDSA, B);
9397 if (NestedLoopCount == 0)
9398 return StmtError();
9399
9400 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9401, __PRETTY_FUNCTION__))
9401 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9401, __PRETTY_FUNCTION__))
;
9402
9403 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9404 // The grainsize clause and num_tasks clause are mutually exclusive and may
9405 // not appear on the same taskloop directive.
9406 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9407 return StmtError();
9408 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9409 // If a reduction clause is present on the taskloop directive, the nogroup
9410 // clause must not be specified.
9411 if (checkReductionClauseWithNogroup(*this, Clauses))
9412 return StmtError();
9413
9414 setFunctionHasBranchProtectedScope();
9415 return OMPParallelMasterTaskLoopDirective::Create(
9416 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9417}
9418
9419StmtResult Sema::ActOnOpenMPDistributeDirective(
9420 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9421 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9422 if (!AStmt)
9423 return StmtError();
9424
9425 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected")((isa<CapturedStmt>(AStmt) && "Captured statement expected"
) ? static_cast<void> (0) : __assert_fail ("isa<CapturedStmt>(AStmt) && \"Captured statement expected\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9425, __PRETTY_FUNCTION__))
;
9426 OMPLoopDirective::HelperExprs B;
9427 // In presence of clause 'collapse' with number of loops, it will
9428 // define the nested loops number.
9429 unsigned NestedLoopCount =
9430 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
9431 nullptr /*ordered not a clause on distribute*/, AStmt,
9432 *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
9433 if (NestedLoopCount == 0)
9434 return StmtError();
9435
9436 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9437, __PRETTY_FUNCTION__))
9437 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9437, __PRETTY_FUNCTION__))
;
9438
9439 setFunctionHasBranchProtectedScope();
9440 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9441 NestedLoopCount, Clauses, AStmt, B);
9442}
9443
9444StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9445 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9446 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9447 if (!AStmt)
9448 return StmtError();
9449
9450 auto *CS = cast<CapturedStmt>(AStmt);
9451 // 1.2.2 OpenMP Language Terminology
9452 // Structured block - An executable statement with a single entry at the
9453 // top and a single exit at the bottom.
9454 // The point of exit cannot be a branch out of the structured block.
9455 // longjmp() and throw() must not violate the entry/exit criteria.
9456 CS->getCapturedDecl()->setNothrow();
9457 for (int ThisCaptureLevel =
9458 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9459 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9460 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9461 // 1.2.2 OpenMP Language Terminology
9462 // Structured block - An executable statement with a single entry at the
9463 // top and a single exit at the bottom.
9464 // The point of exit cannot be a branch out of the structured block.
9465 // longjmp() and throw() must not violate the entry/exit criteria.
9466 CS->getCapturedDecl()->setNothrow();
9467 }
9468
9469 OMPLoopDirective::HelperExprs B;
9470 // In presence of clause 'collapse' with number of loops, it will
9471 // define the nested loops number.
9472 unsigned NestedLoopCount = checkOpenMPLoop(
9473 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
9474 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9475 VarsWithImplicitDSA, B);
9476 if (NestedLoopCount == 0)
9477 return StmtError();
9478
9479 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9480, __PRETTY_FUNCTION__))
9480 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9480, __PRETTY_FUNCTION__))
;
9481
9482 setFunctionHasBranchProtectedScope();
9483 return OMPDistributeParallelForDirective::Create(
9484 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9485 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
9486}
9487
9488StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
9489 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9490 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9491 if (!AStmt)
9492 return StmtError();
9493
9494 auto *CS = cast<CapturedStmt>(AStmt);
9495 // 1.2.2 OpenMP Language Terminology
9496 // Structured block - An executable statement with a single entry at the
9497 // top and a single exit at the bottom.
9498 // The point of exit cannot be a branch out of the structured block.
9499 // longjmp() and throw() must not violate the entry/exit criteria.
9500 CS->getCapturedDecl()->setNothrow();
9501 for (int ThisCaptureLevel =
9502 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
9503 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9504 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9505 // 1.2.2 OpenMP Language Terminology
9506 // Structured block - An executable statement with a single entry at the
9507 // top and a single exit at the bottom.
9508 // The point of exit cannot be a branch out of the structured block.
9509 // longjmp() and throw() must not violate the entry/exit criteria.
9510 CS->getCapturedDecl()->setNothrow();
9511 }
9512
9513 OMPLoopDirective::HelperExprs B;
9514 // In presence of clause 'collapse' with number of loops, it will
9515 // define the nested loops number.
9516 unsigned NestedLoopCount = checkOpenMPLoop(
9517 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
9518 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9519 VarsWithImplicitDSA, B);
9520 if (NestedLoopCount == 0)
9521 return StmtError();
9522
9523 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9524, __PRETTY_FUNCTION__))
9524 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9524, __PRETTY_FUNCTION__))
;
9525
9526 if (!CurContext->isDependentContext()) {
9527 // Finalize the clauses that need pre-built expressions for CodeGen.
9528 for (OMPClause *C : Clauses) {
9529 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9530 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9531 B.NumIterations, *this, CurScope,
9532 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
9533 return StmtError();
9534 }
9535 }
9536
9537 if (checkSimdlenSafelenSpecified(*this, Clauses))
9538 return StmtError();
9539
9540 setFunctionHasBranchProtectedScope();
9541 return OMPDistributeParallelForSimdDirective::Create(
9542 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9543}
9544
9545StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
9546 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9547 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9548 if (!AStmt)
9549 return StmtError();
9550
9551 auto *CS = cast<CapturedStmt>(AStmt);
9552 // 1.2.2 OpenMP Language Terminology
9553 // Structured block - An executable statement with a single entry at the
9554 // top and a single exit at the bottom.
9555 // The point of exit cannot be a branch out of the structured block.
9556 // longjmp() and throw() must not violate the entry/exit criteria.
9557 CS->getCapturedDecl()->setNothrow();
9558 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
9559 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9560 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9561 // 1.2.2 OpenMP Language Terminology
9562 // Structured block - An executable statement with a single entry at the
9563 // top and a single exit at the bottom.
9564 // The point of exit cannot be a branch out of the structured block.
9565 // longjmp() and throw() must not violate the entry/exit criteria.
9566 CS->getCapturedDecl()->setNothrow();
9567 }
9568
9569 OMPLoopDirective::HelperExprs B;
9570 // In presence of clause 'collapse' with number of loops, it will
9571 // define the nested loops number.
9572 unsigned NestedLoopCount =
9573 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
9574 nullptr /*ordered not a clause on distribute*/, CS, *this,
9575 *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
9576 if (NestedLoopCount == 0)
9577 return StmtError();
9578
9579 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9580, __PRETTY_FUNCTION__))
9580 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9580, __PRETTY_FUNCTION__))
;
9581
9582 if (!CurContext->isDependentContext()) {
9583 // Finalize the clauses that need pre-built expressions for CodeGen.
9584 for (OMPClause *C : Clauses) {
9585 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9586 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9587 B.NumIterations, *this, CurScope,
9588 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
9589 return StmtError();
9590 }
9591 }
9592
9593 if (checkSimdlenSafelenSpecified(*this, Clauses))
9594 return StmtError();
9595
9596 setFunctionHasBranchProtectedScope();
9597 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
9598 NestedLoopCount, Clauses, AStmt, B);
9599}
9600
9601StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
9602 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9603 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9604 if (!AStmt)
9605 return StmtError();
9606
9607 auto *CS = cast<CapturedStmt>(AStmt);
9608 // 1.2.2 OpenMP Language Terminology
9609 // Structured block - An executable statement with a single entry at the
9610 // top and a single exit at the bottom.
9611 // The point of exit cannot be a branch out of the structured block.
9612 // longjmp() and throw() must not violate the entry/exit criteria.
9613 CS->getCapturedDecl()->setNothrow();
9614 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9615 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9616 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9617 // 1.2.2 OpenMP Language Terminology
9618 // Structured block - An executable statement with a single entry at the
9619 // top and a single exit at the bottom.
9620 // The point of exit cannot be a branch out of the structured block.
9621 // longjmp() and throw() must not violate the entry/exit criteria.
9622 CS->getCapturedDecl()->setNothrow();
9623 }
9624
9625 OMPLoopDirective::HelperExprs B;
9626 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9627 // define the nested loops number.
9628 unsigned NestedLoopCount = checkOpenMPLoop(
9629 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
9630 getOrderedNumberExpr(Clauses), CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9631 VarsWithImplicitDSA, B);
9632 if (NestedLoopCount == 0)
9633 return StmtError();
9634
9635 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9636, __PRETTY_FUNCTION__))
9636 "omp target parallel for simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target parallel for simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target parallel for simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9636, __PRETTY_FUNCTION__))
;
9637
9638 if (!CurContext->isDependentContext()) {
9639 // Finalize the clauses that need pre-built expressions for CodeGen.
9640 for (OMPClause *C : Clauses) {
9641 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9642 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9643 B.NumIterations, *this, CurScope,
9644 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
9645 return StmtError();
9646 }
9647 }
9648 if (checkSimdlenSafelenSpecified(*this, Clauses))
9649 return StmtError();
9650
9651 setFunctionHasBranchProtectedScope();
9652 return OMPTargetParallelForSimdDirective::Create(
9653 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9654}
9655
9656StmtResult Sema::ActOnOpenMPTargetSimdDirective(
9657 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9658 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9659 if (!AStmt)
9660 return StmtError();
9661
9662 auto *CS = cast<CapturedStmt>(AStmt);
9663 // 1.2.2 OpenMP Language Terminology
9664 // Structured block - An executable statement with a single entry at the
9665 // top and a single exit at the bottom.
9666 // The point of exit cannot be a branch out of the structured block.
9667 // longjmp() and throw() must not violate the entry/exit criteria.
9668 CS->getCapturedDecl()->setNothrow();
9669 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
9670 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9671 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9672 // 1.2.2 OpenMP Language Terminology
9673 // Structured block - An executable statement with a single entry at the
9674 // top and a single exit at the bottom.
9675 // The point of exit cannot be a branch out of the structured block.
9676 // longjmp() and throw() must not violate the entry/exit criteria.
9677 CS->getCapturedDecl()->setNothrow();
9678 }
9679
9680 OMPLoopDirective::HelperExprs B;
9681 // In presence of clause 'collapse' with number of loops, it will define the
9682 // nested loops number.
9683 unsigned NestedLoopCount =
9684 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
9685 getOrderedNumberExpr(Clauses), CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9686 VarsWithImplicitDSA, B);
9687 if (NestedLoopCount == 0)
9688 return StmtError();
9689
9690 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target simd loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9691, __PRETTY_FUNCTION__))
9691 "omp target simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target simd loop exprs were not built") ? static_cast<
void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9691, __PRETTY_FUNCTION__))
;
9692
9693 if (!CurContext->isDependentContext()) {
9694 // Finalize the clauses that need pre-built expressions for CodeGen.
9695 for (OMPClause *C : Clauses) {
9696 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9697 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9698 B.NumIterations, *this, CurScope,
9699 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
9700 return StmtError();
9701 }
9702 }
9703
9704 if (checkSimdlenSafelenSpecified(*this, Clauses))
9705 return StmtError();
9706
9707 setFunctionHasBranchProtectedScope();
9708 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
9709 NestedLoopCount, Clauses, AStmt, B);
9710}
9711
9712StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
9713 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9714 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9715 if (!AStmt)
9716 return StmtError();
9717
9718 auto *CS = cast<CapturedStmt>(AStmt);
9719 // 1.2.2 OpenMP Language Terminology
9720 // Structured block - An executable statement with a single entry at the
9721 // top and a single exit at the bottom.
9722 // The point of exit cannot be a branch out of the structured block.
9723 // longjmp() and throw() must not violate the entry/exit criteria.
9724 CS->getCapturedDecl()->setNothrow();
9725 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
9726 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9727 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9728 // 1.2.2 OpenMP Language Terminology
9729 // Structured block - An executable statement with a single entry at the
9730 // top and a single exit at the bottom.
9731 // The point of exit cannot be a branch out of the structured block.
9732 // longjmp() and throw() must not violate the entry/exit criteria.
9733 CS->getCapturedDecl()->setNothrow();
9734 }
9735
9736 OMPLoopDirective::HelperExprs B;
9737 // In presence of clause 'collapse' with number of loops, it will
9738 // define the nested loops number.
9739 unsigned NestedLoopCount =
9740 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
9741 nullptr /*ordered not a clause on distribute*/, CS, *this,
9742 *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
9743 if (NestedLoopCount == 0)
9744 return StmtError();
9745
9746 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9747, __PRETTY_FUNCTION__))
9747 "omp teams distribute loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9747, __PRETTY_FUNCTION__))
;
9748
9749 setFunctionHasBranchProtectedScope();
9750
9751 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentTeamsRegionLoc(StartLoc);
9752
9753 return OMPTeamsDistributeDirective::Create(
9754 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9755}
9756
9757StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
9758 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9759 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9760 if (!AStmt)
9761 return StmtError();
9762
9763 auto *CS = cast<CapturedStmt>(AStmt);
9764 // 1.2.2 OpenMP Language Terminology
9765 // Structured block - An executable statement with a single entry at the
9766 // top and a single exit at the bottom.
9767 // The point of exit cannot be a branch out of the structured block.
9768 // longjmp() and throw() must not violate the entry/exit criteria.
9769 CS->getCapturedDecl()->setNothrow();
9770 for (int ThisCaptureLevel =
9771 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
9772 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9773 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9774 // 1.2.2 OpenMP Language Terminology
9775 // Structured block - An executable statement with a single entry at the
9776 // top and a single exit at the bottom.
9777 // The point of exit cannot be a branch out of the structured block.
9778 // longjmp() and throw() must not violate the entry/exit criteria.
9779 CS->getCapturedDecl()->setNothrow();
9780 }
9781
9782
9783 OMPLoopDirective::HelperExprs B;
9784 // In presence of clause 'collapse' with number of loops, it will
9785 // define the nested loops number.
9786 unsigned NestedLoopCount = checkOpenMPLoop(
9787 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
9788 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9789 VarsWithImplicitDSA, B);
9790
9791 if (NestedLoopCount == 0)
9792 return StmtError();
9793
9794 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9795, __PRETTY_FUNCTION__))
9795 "omp teams distribute simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp teams distribute simd loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9795, __PRETTY_FUNCTION__))
;
9796
9797 if (!CurContext->isDependentContext()) {
9798 // Finalize the clauses that need pre-built expressions for CodeGen.
9799 for (OMPClause *C : Clauses) {
9800 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9801 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9802 B.NumIterations, *this, CurScope,
9803 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
9804 return StmtError();
9805 }
9806 }
9807
9808 if (checkSimdlenSafelenSpecified(*this, Clauses))
9809 return StmtError();
9810
9811 setFunctionHasBranchProtectedScope();
9812
9813 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentTeamsRegionLoc(StartLoc);
9814
9815 return OMPTeamsDistributeSimdDirective::Create(
9816 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9817}
9818
9819StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
9820 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9821 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9822 if (!AStmt)
9823 return StmtError();
9824
9825 auto *CS = cast<CapturedStmt>(AStmt);
9826 // 1.2.2 OpenMP Language Terminology
9827 // Structured block - An executable statement with a single entry at the
9828 // top and a single exit at the bottom.
9829 // The point of exit cannot be a branch out of the structured block.
9830 // longjmp() and throw() must not violate the entry/exit criteria.
9831 CS->getCapturedDecl()->setNothrow();
9832
9833 for (int ThisCaptureLevel =
9834 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
9835 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9836 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9837 // 1.2.2 OpenMP Language Terminology
9838 // Structured block - An executable statement with a single entry at the
9839 // top and a single exit at the bottom.
9840 // The point of exit cannot be a branch out of the structured block.
9841 // longjmp() and throw() must not violate the entry/exit criteria.
9842 CS->getCapturedDecl()->setNothrow();
9843 }
9844
9845 OMPLoopDirective::HelperExprs B;
9846 // In presence of clause 'collapse' with number of loops, it will
9847 // define the nested loops number.
9848 unsigned NestedLoopCount = checkOpenMPLoop(
9849 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
9850 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9851 VarsWithImplicitDSA, B);
9852
9853 if (NestedLoopCount == 0)
9854 return StmtError();
9855
9856 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9857, __PRETTY_FUNCTION__))
9857 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9857, __PRETTY_FUNCTION__))
;
9858
9859 if (!CurContext->isDependentContext()) {
9860 // Finalize the clauses that need pre-built expressions for CodeGen.
9861 for (OMPClause *C : Clauses) {
9862 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9863 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9864 B.NumIterations, *this, CurScope,
9865 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
9866 return StmtError();
9867 }
9868 }
9869
9870 if (checkSimdlenSafelenSpecified(*this, Clauses))
9871 return StmtError();
9872
9873 setFunctionHasBranchProtectedScope();
9874
9875 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentTeamsRegionLoc(StartLoc);
9876
9877 return OMPTeamsDistributeParallelForSimdDirective::Create(
9878 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9879}
9880
9881StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
9882 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9883 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9884 if (!AStmt)
9885 return StmtError();
9886
9887 auto *CS = cast<CapturedStmt>(AStmt);
9888 // 1.2.2 OpenMP Language Terminology
9889 // Structured block - An executable statement with a single entry at the
9890 // top and a single exit at the bottom.
9891 // The point of exit cannot be a branch out of the structured block.
9892 // longjmp() and throw() must not violate the entry/exit criteria.
9893 CS->getCapturedDecl()->setNothrow();
9894
9895 for (int ThisCaptureLevel =
9896 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
9897 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9898 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9899 // 1.2.2 OpenMP Language Terminology
9900 // Structured block - An executable statement with a single entry at the
9901 // top and a single exit at the bottom.
9902 // The point of exit cannot be a branch out of the structured block.
9903 // longjmp() and throw() must not violate the entry/exit criteria.
9904 CS->getCapturedDecl()->setNothrow();
9905 }
9906
9907 OMPLoopDirective::HelperExprs B;
9908 // In presence of clause 'collapse' with number of loops, it will
9909 // define the nested loops number.
9910 unsigned NestedLoopCount = checkOpenMPLoop(
9911 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
9912 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9913 VarsWithImplicitDSA, B);
9914
9915 if (NestedLoopCount == 0)
9916 return StmtError();
9917
9918 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9919, __PRETTY_FUNCTION__))
9919 "omp for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp for loop exprs were not built") ? static_cast<void>
(0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9919, __PRETTY_FUNCTION__))
;
9920
9921 setFunctionHasBranchProtectedScope();
9922
9923 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setParentTeamsRegionLoc(StartLoc);
9924
9925 return OMPTeamsDistributeParallelForDirective::Create(
9926 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9927 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
9928}
9929
9930StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
9931 Stmt *AStmt,
9932 SourceLocation StartLoc,
9933 SourceLocation EndLoc) {
9934 if (!AStmt)
9935 return StmtError();
9936
9937 auto *CS = cast<CapturedStmt>(AStmt);
9938 // 1.2.2 OpenMP Language Terminology
9939 // Structured block - An executable statement with a single entry at the
9940 // top and a single exit at the bottom.
9941 // The point of exit cannot be a branch out of the structured block.
9942 // longjmp() and throw() must not violate the entry/exit criteria.
9943 CS->getCapturedDecl()->setNothrow();
9944
9945 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
9946 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9947 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9948 // 1.2.2 OpenMP Language Terminology
9949 // Structured block - An executable statement with a single entry at the
9950 // top and a single exit at the bottom.
9951 // The point of exit cannot be a branch out of the structured block.
9952 // longjmp() and throw() must not violate the entry/exit criteria.
9953 CS->getCapturedDecl()->setNothrow();
9954 }
9955 setFunctionHasBranchProtectedScope();
9956
9957 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
9958 AStmt);
9959}
9960
9961StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
9962 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9963 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9964 if (!AStmt)
9965 return StmtError();
9966
9967 auto *CS = cast<CapturedStmt>(AStmt);
9968 // 1.2.2 OpenMP Language Terminology
9969 // Structured block - An executable statement with a single entry at the
9970 // top and a single exit at the bottom.
9971 // The point of exit cannot be a branch out of the structured block.
9972 // longjmp() and throw() must not violate the entry/exit criteria.
9973 CS->getCapturedDecl()->setNothrow();
9974 for (int ThisCaptureLevel =
9975 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
9976 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9977 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9978 // 1.2.2 OpenMP Language Terminology
9979 // Structured block - An executable statement with a single entry at the
9980 // top and a single exit at the bottom.
9981 // The point of exit cannot be a branch out of the structured block.
9982 // longjmp() and throw() must not violate the entry/exit criteria.
9983 CS->getCapturedDecl()->setNothrow();
9984 }
9985
9986 OMPLoopDirective::HelperExprs B;
9987 // In presence of clause 'collapse' with number of loops, it will
9988 // define the nested loops number.
9989 unsigned NestedLoopCount = checkOpenMPLoop(
9990 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
9991 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
9992 VarsWithImplicitDSA, B);
9993 if (NestedLoopCount == 0)
9994 return StmtError();
9995
9996 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9997, __PRETTY_FUNCTION__))
9997 "omp target teams distribute loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute loop exprs were not built") ? static_cast
<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 9997, __PRETTY_FUNCTION__))
;
9998
9999 setFunctionHasBranchProtectedScope();
10000 return OMPTargetTeamsDistributeDirective::Create(
10001 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10002}
10003
10004StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10005 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10006 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10007 if (!AStmt)
10008 return StmtError();
10009
10010 auto *CS = cast<CapturedStmt>(AStmt);
10011 // 1.2.2 OpenMP Language Terminology
10012 // Structured block - An executable statement with a single entry at the
10013 // top and a single exit at the bottom.
10014 // The point of exit cannot be a branch out of the structured block.
10015 // longjmp() and throw() must not violate the entry/exit criteria.
10016 CS->getCapturedDecl()->setNothrow();
10017 for (int ThisCaptureLevel =
10018 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10019 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10020 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10021 // 1.2.2 OpenMP Language Terminology
10022 // Structured block - An executable statement with a single entry at the
10023 // top and a single exit at the bottom.
10024 // The point of exit cannot be a branch out of the structured block.
10025 // longjmp() and throw() must not violate the entry/exit criteria.
10026 CS->getCapturedDecl()->setNothrow();
10027 }
10028
10029 OMPLoopDirective::HelperExprs B;
10030 // In presence of clause 'collapse' with number of loops, it will
10031 // define the nested loops number.
10032 unsigned NestedLoopCount = checkOpenMPLoop(
10033 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10034 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
10035 VarsWithImplicitDSA, B);
10036 if (NestedLoopCount == 0)
10037 return StmtError();
10038
10039 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10040, __PRETTY_FUNCTION__))
10040 "omp target teams distribute parallel for loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10040, __PRETTY_FUNCTION__))
;
10041
10042 if (!CurContext->isDependentContext()) {
10043 // Finalize the clauses that need pre-built expressions for CodeGen.
10044 for (OMPClause *C : Clauses) {
10045 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10046 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10047 B.NumIterations, *this, CurScope,
10048 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
10049 return StmtError();
10050 }
10051 }
10052
10053 setFunctionHasBranchProtectedScope();
10054 return OMPTargetTeamsDistributeParallelForDirective::Create(
10055 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10056 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isCancelRegion());
10057}
10058
10059StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10060 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10061 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10062 if (!AStmt)
10063 return StmtError();
10064
10065 auto *CS = cast<CapturedStmt>(AStmt);
10066 // 1.2.2 OpenMP Language Terminology
10067 // Structured block - An executable statement with a single entry at the
10068 // top and a single exit at the bottom.
10069 // The point of exit cannot be a branch out of the structured block.
10070 // longjmp() and throw() must not violate the entry/exit criteria.
10071 CS->getCapturedDecl()->setNothrow();
10072 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10073 OMPD_target_teams_distribute_parallel_for_simd);
10074 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10075 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10076 // 1.2.2 OpenMP Language Terminology
10077 // Structured block - An executable statement with a single entry at the
10078 // top and a single exit at the bottom.
10079 // The point of exit cannot be a branch out of the structured block.
10080 // longjmp() and throw() must not violate the entry/exit criteria.
10081 CS->getCapturedDecl()->setNothrow();
10082 }
10083
10084 OMPLoopDirective::HelperExprs B;
10085 // In presence of clause 'collapse' with number of loops, it will
10086 // define the nested loops number.
10087 unsigned NestedLoopCount =
10088 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
10089 getCollapseNumberExpr(Clauses),
10090 nullptr /*ordered not a clause on distribute*/, CS, *this,
10091 *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VarsWithImplicitDSA, B);
10092 if (NestedLoopCount == 0)
10093 return StmtError();
10094
10095 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for simd loop exprs were not "
"built") ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for simd loop exprs were not \" \"built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10097, __PRETTY_FUNCTION__))
10096 "omp target teams distribute parallel for simd loop exprs were not "(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for simd loop exprs were not "
"built") ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for simd loop exprs were not \" \"built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10097, __PRETTY_FUNCTION__))
10097 "built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute parallel for simd loop exprs were not "
"built") ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute parallel for simd loop exprs were not \" \"built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10097, __PRETTY_FUNCTION__))
;
10098
10099 if (!CurContext->isDependentContext()) {
10100 // Finalize the clauses that need pre-built expressions for CodeGen.
10101 for (OMPClause *C : Clauses) {
10102 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10103 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10104 B.NumIterations, *this, CurScope,
10105 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
10106 return StmtError();
10107 }
10108 }
10109
10110 if (checkSimdlenSafelenSpecified(*this, Clauses))
10111 return StmtError();
10112
10113 setFunctionHasBranchProtectedScope();
10114 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10115 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10116}
10117
10118StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10119 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10120 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
10121 if (!AStmt)
10122 return StmtError();
10123
10124 auto *CS = cast<CapturedStmt>(AStmt);
10125 // 1.2.2 OpenMP Language Terminology
10126 // Structured block - An executable statement with a single entry at the
10127 // top and a single exit at the bottom.
10128 // The point of exit cannot be a branch out of the structured block.
10129 // longjmp() and throw() must not violate the entry/exit criteria.
10130 CS->getCapturedDecl()->setNothrow();
10131 for (int ThisCaptureLevel =
10132 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10133 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10134 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10135 // 1.2.2 OpenMP Language Terminology
10136 // Structured block - An executable statement with a single entry at the
10137 // top and a single exit at the bottom.
10138 // The point of exit cannot be a branch out of the structured block.
10139 // longjmp() and throw() must not violate the entry/exit criteria.
10140 CS->getCapturedDecl()->setNothrow();
10141 }
10142
10143 OMPLoopDirective::HelperExprs B;
10144 // In presence of clause 'collapse' with number of loops, it will
10145 // define the nested loops number.
10146 unsigned NestedLoopCount = checkOpenMPLoop(
10147 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
10148 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
,
10149 VarsWithImplicitDSA, B);
10150 if (NestedLoopCount == 0)
10151 return StmtError();
10152
10153 assert((CurContext->isDependentContext() || B.builtAll()) &&(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute simd loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10154, __PRETTY_FUNCTION__))
10154 "omp target teams distribute simd loop exprs were not built")(((CurContext->isDependentContext() || B.builtAll()) &&
"omp target teams distribute simd loop exprs were not built"
) ? static_cast<void> (0) : __assert_fail ("(CurContext->isDependentContext() || B.builtAll()) && \"omp target teams distribute simd loop exprs were not built\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10154, __PRETTY_FUNCTION__))
;
10155
10156 if (!CurContext->isDependentContext()) {
10157 // Finalize the clauses that need pre-built expressions for CodeGen.
10158 for (OMPClause *C : Clauses) {
10159 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10160 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10161 B.NumIterations, *this, CurScope,
10162 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
10163 return StmtError();
10164 }
10165 }
10166
10167 if (checkSimdlenSafelenSpecified(*this, Clauses))
10168 return StmtError();
10169
10170 setFunctionHasBranchProtectedScope();
10171 return OMPTargetTeamsDistributeSimdDirective::Create(
10172 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10173}
10174
10175OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
10176 SourceLocation StartLoc,
10177 SourceLocation LParenLoc,
10178 SourceLocation EndLoc) {
10179 OMPClause *Res = nullptr;
10180 switch (Kind) {
10181 case OMPC_final:
10182 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10183 break;
10184 case OMPC_num_threads:
10185 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10186 break;
10187 case OMPC_safelen:
10188 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10189 break;
10190 case OMPC_simdlen:
10191 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10192 break;
10193 case OMPC_allocator:
10194 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10195 break;
10196 case OMPC_collapse:
10197 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10198 break;
10199 case OMPC_ordered:
10200 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10201 break;
10202 case OMPC_device:
10203 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10204 break;
10205 case OMPC_num_teams:
10206 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10207 break;
10208 case OMPC_thread_limit:
10209 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10210 break;
10211 case OMPC_priority:
10212 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10213 break;
10214 case OMPC_grainsize:
10215 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10216 break;
10217 case OMPC_num_tasks:
10218 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10219 break;
10220 case OMPC_hint:
10221 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10222 break;
10223 case OMPC_if:
10224 case OMPC_default:
10225 case OMPC_proc_bind:
10226 case OMPC_schedule:
10227 case OMPC_private:
10228 case OMPC_firstprivate:
10229 case OMPC_lastprivate:
10230 case OMPC_shared:
10231 case OMPC_reduction:
10232 case OMPC_task_reduction:
10233 case OMPC_in_reduction:
10234 case OMPC_linear:
10235 case OMPC_aligned:
10236 case OMPC_copyin:
10237 case OMPC_copyprivate:
10238 case OMPC_nowait:
10239 case OMPC_untied:
10240 case OMPC_mergeable:
10241 case OMPC_threadprivate:
10242 case OMPC_allocate:
10243 case OMPC_flush:
10244 case OMPC_read:
10245 case OMPC_write:
10246 case OMPC_update:
10247 case OMPC_capture:
10248 case OMPC_seq_cst:
10249 case OMPC_depend:
10250 case OMPC_threads:
10251 case OMPC_simd:
10252 case OMPC_map:
10253 case OMPC_nogroup:
10254 case OMPC_dist_schedule:
10255 case OMPC_defaultmap:
10256 case OMPC_unknown:
10257 case OMPC_uniform:
10258 case OMPC_to:
10259 case OMPC_from:
10260 case OMPC_use_device_ptr:
10261 case OMPC_is_device_ptr:
10262 case OMPC_unified_address:
10263 case OMPC_unified_shared_memory:
10264 case OMPC_reverse_offload:
10265 case OMPC_dynamic_allocators:
10266 case OMPC_atomic_default_mem_order:
10267 case OMPC_device_type:
10268 case OMPC_match:
10269 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10269)
;
10270 }
10271 return Res;
10272}
10273
10274// An OpenMP directive such as 'target parallel' has two captured regions:
10275// for the 'target' and 'parallel' respectively. This function returns
10276// the region in which to capture expressions associated with a clause.
10277// A return value of OMPD_unknown signifies that the expression should not
10278// be captured.
10279static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
10280 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
10281 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
10282 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
10283 switch (CKind) {
10284 case OMPC_if:
10285 switch (DKind) {
10286 case OMPD_target_parallel:
10287 case OMPD_target_parallel_for:
10288 case OMPD_target_parallel_for_simd:
10289 // If this clause applies to the nested 'parallel' region, capture within
10290 // the 'target' region, otherwise do not capture.
10291 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10292 CaptureRegion = OMPD_target;
10293 break;
10294 case OMPD_target_teams_distribute_parallel_for:
10295 case OMPD_target_teams_distribute_parallel_for_simd:
10296 // If this clause applies to the nested 'parallel' region, capture within
10297 // the 'teams' region, otherwise do not capture.
10298 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10299 CaptureRegion = OMPD_teams;
10300 break;
10301 case OMPD_teams_distribute_parallel_for:
10302 case OMPD_teams_distribute_parallel_for_simd:
10303 CaptureRegion = OMPD_teams;
10304 break;
10305 case OMPD_target_update:
10306 case OMPD_target_enter_data:
10307 case OMPD_target_exit_data:
10308 CaptureRegion = OMPD_task;
10309 break;
10310 case OMPD_parallel_master_taskloop:
10311 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10312 CaptureRegion = OMPD_parallel;
10313 break;
10314 case OMPD_cancel:
10315 case OMPD_parallel:
10316 case OMPD_parallel_sections:
10317 case OMPD_parallel_for:
10318 case OMPD_parallel_for_simd:
10319 case OMPD_target:
10320 case OMPD_target_simd:
10321 case OMPD_target_teams:
10322 case OMPD_target_teams_distribute:
10323 case OMPD_target_teams_distribute_simd:
10324 case OMPD_distribute_parallel_for:
10325 case OMPD_distribute_parallel_for_simd:
10326 case OMPD_task:
10327 case OMPD_taskloop:
10328 case OMPD_taskloop_simd:
10329 case OMPD_master_taskloop:
10330 case OMPD_target_data:
10331 // Do not capture if-clause expressions.
10332 break;
10333 case OMPD_threadprivate:
10334 case OMPD_allocate:
10335 case OMPD_taskyield:
10336 case OMPD_barrier:
10337 case OMPD_taskwait:
10338 case OMPD_cancellation_point:
10339 case OMPD_flush:
10340 case OMPD_declare_reduction:
10341 case OMPD_declare_mapper:
10342 case OMPD_declare_simd:
10343 case OMPD_declare_variant:
10344 case OMPD_declare_target:
10345 case OMPD_end_declare_target:
10346 case OMPD_teams:
10347 case OMPD_simd:
10348 case OMPD_for:
10349 case OMPD_for_simd:
10350 case OMPD_sections:
10351 case OMPD_section:
10352 case OMPD_single:
10353 case OMPD_master:
10354 case OMPD_critical:
10355 case OMPD_taskgroup:
10356 case OMPD_distribute:
10357 case OMPD_ordered:
10358 case OMPD_atomic:
10359 case OMPD_distribute_simd:
10360 case OMPD_teams_distribute:
10361 case OMPD_teams_distribute_simd:
10362 case OMPD_requires:
10363 llvm_unreachable("Unexpected OpenMP directive with if-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with if-clause"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10363)
;
10364 case OMPD_unknown:
10365 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10365)
;
10366 }
10367 break;
10368 case OMPC_num_threads:
10369 switch (DKind) {
10370 case OMPD_target_parallel:
10371 case OMPD_target_parallel_for:
10372 case OMPD_target_parallel_for_simd:
10373 CaptureRegion = OMPD_target;
10374 break;
10375 case OMPD_teams_distribute_parallel_for:
10376 case OMPD_teams_distribute_parallel_for_simd:
10377 case OMPD_target_teams_distribute_parallel_for:
10378 case OMPD_target_teams_distribute_parallel_for_simd:
10379 CaptureRegion = OMPD_teams;
10380 break;
10381 case OMPD_parallel:
10382 case OMPD_parallel_sections:
10383 case OMPD_parallel_for:
10384 case OMPD_parallel_for_simd:
10385 case OMPD_distribute_parallel_for:
10386 case OMPD_distribute_parallel_for_simd:
10387 case OMPD_parallel_master_taskloop:
10388 // Do not capture num_threads-clause expressions.
10389 break;
10390 case OMPD_target_data:
10391 case OMPD_target_enter_data:
10392 case OMPD_target_exit_data:
10393 case OMPD_target_update:
10394 case OMPD_target:
10395 case OMPD_target_simd:
10396 case OMPD_target_teams:
10397 case OMPD_target_teams_distribute:
10398 case OMPD_target_teams_distribute_simd:
10399 case OMPD_cancel:
10400 case OMPD_task:
10401 case OMPD_taskloop:
10402 case OMPD_taskloop_simd:
10403 case OMPD_master_taskloop:
10404 case OMPD_threadprivate:
10405 case OMPD_allocate:
10406 case OMPD_taskyield:
10407 case OMPD_barrier:
10408 case OMPD_taskwait:
10409 case OMPD_cancellation_point:
10410 case OMPD_flush:
10411 case OMPD_declare_reduction:
10412 case OMPD_declare_mapper:
10413 case OMPD_declare_simd:
10414 case OMPD_declare_variant:
10415 case OMPD_declare_target:
10416 case OMPD_end_declare_target:
10417 case OMPD_teams:
10418 case OMPD_simd:
10419 case OMPD_for:
10420 case OMPD_for_simd:
10421 case OMPD_sections:
10422 case OMPD_section:
10423 case OMPD_single:
10424 case OMPD_master:
10425 case OMPD_critical:
10426 case OMPD_taskgroup:
10427 case OMPD_distribute:
10428 case OMPD_ordered:
10429 case OMPD_atomic:
10430 case OMPD_distribute_simd:
10431 case OMPD_teams_distribute:
10432 case OMPD_teams_distribute_simd:
10433 case OMPD_requires:
10434 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with num_threads-clause"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10434)
;
10435 case OMPD_unknown:
10436 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10436)
;
10437 }
10438 break;
10439 case OMPC_num_teams:
10440 switch (DKind) {
10441 case OMPD_target_teams:
10442 case OMPD_target_teams_distribute:
10443 case OMPD_target_teams_distribute_simd:
10444 case OMPD_target_teams_distribute_parallel_for:
10445 case OMPD_target_teams_distribute_parallel_for_simd:
10446 CaptureRegion = OMPD_target;
10447 break;
10448 case OMPD_teams_distribute_parallel_for:
10449 case OMPD_teams_distribute_parallel_for_simd:
10450 case OMPD_teams:
10451 case OMPD_teams_distribute:
10452 case OMPD_teams_distribute_simd:
10453 // Do not capture num_teams-clause expressions.
10454 break;
10455 case OMPD_distribute_parallel_for:
10456 case OMPD_distribute_parallel_for_simd:
10457 case OMPD_task:
10458 case OMPD_taskloop:
10459 case OMPD_taskloop_simd:
10460 case OMPD_master_taskloop:
10461 case OMPD_parallel_master_taskloop:
10462 case OMPD_target_data:
10463 case OMPD_target_enter_data:
10464 case OMPD_target_exit_data:
10465 case OMPD_target_update:
10466 case OMPD_cancel:
10467 case OMPD_parallel:
10468 case OMPD_parallel_sections:
10469 case OMPD_parallel_for:
10470 case OMPD_parallel_for_simd:
10471 case OMPD_target:
10472 case OMPD_target_simd:
10473 case OMPD_target_parallel:
10474 case OMPD_target_parallel_for:
10475 case OMPD_target_parallel_for_simd:
10476 case OMPD_threadprivate:
10477 case OMPD_allocate:
10478 case OMPD_taskyield:
10479 case OMPD_barrier:
10480 case OMPD_taskwait:
10481 case OMPD_cancellation_point:
10482 case OMPD_flush:
10483 case OMPD_declare_reduction:
10484 case OMPD_declare_mapper:
10485 case OMPD_declare_simd:
10486 case OMPD_declare_variant:
10487 case OMPD_declare_target:
10488 case OMPD_end_declare_target:
10489 case OMPD_simd:
10490 case OMPD_for:
10491 case OMPD_for_simd:
10492 case OMPD_sections:
10493 case OMPD_section:
10494 case OMPD_single:
10495 case OMPD_master:
10496 case OMPD_critical:
10497 case OMPD_taskgroup:
10498 case OMPD_distribute:
10499 case OMPD_ordered:
10500 case OMPD_atomic:
10501 case OMPD_distribute_simd:
10502 case OMPD_requires:
10503 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with num_teams-clause"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10503)
;
10504 case OMPD_unknown:
10505 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10505)
;
10506 }
10507 break;
10508 case OMPC_thread_limit:
10509 switch (DKind) {
10510 case OMPD_target_teams:
10511 case OMPD_target_teams_distribute:
10512 case OMPD_target_teams_distribute_simd:
10513 case OMPD_target_teams_distribute_parallel_for:
10514 case OMPD_target_teams_distribute_parallel_for_simd:
10515 CaptureRegion = OMPD_target;
10516 break;
10517 case OMPD_teams_distribute_parallel_for:
10518 case OMPD_teams_distribute_parallel_for_simd:
10519 case OMPD_teams:
10520 case OMPD_teams_distribute:
10521 case OMPD_teams_distribute_simd:
10522 // Do not capture thread_limit-clause expressions.
10523 break;
10524 case OMPD_distribute_parallel_for:
10525 case OMPD_distribute_parallel_for_simd:
10526 case OMPD_task:
10527 case OMPD_taskloop:
10528 case OMPD_taskloop_simd:
10529 case OMPD_master_taskloop:
10530 case OMPD_parallel_master_taskloop:
10531 case OMPD_target_data:
10532 case OMPD_target_enter_data:
10533 case OMPD_target_exit_data:
10534 case OMPD_target_update:
10535 case OMPD_cancel:
10536 case OMPD_parallel:
10537 case OMPD_parallel_sections:
10538 case OMPD_parallel_for:
10539 case OMPD_parallel_for_simd:
10540 case OMPD_target:
10541 case OMPD_target_simd:
10542 case OMPD_target_parallel:
10543 case OMPD_target_parallel_for:
10544 case OMPD_target_parallel_for_simd:
10545 case OMPD_threadprivate:
10546 case OMPD_allocate:
10547 case OMPD_taskyield:
10548 case OMPD_barrier:
10549 case OMPD_taskwait:
10550 case OMPD_cancellation_point:
10551 case OMPD_flush:
10552 case OMPD_declare_reduction:
10553 case OMPD_declare_mapper:
10554 case OMPD_declare_simd:
10555 case OMPD_declare_variant:
10556 case OMPD_declare_target:
10557 case OMPD_end_declare_target:
10558 case OMPD_simd:
10559 case OMPD_for:
10560 case OMPD_for_simd:
10561 case OMPD_sections:
10562 case OMPD_section:
10563 case OMPD_single:
10564 case OMPD_master:
10565 case OMPD_critical:
10566 case OMPD_taskgroup:
10567 case OMPD_distribute:
10568 case OMPD_ordered:
10569 case OMPD_atomic:
10570 case OMPD_distribute_simd:
10571 case OMPD_requires:
10572 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with thread_limit-clause"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10572)
;
10573 case OMPD_unknown:
10574 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10574)
;
10575 }
10576 break;
10577 case OMPC_schedule:
10578 switch (DKind) {
10579 case OMPD_parallel_for:
10580 case OMPD_parallel_for_simd:
10581 case OMPD_distribute_parallel_for:
10582 case OMPD_distribute_parallel_for_simd:
10583 case OMPD_teams_distribute_parallel_for:
10584 case OMPD_teams_distribute_parallel_for_simd:
10585 case OMPD_target_parallel_for:
10586 case OMPD_target_parallel_for_simd:
10587 case OMPD_target_teams_distribute_parallel_for:
10588 case OMPD_target_teams_distribute_parallel_for_simd:
10589 CaptureRegion = OMPD_parallel;
10590 break;
10591 case OMPD_for:
10592 case OMPD_for_simd:
10593 // Do not capture schedule-clause expressions.
10594 break;
10595 case OMPD_task:
10596 case OMPD_taskloop:
10597 case OMPD_taskloop_simd:
10598 case OMPD_master_taskloop:
10599 case OMPD_parallel_master_taskloop:
10600 case OMPD_target_data:
10601 case OMPD_target_enter_data:
10602 case OMPD_target_exit_data:
10603 case OMPD_target_update:
10604 case OMPD_teams:
10605 case OMPD_teams_distribute:
10606 case OMPD_teams_distribute_simd:
10607 case OMPD_target_teams_distribute:
10608 case OMPD_target_teams_distribute_simd:
10609 case OMPD_target:
10610 case OMPD_target_simd:
10611 case OMPD_target_parallel:
10612 case OMPD_cancel:
10613 case OMPD_parallel:
10614 case OMPD_parallel_sections:
10615 case OMPD_threadprivate:
10616 case OMPD_allocate:
10617 case OMPD_taskyield:
10618 case OMPD_barrier:
10619 case OMPD_taskwait:
10620 case OMPD_cancellation_point:
10621 case OMPD_flush:
10622 case OMPD_declare_reduction:
10623 case OMPD_declare_mapper:
10624 case OMPD_declare_simd:
10625 case OMPD_declare_variant:
10626 case OMPD_declare_target:
10627 case OMPD_end_declare_target:
10628 case OMPD_simd:
10629 case OMPD_sections:
10630 case OMPD_section:
10631 case OMPD_single:
10632 case OMPD_master:
10633 case OMPD_critical:
10634 case OMPD_taskgroup:
10635 case OMPD_distribute:
10636 case OMPD_ordered:
10637 case OMPD_atomic:
10638 case OMPD_distribute_simd:
10639 case OMPD_target_teams:
10640 case OMPD_requires:
10641 llvm_unreachable("Unexpected OpenMP directive with schedule clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with schedule clause"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10641)
;
10642 case OMPD_unknown:
10643 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10643)
;
10644 }
10645 break;
10646 case OMPC_dist_schedule:
10647 switch (DKind) {
10648 case OMPD_teams_distribute_parallel_for:
10649 case OMPD_teams_distribute_parallel_for_simd:
10650 case OMPD_teams_distribute:
10651 case OMPD_teams_distribute_simd:
10652 case OMPD_target_teams_distribute_parallel_for:
10653 case OMPD_target_teams_distribute_parallel_for_simd:
10654 case OMPD_target_teams_distribute:
10655 case OMPD_target_teams_distribute_simd:
10656 CaptureRegion = OMPD_teams;
10657 break;
10658 case OMPD_distribute_parallel_for:
10659 case OMPD_distribute_parallel_for_simd:
10660 case OMPD_distribute:
10661 case OMPD_distribute_simd:
10662 // Do not capture thread_limit-clause expressions.
10663 break;
10664 case OMPD_parallel_for:
10665 case OMPD_parallel_for_simd:
10666 case OMPD_target_parallel_for_simd:
10667 case OMPD_target_parallel_for:
10668 case OMPD_task:
10669 case OMPD_taskloop:
10670 case OMPD_taskloop_simd:
10671 case OMPD_master_taskloop:
10672 case OMPD_parallel_master_taskloop:
10673 case OMPD_target_data:
10674 case OMPD_target_enter_data:
10675 case OMPD_target_exit_data:
10676 case OMPD_target_update:
10677 case OMPD_teams:
10678 case OMPD_target:
10679 case OMPD_target_simd:
10680 case OMPD_target_parallel:
10681 case OMPD_cancel:
10682 case OMPD_parallel:
10683 case OMPD_parallel_sections:
10684 case OMPD_threadprivate:
10685 case OMPD_allocate:
10686 case OMPD_taskyield:
10687 case OMPD_barrier:
10688 case OMPD_taskwait:
10689 case OMPD_cancellation_point:
10690 case OMPD_flush:
10691 case OMPD_declare_reduction:
10692 case OMPD_declare_mapper:
10693 case OMPD_declare_simd:
10694 case OMPD_declare_variant:
10695 case OMPD_declare_target:
10696 case OMPD_end_declare_target:
10697 case OMPD_simd:
10698 case OMPD_for:
10699 case OMPD_for_simd:
10700 case OMPD_sections:
10701 case OMPD_section:
10702 case OMPD_single:
10703 case OMPD_master:
10704 case OMPD_critical:
10705 case OMPD_taskgroup:
10706 case OMPD_ordered:
10707 case OMPD_atomic:
10708 case OMPD_target_teams:
10709 case OMPD_requires:
10710 llvm_unreachable("Unexpected OpenMP directive with schedule clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with schedule clause"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10710)
;
10711 case OMPD_unknown:
10712 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10712)
;
10713 }
10714 break;
10715 case OMPC_device:
10716 switch (DKind) {
10717 case OMPD_target_update:
10718 case OMPD_target_enter_data:
10719 case OMPD_target_exit_data:
10720 case OMPD_target:
10721 case OMPD_target_simd:
10722 case OMPD_target_teams:
10723 case OMPD_target_parallel:
10724 case OMPD_target_teams_distribute:
10725 case OMPD_target_teams_distribute_simd:
10726 case OMPD_target_parallel_for:
10727 case OMPD_target_parallel_for_simd:
10728 case OMPD_target_teams_distribute_parallel_for:
10729 case OMPD_target_teams_distribute_parallel_for_simd:
10730 CaptureRegion = OMPD_task;
10731 break;
10732 case OMPD_target_data:
10733 // Do not capture device-clause expressions.
10734 break;
10735 case OMPD_teams_distribute_parallel_for:
10736 case OMPD_teams_distribute_parallel_for_simd:
10737 case OMPD_teams:
10738 case OMPD_teams_distribute:
10739 case OMPD_teams_distribute_simd:
10740 case OMPD_distribute_parallel_for:
10741 case OMPD_distribute_parallel_for_simd:
10742 case OMPD_task:
10743 case OMPD_taskloop:
10744 case OMPD_taskloop_simd:
10745 case OMPD_master_taskloop:
10746 case OMPD_parallel_master_taskloop:
10747 case OMPD_cancel:
10748 case OMPD_parallel:
10749 case OMPD_parallel_sections:
10750 case OMPD_parallel_for:
10751 case OMPD_parallel_for_simd:
10752 case OMPD_threadprivate:
10753 case OMPD_allocate:
10754 case OMPD_taskyield:
10755 case OMPD_barrier:
10756 case OMPD_taskwait:
10757 case OMPD_cancellation_point:
10758 case OMPD_flush:
10759 case OMPD_declare_reduction:
10760 case OMPD_declare_mapper:
10761 case OMPD_declare_simd:
10762 case OMPD_declare_variant:
10763 case OMPD_declare_target:
10764 case OMPD_end_declare_target:
10765 case OMPD_simd:
10766 case OMPD_for:
10767 case OMPD_for_simd:
10768 case OMPD_sections:
10769 case OMPD_section:
10770 case OMPD_single:
10771 case OMPD_master:
10772 case OMPD_critical:
10773 case OMPD_taskgroup:
10774 case OMPD_distribute:
10775 case OMPD_ordered:
10776 case OMPD_atomic:
10777 case OMPD_distribute_simd:
10778 case OMPD_requires:
10779 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with num_teams-clause"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10779)
;
10780 case OMPD_unknown:
10781 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10781)
;
10782 }
10783 break;
10784 case OMPC_grainsize:
10785 case OMPC_num_tasks:
10786 switch (DKind) {
10787 case OMPD_task:
10788 case OMPD_taskloop:
10789 case OMPD_taskloop_simd:
10790 case OMPD_master_taskloop:
10791 break;
10792 case OMPD_parallel_master_taskloop:
10793 CaptureRegion = OMPD_parallel;
10794 break;
10795 case OMPD_target_update:
10796 case OMPD_target_enter_data:
10797 case OMPD_target_exit_data:
10798 case OMPD_target:
10799 case OMPD_target_simd:
10800 case OMPD_target_teams:
10801 case OMPD_target_parallel:
10802 case OMPD_target_teams_distribute:
10803 case OMPD_target_teams_distribute_simd:
10804 case OMPD_target_parallel_for:
10805 case OMPD_target_parallel_for_simd:
10806 case OMPD_target_teams_distribute_parallel_for:
10807 case OMPD_target_teams_distribute_parallel_for_simd:
10808 case OMPD_target_data:
10809 case OMPD_teams_distribute_parallel_for:
10810 case OMPD_teams_distribute_parallel_for_simd:
10811 case OMPD_teams:
10812 case OMPD_teams_distribute:
10813 case OMPD_teams_distribute_simd:
10814 case OMPD_distribute_parallel_for:
10815 case OMPD_distribute_parallel_for_simd:
10816 case OMPD_cancel:
10817 case OMPD_parallel:
10818 case OMPD_parallel_sections:
10819 case OMPD_parallel_for:
10820 case OMPD_parallel_for_simd:
10821 case OMPD_threadprivate:
10822 case OMPD_allocate:
10823 case OMPD_taskyield:
10824 case OMPD_barrier:
10825 case OMPD_taskwait:
10826 case OMPD_cancellation_point:
10827 case OMPD_flush:
10828 case OMPD_declare_reduction:
10829 case OMPD_declare_mapper:
10830 case OMPD_declare_simd:
10831 case OMPD_declare_variant:
10832 case OMPD_declare_target:
10833 case OMPD_end_declare_target:
10834 case OMPD_simd:
10835 case OMPD_for:
10836 case OMPD_for_simd:
10837 case OMPD_sections:
10838 case OMPD_section:
10839 case OMPD_single:
10840 case OMPD_master:
10841 case OMPD_critical:
10842 case OMPD_taskgroup:
10843 case OMPD_distribute:
10844 case OMPD_ordered:
10845 case OMPD_atomic:
10846 case OMPD_distribute_simd:
10847 case OMPD_requires:
10848 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause")::llvm::llvm_unreachable_internal("Unexpected OpenMP directive with grainsize-clause"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10848)
;
10849 case OMPD_unknown:
10850 llvm_unreachable("Unknown OpenMP directive")::llvm::llvm_unreachable_internal("Unknown OpenMP directive",
"/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10850)
;
10851 }
10852 break;
10853 case OMPC_firstprivate:
10854 case OMPC_lastprivate:
10855 case OMPC_reduction:
10856 case OMPC_task_reduction:
10857 case OMPC_in_reduction:
10858 case OMPC_linear:
10859 case OMPC_default:
10860 case OMPC_proc_bind:
10861 case OMPC_final:
10862 case OMPC_safelen:
10863 case OMPC_simdlen:
10864 case OMPC_allocator:
10865 case OMPC_collapse:
10866 case OMPC_private:
10867 case OMPC_shared:
10868 case OMPC_aligned:
10869 case OMPC_copyin:
10870 case OMPC_copyprivate:
10871 case OMPC_ordered:
10872 case OMPC_nowait:
10873 case OMPC_untied:
10874 case OMPC_mergeable:
10875 case OMPC_threadprivate:
10876 case OMPC_allocate:
10877 case OMPC_flush:
10878 case OMPC_read:
10879 case OMPC_write:
10880 case OMPC_update:
10881 case OMPC_capture:
10882 case OMPC_seq_cst:
10883 case OMPC_depend:
10884 case OMPC_threads:
10885 case OMPC_simd:
10886 case OMPC_map:
10887 case OMPC_priority:
10888 case OMPC_nogroup:
10889 case OMPC_hint:
10890 case OMPC_defaultmap:
10891 case OMPC_unknown:
10892 case OMPC_uniform:
10893 case OMPC_to:
10894 case OMPC_from:
10895 case OMPC_use_device_ptr:
10896 case OMPC_is_device_ptr:
10897 case OMPC_unified_address:
10898 case OMPC_unified_shared_memory:
10899 case OMPC_reverse_offload:
10900 case OMPC_dynamic_allocators:
10901 case OMPC_atomic_default_mem_order:
10902 case OMPC_device_type:
10903 case OMPC_match:
10904 llvm_unreachable("Unexpected OpenMP clause.")::llvm::llvm_unreachable_internal("Unexpected OpenMP clause."
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10904)
;
10905 }
10906 return CaptureRegion;
10907}
10908
10909OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10910 Expr *Condition, SourceLocation StartLoc,
10911 SourceLocation LParenLoc,
10912 SourceLocation NameModifierLoc,
10913 SourceLocation ColonLoc,
10914 SourceLocation EndLoc) {
10915 Expr *ValExpr = Condition;
10916 Stmt *HelperValStmt = nullptr;
10917 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
10918 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
10919 !Condition->isInstantiationDependent() &&
10920 !Condition->containsUnexpandedParameterPack()) {
10921 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
10922 if (Val.isInvalid())
10923 return nullptr;
10924
10925 ValExpr = Val.get();
10926
10927 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
10928 CaptureRegion =
10929 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
10930 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
10931 ValExpr = MakeFullExpr(ValExpr).get();
10932 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
10933 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10934 HelperValStmt = buildPreInits(Context, Captures);
10935 }
10936 }
10937
10938 return new (Context)
10939 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
10940 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
10941}
10942
10943OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
10944 SourceLocation StartLoc,
10945 SourceLocation LParenLoc,
10946 SourceLocation EndLoc) {
10947 Expr *ValExpr = Condition;
10948 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
10949 !Condition->isInstantiationDependent() &&
10950 !Condition->containsUnexpandedParameterPack()) {
10951 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
10952 if (Val.isInvalid())
10953 return nullptr;
10954
10955 ValExpr = MakeFullExpr(Val.get()).get();
10956 }
10957
10958 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10959}
10960ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
10961 Expr *Op) {
10962 if (!Op)
10963 return ExprError();
10964
10965 class IntConvertDiagnoser : public ICEConvertDiagnoser {
10966 public:
10967 IntConvertDiagnoser()
10968 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
10969 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10970 QualType T) override {
10971 return S.Diag(Loc, diag::err_omp_not_integral) << T;
10972 }
10973 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
10974 QualType T) override {
10975 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
10976 }
10977 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
10978 QualType T,
10979 QualType ConvTy) override {
10980 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
10981 }
10982 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
10983 QualType ConvTy) override {
10984 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
10985 << ConvTy->isEnumeralType() << ConvTy;
10986 }
10987 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10988 QualType T) override {
10989 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
10990 }
10991 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
10992 QualType ConvTy) override {
10993 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
10994 << ConvTy->isEnumeralType() << ConvTy;
10995 }
10996 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
10997 QualType) override {
10998 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 10998)
;
10999 }
11000 } ConvertDiagnoser;
11001 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11002}
11003
11004static bool
11005isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11006 bool StrictlyPositive, bool BuildCapture = false,
11007 OpenMPDirectiveKind DKind = OMPD_unknown,
11008 OpenMPDirectiveKind *CaptureRegion = nullptr,
11009 Stmt **HelperValStmt = nullptr) {
11010 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11011 !ValExpr->isInstantiationDependent()) {
11012 SourceLocation Loc = ValExpr->getExprLoc();
11013 ExprResult Value =
11014 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11015 if (Value.isInvalid())
11016 return false;
11017
11018 ValExpr = Value.get();
11019 // The expression must evaluate to a non-negative integer value.
11020 llvm::APSInt Result;
11021 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
11022 Result.isSigned() &&
11023 !((!StrictlyPositive && Result.isNonNegative()) ||
11024 (StrictlyPositive && Result.isStrictlyPositive()))) {
11025 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
11026 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11027 << ValExpr->getSourceRange();
11028 return false;
11029 }
11030 if (!BuildCapture)
11031 return true;
11032 *CaptureRegion = getOpenMPCaptureRegionForClause(DKind, CKind);
11033 if (*CaptureRegion != OMPD_unknown &&
11034 !SemaRef.CurContext->isDependentContext()) {
11035 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11036 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11037 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11038 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11039 }
11040 }
11041 return true;
11042}
11043
11044OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11045 SourceLocation StartLoc,
11046 SourceLocation LParenLoc,
11047 SourceLocation EndLoc) {
11048 Expr *ValExpr = NumThreads;
11049 Stmt *HelperValStmt = nullptr;
11050
11051 // OpenMP [2.5, Restrictions]
11052 // The num_threads expression must evaluate to a positive integer value.
11053 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
11054 /*StrictlyPositive=*/true))
11055 return nullptr;
11056
11057 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
11058 OpenMPDirectiveKind CaptureRegion =
11059 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
11060 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11061 ValExpr = MakeFullExpr(ValExpr).get();
11062 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11063 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11064 HelperValStmt = buildPreInits(Context, Captures);
11065 }
11066
11067 return new (Context) OMPNumThreadsClause(
11068 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
11069}
11070
11071ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
11072 OpenMPClauseKind CKind,
11073 bool StrictlyPositive) {
11074 if (!E)
11075 return ExprError();
11076 if (E->isValueDependent() || E->isTypeDependent() ||
11077 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
11078 return E;
11079 llvm::APSInt Result;
11080 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11081 if (ICE.isInvalid())
11082 return ExprError();
11083 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11084 (!StrictlyPositive && !Result.isNonNegative())) {
11085 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
11086 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11087 << E->getSourceRange();
11088 return ExprError();
11089 }
11090 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11091 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11092 << E->getSourceRange();
11093 return ExprError();
11094 }
11095 if (CKind == OMPC_collapse && DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops() == 1)
11096 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setAssociatedLoops(Result.getExtValue());
11097 else if (CKind == OMPC_ordered)
11098 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setAssociatedLoops(Result.getExtValue());
11099 return ICE;
11100}
11101
11102OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11103 SourceLocation LParenLoc,
11104 SourceLocation EndLoc) {
11105 // OpenMP [2.8.1, simd construct, Description]
11106 // The parameter of the safelen clause must be a constant
11107 // positive integer expression.
11108 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11109 if (Safelen.isInvalid())
11110 return nullptr;
11111 return new (Context)
11112 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
11113}
11114
11115OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11116 SourceLocation LParenLoc,
11117 SourceLocation EndLoc) {
11118 // OpenMP [2.8.1, simd construct, Description]
11119 // The parameter of the simdlen clause must be a constant
11120 // positive integer expression.
11121 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11122 if (Simdlen.isInvalid())
11123 return nullptr;
11124 return new (Context)
11125 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11126}
11127
11128/// Tries to find omp_allocator_handle_t type.
11129static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11130 DSAStackTy *Stack) {
11131 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
11132 if (!OMPAllocatorHandleT.isNull())
11133 return true;
11134 // Build the predefined allocator expressions.
11135 bool ErrorFound = false;
11136 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11137 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11138 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11139 StringRef Allocator =
11140 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11141 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11142 auto *VD = dyn_cast_or_null<ValueDecl>(
11143 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11144 if (!VD) {
11145 ErrorFound = true;
11146 break;
11147 }
11148 QualType AllocatorType =
11149 VD->getType().getNonLValueExprType(S.getASTContext());
11150 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11151 if (!Res.isUsable()) {
11152 ErrorFound = true;
11153 break;
11154 }
11155 if (OMPAllocatorHandleT.isNull())
11156 OMPAllocatorHandleT = AllocatorType;
11157 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11158 ErrorFound = true;
11159 break;
11160 }
11161 Stack->setAllocator(AllocatorKind, Res.get());
11162 }
11163 if (ErrorFound) {
11164 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11165 return false;
11166 }
11167 OMPAllocatorHandleT.addConst();
11168 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
11169 return true;
11170}
11171
11172OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11173 SourceLocation LParenLoc,
11174 SourceLocation EndLoc) {
11175 // OpenMP [2.11.3, allocate Directive, Description]
11176 // allocator is an expression of omp_allocator_handle_t type.
11177 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
11178 return nullptr;
11179
11180 ExprResult Allocator = DefaultLvalueConversion(A);
11181 if (Allocator.isInvalid())
11182 return nullptr;
11183 Allocator = PerformImplicitConversion(Allocator.get(),
11184 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getOMPAllocatorHandleT(),
11185 Sema::AA_Initializing,
11186 /*AllowExplicit=*/true);
11187 if (Allocator.isInvalid())
11188 return nullptr;
11189 return new (Context)
11190 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11191}
11192
11193OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11194 SourceLocation StartLoc,
11195 SourceLocation LParenLoc,
11196 SourceLocation EndLoc) {
11197 // OpenMP [2.7.1, loop construct, Description]
11198 // OpenMP [2.8.1, simd construct, Description]
11199 // OpenMP [2.9.6, distribute construct, Description]
11200 // The parameter of the collapse clause must be a constant
11201 // positive integer expression.
11202 ExprResult NumForLoopsResult =
11203 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11204 if (NumForLoopsResult.isInvalid())
11205 return nullptr;
11206 return new (Context)
11207 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
11208}
11209
11210OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11211 SourceLocation EndLoc,
11212 SourceLocation LParenLoc,
11213 Expr *NumForLoops) {
11214 // OpenMP [2.7.1, loop construct, Description]
11215 // OpenMP [2.8.1, simd construct, Description]
11216 // OpenMP [2.9.6, distribute construct, Description]
11217 // The parameter of the ordered clause must be a constant
11218 // positive integer expression if any.
11219 if (NumForLoops && LParenLoc.isValid()) {
11220 ExprResult NumForLoopsResult =
11221 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11222 if (NumForLoopsResult.isInvalid())
11223 return nullptr;
11224 NumForLoops = NumForLoopsResult.get();
11225 } else {
11226 NumForLoops = nullptr;
11227 }
11228 auto *Clause = OMPOrderedClause::Create(
11229 Context, NumForLoops, NumForLoops ? DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getAssociatedLoops() : 0,
11230 StartLoc, LParenLoc, EndLoc);
11231 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11232 return Clause;
11233}
11234
11235OMPClause *Sema::ActOnOpenMPSimpleClause(
11236 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11237 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11238 OMPClause *Res = nullptr;
11239 switch (Kind) {
11240 case OMPC_default:
11241 Res =
11242 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11243 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11244 break;
11245 case OMPC_proc_bind:
11246 Res = ActOnOpenMPProcBindClause(
11247 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
11248 LParenLoc, EndLoc);
11249 break;
11250 case OMPC_atomic_default_mem_order:
11251 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11252 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11253 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11254 break;
11255 case OMPC_if:
11256 case OMPC_final:
11257 case OMPC_num_threads:
11258 case OMPC_safelen:
11259 case OMPC_simdlen:
11260 case OMPC_allocator:
11261 case OMPC_collapse:
11262 case OMPC_schedule:
11263 case OMPC_private:
11264 case OMPC_firstprivate:
11265 case OMPC_lastprivate:
11266 case OMPC_shared:
11267 case OMPC_reduction:
11268 case OMPC_task_reduction:
11269 case OMPC_in_reduction:
11270 case OMPC_linear:
11271 case OMPC_aligned:
11272 case OMPC_copyin:
11273 case OMPC_copyprivate:
11274 case OMPC_ordered:
11275 case OMPC_nowait:
11276 case OMPC_untied:
11277 case OMPC_mergeable:
11278 case OMPC_threadprivate:
11279 case OMPC_allocate:
11280 case OMPC_flush:
11281 case OMPC_read:
11282 case OMPC_write:
11283 case OMPC_update:
11284 case OMPC_capture:
11285 case OMPC_seq_cst:
11286 case OMPC_depend:
11287 case OMPC_device:
11288 case OMPC_threads:
11289 case OMPC_simd:
11290 case OMPC_map:
11291 case OMPC_num_teams:
11292 case OMPC_thread_limit:
11293 case OMPC_priority:
11294 case OMPC_grainsize:
11295 case OMPC_nogroup:
11296 case OMPC_num_tasks:
11297 case OMPC_hint:
11298 case OMPC_dist_schedule:
11299 case OMPC_defaultmap:
11300 case OMPC_unknown:
11301 case OMPC_uniform:
11302 case OMPC_to:
11303 case OMPC_from:
11304 case OMPC_use_device_ptr:
11305 case OMPC_is_device_ptr:
11306 case OMPC_unified_address:
11307 case OMPC_unified_shared_memory:
11308 case OMPC_reverse_offload:
11309 case OMPC_dynamic_allocators:
11310 case OMPC_device_type:
11311 case OMPC_match:
11312 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11312)
;
11313 }
11314 return Res;
11315}
11316
11317static std::string
11318getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11319 ArrayRef<unsigned> Exclude = llvm::None) {
11320 SmallString<256> Buffer;
11321 llvm::raw_svector_ostream Out(Buffer);
11322 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11323 unsigned Skipped = Exclude.size();
11324 auto S = Exclude.begin(), E = Exclude.end();
11325 for (unsigned I = First; I < Last; ++I) {
11326 if (std::find(S, E, I) != E) {
11327 --Skipped;
11328 continue;
11329 }
11330 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11331 if (I == Bound - Skipped)
11332 Out << " or ";
11333 else if (I != Bound + 1 - Skipped)
11334 Out << ", ";
11335 }
11336 return Out.str();
11337}
11338
11339OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11340 SourceLocation KindKwLoc,
11341 SourceLocation StartLoc,
11342 SourceLocation LParenLoc,
11343 SourceLocation EndLoc) {
11344 if (Kind == OMPC_DEFAULT_unknown) {
11345 static_assert(OMPC_DEFAULT_unknown > 0,
11346 "OMPC_DEFAULT_unknown not greater than 0");
11347 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11348 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11349 /*Last=*/OMPC_DEFAULT_unknown)
11350 << getOpenMPClauseName(OMPC_default);
11351 return nullptr;
11352 }
11353 switch (Kind) {
11354 case OMPC_DEFAULT_none:
11355 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setDefaultDSANone(KindKwLoc);
11356 break;
11357 case OMPC_DEFAULT_shared:
11358 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setDefaultDSAShared(KindKwLoc);
11359 break;
11360 case OMPC_DEFAULT_unknown:
11361 llvm_unreachable("Clause kind is not allowed.")::llvm::llvm_unreachable_internal("Clause kind is not allowed."
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11361)
;
11362 break;
11363 }
11364 return new (Context)
11365 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
11366}
11367
11368OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11369 SourceLocation KindKwLoc,
11370 SourceLocation StartLoc,
11371 SourceLocation LParenLoc,
11372 SourceLocation EndLoc) {
11373 if (Kind == OMPC_PROC_BIND_unknown) {
11374 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11375 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11376 /*Last=*/OMPC_PROC_BIND_unknown)
11377 << getOpenMPClauseName(OMPC_proc_bind);
11378 return nullptr;
11379 }
11380 return new (Context)
11381 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
11382}
11383
11384OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
11385 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
11386 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11387 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
11388 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11389 << getListOfPossibleValues(
11390 OMPC_atomic_default_mem_order, /*First=*/0,
11391 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
11392 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
11393 return nullptr;
11394 }
11395 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
11396 LParenLoc, EndLoc);
11397}
11398
11399OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
11400 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
11401 SourceLocation StartLoc, SourceLocation LParenLoc,
11402 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
11403 SourceLocation EndLoc) {
11404 OMPClause *Res = nullptr;
11405 switch (Kind) {
11406 case OMPC_schedule:
11407 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
11408 assert(Argument.size() == NumberOfElements &&((Argument.size() == NumberOfElements && ArgumentLoc.
size() == NumberOfElements) ? static_cast<void> (0) : __assert_fail
("Argument.size() == NumberOfElements && ArgumentLoc.size() == NumberOfElements"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11409, __PRETTY_FUNCTION__))
11409 ArgumentLoc.size() == NumberOfElements)((Argument.size() == NumberOfElements && ArgumentLoc.
size() == NumberOfElements) ? static_cast<void> (0) : __assert_fail
("Argument.size() == NumberOfElements && ArgumentLoc.size() == NumberOfElements"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11409, __PRETTY_FUNCTION__))
;
11410 Res = ActOnOpenMPScheduleClause(
11411 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
11412 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
11413 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
11414 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
11415 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
11416 break;
11417 case OMPC_if:
11418 assert(Argument.size() == 1 && ArgumentLoc.size() == 1)((Argument.size() == 1 && ArgumentLoc.size() == 1) ? static_cast
<void> (0) : __assert_fail ("Argument.size() == 1 && ArgumentLoc.size() == 1"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11418, __PRETTY_FUNCTION__))
;
11419 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
11420 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
11421 DelimLoc, EndLoc);
11422 break;
11423 case OMPC_dist_schedule:
11424 Res = ActOnOpenMPDistScheduleClause(
11425 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
11426 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
11427 break;
11428 case OMPC_defaultmap:
11429 enum { Modifier, DefaultmapKind };
11430 Res = ActOnOpenMPDefaultmapClause(
11431 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
11432 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
11433 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
11434 EndLoc);
11435 break;
11436 case OMPC_final:
11437 case OMPC_num_threads:
11438 case OMPC_safelen:
11439 case OMPC_simdlen:
11440 case OMPC_allocator:
11441 case OMPC_collapse:
11442 case OMPC_default:
11443 case OMPC_proc_bind:
11444 case OMPC_private:
11445 case OMPC_firstprivate:
11446 case OMPC_lastprivate:
11447 case OMPC_shared:
11448 case OMPC_reduction:
11449 case OMPC_task_reduction:
11450 case OMPC_in_reduction:
11451 case OMPC_linear:
11452 case OMPC_aligned:
11453 case OMPC_copyin:
11454 case OMPC_copyprivate:
11455 case OMPC_ordered:
11456 case OMPC_nowait:
11457 case OMPC_untied:
11458 case OMPC_mergeable:
11459 case OMPC_threadprivate:
11460 case OMPC_allocate:
11461 case OMPC_flush:
11462 case OMPC_read:
11463 case OMPC_write:
11464 case OMPC_update:
11465 case OMPC_capture:
11466 case OMPC_seq_cst:
11467 case OMPC_depend:
11468 case OMPC_device:
11469 case OMPC_threads:
11470 case OMPC_simd:
11471 case OMPC_map:
11472 case OMPC_num_teams:
11473 case OMPC_thread_limit:
11474 case OMPC_priority:
11475 case OMPC_grainsize:
11476 case OMPC_nogroup:
11477 case OMPC_num_tasks:
11478 case OMPC_hint:
11479 case OMPC_unknown:
11480 case OMPC_uniform:
11481 case OMPC_to:
11482 case OMPC_from:
11483 case OMPC_use_device_ptr:
11484 case OMPC_is_device_ptr:
11485 case OMPC_unified_address:
11486 case OMPC_unified_shared_memory:
11487 case OMPC_reverse_offload:
11488 case OMPC_dynamic_allocators:
11489 case OMPC_atomic_default_mem_order:
11490 case OMPC_device_type:
11491 case OMPC_match:
11492 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11492)
;
11493 }
11494 return Res;
11495}
11496
11497static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
11498 OpenMPScheduleClauseModifier M2,
11499 SourceLocation M1Loc, SourceLocation M2Loc) {
11500 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
11501 SmallVector<unsigned, 2> Excluded;
11502 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
11503 Excluded.push_back(M2);
11504 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
11505 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
11506 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
11507 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
11508 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
11509 << getListOfPossibleValues(OMPC_schedule,
11510 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
11511 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11512 Excluded)
11513 << getOpenMPClauseName(OMPC_schedule);
11514 return true;
11515 }
11516 return false;
11517}
11518
11519OMPClause *Sema::ActOnOpenMPScheduleClause(
11520 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
11521 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11522 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11523 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
11524 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
11525 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
11526 return nullptr;
11527 // OpenMP, 2.7.1, Loop Construct, Restrictions
11528 // Either the monotonic modifier or the nonmonotonic modifier can be specified
11529 // but not both.
11530 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
11531 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
11532 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
11533 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
11534 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
11535 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
11536 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
11537 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
11538 return nullptr;
11539 }
11540 if (Kind == OMPC_SCHEDULE_unknown) {
11541 std::string Values;
11542 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
11543 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
11544 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11545 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11546 Exclude);
11547 } else {
11548 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11549 /*Last=*/OMPC_SCHEDULE_unknown);
11550 }
11551 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11552 << Values << getOpenMPClauseName(OMPC_schedule);
11553 return nullptr;
11554 }
11555 // OpenMP, 2.7.1, Loop Construct, Restrictions
11556 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
11557 // schedule(guided).
11558 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
11559 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
11560 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
11561 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
11562 diag::err_omp_schedule_nonmonotonic_static);
11563 return nullptr;
11564 }
11565 Expr *ValExpr = ChunkSize;
11566 Stmt *HelperValStmt = nullptr;
11567 if (ChunkSize) {
11568 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11569 !ChunkSize->isInstantiationDependent() &&
11570 !ChunkSize->containsUnexpandedParameterPack()) {
11571 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
11572 ExprResult Val =
11573 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11574 if (Val.isInvalid())
11575 return nullptr;
11576
11577 ValExpr = Val.get();
11578
11579 // OpenMP [2.7.1, Restrictions]
11580 // chunk_size must be a loop invariant integer expression with a positive
11581 // value.
11582 llvm::APSInt Result;
11583 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11584 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11585 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
11586 << "schedule" << 1 << ChunkSize->getSourceRange();
11587 return nullptr;
11588 }
11589 } else if (getOpenMPCaptureRegionForClause(
11590 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective(), OMPC_schedule) !=
11591 OMPD_unknown &&
11592 !CurContext->isDependentContext()) {
11593 ValExpr = MakeFullExpr(ValExpr).get();
11594 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11595 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11596 HelperValStmt = buildPreInits(Context, Captures);
11597 }
11598 }
11599 }
11600
11601 return new (Context)
11602 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
11603 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
11604}
11605
11606OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
11607 SourceLocation StartLoc,
11608 SourceLocation EndLoc) {
11609 OMPClause *Res = nullptr;
11610 switch (Kind) {
11611 case OMPC_ordered:
11612 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
11613 break;
11614 case OMPC_nowait:
11615 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
11616 break;
11617 case OMPC_untied:
11618 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
11619 break;
11620 case OMPC_mergeable:
11621 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
11622 break;
11623 case OMPC_read:
11624 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
11625 break;
11626 case OMPC_write:
11627 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
11628 break;
11629 case OMPC_update:
11630 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
11631 break;
11632 case OMPC_capture:
11633 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
11634 break;
11635 case OMPC_seq_cst:
11636 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
11637 break;
11638 case OMPC_threads:
11639 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
11640 break;
11641 case OMPC_simd:
11642 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
11643 break;
11644 case OMPC_nogroup:
11645 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
11646 break;
11647 case OMPC_unified_address:
11648 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
11649 break;
11650 case OMPC_unified_shared_memory:
11651 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11652 break;
11653 case OMPC_reverse_offload:
11654 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
11655 break;
11656 case OMPC_dynamic_allocators:
11657 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
11658 break;
11659 case OMPC_if:
11660 case OMPC_final:
11661 case OMPC_num_threads:
11662 case OMPC_safelen:
11663 case OMPC_simdlen:
11664 case OMPC_allocator:
11665 case OMPC_collapse:
11666 case OMPC_schedule:
11667 case OMPC_private:
11668 case OMPC_firstprivate:
11669 case OMPC_lastprivate:
11670 case OMPC_shared:
11671 case OMPC_reduction:
11672 case OMPC_task_reduction:
11673 case OMPC_in_reduction:
11674 case OMPC_linear:
11675 case OMPC_aligned:
11676 case OMPC_copyin:
11677 case OMPC_copyprivate:
11678 case OMPC_default:
11679 case OMPC_proc_bind:
11680 case OMPC_threadprivate:
11681 case OMPC_allocate:
11682 case OMPC_flush:
11683 case OMPC_depend:
11684 case OMPC_device:
11685 case OMPC_map:
11686 case OMPC_num_teams:
11687 case OMPC_thread_limit:
11688 case OMPC_priority:
11689 case OMPC_grainsize:
11690 case OMPC_num_tasks:
11691 case OMPC_hint:
11692 case OMPC_dist_schedule:
11693 case OMPC_defaultmap:
11694 case OMPC_unknown:
11695 case OMPC_uniform:
11696 case OMPC_to:
11697 case OMPC_from:
11698 case OMPC_use_device_ptr:
11699 case OMPC_is_device_ptr:
11700 case OMPC_atomic_default_mem_order:
11701 case OMPC_device_type:
11702 case OMPC_match:
11703 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11703)
;
11704 }
11705 return Res;
11706}
11707
11708OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11709 SourceLocation EndLoc) {
11710 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setNowaitRegion();
11711 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
11712}
11713
11714OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11715 SourceLocation EndLoc) {
11716 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
11717}
11718
11719OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11720 SourceLocation EndLoc) {
11721 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
11722}
11723
11724OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
11725 SourceLocation EndLoc) {
11726 return new (Context) OMPReadClause(StartLoc, EndLoc);
11727}
11728
11729OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
11730 SourceLocation EndLoc) {
11731 return new (Context) OMPWriteClause(StartLoc, EndLoc);
11732}
11733
11734OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11735 SourceLocation EndLoc) {
11736 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
11737}
11738
11739OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11740 SourceLocation EndLoc) {
11741 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
11742}
11743
11744OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11745 SourceLocation EndLoc) {
11746 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
11747}
11748
11749OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11750 SourceLocation EndLoc) {
11751 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
11752}
11753
11754OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11755 SourceLocation EndLoc) {
11756 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
11757}
11758
11759OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11760 SourceLocation EndLoc) {
11761 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
11762}
11763
11764OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11765 SourceLocation EndLoc) {
11766 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
11767}
11768
11769OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11770 SourceLocation EndLoc) {
11771 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11772}
11773
11774OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11775 SourceLocation EndLoc) {
11776 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
11777}
11778
11779OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11780 SourceLocation EndLoc) {
11781 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
11782}
11783
11784OMPClause *Sema::ActOnOpenMPVarListClause(
11785 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
11786 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
11787 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
11788 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
11789 OpenMPLinearClauseKind LinKind,
11790 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11791 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
11792 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
11793 SourceLocation StartLoc = Locs.StartLoc;
11794 SourceLocation LParenLoc = Locs.LParenLoc;
11795 SourceLocation EndLoc = Locs.EndLoc;
11796 OMPClause *Res = nullptr;
11797 switch (Kind) {
11798 case OMPC_private:
11799 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11800 break;
11801 case OMPC_firstprivate:
11802 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11803 break;
11804 case OMPC_lastprivate:
11805 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11806 break;
11807 case OMPC_shared:
11808 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
11809 break;
11810 case OMPC_reduction:
11811 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
11812 EndLoc, ReductionOrMapperIdScopeSpec,
11813 ReductionOrMapperId);
11814 break;
11815 case OMPC_task_reduction:
11816 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
11817 EndLoc, ReductionOrMapperIdScopeSpec,
11818 ReductionOrMapperId);
11819 break;
11820 case OMPC_in_reduction:
11821 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
11822 EndLoc, ReductionOrMapperIdScopeSpec,
11823 ReductionOrMapperId);
11824 break;
11825 case OMPC_linear:
11826 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
11827 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
11828 break;
11829 case OMPC_aligned:
11830 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
11831 ColonLoc, EndLoc);
11832 break;
11833 case OMPC_copyin:
11834 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
11835 break;
11836 case OMPC_copyprivate:
11837 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11838 break;
11839 case OMPC_flush:
11840 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
11841 break;
11842 case OMPC_depend:
11843 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
11844 StartLoc, LParenLoc, EndLoc);
11845 break;
11846 case OMPC_map:
11847 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
11848 ReductionOrMapperIdScopeSpec,
11849 ReductionOrMapperId, MapType, IsMapTypeImplicit,
11850 DepLinMapLoc, ColonLoc, VarList, Locs);
11851 break;
11852 case OMPC_to:
11853 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
11854 ReductionOrMapperId, Locs);
11855 break;
11856 case OMPC_from:
11857 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
11858 ReductionOrMapperId, Locs);
11859 break;
11860 case OMPC_use_device_ptr:
11861 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
11862 break;
11863 case OMPC_is_device_ptr:
11864 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
11865 break;
11866 case OMPC_allocate:
11867 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
11868 ColonLoc, EndLoc);
11869 break;
11870 case OMPC_if:
11871 case OMPC_final:
11872 case OMPC_num_threads:
11873 case OMPC_safelen:
11874 case OMPC_simdlen:
11875 case OMPC_allocator:
11876 case OMPC_collapse:
11877 case OMPC_default:
11878 case OMPC_proc_bind:
11879 case OMPC_schedule:
11880 case OMPC_ordered:
11881 case OMPC_nowait:
11882 case OMPC_untied:
11883 case OMPC_mergeable:
11884 case OMPC_threadprivate:
11885 case OMPC_read:
11886 case OMPC_write:
11887 case OMPC_update:
11888 case OMPC_capture:
11889 case OMPC_seq_cst:
11890 case OMPC_device:
11891 case OMPC_threads:
11892 case OMPC_simd:
11893 case OMPC_num_teams:
11894 case OMPC_thread_limit:
11895 case OMPC_priority:
11896 case OMPC_grainsize:
11897 case OMPC_nogroup:
11898 case OMPC_num_tasks:
11899 case OMPC_hint:
11900 case OMPC_dist_schedule:
11901 case OMPC_defaultmap:
11902 case OMPC_unknown:
11903 case OMPC_uniform:
11904 case OMPC_unified_address:
11905 case OMPC_unified_shared_memory:
11906 case OMPC_reverse_offload:
11907 case OMPC_dynamic_allocators:
11908 case OMPC_atomic_default_mem_order:
11909 case OMPC_device_type:
11910 case OMPC_match:
11911 llvm_unreachable("Clause is not allowed.")::llvm::llvm_unreachable_internal("Clause is not allowed.", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11911)
;
11912 }
11913 return Res;
11914}
11915
11916ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
11917 ExprObjectKind OK, SourceLocation Loc) {
11918 ExprResult Res = BuildDeclRefExpr(
11919 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
11920 if (!Res.isUsable())
11921 return ExprError();
11922 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
11923 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
11924 if (!Res.isUsable())
11925 return ExprError();
11926 }
11927 if (VK != VK_LValue && Res.get()->isGLValue()) {
11928 Res = DefaultLvalueConversion(Res.get());
11929 if (!Res.isUsable())
11930 return ExprError();
11931 }
11932 return Res;
11933}
11934
11935OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11936 SourceLocation StartLoc,
11937 SourceLocation LParenLoc,
11938 SourceLocation EndLoc) {
11939 SmallVector<Expr *, 8> Vars;
11940 SmallVector<Expr *, 8> PrivateCopies;
11941 for (Expr *RefExpr : VarList) {
11942 assert(RefExpr && "NULL expr in OpenMP private clause.")((RefExpr && "NULL expr in OpenMP private clause.") ?
static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP private clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 11942, __PRETTY_FUNCTION__))
;
11943 SourceLocation ELoc;
11944 SourceRange ERange;
11945 Expr *SimpleRefExpr = RefExpr;
11946 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11947 if (Res.second) {
11948 // It will be analyzed later.
11949 Vars.push_back(RefExpr);
11950 PrivateCopies.push_back(nullptr);
11951 }
11952 ValueDecl *D = Res.first;
11953 if (!D)
11954 continue;
11955
11956 QualType Type = D->getType();
11957 auto *VD = dyn_cast<VarDecl>(D);
11958
11959 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11960 // A variable that appears in a private clause must not have an incomplete
11961 // type or a reference type.
11962 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
11963 continue;
11964 Type = Type.getNonReferenceType();
11965
11966 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11967 // A variable that is privatized must not have a const-qualified type
11968 // unless it is of class type with a mutable member. This restriction does
11969 // not apply to the firstprivate clause.
11970 //
11971 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
11972 // A variable that appears in a private clause must not have a
11973 // const-qualified type unless it is of class type with a mutable member.
11974 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
11975 continue;
11976
11977 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11978 // in a Construct]
11979 // Variables with the predetermined data-sharing attributes may not be
11980 // listed in data-sharing attributes clauses, except for the cases
11981 // listed below. For these exceptions only, listing a predetermined
11982 // variable in a data-sharing attribute clause is allowed and overrides
11983 // the variable's predetermined data-sharing attributes.
11984 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
11985 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
11986 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11987 << getOpenMPClauseName(OMPC_private);
11988 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
11989 continue;
11990 }
11991
11992 OpenMPDirectiveKind CurrDir = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
11993 // Variably modified types are not supported for tasks.
11994 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
11995 isOpenMPTaskingDirective(CurrDir)) {
11996 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11997 << getOpenMPClauseName(OMPC_private) << Type
11998 << getOpenMPDirectiveName(CurrDir);
11999 bool IsDecl =
12000 !VD ||
12001 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12002 Diag(D->getLocation(),
12003 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12004 << D;
12005 continue;
12006 }
12007
12008 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12009 // A list item cannot appear in both a map clause and a data-sharing
12010 // attribute clause on the same construct
12011 //
12012 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12013 // A list item cannot appear in both a map clause and a data-sharing
12014 // attribute clause on the same construct unless the construct is a
12015 // combined construct.
12016 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12017 CurrDir == OMPD_target) {
12018 OpenMPClauseKind ConflictKind;
12019 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDecl(
12020 VD, /*CurrentRegionOnly=*/true,
12021 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12022 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12023 ConflictKind = WhereFoundClauseKind;
12024 return true;
12025 })) {
12026 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12027 << getOpenMPClauseName(OMPC_private)
12028 << getOpenMPClauseName(ConflictKind)
12029 << getOpenMPDirectiveName(CurrDir);
12030 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12031 continue;
12032 }
12033 }
12034
12035 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12036 // A variable of class type (or array thereof) that appears in a private
12037 // clause requires an accessible, unambiguous default constructor for the
12038 // class type.
12039 // Generate helper private variable and initialize it with the default
12040 // value. The address of the original variable is replaced by the address of
12041 // the new private variable in CodeGen. This new variable is not added to
12042 // IdResolver, so the code in the OpenMP region uses original variable for
12043 // proper diagnostics.
12044 Type = Type.getUnqualifiedType();
12045 VarDecl *VDPrivate =
12046 buildVarDecl(*this, ELoc, Type, D->getName(),
12047 D->hasAttrs() ? &D->getAttrs() : nullptr,
12048 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
12049 ActOnUninitializedDecl(VDPrivate);
12050 if (VDPrivate->isInvalidDecl())
12051 continue;
12052 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
12053 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12054
12055 DeclRefExpr *Ref = nullptr;
12056 if (!VD && !CurContext->isDependentContext())
12057 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
12058 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
12059 Vars.push_back((VD || CurContext->isDependentContext())
12060 ? RefExpr->IgnoreParens()
12061 : Ref);
12062 PrivateCopies.push_back(VDPrivateRefExpr);
12063 }
12064
12065 if (Vars.empty())
12066 return nullptr;
12067
12068 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12069 PrivateCopies);
12070}
12071
12072namespace {
12073class DiagsUninitializedSeveretyRAII {
12074private:
12075 DiagnosticsEngine &Diags;
12076 SourceLocation SavedLoc;
12077 bool IsIgnored = false;
12078
12079public:
12080 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12081 bool IsIgnored)
12082 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12083 if (!IsIgnored) {
12084 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12085 /*Map*/ diag::Severity::Ignored, Loc);
12086 }
12087 }
12088 ~DiagsUninitializedSeveretyRAII() {
12089 if (!IsIgnored)
12090 Diags.popMappings(SavedLoc);
12091 }
12092};
12093}
12094
12095OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12096 SourceLocation StartLoc,
12097 SourceLocation LParenLoc,
12098 SourceLocation EndLoc) {
12099 SmallVector<Expr *, 8> Vars;
12100 SmallVector<Expr *, 8> PrivateCopies;
12101 SmallVector<Expr *, 8> Inits;
12102 SmallVector<Decl *, 4> ExprCaptures;
12103 bool IsImplicitClause =
12104 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
12105 SourceLocation ImplicitClauseLoc = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getConstructLoc();
12106
12107 for (Expr *RefExpr : VarList) {
12108 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.")((RefExpr && "NULL expr in OpenMP firstprivate clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP firstprivate clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12108, __PRETTY_FUNCTION__))
;
12109 SourceLocation ELoc;
12110 SourceRange ERange;
12111 Expr *SimpleRefExpr = RefExpr;
12112 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12113 if (Res.second) {
12114 // It will be analyzed later.
12115 Vars.push_back(RefExpr);
12116 PrivateCopies.push_back(nullptr);
12117 Inits.push_back(nullptr);
12118 }
12119 ValueDecl *D = Res.first;
12120 if (!D)
12121 continue;
12122
12123 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
12124 QualType Type = D->getType();
12125 auto *VD = dyn_cast<VarDecl>(D);
12126
12127 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12128 // A variable that appears in a private clause must not have an incomplete
12129 // type or a reference type.
12130 if (RequireCompleteType(ELoc, Type,
12131 diag::err_omp_firstprivate_incomplete_type))
12132 continue;
12133 Type = Type.getNonReferenceType();
12134
12135 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12136 // A variable of class type (or array thereof) that appears in a private
12137 // clause requires an accessible, unambiguous copy constructor for the
12138 // class type.
12139 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12140
12141 // If an implicit firstprivate variable found it was checked already.
12142 DSAStackTy::DSAVarData TopDVar;
12143 if (!IsImplicitClause) {
12144 DSAStackTy::DSAVarData DVar =
12145 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
12146 TopDVar = DVar;
12147 OpenMPDirectiveKind CurrDir = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
12148 bool IsConstant = ElemType.isConstant(Context);
12149 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12150 // A list item that specifies a given variable may not appear in more
12151 // than one clause on the same directive, except that a variable may be
12152 // specified in both firstprivate and lastprivate clauses.
12153 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12154 // A list item may appear in a firstprivate or lastprivate clause but not
12155 // both.
12156 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
12157 (isOpenMPDistributeDirective(CurrDir) ||
12158 DVar.CKind != OMPC_lastprivate) &&
12159 DVar.RefExpr) {
12160 Diag(ELoc, diag::err_omp_wrong_dsa)
12161 << getOpenMPClauseName(DVar.CKind)
12162 << getOpenMPClauseName(OMPC_firstprivate);
12163 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12164 continue;
12165 }
12166
12167 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12168 // in a Construct]
12169 // Variables with the predetermined data-sharing attributes may not be
12170 // listed in data-sharing attributes clauses, except for the cases
12171 // listed below. For these exceptions only, listing a predetermined
12172 // variable in a data-sharing attribute clause is allowed and overrides
12173 // the variable's predetermined data-sharing attributes.
12174 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12175 // in a Construct, C/C++, p.2]
12176 // Variables with const-qualified type having no mutable member may be
12177 // listed in a firstprivate clause, even if they are static data members.
12178 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
12179 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12180 Diag(ELoc, diag::err_omp_wrong_dsa)
12181 << getOpenMPClauseName(DVar.CKind)
12182 << getOpenMPClauseName(OMPC_firstprivate);
12183 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12184 continue;
12185 }
12186
12187 // OpenMP [2.9.3.4, Restrictions, p.2]
12188 // A list item that is private within a parallel region must not appear
12189 // in a firstprivate clause on a worksharing construct if any of the
12190 // worksharing regions arising from the worksharing construct ever bind
12191 // to any of the parallel regions arising from the parallel construct.
12192 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12193 // A list item that is private within a teams region must not appear in a
12194 // firstprivate clause on a distribute construct if any of the distribute
12195 // regions arising from the distribute construct ever bind to any of the
12196 // teams regions arising from the teams construct.
12197 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12198 // A list item that appears in a reduction clause of a teams construct
12199 // must not appear in a firstprivate clause on a distribute construct if
12200 // any of the distribute regions arising from the distribute construct
12201 // ever bind to any of the teams regions arising from the teams construct.
12202 if ((isOpenMPWorksharingDirective(CurrDir) ||
12203 isOpenMPDistributeDirective(CurrDir)) &&
12204 !isOpenMPParallelDirective(CurrDir) &&
12205 !isOpenMPTeamsDirective(CurrDir)) {
12206 DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getImplicitDSA(D, true);
12207 if (DVar.CKind != OMPC_shared &&
12208 (isOpenMPParallelDirective(DVar.DKind) ||
12209 isOpenMPTeamsDirective(DVar.DKind) ||
12210 DVar.DKind == OMPD_unknown)) {
12211 Diag(ELoc, diag::err_omp_required_access)
12212 << getOpenMPClauseName(OMPC_firstprivate)
12213 << getOpenMPClauseName(OMPC_shared);
12214 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12215 continue;
12216 }
12217 }
12218 // OpenMP [2.9.3.4, Restrictions, p.3]
12219 // A list item that appears in a reduction clause of a parallel construct
12220 // must not appear in a firstprivate clause on a worksharing or task
12221 // construct if any of the worksharing or task regions arising from the
12222 // worksharing or task construct ever bind to any of the parallel regions
12223 // arising from the parallel construct.
12224 // OpenMP [2.9.3.4, Restrictions, p.4]
12225 // A list item that appears in a reduction clause in worksharing
12226 // construct must not appear in a firstprivate clause in a task construct
12227 // encountered during execution of any of the worksharing regions arising
12228 // from the worksharing construct.
12229 if (isOpenMPTaskingDirective(CurrDir)) {
12230 DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasInnermostDSA(
12231 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12232 [](OpenMPDirectiveKind K) {
12233 return isOpenMPParallelDirective(K) ||
12234 isOpenMPWorksharingDirective(K) ||
12235 isOpenMPTeamsDirective(K);
12236 },
12237 /*FromParent=*/true);
12238 if (DVar.CKind == OMPC_reduction &&
12239 (isOpenMPParallelDirective(DVar.DKind) ||
12240 isOpenMPWorksharingDirective(DVar.DKind) ||
12241 isOpenMPTeamsDirective(DVar.DKind))) {
12242 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12243 << getOpenMPDirectiveName(DVar.DKind);
12244 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12245 continue;
12246 }
12247 }
12248
12249 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12250 // A list item cannot appear in both a map clause and a data-sharing
12251 // attribute clause on the same construct
12252 //
12253 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12254 // A list item cannot appear in both a map clause and a data-sharing
12255 // attribute clause on the same construct unless the construct is a
12256 // combined construct.
12257 if ((LangOpts.OpenMP <= 45 &&
12258 isOpenMPTargetExecutionDirective(CurrDir)) ||
12259 CurrDir == OMPD_target) {
12260 OpenMPClauseKind ConflictKind;
12261 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDecl(
12262 VD, /*CurrentRegionOnly=*/true,
12263 [&ConflictKind](
12264 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12265 OpenMPClauseKind WhereFoundClauseKind) {
12266 ConflictKind = WhereFoundClauseKind;
12267 return true;
12268 })) {
12269 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
12270 << getOpenMPClauseName(OMPC_firstprivate)
12271 << getOpenMPClauseName(ConflictKind)
12272 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
12273 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12274 continue;
12275 }
12276 }
12277 }
12278
12279 // Variably modified types are not supported for tasks.
12280 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
12281 isOpenMPTaskingDirective(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective())) {
12282 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12283 << getOpenMPClauseName(OMPC_firstprivate) << Type
12284 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
12285 bool IsDecl =
12286 !VD ||
12287 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12288 Diag(D->getLocation(),
12289 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12290 << D;
12291 continue;
12292 }
12293
12294 Type = Type.getUnqualifiedType();
12295 VarDecl *VDPrivate =
12296 buildVarDecl(*this, ELoc, Type, D->getName(),
12297 D->hasAttrs() ? &D->getAttrs() : nullptr,
12298 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
12299 // Generate helper private variable and initialize it with the value of the
12300 // original variable. The address of the original variable is replaced by
12301 // the address of the new private variable in the CodeGen. This new variable
12302 // is not added to IdResolver, so the code in the OpenMP region uses
12303 // original variable for proper diagnostics and variable capturing.
12304 Expr *VDInitRefExpr = nullptr;
12305 // For arrays generate initializer for single element and replace it by the
12306 // original array element in CodeGen.
12307 if (Type->isArrayType()) {
12308 VarDecl *VDInit =
12309 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
12310 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
12311 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
12312 ElemType = ElemType.getUnqualifiedType();
12313 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12314 ".firstprivate.temp");
12315 InitializedEntity Entity =
12316 InitializedEntity::InitializeVariable(VDInitTemp);
12317 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12318
12319 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12320 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12321 if (Result.isInvalid())
12322 VDPrivate->setInvalidDecl();
12323 else
12324 VDPrivate->setInit(Result.getAs<Expr>());
12325 // Remove temp variable declaration.
12326 Context.Deallocate(VDInitTemp);
12327 } else {
12328 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12329 ".firstprivate.temp");
12330 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12331 RefExpr->getExprLoc());
12332 AddInitializerToDecl(VDPrivate,
12333 DefaultLvalueConversion(VDInitRefExpr).get(),
12334 /*DirectInit=*/false);
12335 }
12336 if (VDPrivate->isInvalidDecl()) {
12337 if (IsImplicitClause) {
12338 Diag(RefExpr->getExprLoc(),
12339 diag::note_omp_task_predetermined_firstprivate_here);
12340 }
12341 continue;
12342 }
12343 CurContext->addDecl(VDPrivate);
12344 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
12345 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12346 RefExpr->getExprLoc());
12347 DeclRefExpr *Ref = nullptr;
12348 if (!VD && !CurContext->isDependentContext()) {
12349 if (TopDVar.CKind == OMPC_lastprivate) {
12350 Ref = TopDVar.PrivateCopy;
12351 } else {
12352 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12353 if (!isOpenMPCapturedDecl(D))
12354 ExprCaptures.push_back(Ref->getDecl());
12355 }
12356 }
12357 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
12358 Vars.push_back((VD || CurContext->isDependentContext())
12359 ? RefExpr->IgnoreParens()
12360 : Ref);
12361 PrivateCopies.push_back(VDPrivateRefExpr);
12362 Inits.push_back(VDInitRefExpr);
12363 }
12364
12365 if (Vars.empty())
12366 return nullptr;
12367
12368 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12369 Vars, PrivateCopies, Inits,
12370 buildPreInits(Context, ExprCaptures));
12371}
12372
12373OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12374 SourceLocation StartLoc,
12375 SourceLocation LParenLoc,
12376 SourceLocation EndLoc) {
12377 SmallVector<Expr *, 8> Vars;
12378 SmallVector<Expr *, 8> SrcExprs;
12379 SmallVector<Expr *, 8> DstExprs;
12380 SmallVector<Expr *, 8> AssignmentOps;
12381 SmallVector<Decl *, 4> ExprCaptures;
12382 SmallVector<Expr *, 4> ExprPostUpdates;
12383 for (Expr *RefExpr : VarList) {
12384 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.")((RefExpr && "NULL expr in OpenMP lastprivate clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP lastprivate clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12384, __PRETTY_FUNCTION__))
;
12385 SourceLocation ELoc;
12386 SourceRange ERange;
12387 Expr *SimpleRefExpr = RefExpr;
12388 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12389 if (Res.second) {
12390 // It will be analyzed later.
12391 Vars.push_back(RefExpr);
12392 SrcExprs.push_back(nullptr);
12393 DstExprs.push_back(nullptr);
12394 AssignmentOps.push_back(nullptr);
12395 }
12396 ValueDecl *D = Res.first;
12397 if (!D)
12398 continue;
12399
12400 QualType Type = D->getType();
12401 auto *VD = dyn_cast<VarDecl>(D);
12402
12403 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
12404 // A variable that appears in a lastprivate clause must not have an
12405 // incomplete type or a reference type.
12406 if (RequireCompleteType(ELoc, Type,
12407 diag::err_omp_lastprivate_incomplete_type))
12408 continue;
12409 Type = Type.getNonReferenceType();
12410
12411 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12412 // A variable that is privatized must not have a const-qualified type
12413 // unless it is of class type with a mutable member. This restriction does
12414 // not apply to the firstprivate clause.
12415 //
12416 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
12417 // A variable that appears in a lastprivate clause must not have a
12418 // const-qualified type unless it is of class type with a mutable member.
12419 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
12420 continue;
12421
12422 OpenMPDirectiveKind CurrDir = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
12423 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12424 // in a Construct]
12425 // Variables with the predetermined data-sharing attributes may not be
12426 // listed in data-sharing attributes clauses, except for the cases
12427 // listed below.
12428 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12429 // A list item may appear in a firstprivate or lastprivate clause but not
12430 // both.
12431 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
12432 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
12433 (isOpenMPDistributeDirective(CurrDir) ||
12434 DVar.CKind != OMPC_firstprivate) &&
12435 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
12436 Diag(ELoc, diag::err_omp_wrong_dsa)
12437 << getOpenMPClauseName(DVar.CKind)
12438 << getOpenMPClauseName(OMPC_lastprivate);
12439 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12440 continue;
12441 }
12442
12443 // OpenMP [2.14.3.5, Restrictions, p.2]
12444 // A list item that is private within a parallel region, or that appears in
12445 // the reduction clause of a parallel construct, must not appear in a
12446 // lastprivate clause on a worksharing construct if any of the corresponding
12447 // worksharing regions ever binds to any of the corresponding parallel
12448 // regions.
12449 DSAStackTy::DSAVarData TopDVar = DVar;
12450 if (isOpenMPWorksharingDirective(CurrDir) &&
12451 !isOpenMPParallelDirective(CurrDir) &&
12452 !isOpenMPTeamsDirective(CurrDir)) {
12453 DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getImplicitDSA(D, true);
12454 if (DVar.CKind != OMPC_shared) {
12455 Diag(ELoc, diag::err_omp_required_access)
12456 << getOpenMPClauseName(OMPC_lastprivate)
12457 << getOpenMPClauseName(OMPC_shared);
12458 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12459 continue;
12460 }
12461 }
12462
12463 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
12464 // A variable of class type (or array thereof) that appears in a
12465 // lastprivate clause requires an accessible, unambiguous default
12466 // constructor for the class type, unless the list item is also specified
12467 // in a firstprivate clause.
12468 // A variable of class type (or array thereof) that appears in a
12469 // lastprivate clause requires an accessible, unambiguous copy assignment
12470 // operator for the class type.
12471 Type = Context.getBaseElementType(Type).getNonReferenceType();
12472 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
12473 Type.getUnqualifiedType(), ".lastprivate.src",
12474 D->hasAttrs() ? &D->getAttrs() : nullptr);
12475 DeclRefExpr *PseudoSrcExpr =
12476 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
12477 VarDecl *DstVD =
12478 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
12479 D->hasAttrs() ? &D->getAttrs() : nullptr);
12480 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12481 // For arrays generate assignment operation for single element and replace
12482 // it by the original array element in CodeGen.
12483 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
12484 PseudoDstExpr, PseudoSrcExpr);
12485 if (AssignmentOp.isInvalid())
12486 continue;
12487 AssignmentOp =
12488 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
12489 if (AssignmentOp.isInvalid())
12490 continue;
12491
12492 DeclRefExpr *Ref = nullptr;
12493 if (!VD && !CurContext->isDependentContext()) {
12494 if (TopDVar.CKind == OMPC_firstprivate) {
12495 Ref = TopDVar.PrivateCopy;
12496 } else {
12497 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
12498 if (!isOpenMPCapturedDecl(D))
12499 ExprCaptures.push_back(Ref->getDecl());
12500 }
12501 if (TopDVar.CKind == OMPC_firstprivate ||
12502 (!isOpenMPCapturedDecl(D) &&
12503 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
12504 ExprResult RefRes = DefaultLvalueConversion(Ref);
12505 if (!RefRes.isUsable())
12506 continue;
12507 ExprResult PostUpdateRes =
12508 BuildBinOp(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12509 RefRes.get());
12510 if (!PostUpdateRes.isUsable())
12511 continue;
12512 ExprPostUpdates.push_back(
12513 IgnoredValueConversions(PostUpdateRes.get()).get());
12514 }
12515 }
12516 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
12517 Vars.push_back((VD || CurContext->isDependentContext())
12518 ? RefExpr->IgnoreParens()
12519 : Ref);
12520 SrcExprs.push_back(PseudoSrcExpr);
12521 DstExprs.push_back(PseudoDstExpr);
12522 AssignmentOps.push_back(AssignmentOp.get());
12523 }
12524
12525 if (Vars.empty())
12526 return nullptr;
12527
12528 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12529 Vars, SrcExprs, DstExprs, AssignmentOps,
12530 buildPreInits(Context, ExprCaptures),
12531 buildPostUpdate(*this, ExprPostUpdates));
12532}
12533
12534OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12535 SourceLocation StartLoc,
12536 SourceLocation LParenLoc,
12537 SourceLocation EndLoc) {
12538 SmallVector<Expr *, 8> Vars;
12539 for (Expr *RefExpr : VarList) {
12540 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.")((RefExpr && "NULL expr in OpenMP lastprivate clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP lastprivate clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12540, __PRETTY_FUNCTION__))
;
12541 SourceLocation ELoc;
12542 SourceRange ERange;
12543 Expr *SimpleRefExpr = RefExpr;
12544 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12545 if (Res.second) {
12546 // It will be analyzed later.
12547 Vars.push_back(RefExpr);
12548 }
12549 ValueDecl *D = Res.first;
12550 if (!D)
12551 continue;
12552
12553 auto *VD = dyn_cast<VarDecl>(D);
12554 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12555 // in a Construct]
12556 // Variables with the predetermined data-sharing attributes may not be
12557 // listed in data-sharing attributes clauses, except for the cases
12558 // listed below. For these exceptions only, listing a predetermined
12559 // variable in a data-sharing attribute clause is allowed and overrides
12560 // the variable's predetermined data-sharing attributes.
12561 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
12562 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
12563 DVar.RefExpr) {
12564 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12565 << getOpenMPClauseName(OMPC_shared);
12566 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
12567 continue;
12568 }
12569
12570 DeclRefExpr *Ref = nullptr;
12571 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
12572 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12573 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
12574 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
12575 ? RefExpr->IgnoreParens()
12576 : Ref);
12577 }
12578
12579 if (Vars.empty())
12580 return nullptr;
12581
12582 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
12583}
12584
12585namespace {
12586class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
12587 DSAStackTy *Stack;
12588
12589public:
12590 bool VisitDeclRefExpr(DeclRefExpr *E) {
12591 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
12592 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
12593 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
12594 return false;
12595 if (DVar.CKind != OMPC_unknown)
12596 return true;
12597 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
12598 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
12599 /*FromParent=*/true);
12600 return DVarPrivate.CKind != OMPC_unknown;
12601 }
12602 return false;
12603 }
12604 bool VisitStmt(Stmt *S) {
12605 for (Stmt *Child : S->children()) {
12606 if (Child && Visit(Child))
12607 return true;
12608 }
12609 return false;
12610 }
12611 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
12612};
12613} // namespace
12614
12615namespace {
12616// Transform MemberExpression for specified FieldDecl of current class to
12617// DeclRefExpr to specified OMPCapturedExprDecl.
12618class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
12619 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
12620 ValueDecl *Field = nullptr;
12621 DeclRefExpr *CapturedExpr = nullptr;
12622
12623public:
12624 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
12625 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
12626
12627 ExprResult TransformMemberExpr(MemberExpr *E) {
12628 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
1
Assuming the object is a 'CXXThisExpr'
3
Taking true branch
12629 E->getMemberDecl() == Field) {
2
Assuming the condition is true
12630 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
4
Calling 'buildCapture'
12631 return CapturedExpr;
12632 }
12633 return BaseTransform::TransformMemberExpr(E);
12634 }
12635 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
12636};
12637} // namespace
12638
12639template <typename T, typename U>
12640static T filterLookupForUDReductionAndMapper(
12641 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
12642 for (U &Set : Lookups) {
12643 for (auto *D : Set) {
12644 if (T Res = Gen(cast<ValueDecl>(D)))
12645 return Res;
12646 }
12647 }
12648 return T();
12649}
12650
12651static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
12652 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case")((!LookupResult::isVisible(SemaRef, D) && "not in slow case"
) ? static_cast<void> (0) : __assert_fail ("!LookupResult::isVisible(SemaRef, D) && \"not in slow case\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 12652, __PRETTY_FUNCTION__))
;
12653
12654 for (auto RD : D->redecls()) {
12655 // Don't bother with extra checks if we already know this one isn't visible.
12656 if (RD == D)
12657 continue;
12658
12659 auto ND = cast<NamedDecl>(RD);
12660 if (LookupResult::isVisible(SemaRef, ND))
12661 return ND;
12662 }
12663
12664 return nullptr;
12665}
12666
12667static void
12668argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
12669 SourceLocation Loc, QualType Ty,
12670 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
12671 // Find all of the associated namespaces and classes based on the
12672 // arguments we have.
12673 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12674 Sema::AssociatedClassSet AssociatedClasses;
12675 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
12676 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
12677 AssociatedClasses);
12678
12679 // C++ [basic.lookup.argdep]p3:
12680 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12681 // and let Y be the lookup set produced by argument dependent
12682 // lookup (defined as follows). If X contains [...] then Y is
12683 // empty. Otherwise Y is the set of declarations found in the
12684 // namespaces associated with the argument types as described
12685 // below. The set of declarations found by the lookup of the name
12686 // is the union of X and Y.
12687 //
12688 // Here, we compute Y and add its members to the overloaded
12689 // candidate set.
12690 for (auto *NS : AssociatedNamespaces) {
12691 // When considering an associated namespace, the lookup is the
12692 // same as the lookup performed when the associated namespace is
12693 // used as a qualifier (3.4.3.2) except that:
12694 //
12695 // -- Any using-directives in the associated namespace are
12696 // ignored.
12697 //
12698 // -- Any namespace-scope friend functions declared in
12699 // associated classes are visible within their respective
12700 // namespaces even if they are not visible during an ordinary
12701 // lookup (11.4).
12702 DeclContext::lookup_result R = NS->lookup(Id.getName());
12703 for (auto *D : R) {
12704 auto *Underlying = D;
12705 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12706 Underlying = USD->getTargetDecl();
12707
12708 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
12709 !isa<OMPDeclareMapperDecl>(Underlying))
12710 continue;
12711
12712 if (!SemaRef.isVisible(D)) {
12713 D = findAcceptableDecl(SemaRef, D);
12714 if (!D)
12715 continue;
12716 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12717 Underlying = USD->getTargetDecl();
12718 }
12719 Lookups.emplace_back();
12720 Lookups.back().addDecl(Underlying);
12721 }
12722 }
12723}
12724
12725static ExprResult
12726buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
12727 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
12728 const DeclarationNameInfo &ReductionId, QualType Ty,
12729 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
12730 if (ReductionIdScopeSpec.isInvalid())
12731 return ExprError();
12732 SmallVector<UnresolvedSet<8>, 4> Lookups;
12733 if (S) {
12734 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12735 Lookup.suppressDiagnostics();
12736 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
12737 NamedDecl *D = Lookup.getRepresentativeDecl();
12738 do {
12739 S = S->getParent();
12740 } while (S && !S->isDeclScope(D));
12741 if (S)
12742 S = S->getParent();
12743 Lookups.emplace_back();
12744 Lookups.back().append(Lookup.begin(), Lookup.end());
12745 Lookup.clear();
12746 }
12747 } else if (auto *ULE =
12748 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
12749 Lookups.push_back(UnresolvedSet<8>());
12750 Decl *PrevD = nullptr;
12751 for (NamedDecl *D : ULE->decls()) {
12752 if (D == PrevD)
12753 Lookups.push_back(UnresolvedSet<8>());
12754 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
12755 Lookups.back().addDecl(DRD);
12756 PrevD = D;
12757 }
12758 }
12759 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
12760 Ty->isInstantiationDependentType() ||
12761 Ty->containsUnexpandedParameterPack() ||
12762 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
12763 return !D->isInvalidDecl() &&
12764 (D->getType()->isDependentType() ||
12765 D->getType()->isInstantiationDependentType() ||
12766 D->getType()->containsUnexpandedParameterPack());
12767 })) {
12768 UnresolvedSet<8> ResSet;
12769 for (const UnresolvedSet<8> &Set : Lookups) {
12770 if (Set.empty())
12771 continue;
12772 ResSet.append(Set.begin(), Set.end());
12773 // The last item marks the end of all declarations at the specified scope.
12774 ResSet.addDecl(Set[Set.size() - 1]);
12775 }
12776 return UnresolvedLookupExpr::Create(
12777 SemaRef.Context, /*NamingClass=*/nullptr,
12778 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
12779 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
12780 }
12781 // Lookup inside the classes.
12782 // C++ [over.match.oper]p3:
12783 // For a unary operator @ with an operand of a type whose
12784 // cv-unqualified version is T1, and for a binary operator @ with
12785 // a left operand of a type whose cv-unqualified version is T1 and
12786 // a right operand of a type whose cv-unqualified version is T2,
12787 // three sets of candidate functions, designated member
12788 // candidates, non-member candidates and built-in candidates, are
12789 // constructed as follows:
12790 // -- If T1 is a complete class type or a class currently being
12791 // defined, the set of member candidates is the result of the
12792 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
12793 // the set of member candidates is empty.
12794 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12795 Lookup.suppressDiagnostics();
12796 if (const auto *TyRec = Ty->getAs<RecordType>()) {
12797 // Complete the type if it can be completed.
12798 // If the type is neither complete nor being defined, bail out now.
12799 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
12800 TyRec->getDecl()->getDefinition()) {
12801 Lookup.clear();
12802 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
12803 if (Lookup.empty()) {
12804 Lookups.emplace_back();
12805 Lookups.back().append(Lookup.begin(), Lookup.end());
12806 }
12807 }
12808 }
12809 // Perform ADL.
12810 if (SemaRef.getLangOpts().CPlusPlus)
12811 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
12812 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
12813 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
12814 if (!D->isInvalidDecl() &&
12815 SemaRef.Context.hasSameType(D->getType(), Ty))
12816 return D;
12817 return nullptr;
12818 }))
12819 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
12820 VK_LValue, Loc);
12821 if (SemaRef.getLangOpts().CPlusPlus) {
12822 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
12823 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
12824 if (!D->isInvalidDecl() &&
12825 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
12826 !Ty.isMoreQualifiedThan(D->getType()))
12827 return D;
12828 return nullptr;
12829 })) {
12830 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
12831 /*DetectVirtual=*/false);
12832 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
12833 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
12834 VD->getType().getUnqualifiedType()))) {
12835 if (SemaRef.CheckBaseClassAccess(
12836 Loc, VD->getType(), Ty, Paths.front(),
12837 /*DiagID=*/0) != Sema::AR_inaccessible) {
12838 SemaRef.BuildBasePathArray(Paths, BasePath);
12839 return SemaRef.BuildDeclRefExpr(
12840 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
12841 }
12842 }
12843 }
12844 }
12845 }
12846 if (ReductionIdScopeSpec.isSet()) {
12847 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
12848 return ExprError();
12849 }
12850 return ExprEmpty();
12851}
12852
12853namespace {
12854/// Data for the reduction-based clauses.
12855struct ReductionData {
12856 /// List of original reduction items.
12857 SmallVector<Expr *, 8> Vars;
12858 /// List of private copies of the reduction items.
12859 SmallVector<Expr *, 8> Privates;
12860 /// LHS expressions for the reduction_op expressions.
12861 SmallVector<Expr *, 8> LHSs;
12862 /// RHS expressions for the reduction_op expressions.
12863 SmallVector<Expr *, 8> RHSs;
12864 /// Reduction operation expression.
12865 SmallVector<Expr *, 8> ReductionOps;
12866 /// Taskgroup descriptors for the corresponding reduction items in
12867 /// in_reduction clauses.
12868 SmallVector<Expr *, 8> TaskgroupDescriptors;
12869 /// List of captures for clause.
12870 SmallVector<Decl *, 4> ExprCaptures;
12871 /// List of postupdate expressions.
12872 SmallVector<Expr *, 4> ExprPostUpdates;
12873 ReductionData() = delete;
12874 /// Reserves required memory for the reduction data.
12875 ReductionData(unsigned Size) {
12876 Vars.reserve(Size);
12877 Privates.reserve(Size);
12878 LHSs.reserve(Size);
12879 RHSs.reserve(Size);
12880 ReductionOps.reserve(Size);
12881 TaskgroupDescriptors.reserve(Size);
12882 ExprCaptures.reserve(Size);
12883 ExprPostUpdates.reserve(Size);
12884 }
12885 /// Stores reduction item and reduction operation only (required for dependent
12886 /// reduction item).
12887 void push(Expr *Item, Expr *ReductionOp) {
12888 Vars.emplace_back(Item);
12889 Privates.emplace_back(nullptr);
12890 LHSs.emplace_back(nullptr);
12891 RHSs.emplace_back(nullptr);
12892 ReductionOps.emplace_back(ReductionOp);
12893 TaskgroupDescriptors.emplace_back(nullptr);
12894 }
12895 /// Stores reduction data.
12896 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
12897 Expr *TaskgroupDescriptor) {
12898 Vars.emplace_back(Item);
12899 Privates.emplace_back(Private);
12900 LHSs.emplace_back(LHS);
12901 RHSs.emplace_back(RHS);
12902 ReductionOps.emplace_back(ReductionOp);
12903 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
12904 }
12905};
12906} // namespace
12907
12908static bool checkOMPArraySectionConstantForReduction(
12909 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
12910 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
12911 const Expr *Length = OASE->getLength();
12912 if (Length == nullptr) {
12913 // For array sections of the form [1:] or [:], we would need to analyze
12914 // the lower bound...
12915 if (OASE->getColonLoc().isValid())
12916 return false;
12917
12918 // This is an array subscript which has implicit length 1!
12919 SingleElement = true;
12920 ArraySizes.push_back(llvm::APSInt::get(1));
12921 } else {
12922 Expr::EvalResult Result;
12923 if (!Length->EvaluateAsInt(Result, Context))
12924 return false;
12925
12926 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
12927 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
12928 ArraySizes.push_back(ConstantLengthValue);
12929 }
12930
12931 // Get the base of this array section and walk up from there.
12932 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
12933
12934 // We require length = 1 for all array sections except the right-most to
12935 // guarantee that the memory region is contiguous and has no holes in it.
12936 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
12937 Length = TempOASE->getLength();
12938 if (Length == nullptr) {
12939 // For array sections of the form [1:] or [:], we would need to analyze
12940 // the lower bound...
12941 if (OASE->getColonLoc().isValid())
12942 return false;
12943
12944 // This is an array subscript which has implicit length 1!
12945 ArraySizes.push_back(llvm::APSInt::get(1));
12946 } else {
12947 Expr::EvalResult Result;
12948 if (!Length->EvaluateAsInt(Result, Context))
12949 return false;
12950
12951 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
12952 if (ConstantLengthValue.getSExtValue() != 1)
12953 return false;
12954
12955 ArraySizes.push_back(ConstantLengthValue);
12956 }
12957 Base = TempOASE->getBase()->IgnoreParenImpCasts();
12958 }
12959
12960 // If we have a single element, we don't need to add the implicit lengths.
12961 if (!SingleElement) {
12962 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
12963 // Has implicit length 1!
12964 ArraySizes.push_back(llvm::APSInt::get(1));
12965 Base = TempASE->getBase()->IgnoreParenImpCasts();
12966 }
12967 }
12968
12969 // This array section can be privatized as a single value or as a constant
12970 // sized array.
12971 return true;
12972}
12973
12974static bool actOnOMPReductionKindClause(
12975 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
12976 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12977 SourceLocation ColonLoc, SourceLocation EndLoc,
12978 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12979 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
12980 DeclarationName DN = ReductionId.getName();
12981 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
12982 BinaryOperatorKind BOK = BO_Comma;
12983
12984 ASTContext &Context = S.Context;
12985 // OpenMP [2.14.3.6, reduction clause]
12986 // C
12987 // reduction-identifier is either an identifier or one of the following
12988 // operators: +, -, *, &, |, ^, && and ||
12989 // C++
12990 // reduction-identifier is either an id-expression or one of the following
12991 // operators: +, -, *, &, |, ^, && and ||
12992 switch (OOK) {
12993 case OO_Plus:
12994 case OO_Minus:
12995 BOK = BO_Add;
12996 break;
12997 case OO_Star:
12998 BOK = BO_Mul;
12999 break;
13000 case OO_Amp:
13001 BOK = BO_And;
13002 break;
13003 case OO_Pipe:
13004 BOK = BO_Or;
13005 break;
13006 case OO_Caret:
13007 BOK = BO_Xor;
13008 break;
13009 case OO_AmpAmp:
13010 BOK = BO_LAnd;
13011 break;
13012 case OO_PipePipe:
13013 BOK = BO_LOr;
13014 break;
13015 case OO_New:
13016 case OO_Delete:
13017 case OO_Array_New:
13018 case OO_Array_Delete:
13019 case OO_Slash:
13020 case OO_Percent:
13021 case OO_Tilde:
13022 case OO_Exclaim:
13023 case OO_Equal:
13024 case OO_Less:
13025 case OO_Greater:
13026 case OO_LessEqual:
13027 case OO_GreaterEqual:
13028 case OO_PlusEqual:
13029 case OO_MinusEqual:
13030 case OO_StarEqual:
13031 case OO_SlashEqual:
13032 case OO_PercentEqual:
13033 case OO_CaretEqual:
13034 case OO_AmpEqual:
13035 case OO_PipeEqual:
13036 case OO_LessLess:
13037 case OO_GreaterGreater:
13038 case OO_LessLessEqual:
13039 case OO_GreaterGreaterEqual:
13040 case OO_EqualEqual:
13041 case OO_ExclaimEqual:
13042 case OO_Spaceship:
13043 case OO_PlusPlus:
13044 case OO_MinusMinus:
13045 case OO_Comma:
13046 case OO_ArrowStar:
13047 case OO_Arrow:
13048 case OO_Call:
13049 case OO_Subscript:
13050 case OO_Conditional:
13051 case OO_Coawait:
13052 case NUM_OVERLOADED_OPERATORS:
13053 llvm_unreachable("Unexpected reduction identifier")::llvm::llvm_unreachable_internal("Unexpected reduction identifier"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13053)
;
13054 case OO_None:
13055 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
13056 if (II->isStr("max"))
13057 BOK = BO_GT;
13058 else if (II->isStr("min"))
13059 BOK = BO_LT;
13060 }
13061 break;
13062 }
13063 SourceRange ReductionIdRange;
13064 if (ReductionIdScopeSpec.isValid())
13065 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
13066 else
13067 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
13068 ReductionIdRange.setEnd(ReductionId.getEndLoc());
13069
13070 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13071 bool FirstIter = true;
13072 for (Expr *RefExpr : VarList) {
13073 assert(RefExpr && "nullptr expr in OpenMP reduction clause.")((RefExpr && "nullptr expr in OpenMP reduction clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"nullptr expr in OpenMP reduction clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13073, __PRETTY_FUNCTION__))
;
13074 // OpenMP [2.1, C/C++]
13075 // A list item is a variable or array section, subject to the restrictions
13076 // specified in Section 2.4 on page 42 and in each of the sections
13077 // describing clauses and directives for which a list appears.
13078 // OpenMP [2.14.3.3, Restrictions, p.1]
13079 // A variable that is part of another variable (as an array or
13080 // structure element) cannot appear in a private clause.
13081 if (!FirstIter && IR != ER)
13082 ++IR;
13083 FirstIter = false;
13084 SourceLocation ELoc;
13085 SourceRange ERange;
13086 Expr *SimpleRefExpr = RefExpr;
13087 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
13088 /*AllowArraySection=*/true);
13089 if (Res.second) {
13090 // Try to find 'declare reduction' corresponding construct before using
13091 // builtin/overloaded operators.
13092 QualType Type = Context.DependentTy;
13093 CXXCastPath BasePath;
13094 ExprResult DeclareReductionRef = buildDeclareReductionRef(
13095 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
13096 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13097 Expr *ReductionOp = nullptr;
13098 if (S.CurContext->isDependentContext() &&
13099 (DeclareReductionRef.isUnset() ||
13100 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
13101 ReductionOp = DeclareReductionRef.get();
13102 // It will be analyzed later.
13103 RD.push(RefExpr, ReductionOp);
13104 }
13105 ValueDecl *D = Res.first;
13106 if (!D)
13107 continue;
13108
13109 Expr *TaskgroupDescriptor = nullptr;
13110 QualType Type;
13111 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13112 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
13113 if (ASE) {
13114 Type = ASE->getType().getNonReferenceType();
13115 } else if (OASE) {
13116 QualType BaseType =
13117 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13118 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
13119 Type = ATy->getElementType();
13120 else
13121 Type = BaseType->getPointeeType();
13122 Type = Type.getNonReferenceType();
13123 } else {
13124 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
13125 }
13126 auto *VD = dyn_cast<VarDecl>(D);
13127
13128 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13129 // A variable that appears in a private clause must not have an incomplete
13130 // type or a reference type.
13131 if (S.RequireCompleteType(ELoc, D->getType(),
13132 diag::err_omp_reduction_incomplete_type))
13133 continue;
13134 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13135 // A list item that appears in a reduction clause must not be
13136 // const-qualified.
13137 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13138 /*AcceptIfMutable*/ false, ASE || OASE))
13139 continue;
13140
13141 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
13142 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13143 // If a list-item is a reference type then it must bind to the same object
13144 // for all threads of the team.
13145 if (!ASE && !OASE) {
13146 if (VD) {
13147 VarDecl *VDDef = VD->getDefinition();
13148 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13149 DSARefChecker Check(Stack);
13150 if (Check.Visit(VDDef->getInit())) {
13151 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13152 << getOpenMPClauseName(ClauseKind) << ERange;
13153 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13154 continue;
13155 }
13156 }
13157 }
13158
13159 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13160 // in a Construct]
13161 // Variables with the predetermined data-sharing attributes may not be
13162 // listed in data-sharing attributes clauses, except for the cases
13163 // listed below. For these exceptions only, listing a predetermined
13164 // variable in a data-sharing attribute clause is allowed and overrides
13165 // the variable's predetermined data-sharing attributes.
13166 // OpenMP [2.14.3.6, Restrictions, p.3]
13167 // Any number of reduction clauses can be specified on the directive,
13168 // but a list item can appear only once in the reduction clauses for that
13169 // directive.
13170 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13171 if (DVar.CKind == OMPC_reduction) {
13172 S.Diag(ELoc, diag::err_omp_once_referenced)
13173 << getOpenMPClauseName(ClauseKind);
13174 if (DVar.RefExpr)
13175 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13176 continue;
13177 }
13178 if (DVar.CKind != OMPC_unknown) {
13179 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13180 << getOpenMPClauseName(DVar.CKind)
13181 << getOpenMPClauseName(OMPC_reduction);
13182 reportOriginalDsa(S, Stack, D, DVar);
13183 continue;
13184 }
13185
13186 // OpenMP [2.14.3.6, Restrictions, p.1]
13187 // A list item that appears in a reduction clause of a worksharing
13188 // construct must be shared in the parallel regions to which any of the
13189 // worksharing regions arising from the worksharing construct bind.
13190 if (isOpenMPWorksharingDirective(CurrDir) &&
13191 !isOpenMPParallelDirective(CurrDir) &&
13192 !isOpenMPTeamsDirective(CurrDir)) {
13193 DVar = Stack->getImplicitDSA(D, true);
13194 if (DVar.CKind != OMPC_shared) {
13195 S.Diag(ELoc, diag::err_omp_required_access)
13196 << getOpenMPClauseName(OMPC_reduction)
13197 << getOpenMPClauseName(OMPC_shared);
13198 reportOriginalDsa(S, Stack, D, DVar);
13199 continue;
13200 }
13201 }
13202 }
13203
13204 // Try to find 'declare reduction' corresponding construct before using
13205 // builtin/overloaded operators.
13206 CXXCastPath BasePath;
13207 ExprResult DeclareReductionRef = buildDeclareReductionRef(
13208 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
13209 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13210 if (DeclareReductionRef.isInvalid())
13211 continue;
13212 if (S.CurContext->isDependentContext() &&
13213 (DeclareReductionRef.isUnset() ||
13214 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
13215 RD.push(RefExpr, DeclareReductionRef.get());
13216 continue;
13217 }
13218 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13219 // Not allowed reduction identifier is found.
13220 S.Diag(ReductionId.getBeginLoc(),
13221 diag::err_omp_unknown_reduction_identifier)
13222 << Type << ReductionIdRange;
13223 continue;
13224 }
13225
13226 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13227 // The type of a list item that appears in a reduction clause must be valid
13228 // for the reduction-identifier. For a max or min reduction in C, the type
13229 // of the list item must be an allowed arithmetic data type: char, int,
13230 // float, double, or _Bool, possibly modified with long, short, signed, or
13231 // unsigned. For a max or min reduction in C++, the type of the list item
13232 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13233 // double, or bool, possibly modified with long, short, signed, or unsigned.
13234 if (DeclareReductionRef.isUnset()) {
13235 if ((BOK == BO_GT || BOK == BO_LT) &&
13236 !(Type->isScalarType() ||
13237 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13238 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
13239 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
13240 if (!ASE && !OASE) {
13241 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13242 VarDecl::DeclarationOnly;
13243 S.Diag(D->getLocation(),
13244 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13245 << D;
13246 }
13247 continue;
13248 }
13249 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
13250 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
13251 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13252 << getOpenMPClauseName(ClauseKind);
13253 if (!ASE && !OASE) {
13254 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13255 VarDecl::DeclarationOnly;
13256 S.Diag(D->getLocation(),
13257 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13258 << D;
13259 }
13260 continue;
13261 }
13262 }
13263
13264 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
13265 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13266 D->hasAttrs() ? &D->getAttrs() : nullptr);
13267 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13268 D->hasAttrs() ? &D->getAttrs() : nullptr);
13269 QualType PrivateTy = Type;
13270
13271 // Try if we can determine constant lengths for all array sections and avoid
13272 // the VLA.
13273 bool ConstantLengthOASE = false;
13274 if (OASE) {
13275 bool SingleElement;
13276 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
13277 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
13278 Context, OASE, SingleElement, ArraySizes);
13279
13280 // If we don't have a single element, we must emit a constant array type.
13281 if (ConstantLengthOASE && !SingleElement) {
13282 for (llvm::APSInt &Size : ArraySizes)
13283 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13284 ArrayType::Normal,
13285 /*IndexTypeQuals=*/0);
13286 }
13287 }
13288
13289 if ((OASE && !ConstantLengthOASE) ||
13290 (!OASE && !ASE &&
13291 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
13292 if (!Context.getTargetInfo().isVLASupported()) {
13293 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13294 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13295 S.Diag(ELoc, diag::note_vla_unsupported);
13296 } else {
13297 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13298 S.targetDiag(ELoc, diag::note_vla_unsupported);
13299 }
13300 continue;
13301 }
13302 // For arrays/array sections only:
13303 // Create pseudo array type for private copy. The size for this array will
13304 // be generated during codegen.
13305 // For array subscripts or single variables Private Ty is the same as Type
13306 // (type of the variable or single array element).
13307 PrivateTy = Context.getVariableArrayType(
13308 Type,
13309 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
13310 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
13311 } else if (!ASE && !OASE &&
13312 Context.getAsArrayType(D->getType().getNonReferenceType())) {
13313 PrivateTy = D->getType().getNonReferenceType();
13314 }
13315 // Private copy.
13316 VarDecl *PrivateVD =
13317 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13318 D->hasAttrs() ? &D->getAttrs() : nullptr,
13319 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13320 // Add initializer for private variable.
13321 Expr *Init = nullptr;
13322 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13323 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
13324 if (DeclareReductionRef.isUsable()) {
13325 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13326 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13327 if (DRD->getInitializer()) {
13328 Init = DRDRef;
13329 RHSVD->setInit(DRDRef);
13330 RHSVD->setInitStyle(VarDecl::CallInit);
13331 }
13332 } else {
13333 switch (BOK) {
13334 case BO_Add:
13335 case BO_Xor:
13336 case BO_Or:
13337 case BO_LOr:
13338 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13339 if (Type->isScalarType() || Type->isAnyComplexType())
13340 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
13341 break;
13342 case BO_Mul:
13343 case BO_LAnd:
13344 if (Type->isScalarType() || Type->isAnyComplexType()) {
13345 // '*' and '&&' reduction ops - initializer is '1'.
13346 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
13347 }
13348 break;
13349 case BO_And: {
13350 // '&' reduction op - initializer is '~0'.
13351 QualType OrigType = Type;
13352 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13353 Type = ComplexTy->getElementType();
13354 if (Type->isRealFloatingType()) {
13355 llvm::APFloat InitValue =
13356 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13357 /*isIEEE=*/true);
13358 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13359 Type, ELoc);
13360 } else if (Type->isScalarType()) {
13361 uint64_t Size = Context.getTypeSize(Type);
13362 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13363 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13364 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13365 }
13366 if (Init && OrigType->isAnyComplexType()) {
13367 // Init = 0xFFFF + 0xFFFFi;
13368 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
13369 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
13370 }
13371 Type = OrigType;
13372 break;
13373 }
13374 case BO_LT:
13375 case BO_GT: {
13376 // 'min' reduction op - initializer is 'Largest representable number in
13377 // the reduction list item type'.
13378 // 'max' reduction op - initializer is 'Least representable number in
13379 // the reduction list item type'.
13380 if (Type->isIntegerType() || Type->isPointerType()) {
13381 bool IsSigned = Type->hasSignedIntegerRepresentation();
13382 uint64_t Size = Context.getTypeSize(Type);
13383 QualType IntTy =
13384 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
13385 llvm::APInt InitValue =
13386 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
13387 : llvm::APInt::getMinValue(Size)
13388 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
13389 : llvm::APInt::getMaxValue(Size);
13390 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13391 if (Type->isPointerType()) {
13392 // Cast to pointer type.
13393 ExprResult CastExpr = S.BuildCStyleCastExpr(
13394 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
13395 if (CastExpr.isInvalid())
13396 continue;
13397 Init = CastExpr.get();
13398 }
13399 } else if (Type->isRealFloatingType()) {
13400 llvm::APFloat InitValue = llvm::APFloat::getLargest(
13401 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
13402 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13403 Type, ELoc);
13404 }
13405 break;
13406 }
13407 case BO_PtrMemD:
13408 case BO_PtrMemI:
13409 case BO_MulAssign:
13410 case BO_Div:
13411 case BO_Rem:
13412 case BO_Sub:
13413 case BO_Shl:
13414 case BO_Shr:
13415 case BO_LE:
13416 case BO_GE:
13417 case BO_EQ:
13418 case BO_NE:
13419 case BO_Cmp:
13420 case BO_AndAssign:
13421 case BO_XorAssign:
13422 case BO_OrAssign:
13423 case BO_Assign:
13424 case BO_AddAssign:
13425 case BO_SubAssign:
13426 case BO_DivAssign:
13427 case BO_RemAssign:
13428 case BO_ShlAssign:
13429 case BO_ShrAssign:
13430 case BO_Comma:
13431 llvm_unreachable("Unexpected reduction operation")::llvm::llvm_unreachable_internal("Unexpected reduction operation"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13431)
;
13432 }
13433 }
13434 if (Init && DeclareReductionRef.isUnset())
13435 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
13436 else if (!Init)
13437 S.ActOnUninitializedDecl(RHSVD);
13438 if (RHSVD->isInvalidDecl())
13439 continue;
13440 if (!RHSVD->hasInit() &&
13441 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
13442 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
13443 << Type << ReductionIdRange;
13444 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13445 VarDecl::DeclarationOnly;
13446 S.Diag(D->getLocation(),
13447 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13448 << D;
13449 continue;
13450 }
13451 // Store initializer for single element in private copy. Will be used during
13452 // codegen.
13453 PrivateVD->setInit(RHSVD->getInit());
13454 PrivateVD->setInitStyle(RHSVD->getInitStyle());
13455 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
13456 ExprResult ReductionOp;
13457 if (DeclareReductionRef.isUsable()) {
13458 QualType RedTy = DeclareReductionRef.get()->getType();
13459 QualType PtrRedTy = Context.getPointerType(RedTy);
13460 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
13461 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
13462 if (!BasePath.empty()) {
13463 LHS = S.DefaultLvalueConversion(LHS.get());
13464 RHS = S.DefaultLvalueConversion(RHS.get());
13465 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13466 CK_UncheckedDerivedToBase, LHS.get(),
13467 &BasePath, LHS.get()->getValueKind());
13468 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13469 CK_UncheckedDerivedToBase, RHS.get(),
13470 &BasePath, RHS.get()->getValueKind());
13471 }
13472 FunctionProtoType::ExtProtoInfo EPI;
13473 QualType Params[] = {PtrRedTy, PtrRedTy};
13474 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
13475 auto *OVE = new (Context) OpaqueValueExpr(
13476 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
13477 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
13478 Expr *Args[] = {LHS.get(), RHS.get()};
13479 ReductionOp =
13480 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
13481 } else {
13482 ReductionOp = S.BuildBinOp(
13483 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
13484 if (ReductionOp.isUsable()) {
13485 if (BOK != BO_LT && BOK != BO_GT) {
13486 ReductionOp =
13487 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
13488 BO_Assign, LHSDRE, ReductionOp.get());
13489 } else {
13490 auto *ConditionalOp = new (Context)
13491 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
13492 Type, VK_LValue, OK_Ordinary);
13493 ReductionOp =
13494 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
13495 BO_Assign, LHSDRE, ConditionalOp);
13496 }
13497 if (ReductionOp.isUsable())
13498 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
13499 /*DiscardedValue*/ false);
13500 }
13501 if (!ReductionOp.isUsable())
13502 continue;
13503 }
13504
13505 // OpenMP [2.15.4.6, Restrictions, p.2]
13506 // A list item that appears in an in_reduction clause of a task construct
13507 // must appear in a task_reduction clause of a construct associated with a
13508 // taskgroup region that includes the participating task in its taskgroup
13509 // set. The construct associated with the innermost region that meets this
13510 // condition must specify the same reduction-identifier as the in_reduction
13511 // clause.
13512 if (ClauseKind == OMPC_in_reduction) {
13513 SourceRange ParentSR;
13514 BinaryOperatorKind ParentBOK;
13515 const Expr *ParentReductionOp;
13516 Expr *ParentBOKTD, *ParentReductionOpTD;
13517 DSAStackTy::DSAVarData ParentBOKDSA =
13518 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
13519 ParentBOKTD);
13520 DSAStackTy::DSAVarData ParentReductionOpDSA =
13521 Stack->getTopMostTaskgroupReductionData(
13522 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
13523 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
13524 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
13525 if (!IsParentBOK && !IsParentReductionOp) {
13526 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
13527 continue;
13528 }
13529 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
13530 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
13531 IsParentReductionOp) {
13532 bool EmitError = true;
13533 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
13534 llvm::FoldingSetNodeID RedId, ParentRedId;
13535 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
13536 DeclareReductionRef.get()->Profile(RedId, Context,
13537 /*Canonical=*/true);
13538 EmitError = RedId != ParentRedId;
13539 }
13540 if (EmitError) {
13541 S.Diag(ReductionId.getBeginLoc(),
13542 diag::err_omp_reduction_identifier_mismatch)
13543 << ReductionIdRange << RefExpr->getSourceRange();
13544 S.Diag(ParentSR.getBegin(),
13545 diag::note_omp_previous_reduction_identifier)
13546 << ParentSR
13547 << (IsParentBOK ? ParentBOKDSA.RefExpr
13548 : ParentReductionOpDSA.RefExpr)
13549 ->getSourceRange();
13550 continue;
13551 }
13552 }
13553 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
13554 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.")((TaskgroupDescriptor && "Taskgroup descriptor must be defined."
) ? static_cast<void> (0) : __assert_fail ("TaskgroupDescriptor && \"Taskgroup descriptor must be defined.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13554, __PRETTY_FUNCTION__))
;
13555 }
13556
13557 DeclRefExpr *Ref = nullptr;
13558 Expr *VarsExpr = RefExpr->IgnoreParens();
13559 if (!VD && !S.CurContext->isDependentContext()) {
13560 if (ASE || OASE) {
13561 TransformExprToCaptures RebuildToCapture(S, D);
13562 VarsExpr =
13563 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
13564 Ref = RebuildToCapture.getCapturedExpr();
13565 } else {
13566 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
13567 }
13568 if (!S.isOpenMPCapturedDecl(D)) {
13569 RD.ExprCaptures.emplace_back(Ref->getDecl());
13570 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
13571 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
13572 if (!RefRes.isUsable())
13573 continue;
13574 ExprResult PostUpdateRes =
13575 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13576 RefRes.get());
13577 if (!PostUpdateRes.isUsable())
13578 continue;
13579 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
13580 Stack->getCurrentDirective() == OMPD_taskgroup) {
13581 S.Diag(RefExpr->getExprLoc(),
13582 diag::err_omp_reduction_non_addressable_expression)
13583 << RefExpr->getSourceRange();
13584 continue;
13585 }
13586 RD.ExprPostUpdates.emplace_back(
13587 S.IgnoredValueConversions(PostUpdateRes.get()).get());
13588 }
13589 }
13590 }
13591 // All reduction items are still marked as reduction (to do not increase
13592 // code base size).
13593 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
13594 if (CurrDir == OMPD_taskgroup) {
13595 if (DeclareReductionRef.isUsable())
13596 Stack->addTaskgroupReductionData(D, ReductionIdRange,
13597 DeclareReductionRef.get());
13598 else
13599 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
13600 }
13601 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
13602 TaskgroupDescriptor);
13603 }
13604 return RD.Vars.empty();
13605}
13606
13607OMPClause *Sema::ActOnOpenMPReductionClause(
13608 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13609 SourceLocation ColonLoc, SourceLocation EndLoc,
13610 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13611 ArrayRef<Expr *> UnresolvedReductions) {
13612 ReductionData RD(VarList.size());
13613 if (actOnOMPReductionKindClause(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_reduction, VarList,
13614 StartLoc, LParenLoc, ColonLoc, EndLoc,
13615 ReductionIdScopeSpec, ReductionId,
13616 UnresolvedReductions, RD))
13617 return nullptr;
13618
13619 return OMPReductionClause::Create(
13620 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13621 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13622 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13623 buildPreInits(Context, RD.ExprCaptures),
13624 buildPostUpdate(*this, RD.ExprPostUpdates));
13625}
13626
13627OMPClause *Sema::ActOnOpenMPTaskReductionClause(
13628 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13629 SourceLocation ColonLoc, SourceLocation EndLoc,
13630 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13631 ArrayRef<Expr *> UnresolvedReductions) {
13632 ReductionData RD(VarList.size());
13633 if (actOnOMPReductionKindClause(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_task_reduction, VarList,
13634 StartLoc, LParenLoc, ColonLoc, EndLoc,
13635 ReductionIdScopeSpec, ReductionId,
13636 UnresolvedReductions, RD))
13637 return nullptr;
13638
13639 return OMPTaskReductionClause::Create(
13640 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13641 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13642 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13643 buildPreInits(Context, RD.ExprCaptures),
13644 buildPostUpdate(*this, RD.ExprPostUpdates));
13645}
13646
13647OMPClause *Sema::ActOnOpenMPInReductionClause(
13648 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13649 SourceLocation ColonLoc, SourceLocation EndLoc,
13650 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13651 ArrayRef<Expr *> UnresolvedReductions) {
13652 ReductionData RD(VarList.size());
13653 if (actOnOMPReductionKindClause(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_in_reduction, VarList,
13654 StartLoc, LParenLoc, ColonLoc, EndLoc,
13655 ReductionIdScopeSpec, ReductionId,
13656 UnresolvedReductions, RD))
13657 return nullptr;
13658
13659 return OMPInReductionClause::Create(
13660 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13661 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13662 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
13663 buildPreInits(Context, RD.ExprCaptures),
13664 buildPostUpdate(*this, RD.ExprPostUpdates));
13665}
13666
13667bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
13668 SourceLocation LinLoc) {
13669 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
13670 LinKind == OMPC_LINEAR_unknown) {
13671 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
13672 return true;
13673 }
13674 return false;
13675}
13676
13677bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
13678 OpenMPLinearClauseKind LinKind,
13679 QualType Type) {
13680 const auto *VD = dyn_cast_or_null<VarDecl>(D);
13681 // A variable must not have an incomplete type or a reference type.
13682 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
13683 return true;
13684 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
13685 !Type->isReferenceType()) {
13686 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
13687 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
13688 return true;
13689 }
13690 Type = Type.getNonReferenceType();
13691
13692 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13693 // A variable that is privatized must not have a const-qualified type
13694 // unless it is of class type with a mutable member. This restriction does
13695 // not apply to the firstprivate clause.
13696 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
13697 return true;
13698
13699 // A list item must be of integral or pointer type.
13700 Type = Type.getUnqualifiedType().getCanonicalType();
13701 const auto *Ty = Type.getTypePtrOrNull();
13702 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
13703 !Ty->isPointerType())) {
13704 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
13705 if (D) {
13706 bool IsDecl =
13707 !VD ||
13708 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13709 Diag(D->getLocation(),
13710 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13711 << D;
13712 }
13713 return true;
13714 }
13715 return false;
13716}
13717
13718OMPClause *Sema::ActOnOpenMPLinearClause(
13719 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
13720 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
13721 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
13722 SmallVector<Expr *, 8> Vars;
13723 SmallVector<Expr *, 8> Privates;
13724 SmallVector<Expr *, 8> Inits;
13725 SmallVector<Decl *, 4> ExprCaptures;
13726 SmallVector<Expr *, 4> ExprPostUpdates;
13727 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
13728 LinKind = OMPC_LINEAR_val;
13729 for (Expr *RefExpr : VarList) {
13730 assert(RefExpr && "NULL expr in OpenMP linear clause.")((RefExpr && "NULL expr in OpenMP linear clause.") ? static_cast
<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP linear clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13730, __PRETTY_FUNCTION__))
;
13731 SourceLocation ELoc;
13732 SourceRange ERange;
13733 Expr *SimpleRefExpr = RefExpr;
13734 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13735 if (Res.second) {
13736 // It will be analyzed later.
13737 Vars.push_back(RefExpr);
13738 Privates.push_back(nullptr);
13739 Inits.push_back(nullptr);
13740 }
13741 ValueDecl *D = Res.first;
13742 if (!D)
13743 continue;
13744
13745 QualType Type = D->getType();
13746 auto *VD = dyn_cast<VarDecl>(D);
13747
13748 // OpenMP [2.14.3.7, linear clause]
13749 // A list-item cannot appear in more than one linear clause.
13750 // A list-item that appears in a linear clause cannot appear in any
13751 // other data-sharing attribute clause.
13752 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
13753 if (DVar.RefExpr) {
13754 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13755 << getOpenMPClauseName(OMPC_linear);
13756 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
13757 continue;
13758 }
13759
13760 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
13761 continue;
13762 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
13763
13764 // Build private copy of original var.
13765 VarDecl *Private =
13766 buildVarDecl(*this, ELoc, Type, D->getName(),
13767 D->hasAttrs() ? &D->getAttrs() : nullptr,
13768 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
13769 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
13770 // Build var to save initial value.
13771 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
13772 Expr *InitExpr;
13773 DeclRefExpr *Ref = nullptr;
13774 if (!VD && !CurContext->isDependentContext()) {
13775 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
13776 if (!isOpenMPCapturedDecl(D)) {
13777 ExprCaptures.push_back(Ref->getDecl());
13778 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
13779 ExprResult RefRes = DefaultLvalueConversion(Ref);
13780 if (!RefRes.isUsable())
13781 continue;
13782 ExprResult PostUpdateRes =
13783 BuildBinOp(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurScope(), ELoc, BO_Assign,
13784 SimpleRefExpr, RefRes.get());
13785 if (!PostUpdateRes.isUsable())
13786 continue;
13787 ExprPostUpdates.push_back(
13788 IgnoredValueConversions(PostUpdateRes.get()).get());
13789 }
13790 }
13791 }
13792 if (LinKind == OMPC_LINEAR_uval)
13793 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
13794 else
13795 InitExpr = VD ? SimpleRefExpr : Ref;
13796 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
13797 /*DirectInit=*/false);
13798 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
13799
13800 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
13801 Vars.push_back((VD || CurContext->isDependentContext())
13802 ? RefExpr->IgnoreParens()
13803 : Ref);
13804 Privates.push_back(PrivateRef);
13805 Inits.push_back(InitRef);
13806 }
13807
13808 if (Vars.empty())
13809 return nullptr;
13810
13811 Expr *StepExpr = Step;
13812 Expr *CalcStepExpr = nullptr;
13813 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
13814 !Step->isInstantiationDependent() &&
13815 !Step->containsUnexpandedParameterPack()) {
13816 SourceLocation StepLoc = Step->getBeginLoc();
13817 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
13818 if (Val.isInvalid())
13819 return nullptr;
13820 StepExpr = Val.get();
13821
13822 // Build var to save the step value.
13823 VarDecl *SaveVar =
13824 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
13825 ExprResult SaveRef =
13826 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
13827 ExprResult CalcStep =
13828 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
13829 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
13830
13831 // Warn about zero linear step (it would be probably better specified as
13832 // making corresponding variables 'const').
13833 llvm::APSInt Result;
13834 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
13835 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
13836 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
13837 << (Vars.size() > 1);
13838 if (!IsConstant && CalcStep.isUsable()) {
13839 // Calculate the step beforehand instead of doing this on each iteration.
13840 // (This is not used if the number of iterations may be kfold-ed).
13841 CalcStepExpr = CalcStep.get();
13842 }
13843 }
13844
13845 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
13846 ColonLoc, EndLoc, Vars, Privates, Inits,
13847 StepExpr, CalcStepExpr,
13848 buildPreInits(Context, ExprCaptures),
13849 buildPostUpdate(*this, ExprPostUpdates));
13850}
13851
13852static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
13853 Expr *NumIterations, Sema &SemaRef,
13854 Scope *S, DSAStackTy *Stack) {
13855 // Walk the vars and build update/final expressions for the CodeGen.
13856 SmallVector<Expr *, 8> Updates;
13857 SmallVector<Expr *, 8> Finals;
13858 SmallVector<Expr *, 8> UsedExprs;
13859 Expr *Step = Clause.getStep();
13860 Expr *CalcStep = Clause.getCalcStep();
13861 // OpenMP [2.14.3.7, linear clause]
13862 // If linear-step is not specified it is assumed to be 1.
13863 if (!Step)
13864 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
13865 else if (CalcStep)
13866 Step = cast<BinaryOperator>(CalcStep)->getLHS();
13867 bool HasErrors = false;
13868 auto CurInit = Clause.inits().begin();
13869 auto CurPrivate = Clause.privates().begin();
13870 OpenMPLinearClauseKind LinKind = Clause.getModifier();
13871 for (Expr *RefExpr : Clause.varlists()) {
13872 SourceLocation ELoc;
13873 SourceRange ERange;
13874 Expr *SimpleRefExpr = RefExpr;
13875 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
13876 ValueDecl *D = Res.first;
13877 if (Res.second || !D) {
13878 Updates.push_back(nullptr);
13879 Finals.push_back(nullptr);
13880 HasErrors = true;
13881 continue;
13882 }
13883 auto &&Info = Stack->isLoopControlVariable(D);
13884 // OpenMP [2.15.11, distribute simd Construct]
13885 // A list item may not appear in a linear clause, unless it is the loop
13886 // iteration variable.
13887 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
13888 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
13889 SemaRef.Diag(ELoc,
13890 diag::err_omp_linear_distribute_var_non_loop_iteration);
13891 Updates.push_back(nullptr);
13892 Finals.push_back(nullptr);
13893 HasErrors = true;
13894 continue;
13895 }
13896 Expr *InitExpr = *CurInit;
13897
13898 // Build privatized reference to the current linear var.
13899 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
13900 Expr *CapturedRef;
13901 if (LinKind == OMPC_LINEAR_uval)
13902 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
13903 else
13904 CapturedRef =
13905 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
13906 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
13907 /*RefersToCapture=*/true);
13908
13909 // Build update: Var = InitExpr + IV * Step
13910 ExprResult Update;
13911 if (!Info.first)
13912 Update = buildCounterUpdate(
13913 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
13914 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
13915 else
13916 Update = *CurPrivate;
13917 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
13918 /*DiscardedValue*/ false);
13919
13920 // Build final: Var = InitExpr + NumIterations * Step
13921 ExprResult Final;
13922 if (!Info.first)
13923 Final =
13924 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
13925 InitExpr, NumIterations, Step, /*Subtract=*/false,
13926 /*IsNonRectangularLB=*/false);
13927 else
13928 Final = *CurPrivate;
13929 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
13930 /*DiscardedValue*/ false);
13931
13932 if (!Update.isUsable() || !Final.isUsable()) {
13933 Updates.push_back(nullptr);
13934 Finals.push_back(nullptr);
13935 UsedExprs.push_back(nullptr);
13936 HasErrors = true;
13937 } else {
13938 Updates.push_back(Update.get());
13939 Finals.push_back(Final.get());
13940 if (!Info.first)
13941 UsedExprs.push_back(SimpleRefExpr);
13942 }
13943 ++CurInit;
13944 ++CurPrivate;
13945 }
13946 if (Expr *S = Clause.getStep())
13947 UsedExprs.push_back(S);
13948 // Fill the remaining part with the nullptr.
13949 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
13950 Clause.setUpdates(Updates);
13951 Clause.setFinals(Finals);
13952 Clause.setUsedExprs(UsedExprs);
13953 return HasErrors;
13954}
13955
13956OMPClause *Sema::ActOnOpenMPAlignedClause(
13957 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
13958 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
13959 SmallVector<Expr *, 8> Vars;
13960 for (Expr *RefExpr : VarList) {
13961 assert(RefExpr && "NULL expr in OpenMP linear clause.")((RefExpr && "NULL expr in OpenMP linear clause.") ? static_cast
<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP linear clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 13961, __PRETTY_FUNCTION__))
;
13962 SourceLocation ELoc;
13963 SourceRange ERange;
13964 Expr *SimpleRefExpr = RefExpr;
13965 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13966 if (Res.second) {
13967 // It will be analyzed later.
13968 Vars.push_back(RefExpr);
13969 }
13970 ValueDecl *D = Res.first;
13971 if (!D)
13972 continue;
13973
13974 QualType QType = D->getType();
13975 auto *VD = dyn_cast<VarDecl>(D);
13976
13977 // OpenMP [2.8.1, simd construct, Restrictions]
13978 // The type of list items appearing in the aligned clause must be
13979 // array, pointer, reference to array, or reference to pointer.
13980 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
13981 const Type *Ty = QType.getTypePtrOrNull();
13982 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
13983 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
13984 << QType << getLangOpts().CPlusPlus << ERange;
13985 bool IsDecl =
13986 !VD ||
13987 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13988 Diag(D->getLocation(),
13989 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13990 << D;
13991 continue;
13992 }
13993
13994 // OpenMP [2.8.1, simd construct, Restrictions]
13995 // A list-item cannot appear in more than one aligned clause.
13996 if (const Expr *PrevRef = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addUniqueAligned(D, SimpleRefExpr)) {
13997 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
13998 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
13999 << getOpenMPClauseName(OMPC_aligned);
14000 continue;
14001 }
14002
14003 DeclRefExpr *Ref = nullptr;
14004 if (!VD && isOpenMPCapturedDecl(D))
14005 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14006 Vars.push_back(DefaultFunctionArrayConversion(
14007 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14008 .get());
14009 }
14010
14011 // OpenMP [2.8.1, simd construct, Description]
14012 // The parameter of the aligned clause, alignment, must be a constant
14013 // positive integer expression.
14014 // If no optional parameter is specified, implementation-defined default
14015 // alignments for SIMD instructions on the target platforms are assumed.
14016 if (Alignment != nullptr) {
14017 ExprResult AlignResult =
14018 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14019 if (AlignResult.isInvalid())
14020 return nullptr;
14021 Alignment = AlignResult.get();
14022 }
14023 if (Vars.empty())
14024 return nullptr;
14025
14026 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14027 EndLoc, Vars, Alignment);
14028}
14029
14030OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14031 SourceLocation StartLoc,
14032 SourceLocation LParenLoc,
14033 SourceLocation EndLoc) {
14034 SmallVector<Expr *, 8> Vars;
14035 SmallVector<Expr *, 8> SrcExprs;
14036 SmallVector<Expr *, 8> DstExprs;
14037 SmallVector<Expr *, 8> AssignmentOps;
14038 for (Expr *RefExpr : VarList) {
14039 assert(RefExpr && "NULL expr in OpenMP copyin clause.")((RefExpr && "NULL expr in OpenMP copyin clause.") ? static_cast
<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP copyin clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14039, __PRETTY_FUNCTION__))
;
14040 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14041 // It will be analyzed later.
14042 Vars.push_back(RefExpr);
14043 SrcExprs.push_back(nullptr);
14044 DstExprs.push_back(nullptr);
14045 AssignmentOps.push_back(nullptr);
14046 continue;
14047 }
14048
14049 SourceLocation ELoc = RefExpr->getExprLoc();
14050 // OpenMP [2.1, C/C++]
14051 // A list item is a variable name.
14052 // OpenMP [2.14.4.1, Restrictions, p.1]
14053 // A list item that appears in a copyin clause must be threadprivate.
14054 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
14055 if (!DE || !isa<VarDecl>(DE->getDecl())) {
14056 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14057 << 0 << RefExpr->getSourceRange();
14058 continue;
14059 }
14060
14061 Decl *D = DE->getDecl();
14062 auto *VD = cast<VarDecl>(D);
14063
14064 QualType Type = VD->getType();
14065 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14066 // It will be analyzed later.
14067 Vars.push_back(DE);
14068 SrcExprs.push_back(nullptr);
14069 DstExprs.push_back(nullptr);
14070 AssignmentOps.push_back(nullptr);
14071 continue;
14072 }
14073
14074 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14075 // A list item that appears in a copyin clause must be threadprivate.
14076 if (!DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
14077 Diag(ELoc, diag::err_omp_required_access)
14078 << getOpenMPClauseName(OMPC_copyin)
14079 << getOpenMPDirectiveName(OMPD_threadprivate);
14080 continue;
14081 }
14082
14083 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14084 // A variable of class type (or array thereof) that appears in a
14085 // copyin clause requires an accessible, unambiguous copy assignment
14086 // operator for the class type.
14087 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14088 VarDecl *SrcVD =
14089 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
14090 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
14091 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
14092 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
14093 VarDecl *DstVD =
14094 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
14095 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
14096 DeclRefExpr *PseudoDstExpr =
14097 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
14098 // For arrays generate assignment operation for single element and replace
14099 // it by the original array element in CodeGen.
14100 ExprResult AssignmentOp =
14101 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14102 PseudoSrcExpr);
14103 if (AssignmentOp.isInvalid())
14104 continue;
14105 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
14106 /*DiscardedValue*/ false);
14107 if (AssignmentOp.isInvalid())
14108 continue;
14109
14110 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(VD, DE, OMPC_copyin);
14111 Vars.push_back(DE);
14112 SrcExprs.push_back(PseudoSrcExpr);
14113 DstExprs.push_back(PseudoDstExpr);
14114 AssignmentOps.push_back(AssignmentOp.get());
14115 }
14116
14117 if (Vars.empty())
14118 return nullptr;
14119
14120 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14121 SrcExprs, DstExprs, AssignmentOps);
14122}
14123
14124OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14125 SourceLocation StartLoc,
14126 SourceLocation LParenLoc,
14127 SourceLocation EndLoc) {
14128 SmallVector<Expr *, 8> Vars;
14129 SmallVector<Expr *, 8> SrcExprs;
14130 SmallVector<Expr *, 8> DstExprs;
14131 SmallVector<Expr *, 8> AssignmentOps;
14132 for (Expr *RefExpr : VarList) {
14133 assert(RefExpr && "NULL expr in OpenMP linear clause.")((RefExpr && "NULL expr in OpenMP linear clause.") ? static_cast
<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP linear clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14133, __PRETTY_FUNCTION__))
;
14134 SourceLocation ELoc;
14135 SourceRange ERange;
14136 Expr *SimpleRefExpr = RefExpr;
14137 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14138 if (Res.second) {
14139 // It will be analyzed later.
14140 Vars.push_back(RefExpr);
14141 SrcExprs.push_back(nullptr);
14142 DstExprs.push_back(nullptr);
14143 AssignmentOps.push_back(nullptr);
14144 }
14145 ValueDecl *D = Res.first;
14146 if (!D)
14147 continue;
14148
14149 QualType Type = D->getType();
14150 auto *VD = dyn_cast<VarDecl>(D);
14151
14152 // OpenMP [2.14.4.2, Restrictions, p.2]
14153 // A list item that appears in a copyprivate clause may not appear in a
14154 // private or firstprivate clause on the single construct.
14155 if (!VD || !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
14156 DSAStackTy::DSAVarData DVar =
14157 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
14158 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14159 DVar.RefExpr) {
14160 Diag(ELoc, diag::err_omp_wrong_dsa)
14161 << getOpenMPClauseName(DVar.CKind)
14162 << getOpenMPClauseName(OMPC_copyprivate);
14163 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
14164 continue;
14165 }
14166
14167 // OpenMP [2.11.4.2, Restrictions, p.1]
14168 // All list items that appear in a copyprivate clause must be either
14169 // threadprivate or private in the enclosing context.
14170 if (DVar.CKind == OMPC_unknown) {
14171 DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getImplicitDSA(D, false);
14172 if (DVar.CKind == OMPC_shared) {
14173 Diag(ELoc, diag::err_omp_required_access)
14174 << getOpenMPClauseName(OMPC_copyprivate)
14175 << "threadprivate or private in the enclosing context";
14176 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
14177 continue;
14178 }
14179 }
14180 }
14181
14182 // Variably modified types are not supported.
14183 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
14184 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
14185 << getOpenMPClauseName(OMPC_copyprivate) << Type
14186 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
14187 bool IsDecl =
14188 !VD ||
14189 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14190 Diag(D->getLocation(),
14191 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14192 << D;
14193 continue;
14194 }
14195
14196 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14197 // A variable of class type (or array thereof) that appears in a
14198 // copyin clause requires an accessible, unambiguous copy assignment
14199 // operator for the class type.
14200 Type = Context.getBaseElementType(Type.getNonReferenceType())
14201 .getUnqualifiedType();
14202 VarDecl *SrcVD =
14203 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
14204 D->hasAttrs() ? &D->getAttrs() : nullptr);
14205 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14206 VarDecl *DstVD =
14207 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
14208 D->hasAttrs() ? &D->getAttrs() : nullptr);
14209 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14210 ExprResult AssignmentOp = BuildBinOp(
14211 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
14212 if (AssignmentOp.isInvalid())
14213 continue;
14214 AssignmentOp =
14215 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
14216 if (AssignmentOp.isInvalid())
14217 continue;
14218
14219 // No need to mark vars as copyprivate, they are already threadprivate or
14220 // implicitly private.
14221 assert(VD || isOpenMPCapturedDecl(D))((VD || isOpenMPCapturedDecl(D)) ? static_cast<void> (0
) : __assert_fail ("VD || isOpenMPCapturedDecl(D)", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14221, __PRETTY_FUNCTION__))
;
14222 Vars.push_back(
14223 VD ? RefExpr->IgnoreParens()
14224 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
14225 SrcExprs.push_back(PseudoSrcExpr);
14226 DstExprs.push_back(PseudoDstExpr);
14227 AssignmentOps.push_back(AssignmentOp.get());
14228 }
14229
14230 if (Vars.empty())
14231 return nullptr;
14232
14233 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14234 Vars, SrcExprs, DstExprs, AssignmentOps);
14235}
14236
14237OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14238 SourceLocation StartLoc,
14239 SourceLocation LParenLoc,
14240 SourceLocation EndLoc) {
14241 if (VarList.empty())
14242 return nullptr;
14243
14244 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14245}
14246
14247OMPClause *
14248Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14249 SourceLocation DepLoc, SourceLocation ColonLoc,
14250 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14251 SourceLocation LParenLoc, SourceLocation EndLoc) {
14252 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() == OMPD_ordered &&
14253 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
14254 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
14255 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
14256 return nullptr;
14257 }
14258 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective() != OMPD_ordered &&
14259 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14260 DepKind == OMPC_DEPEND_sink)) {
14261 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
14262 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
14263 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14264 /*Last=*/OMPC_DEPEND_unknown, Except)
14265 << getOpenMPClauseName(OMPC_depend);
14266 return nullptr;
14267 }
14268 SmallVector<Expr *, 8> Vars;
14269 DSAStackTy::OperatorOffsetTy OpsOffs;
14270 llvm::APSInt DepCounter(/*BitWidth=*/32);
14271 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
14272 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14273 if (const Expr *OrderedCountExpr =
14274 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first) {
14275 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14276 TotalDepCount.setIsUnsigned(/*Val=*/true);
14277 }
14278 }
14279 for (Expr *RefExpr : VarList) {
14280 assert(RefExpr && "NULL expr in OpenMP shared clause.")((RefExpr && "NULL expr in OpenMP shared clause.") ? static_cast
<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP shared clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14280, __PRETTY_FUNCTION__))
;
14281 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14282 // It will be analyzed later.
14283 Vars.push_back(RefExpr);
14284 continue;
14285 }
14286
14287 SourceLocation ELoc = RefExpr->getExprLoc();
14288 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
14289 if (DepKind == OMPC_DEPEND_sink) {
14290 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first &&
14291 DepCounter >= TotalDepCount) {
14292 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14293 continue;
14294 }
14295 ++DepCounter;
14296 // OpenMP [2.13.9, Summary]
14297 // depend(dependence-type : vec), where dependence-type is:
14298 // 'sink' and where vec is the iteration vector, which has the form:
14299 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14300 // where n is the value specified by the ordered clause in the loop
14301 // directive, xi denotes the loop iteration variable of the i-th nested
14302 // loop associated with the loop directive, and di is a constant
14303 // non-negative integer.
14304 if (CurContext->isDependentContext()) {
14305 // It will be analyzed later.
14306 Vars.push_back(RefExpr);
14307 continue;
14308 }
14309 SimpleExpr = SimpleExpr->IgnoreImplicit();
14310 OverloadedOperatorKind OOK = OO_None;
14311 SourceLocation OOLoc;
14312 Expr *LHS = SimpleExpr;
14313 Expr *RHS = nullptr;
14314 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14315 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14316 OOLoc = BO->getOperatorLoc();
14317 LHS = BO->getLHS()->IgnoreParenImpCasts();
14318 RHS = BO->getRHS()->IgnoreParenImpCasts();
14319 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14320 OOK = OCE->getOperator();
14321 OOLoc = OCE->getOperatorLoc();
14322 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14323 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14324 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14325 OOK = MCE->getMethodDecl()
14326 ->getNameInfo()
14327 .getName()
14328 .getCXXOverloadedOperator();
14329 OOLoc = MCE->getCallee()->getExprLoc();
14330 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14331 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14332 }
14333 SourceLocation ELoc;
14334 SourceRange ERange;
14335 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
14336 if (Res.second) {
14337 // It will be analyzed later.
14338 Vars.push_back(RefExpr);
14339 }
14340 ValueDecl *D = Res.first;
14341 if (!D)
14342 continue;
14343
14344 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14345 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14346 continue;
14347 }
14348 if (RHS) {
14349 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14350 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14351 if (RHSRes.isInvalid())
14352 continue;
14353 }
14354 if (!CurContext->isDependentContext() &&
14355 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first &&
14356 DepCounter != DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentLoopControlVariable(D).first) {
14357 const ValueDecl *VD =
14358 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentLoopControlVariable(DepCounter.getZExtValue());
14359 if (VD)
14360 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14361 << 1 << VD;
14362 else
14363 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
14364 continue;
14365 }
14366 OpsOffs.emplace_back(RHS, OOK);
14367 } else {
14368 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14369 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14370 (ASE &&
14371 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14372 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14373 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14374 << RefExpr->getSourceRange();
14375 continue;
14376 }
14377
14378 ExprResult Res;
14379 {
14380 Sema::TentativeAnalysisScope Trap(*this);
14381 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
14382 RefExpr->IgnoreParenImpCasts());
14383 }
14384 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
14385 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14386 << RefExpr->getSourceRange();
14387 continue;
14388 }
14389 }
14390 Vars.push_back(RefExpr->IgnoreParenImpCasts());
14391 }
14392
14393 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
14394 TotalDepCount > VarList.size() &&
14395 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentOrderedRegionParam().first &&
14396 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentLoopControlVariable(VarList.size() + 1)) {
14397 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
14398 << 1 << DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getParentLoopControlVariable(VarList.size() + 1);
14399 }
14400 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
14401 Vars.empty())
14402 return nullptr;
14403
14404 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14405 DepKind, DepLoc, ColonLoc, Vars,
14406 TotalDepCount.getZExtValue());
14407 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
14408 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isParentOrderedRegion())
14409 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDoacrossDependClause(C, OpsOffs);
14410 return C;
14411}
14412
14413OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
14414 SourceLocation LParenLoc,
14415 SourceLocation EndLoc) {
14416 Expr *ValExpr = Device;
14417 Stmt *HelperValStmt = nullptr;
14418
14419 // OpenMP [2.9.1, Restrictions]
14420 // The device expression must evaluate to a non-negative integer value.
14421 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
14422 /*StrictlyPositive=*/false))
14423 return nullptr;
14424
14425 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
14426 OpenMPDirectiveKind CaptureRegion =
14427 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
14428 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
14429 ValExpr = MakeFullExpr(ValExpr).get();
14430 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
14431 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14432 HelperValStmt = buildPreInits(Context, Captures);
14433 }
14434
14435 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
14436 StartLoc, LParenLoc, EndLoc);
14437}
14438
14439static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
14440 DSAStackTy *Stack, QualType QTy,
14441 bool FullCheck = true) {
14442 NamedDecl *ND;
14443 if (QTy->isIncompleteType(&ND)) {
14444 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
14445 return false;
14446 }
14447 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
14448 !QTy.isTrivialType(SemaRef.Context))
14449 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
14450 return true;
14451}
14452
14453/// Return true if it can be proven that the provided array expression
14454/// (array section or array subscript) does NOT specify the whole size of the
14455/// array whose base type is \a BaseQTy.
14456static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
14457 const Expr *E,
14458 QualType BaseQTy) {
14459 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
14460
14461 // If this is an array subscript, it refers to the whole size if the size of
14462 // the dimension is constant and equals 1. Also, an array section assumes the
14463 // format of an array subscript if no colon is used.
14464 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
14465 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
14466 return ATy->getSize().getSExtValue() != 1;
14467 // Size can't be evaluated statically.
14468 return false;
14469 }
14470
14471 assert(OASE && "Expecting array section if not an array subscript.")((OASE && "Expecting array section if not an array subscript."
) ? static_cast<void> (0) : __assert_fail ("OASE && \"Expecting array section if not an array subscript.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14471, __PRETTY_FUNCTION__))
;
14472 const Expr *LowerBound = OASE->getLowerBound();
14473 const Expr *Length = OASE->getLength();
14474
14475 // If there is a lower bound that does not evaluates to zero, we are not
14476 // covering the whole dimension.
14477 if (LowerBound) {
14478 Expr::EvalResult Result;
14479 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
14480 return false; // Can't get the integer value as a constant.
14481
14482 llvm::APSInt ConstLowerBound = Result.Val.getInt();
14483 if (ConstLowerBound.getSExtValue())
14484 return true;
14485 }
14486
14487 // If we don't have a length we covering the whole dimension.
14488 if (!Length)
14489 return false;
14490
14491 // If the base is a pointer, we don't have a way to get the size of the
14492 // pointee.
14493 if (BaseQTy->isPointerType())
14494 return false;
14495
14496 // We can only check if the length is the same as the size of the dimension
14497 // if we have a constant array.
14498 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
14499 if (!CATy)
14500 return false;
14501
14502 Expr::EvalResult Result;
14503 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
14504 return false; // Can't get the integer value as a constant.
14505
14506 llvm::APSInt ConstLength = Result.Val.getInt();
14507 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
14508}
14509
14510// Return true if it can be proven that the provided array expression (array
14511// section or array subscript) does NOT specify a single element of the array
14512// whose base type is \a BaseQTy.
14513static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
14514 const Expr *E,
14515 QualType BaseQTy) {
14516 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
14517
14518 // An array subscript always refer to a single element. Also, an array section
14519 // assumes the format of an array subscript if no colon is used.
14520 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
14521 return false;
14522
14523 assert(OASE && "Expecting array section if not an array subscript.")((OASE && "Expecting array section if not an array subscript."
) ? static_cast<void> (0) : __assert_fail ("OASE && \"Expecting array section if not an array subscript.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14523, __PRETTY_FUNCTION__))
;
14524 const Expr *Length = OASE->getLength();
14525
14526 // If we don't have a length we have to check if the array has unitary size
14527 // for this dimension. Also, we should always expect a length if the base type
14528 // is pointer.
14529 if (!Length) {
14530 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
14531 return ATy->getSize().getSExtValue() != 1;
14532 // We cannot assume anything.
14533 return false;
14534 }
14535
14536 // Check if the length evaluates to 1.
14537 Expr::EvalResult Result;
14538 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
14539 return false; // Can't get the integer value as a constant.
14540
14541 llvm::APSInt ConstLength = Result.Val.getInt();
14542 return ConstLength.getSExtValue() != 1;
14543}
14544
14545// Return the expression of the base of the mappable expression or null if it
14546// cannot be determined and do all the necessary checks to see if the expression
14547// is valid as a standalone mappable expression. In the process, record all the
14548// components of the expression.
14549static const Expr *checkMapClauseExpressionBase(
14550 Sema &SemaRef, Expr *E,
14551 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
14552 OpenMPClauseKind CKind, bool NoDiagnose) {
14553 SourceLocation ELoc = E->getExprLoc();
14554 SourceRange ERange = E->getSourceRange();
14555
14556 // The base of elements of list in a map clause have to be either:
14557 // - a reference to variable or field.
14558 // - a member expression.
14559 // - an array expression.
14560 //
14561 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
14562 // reference to 'r'.
14563 //
14564 // If we have:
14565 //
14566 // struct SS {
14567 // Bla S;
14568 // foo() {
14569 // #pragma omp target map (S.Arr[:12]);
14570 // }
14571 // }
14572 //
14573 // We want to retrieve the member expression 'this->S';
14574
14575 const Expr *RelevantExpr = nullptr;
14576
14577 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
14578 // If a list item is an array section, it must specify contiguous storage.
14579 //
14580 // For this restriction it is sufficient that we make sure only references
14581 // to variables or fields and array expressions, and that no array sections
14582 // exist except in the rightmost expression (unless they cover the whole
14583 // dimension of the array). E.g. these would be invalid:
14584 //
14585 // r.ArrS[3:5].Arr[6:7]
14586 //
14587 // r.ArrS[3:5].x
14588 //
14589 // but these would be valid:
14590 // r.ArrS[3].Arr[6:7]
14591 //
14592 // r.ArrS[3].x
14593
14594 bool AllowUnitySizeArraySection = true;
14595 bool AllowWholeSizeArraySection = true;
14596
14597 while (!RelevantExpr) {
14598 E = E->IgnoreParenImpCasts();
14599
14600 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
14601 if (!isa<VarDecl>(CurE->getDecl()))
14602 return nullptr;
14603
14604 RelevantExpr = CurE;
14605
14606 // If we got a reference to a declaration, we should not expect any array
14607 // section before that.
14608 AllowUnitySizeArraySection = false;
14609 AllowWholeSizeArraySection = false;
14610
14611 // Record the component.
14612 CurComponents.emplace_back(CurE, CurE->getDecl());
14613 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
14614 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
14615
14616 if (isa<CXXThisExpr>(BaseE))
14617 // We found a base expression: this->Val.
14618 RelevantExpr = CurE;
14619 else
14620 E = BaseE;
14621
14622 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
14623 if (!NoDiagnose) {
14624 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
14625 << CurE->getSourceRange();
14626 return nullptr;
14627 }
14628 if (RelevantExpr)
14629 return nullptr;
14630 continue;
14631 }
14632
14633 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
14634
14635 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
14636 // A bit-field cannot appear in a map clause.
14637 //
14638 if (FD->isBitField()) {
14639 if (!NoDiagnose) {
14640 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
14641 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
14642 return nullptr;
14643 }
14644 if (RelevantExpr)
14645 return nullptr;
14646 continue;
14647 }
14648
14649 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14650 // If the type of a list item is a reference to a type T then the type
14651 // will be considered to be T for all purposes of this clause.
14652 QualType CurType = BaseE->getType().getNonReferenceType();
14653
14654 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
14655 // A list item cannot be a variable that is a member of a structure with
14656 // a union type.
14657 //
14658 if (CurType->isUnionType()) {
14659 if (!NoDiagnose) {
14660 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
14661 << CurE->getSourceRange();
14662 return nullptr;
14663 }
14664 continue;
14665 }
14666
14667 // If we got a member expression, we should not expect any array section
14668 // before that:
14669 //
14670 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
14671 // If a list item is an element of a structure, only the rightmost symbol
14672 // of the variable reference can be an array section.
14673 //
14674 AllowUnitySizeArraySection = false;
14675 AllowWholeSizeArraySection = false;
14676
14677 // Record the component.
14678 CurComponents.emplace_back(CurE, FD);
14679 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
14680 E = CurE->getBase()->IgnoreParenImpCasts();
14681
14682 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
14683 if (!NoDiagnose) {
14684 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14685 << 0 << CurE->getSourceRange();
14686 return nullptr;
14687 }
14688 continue;
14689 }
14690
14691 // If we got an array subscript that express the whole dimension we
14692 // can have any array expressions before. If it only expressing part of
14693 // the dimension, we can only have unitary-size array expressions.
14694 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
14695 E->getType()))
14696 AllowWholeSizeArraySection = false;
14697
14698 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14699 Expr::EvalResult Result;
14700 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
14701 if (!Result.Val.getInt().isNullValue()) {
14702 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14703 diag::err_omp_invalid_map_this_expr);
14704 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14705 diag::note_omp_invalid_subscript_on_this_ptr_map);
14706 }
14707 }
14708 RelevantExpr = TE;
14709 }
14710
14711 // Record the component - we don't have any declaration associated.
14712 CurComponents.emplace_back(CurE, nullptr);
14713 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
14714 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.")((!NoDiagnose && "Array sections cannot be implicitly mapped."
) ? static_cast<void> (0) : __assert_fail ("!NoDiagnose && \"Array sections cannot be implicitly mapped.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14714, __PRETTY_FUNCTION__))
;
14715 E = CurE->getBase()->IgnoreParenImpCasts();
14716
14717 QualType CurType =
14718 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14719
14720 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14721 // If the type of a list item is a reference to a type T then the type
14722 // will be considered to be T for all purposes of this clause.
14723 if (CurType->isReferenceType())
14724 CurType = CurType->getPointeeType();
14725
14726 bool IsPointer = CurType->isAnyPointerType();
14727
14728 if (!IsPointer && !CurType->isArrayType()) {
14729 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14730 << 0 << CurE->getSourceRange();
14731 return nullptr;
14732 }
14733
14734 bool NotWhole =
14735 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
14736 bool NotUnity =
14737 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
14738
14739 if (AllowWholeSizeArraySection) {
14740 // Any array section is currently allowed. Allowing a whole size array
14741 // section implies allowing a unity array section as well.
14742 //
14743 // If this array section refers to the whole dimension we can still
14744 // accept other array sections before this one, except if the base is a
14745 // pointer. Otherwise, only unitary sections are accepted.
14746 if (NotWhole || IsPointer)
14747 AllowWholeSizeArraySection = false;
14748 } else if (AllowUnitySizeArraySection && NotUnity) {
14749 // A unity or whole array section is not allowed and that is not
14750 // compatible with the properties of the current array section.
14751 SemaRef.Diag(
14752 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
14753 << CurE->getSourceRange();
14754 return nullptr;
14755 }
14756
14757 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14758 Expr::EvalResult ResultR;
14759 Expr::EvalResult ResultL;
14760 if (CurE->getLength()->EvaluateAsInt(ResultR,
14761 SemaRef.getASTContext())) {
14762 if (!ResultR.Val.getInt().isOneValue()) {
14763 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14764 diag::err_omp_invalid_map_this_expr);
14765 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14766 diag::note_omp_invalid_length_on_this_ptr_mapping);
14767 }
14768 }
14769 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
14770 ResultL, SemaRef.getASTContext())) {
14771 if (!ResultL.Val.getInt().isNullValue()) {
14772 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14773 diag::err_omp_invalid_map_this_expr);
14774 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14775 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
14776 }
14777 }
14778 RelevantExpr = TE;
14779 }
14780
14781 // Record the component - we don't have any declaration associated.
14782 CurComponents.emplace_back(CurE, nullptr);
14783 } else {
14784 if (!NoDiagnose) {
14785 // If nothing else worked, this is not a valid map clause expression.
14786 SemaRef.Diag(
14787 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
14788 << ERange;
14789 }
14790 return nullptr;
14791 }
14792 }
14793
14794 return RelevantExpr;
14795}
14796
14797// Return true if expression E associated with value VD has conflicts with other
14798// map information.
14799static bool checkMapConflicts(
14800 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
14801 bool CurrentRegionOnly,
14802 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
14803 OpenMPClauseKind CKind) {
14804 assert(VD && E)((VD && E) ? static_cast<void> (0) : __assert_fail
("VD && E", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14804, __PRETTY_FUNCTION__))
;
14805 SourceLocation ELoc = E->getExprLoc();
14806 SourceRange ERange = E->getSourceRange();
14807
14808 // In order to easily check the conflicts we need to match each component of
14809 // the expression under test with the components of the expressions that are
14810 // already in the stack.
14811
14812 assert(!CurComponents.empty() && "Map clause expression with no components!")((!CurComponents.empty() && "Map clause expression with no components!"
) ? static_cast<void> (0) : __assert_fail ("!CurComponents.empty() && \"Map clause expression with no components!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14812, __PRETTY_FUNCTION__))
;
14813 assert(CurComponents.back().getAssociatedDeclaration() == VD &&((CurComponents.back().getAssociatedDeclaration() == VD &&
"Map clause expression with unexpected base!") ? static_cast
<void> (0) : __assert_fail ("CurComponents.back().getAssociatedDeclaration() == VD && \"Map clause expression with unexpected base!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14814, __PRETTY_FUNCTION__))
14814 "Map clause expression with unexpected base!")((CurComponents.back().getAssociatedDeclaration() == VD &&
"Map clause expression with unexpected base!") ? static_cast
<void> (0) : __assert_fail ("CurComponents.back().getAssociatedDeclaration() == VD && \"Map clause expression with unexpected base!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14814, __PRETTY_FUNCTION__))
;
14815
14816 // Variables to help detecting enclosing problems in data environment nests.
14817 bool IsEnclosedByDataEnvironmentExpr = false;
14818 const Expr *EnclosingExpr = nullptr;
14819
14820 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
14821 VD, CurrentRegionOnly,
14822 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
14823 ERange, CKind, &EnclosingExpr,
14824 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
14825 StackComponents,
14826 OpenMPClauseKind) {
14827 assert(!StackComponents.empty() &&((!StackComponents.empty() && "Map clause expression with no components!"
) ? static_cast<void> (0) : __assert_fail ("!StackComponents.empty() && \"Map clause expression with no components!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14828, __PRETTY_FUNCTION__))
14828 "Map clause expression with no components!")((!StackComponents.empty() && "Map clause expression with no components!"
) ? static_cast<void> (0) : __assert_fail ("!StackComponents.empty() && \"Map clause expression with no components!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14828, __PRETTY_FUNCTION__))
;
14829 assert(StackComponents.back().getAssociatedDeclaration() == VD &&((StackComponents.back().getAssociatedDeclaration() == VD &&
"Map clause expression with unexpected base!") ? static_cast
<void> (0) : __assert_fail ("StackComponents.back().getAssociatedDeclaration() == VD && \"Map clause expression with unexpected base!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14830, __PRETTY_FUNCTION__))
14830 "Map clause expression with unexpected base!")((StackComponents.back().getAssociatedDeclaration() == VD &&
"Map clause expression with unexpected base!") ? static_cast
<void> (0) : __assert_fail ("StackComponents.back().getAssociatedDeclaration() == VD && \"Map clause expression with unexpected base!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14830, __PRETTY_FUNCTION__))
;
14831 (void)VD;
14832
14833 // The whole expression in the stack.
14834 const Expr *RE = StackComponents.front().getAssociatedExpression();
14835
14836 // Expressions must start from the same base. Here we detect at which
14837 // point both expressions diverge from each other and see if we can
14838 // detect if the memory referred to both expressions is contiguous and
14839 // do not overlap.
14840 auto CI = CurComponents.rbegin();
14841 auto CE = CurComponents.rend();
14842 auto SI = StackComponents.rbegin();
14843 auto SE = StackComponents.rend();
14844 for (; CI != CE && SI != SE; ++CI, ++SI) {
14845
14846 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
14847 // At most one list item can be an array item derived from a given
14848 // variable in map clauses of the same construct.
14849 if (CurrentRegionOnly &&
14850 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
14851 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
14852 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
14853 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
14854 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
14855 diag::err_omp_multiple_array_items_in_map_clause)
14856 << CI->getAssociatedExpression()->getSourceRange();
14857 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
14858 diag::note_used_here)
14859 << SI->getAssociatedExpression()->getSourceRange();
14860 return true;
14861 }
14862
14863 // Do both expressions have the same kind?
14864 if (CI->getAssociatedExpression()->getStmtClass() !=
14865 SI->getAssociatedExpression()->getStmtClass())
14866 break;
14867
14868 // Are we dealing with different variables/fields?
14869 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
14870 break;
14871 }
14872 // Check if the extra components of the expressions in the enclosing
14873 // data environment are redundant for the current base declaration.
14874 // If they are, the maps completely overlap, which is legal.
14875 for (; SI != SE; ++SI) {
14876 QualType Type;
14877 if (const auto *ASE =
14878 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
14879 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
14880 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
14881 SI->getAssociatedExpression())) {
14882 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
14883 Type =
14884 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14885 }
14886 if (Type.isNull() || Type->isAnyPointerType() ||
14887 checkArrayExpressionDoesNotReferToWholeSize(
14888 SemaRef, SI->getAssociatedExpression(), Type))
14889 break;
14890 }
14891
14892 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
14893 // List items of map clauses in the same construct must not share
14894 // original storage.
14895 //
14896 // If the expressions are exactly the same or one is a subset of the
14897 // other, it means they are sharing storage.
14898 if (CI == CE && SI == SE) {
14899 if (CurrentRegionOnly) {
14900 if (CKind == OMPC_map) {
14901 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
14902 } else {
14903 assert(CKind == OMPC_to || CKind == OMPC_from)((CKind == OMPC_to || CKind == OMPC_from) ? static_cast<void
> (0) : __assert_fail ("CKind == OMPC_to || CKind == OMPC_from"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14903, __PRETTY_FUNCTION__))
;
14904 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
14905 << ERange;
14906 }
14907 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14908 << RE->getSourceRange();
14909 return true;
14910 }
14911 // If we find the same expression in the enclosing data environment,
14912 // that is legal.
14913 IsEnclosedByDataEnvironmentExpr = true;
14914 return false;
14915 }
14916
14917 QualType DerivedType =
14918 std::prev(CI)->getAssociatedDeclaration()->getType();
14919 SourceLocation DerivedLoc =
14920 std::prev(CI)->getAssociatedExpression()->getExprLoc();
14921
14922 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14923 // If the type of a list item is a reference to a type T then the type
14924 // will be considered to be T for all purposes of this clause.
14925 DerivedType = DerivedType.getNonReferenceType();
14926
14927 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
14928 // A variable for which the type is pointer and an array section
14929 // derived from that variable must not appear as list items of map
14930 // clauses of the same construct.
14931 //
14932 // Also, cover one of the cases in:
14933 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
14934 // If any part of the original storage of a list item has corresponding
14935 // storage in the device data environment, all of the original storage
14936 // must have corresponding storage in the device data environment.
14937 //
14938 if (DerivedType->isAnyPointerType()) {
14939 if (CI == CE || SI == SE) {
14940 SemaRef.Diag(
14941 DerivedLoc,
14942 diag::err_omp_pointer_mapped_along_with_derived_section)
14943 << DerivedLoc;
14944 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14945 << RE->getSourceRange();
14946 return true;
14947 }
14948 if (CI->getAssociatedExpression()->getStmtClass() !=
14949 SI->getAssociatedExpression()->getStmtClass() ||
14950 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
14951 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
14952 assert(CI != CE && SI != SE)((CI != CE && SI != SE) ? static_cast<void> (0)
: __assert_fail ("CI != CE && SI != SE", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14952, __PRETTY_FUNCTION__))
;
14953 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
14954 << DerivedLoc;
14955 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14956 << RE->getSourceRange();
14957 return true;
14958 }
14959 }
14960
14961 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
14962 // List items of map clauses in the same construct must not share
14963 // original storage.
14964 //
14965 // An expression is a subset of the other.
14966 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
14967 if (CKind == OMPC_map) {
14968 if (CI != CE || SI != SE) {
14969 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
14970 // a pointer.
14971 auto Begin =
14972 CI != CE ? CurComponents.begin() : StackComponents.begin();
14973 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
14974 auto It = Begin;
14975 while (It != End && !It->getAssociatedDeclaration())
14976 std::advance(It, 1);
14977 assert(It != End &&((It != End && "Expected at least one component with the declaration."
) ? static_cast<void> (0) : __assert_fail ("It != End && \"Expected at least one component with the declaration.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14978, __PRETTY_FUNCTION__))
14978 "Expected at least one component with the declaration.")((It != End && "Expected at least one component with the declaration."
) ? static_cast<void> (0) : __assert_fail ("It != End && \"Expected at least one component with the declaration.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14978, __PRETTY_FUNCTION__))
;
14979 if (It != Begin && It->getAssociatedDeclaration()
14980 ->getType()
14981 .getCanonicalType()
14982 ->isAnyPointerType()) {
14983 IsEnclosedByDataEnvironmentExpr = false;
14984 EnclosingExpr = nullptr;
14985 return false;
14986 }
14987 }
14988 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
14989 } else {
14990 assert(CKind == OMPC_to || CKind == OMPC_from)((CKind == OMPC_to || CKind == OMPC_from) ? static_cast<void
> (0) : __assert_fail ("CKind == OMPC_to || CKind == OMPC_from"
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 14990, __PRETTY_FUNCTION__))
;
14991 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
14992 << ERange;
14993 }
14994 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14995 << RE->getSourceRange();
14996 return true;
14997 }
14998
14999 // The current expression uses the same base as other expression in the
15000 // data environment but does not contain it completely.
15001 if (!CurrentRegionOnly && SI != SE)
15002 EnclosingExpr = RE;
15003
15004 // The current expression is a subset of the expression in the data
15005 // environment.
15006 IsEnclosedByDataEnvironmentExpr |=
15007 (!CurrentRegionOnly && CI != CE && SI == SE);
15008
15009 return false;
15010 });
15011
15012 if (CurrentRegionOnly)
15013 return FoundError;
15014
15015 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15016 // If any part of the original storage of a list item has corresponding
15017 // storage in the device data environment, all of the original storage must
15018 // have corresponding storage in the device data environment.
15019 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15020 // If a list item is an element of a structure, and a different element of
15021 // the structure has a corresponding list item in the device data environment
15022 // prior to a task encountering the construct associated with the map clause,
15023 // then the list item must also have a corresponding list item in the device
15024 // data environment prior to the task encountering the construct.
15025 //
15026 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15027 SemaRef.Diag(ELoc,
15028 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15029 << ERange;
15030 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15031 << EnclosingExpr->getSourceRange();
15032 return true;
15033 }
15034
15035 return FoundError;
15036}
15037
15038// Look up the user-defined mapper given the mapper name and mapped type, and
15039// build a reference to it.
15040static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15041 CXXScopeSpec &MapperIdScopeSpec,
15042 const DeclarationNameInfo &MapperId,
15043 QualType Type,
15044 Expr *UnresolvedMapper) {
15045 if (MapperIdScopeSpec.isInvalid())
15046 return ExprError();
15047 // Get the actual type for the array type.
15048 if (Type->isArrayType()) {
15049 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type")((Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type"
) ? static_cast<void> (0) : __assert_fail ("Type->getAsArrayTypeUnsafe() && \"Expect to get a valid array type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15049, __PRETTY_FUNCTION__))
;
15050 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15051 }
15052 // Find all user-defined mappers with the given MapperId.
15053 SmallVector<UnresolvedSet<8>, 4> Lookups;
15054 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15055 Lookup.suppressDiagnostics();
15056 if (S) {
15057 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15058 NamedDecl *D = Lookup.getRepresentativeDecl();
15059 while (S && !S->isDeclScope(D))
15060 S = S->getParent();
15061 if (S)
15062 S = S->getParent();
15063 Lookups.emplace_back();
15064 Lookups.back().append(Lookup.begin(), Lookup.end());
15065 Lookup.clear();
15066 }
15067 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15068 // Extract the user-defined mappers with the given MapperId.
15069 Lookups.push_back(UnresolvedSet<8>());
15070 for (NamedDecl *D : ULE->decls()) {
15071 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15072 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.")((DMD && "Expect valid OMPDeclareMapperDecl during instantiation."
) ? static_cast<void> (0) : __assert_fail ("DMD && \"Expect valid OMPDeclareMapperDecl during instantiation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15072, __PRETTY_FUNCTION__))
;
15073 Lookups.back().addDecl(DMD);
15074 }
15075 }
15076 // Defer the lookup for dependent types. The results will be passed through
15077 // UnresolvedMapper on instantiation.
15078 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15079 Type->isInstantiationDependentType() ||
15080 Type->containsUnexpandedParameterPack() ||
15081 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15082 return !D->isInvalidDecl() &&
15083 (D->getType()->isDependentType() ||
15084 D->getType()->isInstantiationDependentType() ||
15085 D->getType()->containsUnexpandedParameterPack());
15086 })) {
15087 UnresolvedSet<8> URS;
15088 for (const UnresolvedSet<8> &Set : Lookups) {
15089 if (Set.empty())
15090 continue;
15091 URS.append(Set.begin(), Set.end());
15092 }
15093 return UnresolvedLookupExpr::Create(
15094 SemaRef.Context, /*NamingClass=*/nullptr,
15095 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15096 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15097 }
15098 SourceLocation Loc = MapperId.getLoc();
15099 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15100 // The type must be of struct, union or class type in C and C++
15101 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15102 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15103 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15104 return ExprError();
15105 }
15106 // Perform argument dependent lookup.
15107 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15108 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15109 // Return the first user-defined mapper with the desired type.
15110 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15111 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15112 if (!D->isInvalidDecl() &&
15113 SemaRef.Context.hasSameType(D->getType(), Type))
15114 return D;
15115 return nullptr;
15116 }))
15117 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15118 // Find the first user-defined mapper with a type derived from the desired
15119 // type.
15120 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15121 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15122 if (!D->isInvalidDecl() &&
15123 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15124 !Type.isMoreQualifiedThan(D->getType()))
15125 return D;
15126 return nullptr;
15127 })) {
15128 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15129 /*DetectVirtual=*/false);
15130 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15131 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15132 VD->getType().getUnqualifiedType()))) {
15133 if (SemaRef.CheckBaseClassAccess(
15134 Loc, VD->getType(), Type, Paths.front(),
15135 /*DiagID=*/0) != Sema::AR_inaccessible) {
15136 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15137 }
15138 }
15139 }
15140 }
15141 // Report error if a mapper is specified, but cannot be found.
15142 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15143 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15144 << Type << MapperId.getName();
15145 return ExprError();
15146 }
15147 return ExprEmpty();
15148}
15149
15150namespace {
15151// Utility struct that gathers all the related lists associated with a mappable
15152// expression.
15153struct MappableVarListInfo {
15154 // The list of expressions.
15155 ArrayRef<Expr *> VarList;
15156 // The list of processed expressions.
15157 SmallVector<Expr *, 16> ProcessedVarList;
15158 // The mappble components for each expression.
15159 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15160 // The base declaration of the variable.
15161 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
15162 // The reference to the user-defined mapper associated with every expression.
15163 SmallVector<Expr *, 16> UDMapperList;
15164
15165 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15166 // We have a list of components and base declarations for each entry in the
15167 // variable list.
15168 VarComponents.reserve(VarList.size());
15169 VarBaseDeclarations.reserve(VarList.size());
15170 }
15171};
15172}
15173
15174// Check the validity of the provided variable list for the provided clause kind
15175// \a CKind. In the check process the valid expressions, mappable expression
15176// components, variables, and user-defined mappers are extracted and used to
15177// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15178// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15179// and \a MapperId are expected to be valid if the clause kind is 'map'.
15180static void checkMappableExpressionList(
15181 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15182 MappableVarListInfo &MVLI, SourceLocation StartLoc,
15183 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15184 ArrayRef<Expr *> UnresolvedMappers,
15185 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
15186 bool IsMapTypeImplicit = false) {
15187 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15188 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&(((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from
) && "Unexpected clause kind with mappable expressions!"
) ? static_cast<void> (0) : __assert_fail ("(CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && \"Unexpected clause kind with mappable expressions!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15189, __PRETTY_FUNCTION__))
15189 "Unexpected clause kind with mappable expressions!")(((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from
) && "Unexpected clause kind with mappable expressions!"
) ? static_cast<void> (0) : __assert_fail ("(CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && \"Unexpected clause kind with mappable expressions!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15189, __PRETTY_FUNCTION__))
;
15190
15191 // If the identifier of user-defined mapper is not specified, it is "default".
15192 // We do not change the actual name in this clause to distinguish whether a
15193 // mapper is specified explicitly, i.e., it is not explicitly specified when
15194 // MapperId.getName() is empty.
15195 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15196 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15197 MapperId.setName(DeclNames.getIdentifier(
15198 &SemaRef.getASTContext().Idents.get("default")));
15199 }
15200
15201 // Iterators to find the current unresolved mapper expression.
15202 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15203 bool UpdateUMIt = false;
15204 Expr *UnresolvedMapper = nullptr;
15205
15206 // Keep track of the mappable components and base declarations in this clause.
15207 // Each entry in the list is going to have a list of components associated. We
15208 // record each set of the components so that we can build the clause later on.
15209 // In the end we should have the same amount of declarations and component
15210 // lists.
15211
15212 for (Expr *RE : MVLI.VarList) {
15213 assert(RE && "Null expr in omp to/from/map clause")((RE && "Null expr in omp to/from/map clause") ? static_cast
<void> (0) : __assert_fail ("RE && \"Null expr in omp to/from/map clause\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15213, __PRETTY_FUNCTION__))
;
15214 SourceLocation ELoc = RE->getExprLoc();
15215
15216 // Find the current unresolved mapper expression.
15217 if (UpdateUMIt && UMIt != UMEnd) {
15218 UMIt++;
15219 assert(((UMIt != UMEnd && "Expect the size of UnresolvedMappers to match with that of VarList"
) ? static_cast<void> (0) : __assert_fail ("UMIt != UMEnd && \"Expect the size of UnresolvedMappers to match with that of VarList\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15221, __PRETTY_FUNCTION__))
15220 UMIt != UMEnd &&((UMIt != UMEnd && "Expect the size of UnresolvedMappers to match with that of VarList"
) ? static_cast<void> (0) : __assert_fail ("UMIt != UMEnd && \"Expect the size of UnresolvedMappers to match with that of VarList\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15221, __PRETTY_FUNCTION__))
15221 "Expect the size of UnresolvedMappers to match with that of VarList")((UMIt != UMEnd && "Expect the size of UnresolvedMappers to match with that of VarList"
) ? static_cast<void> (0) : __assert_fail ("UMIt != UMEnd && \"Expect the size of UnresolvedMappers to match with that of VarList\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15221, __PRETTY_FUNCTION__))
;
15222 }
15223 UpdateUMIt = true;
15224 if (UMIt != UMEnd)
15225 UnresolvedMapper = *UMIt;
15226
15227 const Expr *VE = RE->IgnoreParenLValueCasts();
15228
15229 if (VE->isValueDependent() || VE->isTypeDependent() ||
15230 VE->isInstantiationDependent() ||
15231 VE->containsUnexpandedParameterPack()) {
15232 // Try to find the associated user-defined mapper.
15233 ExprResult ER = buildUserDefinedMapperRef(
15234 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15235 VE->getType().getCanonicalType(), UnresolvedMapper);
15236 if (ER.isInvalid())
15237 continue;
15238 MVLI.UDMapperList.push_back(ER.get());
15239 // We can only analyze this information once the missing information is
15240 // resolved.
15241 MVLI.ProcessedVarList.push_back(RE);
15242 continue;
15243 }
15244
15245 Expr *SimpleExpr = RE->IgnoreParenCasts();
15246
15247 if (!RE->IgnoreParenImpCasts()->isLValue()) {
15248 SemaRef.Diag(ELoc,
15249 diag::err_omp_expected_named_var_member_or_array_expression)
15250 << RE->getSourceRange();
15251 continue;
15252 }
15253
15254 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15255 ValueDecl *CurDeclaration = nullptr;
15256
15257 // Obtain the array or member expression bases if required. Also, fill the
15258 // components array with all the components identified in the process.
15259 const Expr *BE = checkMapClauseExpressionBase(
15260 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
15261 if (!BE)
15262 continue;
15263
15264 assert(!CurComponents.empty() &&((!CurComponents.empty() && "Invalid mappable expression information."
) ? static_cast<void> (0) : __assert_fail ("!CurComponents.empty() && \"Invalid mappable expression information.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15265, __PRETTY_FUNCTION__))
15265 "Invalid mappable expression information.")((!CurComponents.empty() && "Invalid mappable expression information."
) ? static_cast<void> (0) : __assert_fail ("!CurComponents.empty() && \"Invalid mappable expression information.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15265, __PRETTY_FUNCTION__))
;
15266
15267 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15268 // Add store "this" pointer to class in DSAStackTy for future checking
15269 DSAS->addMappedClassesQualTypes(TE->getType());
15270 // Try to find the associated user-defined mapper.
15271 ExprResult ER = buildUserDefinedMapperRef(
15272 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15273 VE->getType().getCanonicalType(), UnresolvedMapper);
15274 if (ER.isInvalid())
15275 continue;
15276 MVLI.UDMapperList.push_back(ER.get());
15277 // Skip restriction checking for variable or field declarations
15278 MVLI.ProcessedVarList.push_back(RE);
15279 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15280 MVLI.VarComponents.back().append(CurComponents.begin(),
15281 CurComponents.end());
15282 MVLI.VarBaseDeclarations.push_back(nullptr);
15283 continue;
15284 }
15285
15286 // For the following checks, we rely on the base declaration which is
15287 // expected to be associated with the last component. The declaration is
15288 // expected to be a variable or a field (if 'this' is being mapped).
15289 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15290 assert(CurDeclaration && "Null decl on map clause.")((CurDeclaration && "Null decl on map clause.") ? static_cast
<void> (0) : __assert_fail ("CurDeclaration && \"Null decl on map clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15290, __PRETTY_FUNCTION__))
;
15291 assert(((CurDeclaration->isCanonicalDecl() && "Expecting components to have associated only canonical declarations."
) ? static_cast<void> (0) : __assert_fail ("CurDeclaration->isCanonicalDecl() && \"Expecting components to have associated only canonical declarations.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15293, __PRETTY_FUNCTION__))
15292 CurDeclaration->isCanonicalDecl() &&((CurDeclaration->isCanonicalDecl() && "Expecting components to have associated only canonical declarations."
) ? static_cast<void> (0) : __assert_fail ("CurDeclaration->isCanonicalDecl() && \"Expecting components to have associated only canonical declarations.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15293, __PRETTY_FUNCTION__))
15293 "Expecting components to have associated only canonical declarations.")((CurDeclaration->isCanonicalDecl() && "Expecting components to have associated only canonical declarations."
) ? static_cast<void> (0) : __assert_fail ("CurDeclaration->isCanonicalDecl() && \"Expecting components to have associated only canonical declarations.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15293, __PRETTY_FUNCTION__))
;
15294
15295 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
15296 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
15297
15298 assert((VD || FD) && "Only variables or fields are expected here!")(((VD || FD) && "Only variables or fields are expected here!"
) ? static_cast<void> (0) : __assert_fail ("(VD || FD) && \"Only variables or fields are expected here!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15298, __PRETTY_FUNCTION__))
;
15299 (void)FD;
15300
15301 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
15302 // threadprivate variables cannot appear in a map clause.
15303 // OpenMP 4.5 [2.10.5, target update Construct]
15304 // threadprivate variables cannot appear in a from clause.
15305 if (VD && DSAS->isThreadPrivate(VD)) {
15306 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
15307 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15308 << getOpenMPClauseName(CKind);
15309 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
15310 continue;
15311 }
15312
15313 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15314 // A list item cannot appear in both a map clause and a data-sharing
15315 // attribute clause on the same construct.
15316
15317 // Check conflicts with other map clause expressions. We check the conflicts
15318 // with the current construct separately from the enclosing data
15319 // environment, because the restrictions are different. We only have to
15320 // check conflicts across regions for the map clauses.
15321 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
15322 /*CurrentRegionOnly=*/true, CurComponents, CKind))
15323 break;
15324 if (CKind == OMPC_map &&
15325 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
15326 /*CurrentRegionOnly=*/false, CurComponents, CKind))
15327 break;
15328
15329 // OpenMP 4.5 [2.10.5, target update Construct]
15330 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15331 // If the type of a list item is a reference to a type T then the type will
15332 // be considered to be T for all purposes of this clause.
15333 auto I = llvm::find_if(
15334 CurComponents,
15335 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15336 return MC.getAssociatedDeclaration();
15337 });
15338 assert(I != CurComponents.end() && "Null decl on map clause.")((I != CurComponents.end() && "Null decl on map clause."
) ? static_cast<void> (0) : __assert_fail ("I != CurComponents.end() && \"Null decl on map clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15338, __PRETTY_FUNCTION__))
;
15339 QualType Type =
15340 I->getAssociatedDeclaration()->getType().getNonReferenceType();
15341
15342 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15343 // A list item in a to or from clause must have a mappable type.
15344 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15345 // A list item must have a mappable type.
15346 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
15347 DSAS, Type))
15348 continue;
15349
15350 if (CKind == OMPC_map) {
15351 // target enter data
15352 // OpenMP [2.10.2, Restrictions, p. 99]
15353 // A map-type must be specified in all map clauses and must be either
15354 // to or alloc.
15355 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15356 if (DKind == OMPD_target_enter_data &&
15357 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15358 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15359 << (IsMapTypeImplicit ? 1 : 0)
15360 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15361 << getOpenMPDirectiveName(DKind);
15362 continue;
15363 }
15364
15365 // target exit_data
15366 // OpenMP [2.10.3, Restrictions, p. 102]
15367 // A map-type must be specified in all map clauses and must be either
15368 // from, release, or delete.
15369 if (DKind == OMPD_target_exit_data &&
15370 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15371 MapType == OMPC_MAP_delete)) {
15372 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15373 << (IsMapTypeImplicit ? 1 : 0)
15374 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15375 << getOpenMPDirectiveName(DKind);
15376 continue;
15377 }
15378
15379 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15380 // A list item cannot appear in both a map clause and a data-sharing
15381 // attribute clause on the same construct
15382 //
15383 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15384 // A list item cannot appear in both a map clause and a data-sharing
15385 // attribute clause on the same construct unless the construct is a
15386 // combined construct.
15387 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
15388 isOpenMPTargetExecutionDirective(DKind)) ||
15389 DKind == OMPD_target)) {
15390 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
15391 if (isOpenMPPrivate(DVar.CKind)) {
15392 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15393 << getOpenMPClauseName(DVar.CKind)
15394 << getOpenMPClauseName(OMPC_map)
15395 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
15396 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
15397 continue;
15398 }
15399 }
15400 }
15401
15402 // Try to find the associated user-defined mapper.
15403 ExprResult ER = buildUserDefinedMapperRef(
15404 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15405 Type.getCanonicalType(), UnresolvedMapper);
15406 if (ER.isInvalid())
15407 continue;
15408 MVLI.UDMapperList.push_back(ER.get());
15409
15410 // Save the current expression.
15411 MVLI.ProcessedVarList.push_back(RE);
15412
15413 // Store the components in the stack so that they can be used to check
15414 // against other clauses later on.
15415 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
15416 /*WhereFoundClauseKind=*/OMPC_map);
15417
15418 // Save the components and declaration to create the clause. For purposes of
15419 // the clause creation, any component list that has has base 'this' uses
15420 // null as base declaration.
15421 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15422 MVLI.VarComponents.back().append(CurComponents.begin(),
15423 CurComponents.end());
15424 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
15425 : CurDeclaration);
15426 }
15427}
15428
15429OMPClause *Sema::ActOnOpenMPMapClause(
15430 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15431 ArrayRef<SourceLocation> MapTypeModifiersLoc,
15432 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
15433 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
15434 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
15435 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
15436 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
15437 OMPC_MAP_MODIFIER_unknown,
15438 OMPC_MAP_MODIFIER_unknown};
15439 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
15440
15441 // Process map-type-modifiers, flag errors for duplicate modifiers.
15442 unsigned Count = 0;
15443 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
15444 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
15445 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
15446 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
15447 continue;
15448 }
15449 assert(Count < OMPMapClause::NumberOfModifiers &&((Count < OMPMapClause::NumberOfModifiers && "Modifiers exceed the allowed number of map type modifiers"
) ? static_cast<void> (0) : __assert_fail ("Count < OMPMapClause::NumberOfModifiers && \"Modifiers exceed the allowed number of map type modifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15450, __PRETTY_FUNCTION__))
15450 "Modifiers exceed the allowed number of map type modifiers")((Count < OMPMapClause::NumberOfModifiers && "Modifiers exceed the allowed number of map type modifiers"
) ? static_cast<void> (0) : __assert_fail ("Count < OMPMapClause::NumberOfModifiers && \"Modifiers exceed the allowed number of map type modifiers\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15450, __PRETTY_FUNCTION__))
;
15451 Modifiers[Count] = MapTypeModifiers[I];
15452 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
15453 ++Count;
15454 }
15455
15456 MappableVarListInfo MVLI(VarList);
15457 checkMappableExpressionList(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_map, MVLI, Locs.StartLoc,
15458 MapperIdScopeSpec, MapperId, UnresolvedMappers,
15459 MapType, IsMapTypeImplicit);
15460
15461 // We need to produce a map clause even if we don't have variables so that
15462 // other diagnostics related with non-existing map clauses are accurate.
15463 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
15464 MVLI.VarBaseDeclarations, MVLI.VarComponents,
15465 MVLI.UDMapperList, Modifiers, ModifiersLoc,
15466 MapperIdScopeSpec.getWithLocInContext(Context),
15467 MapperId, MapType, IsMapTypeImplicit, MapLoc);
15468}
15469
15470QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
15471 TypeResult ParsedType) {
15472 assert(ParsedType.isUsable())((ParsedType.isUsable()) ? static_cast<void> (0) : __assert_fail
("ParsedType.isUsable()", "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15472, __PRETTY_FUNCTION__))
;
15473
15474 QualType ReductionType = GetTypeFromParser(ParsedType.get());
15475 if (ReductionType.isNull())
15476 return QualType();
15477
15478 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
15479 // A type name in a declare reduction directive cannot be a function type, an
15480 // array type, a reference type, or a type qualified with const, volatile or
15481 // restrict.
15482 if (ReductionType.hasQualifiers()) {
15483 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
15484 return QualType();
15485 }
15486
15487 if (ReductionType->isFunctionType()) {
15488 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
15489 return QualType();
15490 }
15491 if (ReductionType->isReferenceType()) {
15492 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
15493 return QualType();
15494 }
15495 if (ReductionType->isArrayType()) {
15496 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
15497 return QualType();
15498 }
15499 return ReductionType;
15500}
15501
15502Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
15503 Scope *S, DeclContext *DC, DeclarationName Name,
15504 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
15505 AccessSpecifier AS, Decl *PrevDeclInScope) {
15506 SmallVector<Decl *, 8> Decls;
15507 Decls.reserve(ReductionTypes.size());
15508
15509 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
15510 forRedeclarationInCurContext());
15511 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
15512 // A reduction-identifier may not be re-declared in the current scope for the
15513 // same type or for a type that is compatible according to the base language
15514 // rules.
15515 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15516 OMPDeclareReductionDecl *PrevDRD = nullptr;
15517 bool InCompoundScope = true;
15518 if (S != nullptr) {
15519 // Find previous declaration with the same name not referenced in other
15520 // declarations.
15521 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15522 InCompoundScope =
15523 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15524 LookupName(Lookup, S);
15525 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15526 /*AllowInlineNamespace=*/false);
15527 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
15528 LookupResult::Filter Filter = Lookup.makeFilter();
15529 while (Filter.hasNext()) {
15530 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
15531 if (InCompoundScope) {
15532 auto I = UsedAsPrevious.find(PrevDecl);
15533 if (I == UsedAsPrevious.end())
15534 UsedAsPrevious[PrevDecl] = false;
15535 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
15536 UsedAsPrevious[D] = true;
15537 }
15538 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15539 PrevDecl->getLocation();
15540 }
15541 Filter.done();
15542 if (InCompoundScope) {
15543 for (const auto &PrevData : UsedAsPrevious) {
15544 if (!PrevData.second) {
15545 PrevDRD = PrevData.first;
15546 break;
15547 }
15548 }
15549 }
15550 } else if (PrevDeclInScope != nullptr) {
15551 auto *PrevDRDInScope = PrevDRD =
15552 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
15553 do {
15554 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
15555 PrevDRDInScope->getLocation();
15556 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
15557 } while (PrevDRDInScope != nullptr);
15558 }
15559 for (const auto &TyData : ReductionTypes) {
15560 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
15561 bool Invalid = false;
15562 if (I != PreviousRedeclTypes.end()) {
15563 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
15564 << TyData.first;
15565 Diag(I->second, diag::note_previous_definition);
15566 Invalid = true;
15567 }
15568 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
15569 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
15570 Name, TyData.first, PrevDRD);
15571 DC->addDecl(DRD);
15572 DRD->setAccess(AS);
15573 Decls.push_back(DRD);
15574 if (Invalid)
15575 DRD->setInvalidDecl();
15576 else
15577 PrevDRD = DRD;
15578 }
15579
15580 return DeclGroupPtrTy::make(
15581 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
15582}
15583
15584void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
15585 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15586
15587 // Enter new function scope.
15588 PushFunctionScope();
15589 setFunctionHasBranchProtectedScope();
15590 getCurFunction()->setHasOMPDeclareReductionCombiner();
15591
15592 if (S != nullptr)
15593 PushDeclContext(S, DRD);
15594 else
15595 CurContext = DRD;
15596
15597 PushExpressionEvaluationContext(
15598 ExpressionEvaluationContext::PotentiallyEvaluated);
15599
15600 QualType ReductionType = DRD->getType();
15601 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
15602 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
15603 // uses semantics of argument handles by value, but it should be passed by
15604 // reference. C lang does not support references, so pass all parameters as
15605 // pointers.
15606 // Create 'T omp_in;' variable.
15607 VarDecl *OmpInParm =
15608 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
15609 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
15610 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
15611 // uses semantics of argument handles by value, but it should be passed by
15612 // reference. C lang does not support references, so pass all parameters as
15613 // pointers.
15614 // Create 'T omp_out;' variable.
15615 VarDecl *OmpOutParm =
15616 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
15617 if (S != nullptr) {
15618 PushOnScopeChains(OmpInParm, S);
15619 PushOnScopeChains(OmpOutParm, S);
15620 } else {
15621 DRD->addDecl(OmpInParm);
15622 DRD->addDecl(OmpOutParm);
15623 }
15624 Expr *InE =
15625 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
15626 Expr *OutE =
15627 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
15628 DRD->setCombinerData(InE, OutE);
15629}
15630
15631void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
15632 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15633 DiscardCleanupsInEvaluationContext();
15634 PopExpressionEvaluationContext();
15635
15636 PopDeclContext();
15637 PopFunctionScopeInfo();
15638
15639 if (Combiner != nullptr)
15640 DRD->setCombiner(Combiner);
15641 else
15642 DRD->setInvalidDecl();
15643}
15644
15645VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
15646 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15647
15648 // Enter new function scope.
15649 PushFunctionScope();
15650 setFunctionHasBranchProtectedScope();
15651
15652 if (S != nullptr)
15653 PushDeclContext(S, DRD);
15654 else
15655 CurContext = DRD;
15656
15657 PushExpressionEvaluationContext(
15658 ExpressionEvaluationContext::PotentiallyEvaluated);
15659
15660 QualType ReductionType = DRD->getType();
15661 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
15662 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
15663 // uses semantics of argument handles by value, but it should be passed by
15664 // reference. C lang does not support references, so pass all parameters as
15665 // pointers.
15666 // Create 'T omp_priv;' variable.
15667 VarDecl *OmpPrivParm =
15668 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
15669 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
15670 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
15671 // uses semantics of argument handles by value, but it should be passed by
15672 // reference. C lang does not support references, so pass all parameters as
15673 // pointers.
15674 // Create 'T omp_orig;' variable.
15675 VarDecl *OmpOrigParm =
15676 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
15677 if (S != nullptr) {
15678 PushOnScopeChains(OmpPrivParm, S);
15679 PushOnScopeChains(OmpOrigParm, S);
15680 } else {
15681 DRD->addDecl(OmpPrivParm);
15682 DRD->addDecl(OmpOrigParm);
15683 }
15684 Expr *OrigE =
15685 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
15686 Expr *PrivE =
15687 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
15688 DRD->setInitializerData(OrigE, PrivE);
15689 return OmpPrivParm;
15690}
15691
15692void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
15693 VarDecl *OmpPrivParm) {
15694 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15695 DiscardCleanupsInEvaluationContext();
15696 PopExpressionEvaluationContext();
15697
15698 PopDeclContext();
15699 PopFunctionScopeInfo();
15700
15701 if (Initializer != nullptr) {
15702 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
15703 } else if (OmpPrivParm->hasInit()) {
15704 DRD->setInitializer(OmpPrivParm->getInit(),
15705 OmpPrivParm->isDirectInit()
15706 ? OMPDeclareReductionDecl::DirectInit
15707 : OMPDeclareReductionDecl::CopyInit);
15708 } else {
15709 DRD->setInvalidDecl();
15710 }
15711}
15712
15713Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
15714 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
15715 for (Decl *D : DeclReductions.get()) {
15716 if (IsValid) {
15717 if (S)
15718 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
15719 /*AddToContext=*/false);
15720 } else {
15721 D->setInvalidDecl();
15722 }
15723 }
15724 return DeclReductions;
15725}
15726
15727TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
15728 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15729 QualType T = TInfo->getType();
15730 if (D.isInvalidType())
15731 return true;
15732
15733 if (getLangOpts().CPlusPlus) {
15734 // Check that there are no default arguments (C++ only).
15735 CheckExtraCXXDefaultArguments(D);
15736 }
15737
15738 return CreateParsedType(T, TInfo);
15739}
15740
15741QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
15742 TypeResult ParsedType) {
15743 assert(ParsedType.isUsable() && "Expect usable parsed mapper type")((ParsedType.isUsable() && "Expect usable parsed mapper type"
) ? static_cast<void> (0) : __assert_fail ("ParsedType.isUsable() && \"Expect usable parsed mapper type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15743, __PRETTY_FUNCTION__))
;
15744
15745 QualType MapperType = GetTypeFromParser(ParsedType.get());
15746 assert(!MapperType.isNull() && "Expect valid mapper type")((!MapperType.isNull() && "Expect valid mapper type")
? static_cast<void> (0) : __assert_fail ("!MapperType.isNull() && \"Expect valid mapper type\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 15746, __PRETTY_FUNCTION__))
;
15747
15748 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15749 // The type must be of struct, union or class type in C and C++
15750 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
15751 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
15752 return QualType();
15753 }
15754 return MapperType;
15755}
15756
15757OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
15758 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
15759 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
15760 Decl *PrevDeclInScope) {
15761 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
15762 forRedeclarationInCurContext());
15763 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15764 // A mapper-identifier may not be redeclared in the current scope for the
15765 // same type or for a type that is compatible according to the base language
15766 // rules.
15767 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15768 OMPDeclareMapperDecl *PrevDMD = nullptr;
15769 bool InCompoundScope = true;
15770 if (S != nullptr) {
15771 // Find previous declaration with the same name not referenced in other
15772 // declarations.
15773 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15774 InCompoundScope =
15775 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15776 LookupName(Lookup, S);
15777 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15778 /*AllowInlineNamespace=*/false);
15779 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
15780 LookupResult::Filter Filter = Lookup.makeFilter();
15781 while (Filter.hasNext()) {
15782 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
15783 if (InCompoundScope) {
15784 auto I = UsedAsPrevious.find(PrevDecl);
15785 if (I == UsedAsPrevious.end())
15786 UsedAsPrevious[PrevDecl] = false;
15787 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
15788 UsedAsPrevious[D] = true;
15789 }
15790 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15791 PrevDecl->getLocation();
15792 }
15793 Filter.done();
15794 if (InCompoundScope) {
15795 for (const auto &PrevData : UsedAsPrevious) {
15796 if (!PrevData.second) {
15797 PrevDMD = PrevData.first;
15798 break;
15799 }
15800 }
15801 }
15802 } else if (PrevDeclInScope) {
15803 auto *PrevDMDInScope = PrevDMD =
15804 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
15805 do {
15806 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
15807 PrevDMDInScope->getLocation();
15808 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
15809 } while (PrevDMDInScope != nullptr);
15810 }
15811 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
15812 bool Invalid = false;
15813 if (I != PreviousRedeclTypes.end()) {
15814 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
15815 << MapperType << Name;
15816 Diag(I->second, diag::note_previous_definition);
15817 Invalid = true;
15818 }
15819 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
15820 MapperType, VN, PrevDMD);
15821 DC->addDecl(DMD);
15822 DMD->setAccess(AS);
15823 if (Invalid)
15824 DMD->setInvalidDecl();
15825
15826 // Enter new function scope.
15827 PushFunctionScope();
15828 setFunctionHasBranchProtectedScope();
15829
15830 CurContext = DMD;
15831
15832 return DMD;
15833}
15834
15835void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
15836 Scope *S,
15837 QualType MapperType,
15838 SourceLocation StartLoc,
15839 DeclarationName VN) {
15840 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
15841 if (S)
15842 PushOnScopeChains(VD, S);
15843 else
15844 DMD->addDecl(VD);
15845 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
15846 DMD->setMapperVarRef(MapperVarRefExpr);
15847}
15848
15849Sema::DeclGroupPtrTy
15850Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
15851 ArrayRef<OMPClause *> ClauseList) {
15852 PopDeclContext();
15853 PopFunctionScopeInfo();
15854
15855 if (D) {
15856 if (S)
15857 PushOnScopeChains(D, S, /*AddToContext=*/false);
15858 D->CreateClauses(Context, ClauseList);
15859 }
15860
15861 return DeclGroupPtrTy::make(DeclGroupRef(D));
15862}
15863
15864OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
15865 SourceLocation StartLoc,
15866 SourceLocation LParenLoc,
15867 SourceLocation EndLoc) {
15868 Expr *ValExpr = NumTeams;
15869 Stmt *HelperValStmt = nullptr;
15870
15871 // OpenMP [teams Constrcut, Restrictions]
15872 // The num_teams expression must evaluate to a positive integer value.
15873 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
15874 /*StrictlyPositive=*/true))
15875 return nullptr;
15876
15877 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
15878 OpenMPDirectiveKind CaptureRegion =
15879 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
15880 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15881 ValExpr = MakeFullExpr(ValExpr).get();
15882 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15883 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15884 HelperValStmt = buildPreInits(Context, Captures);
15885 }
15886
15887 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
15888 StartLoc, LParenLoc, EndLoc);
15889}
15890
15891OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
15892 SourceLocation StartLoc,
15893 SourceLocation LParenLoc,
15894 SourceLocation EndLoc) {
15895 Expr *ValExpr = ThreadLimit;
15896 Stmt *HelperValStmt = nullptr;
15897
15898 // OpenMP [teams Constrcut, Restrictions]
15899 // The thread_limit expression must evaluate to a positive integer value.
15900 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
15901 /*StrictlyPositive=*/true))
15902 return nullptr;
15903
15904 OpenMPDirectiveKind DKind = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective();
15905 OpenMPDirectiveKind CaptureRegion =
15906 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
15907 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
15908 ValExpr = MakeFullExpr(ValExpr).get();
15909 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
15910 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15911 HelperValStmt = buildPreInits(Context, Captures);
15912 }
15913
15914 return new (Context) OMPThreadLimitClause(
15915 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
15916}
15917
15918OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
15919 SourceLocation StartLoc,
15920 SourceLocation LParenLoc,
15921 SourceLocation EndLoc) {
15922 Expr *ValExpr = Priority;
15923
15924 // OpenMP [2.9.1, task Constrcut]
15925 // The priority-value is a non-negative numerical scalar expression.
15926 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
15927 /*StrictlyPositive=*/false))
15928 return nullptr;
15929
15930 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
15931}
15932
15933OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
15934 SourceLocation StartLoc,
15935 SourceLocation LParenLoc,
15936 SourceLocation EndLoc) {
15937 Expr *ValExpr = Grainsize;
15938 Stmt *HelperValStmt = nullptr;
15939 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15940
15941 // OpenMP [2.9.2, taskloop Constrcut]
15942 // The parameter of the grainsize clause must be a positive integer
15943 // expression.
15944 if (!isNonNegativeIntegerValue(
15945 ValExpr, *this, OMPC_grainsize,
15946 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
15947 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
15948 return nullptr;
15949
15950 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
15951 StartLoc, LParenLoc, EndLoc);
15952}
15953
15954OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
15955 SourceLocation StartLoc,
15956 SourceLocation LParenLoc,
15957 SourceLocation EndLoc) {
15958 Expr *ValExpr = NumTasks;
15959 Stmt *HelperValStmt = nullptr;
15960 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
15961
15962 // OpenMP [2.9.2, taskloop Constrcut]
15963 // The parameter of the num_tasks clause must be a positive integer
15964 // expression.
15965 if (!isNonNegativeIntegerValue(
15966 ValExpr, *this, OMPC_num_tasks,
15967 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
15968 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
15969 return nullptr;
15970
15971 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
15972 StartLoc, LParenLoc, EndLoc);
15973}
15974
15975OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
15976 SourceLocation LParenLoc,
15977 SourceLocation EndLoc) {
15978 // OpenMP [2.13.2, critical construct, Description]
15979 // ... where hint-expression is an integer constant expression that evaluates
15980 // to a valid lock hint.
15981 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
15982 if (HintExpr.isInvalid())
15983 return nullptr;
15984 return new (Context)
15985 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
15986}
15987
15988OMPClause *Sema::ActOnOpenMPDistScheduleClause(
15989 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
15990 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
15991 SourceLocation EndLoc) {
15992 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
15993 std::string Values;
15994 Values += "'";
15995 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
15996 Values += "'";
15997 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
15998 << Values << getOpenMPClauseName(OMPC_dist_schedule);
15999 return nullptr;
16000 }
16001 Expr *ValExpr = ChunkSize;
16002 Stmt *HelperValStmt = nullptr;
16003 if (ChunkSize) {
16004 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16005 !ChunkSize->isInstantiationDependent() &&
16006 !ChunkSize->containsUnexpandedParameterPack()) {
16007 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
16008 ExprResult Val =
16009 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16010 if (Val.isInvalid())
16011 return nullptr;
16012
16013 ValExpr = Val.get();
16014
16015 // OpenMP [2.7.1, Restrictions]
16016 // chunk_size must be a loop invariant integer expression with a positive
16017 // value.
16018 llvm::APSInt Result;
16019 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16020 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16021 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16022 << "dist_schedule" << ChunkSize->getSourceRange();
16023 return nullptr;
16024 }
16025 } else if (getOpenMPCaptureRegionForClause(
16026 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective(), OMPC_dist_schedule) !=
16027 OMPD_unknown &&
16028 !CurContext->isDependentContext()) {
16029 ValExpr = MakeFullExpr(ValExpr).get();
16030 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
16031 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16032 HelperValStmt = buildPreInits(Context, Captures);
16033 }
16034 }
16035 }
16036
16037 return new (Context)
16038 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
16039 Kind, ValExpr, HelperValStmt);
16040}
16041
16042OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16043 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16044 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16045 SourceLocation KindLoc, SourceLocation EndLoc) {
16046 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
16047 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
16048 std::string Value;
16049 SourceLocation Loc;
16050 Value += "'";
16051 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16052 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16053 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16054 Loc = MLoc;
16055 } else {
16056 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16057 OMPC_DEFAULTMAP_scalar);
16058 Loc = KindLoc;
16059 }
16060 Value += "'";
16061 Diag(Loc, diag::err_omp_unexpected_clause_value)
16062 << Value << getOpenMPClauseName(OMPC_defaultmap);
16063 return nullptr;
16064 }
16065 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->setDefaultDMAToFromScalar(StartLoc);
16066
16067 return new (Context)
16068 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16069}
16070
16071bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16072 DeclContext *CurLexicalContext = getCurLexicalContext();
16073 if (!CurLexicalContext->isFileContext() &&
16074 !CurLexicalContext->isExternCContext() &&
16075 !CurLexicalContext->isExternCXXContext() &&
16076 !isa<CXXRecordDecl>(CurLexicalContext) &&
16077 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16078 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16079 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
16080 Diag(Loc, diag::err_omp_region_not_file_context);
16081 return false;
16082 }
16083 ++DeclareTargetNestingLevel;
16084 return true;
16085}
16086
16087void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
16088 assert(DeclareTargetNestingLevel > 0 &&((DeclareTargetNestingLevel > 0 && "Unexpected ActOnFinishOpenMPDeclareTargetDirective"
) ? static_cast<void> (0) : __assert_fail ("DeclareTargetNestingLevel > 0 && \"Unexpected ActOnFinishOpenMPDeclareTargetDirective\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16089, __PRETTY_FUNCTION__))
16089 "Unexpected ActOnFinishOpenMPDeclareTargetDirective")((DeclareTargetNestingLevel > 0 && "Unexpected ActOnFinishOpenMPDeclareTargetDirective"
) ? static_cast<void> (0) : __assert_fail ("DeclareTargetNestingLevel > 0 && \"Unexpected ActOnFinishOpenMPDeclareTargetDirective\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16089, __PRETTY_FUNCTION__))
;
16090 --DeclareTargetNestingLevel;
16091}
16092
16093NamedDecl *
16094Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16095 const DeclarationNameInfo &Id,
16096 NamedDeclSetType &SameDirectiveDecls) {
16097 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16098 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16099
16100 if (Lookup.isAmbiguous())
16101 return nullptr;
16102 Lookup.suppressDiagnostics();
16103
16104 if (!Lookup.isSingleResult()) {
16105 VarOrFuncDeclFilterCCC CCC(*this);
16106 if (TypoCorrection Corrected =
16107 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
16108 CTK_ErrorRecovery)) {
16109 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16110 << Id.getName());
16111 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
16112 return nullptr;
16113 }
16114
16115 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
16116 return nullptr;
16117 }
16118
16119 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
16120 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16121 !isa<FunctionTemplateDecl>(ND)) {
16122 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
16123 return nullptr;
16124 }
16125 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16126 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16127 return ND;
16128}
16129
16130void Sema::ActOnOpenMPDeclareTargetName(
16131 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16132 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16133 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||(((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || isa
<FunctionTemplateDecl>(ND)) && "Expected variable, function or function template."
) ? static_cast<void> (0) : __assert_fail ("(isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND)) && \"Expected variable, function or function template.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16135, __PRETTY_FUNCTION__))
16134 isa<FunctionTemplateDecl>(ND)) &&(((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || isa
<FunctionTemplateDecl>(ND)) && "Expected variable, function or function template."
) ? static_cast<void> (0) : __assert_fail ("(isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND)) && \"Expected variable, function or function template.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16135, __PRETTY_FUNCTION__))
16135 "Expected variable, function or function template.")(((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || isa
<FunctionTemplateDecl>(ND)) && "Expected variable, function or function template."
) ? static_cast<void> (0) : __assert_fail ("(isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND)) && \"Expected variable, function or function template.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16135, __PRETTY_FUNCTION__))
;
16136
16137 // Diagnose marking after use as it may lead to incorrect diagnosis and
16138 // codegen.
16139 if (LangOpts.OpenMP >= 50 &&
16140 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16141 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16142
16143 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16144 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16145 if (DevTy.hasValue() && *DevTy != DT) {
16146 Diag(Loc, diag::err_omp_device_type_mismatch)
16147 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16148 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16149 return;
16150 }
16151 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16152 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16153 if (!Res) {
16154 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16155 SourceRange(Loc, Loc));
16156 ND->addAttr(A);
16157 if (ASTMutationListener *ML = Context.getASTMutationListener())
16158 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16159 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16160 } else if (*Res != MT) {
16161 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
16162 }
16163}
16164
16165static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16166 Sema &SemaRef, Decl *D) {
16167 if (!D || !isa<VarDecl>(D))
16168 return;
16169 auto *VD = cast<VarDecl>(D);
16170 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16171 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16172 if (SemaRef.LangOpts.OpenMP >= 50 &&
16173 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16174 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16175 VD->hasGlobalStorage()) {
16176 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16177 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16178 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16179 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16180 // If a lambda declaration and definition appears between a
16181 // declare target directive and the matching end declare target
16182 // directive, all variables that are captured by the lambda
16183 // expression must also appear in a to clause.
16184 SemaRef.Diag(VD->getLocation(),
16185 diag::err_omp_lambda_capture_in_declare_target_not_to);
16186 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16187 << VD << 0 << SR;
16188 return;
16189 }
16190 }
16191 if (MapTy.hasValue())
16192 return;
16193 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16194 SemaRef.Diag(SL, diag::note_used_here) << SR;
16195}
16196
16197static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16198 Sema &SemaRef, DSAStackTy *Stack,
16199 ValueDecl *VD) {
16200 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
16201 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16202 /*FullCheck=*/false);
16203}
16204
16205void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16206 SourceLocation IdLoc) {
16207 if (!D || D->isInvalidDecl())
16208 return;
16209 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
16210 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
16211 if (auto *VD = dyn_cast<VarDecl>(D)) {
16212 // Only global variables can be marked as declare target.
16213 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16214 !VD->isStaticDataMember())
16215 return;
16216 // 2.10.6: threadprivate variable cannot appear in a declare target
16217 // directive.
16218 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->isThreadPrivate(VD)) {
16219 Diag(SL, diag::err_omp_threadprivate_in_target);
16220 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VD, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(VD, false));
16221 return;
16222 }
16223 }
16224 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16225 D = FTD->getTemplatedDecl();
16226 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
16227 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16228 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
16229 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
16230 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16231 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16232 return;
16233 }
16234 // Mark the function as must be emitted for the device.
16235 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16236 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16237 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16238 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
16239 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
16240 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16241 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16242 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
16243 }
16244 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16245 // Problem if any with var declared with incomplete type will be reported
16246 // as normal, so no need to check it here.
16247 if ((E || !VD->getType()->isIncompleteType()) &&
16248 !checkValueDeclInTarget(SL, SR, *this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, VD))
16249 return;
16250 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16251 // Checking declaration inside declare target region.
16252 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16253 isa<FunctionTemplateDecl>(D)) {
16254 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
16255 Context, OMPDeclareTargetDeclAttr::MT_To,
16256 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
16257 D->addAttr(A);
16258 if (ASTMutationListener *ML = Context.getASTMutationListener())
16259 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
16260 }
16261 return;
16262 }
16263 }
16264 if (!E)
16265 return;
16266 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
16267}
16268
16269OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
16270 CXXScopeSpec &MapperIdScopeSpec,
16271 DeclarationNameInfo &MapperId,
16272 const OMPVarListLocTy &Locs,
16273 ArrayRef<Expr *> UnresolvedMappers) {
16274 MappableVarListInfo MVLI(VarList);
16275 checkMappableExpressionList(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_to, MVLI, Locs.StartLoc,
16276 MapperIdScopeSpec, MapperId, UnresolvedMappers);
16277 if (MVLI.ProcessedVarList.empty())
16278 return nullptr;
16279
16280 return OMPToClause::Create(
16281 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16282 MVLI.VarComponents, MVLI.UDMapperList,
16283 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
16284}
16285
16286OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
16287 CXXScopeSpec &MapperIdScopeSpec,
16288 DeclarationNameInfo &MapperId,
16289 const OMPVarListLocTy &Locs,
16290 ArrayRef<Expr *> UnresolvedMappers) {
16291 MappableVarListInfo MVLI(VarList);
16292 checkMappableExpressionList(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, OMPC_from, MVLI, Locs.StartLoc,
16293 MapperIdScopeSpec, MapperId, UnresolvedMappers);
16294 if (MVLI.ProcessedVarList.empty())
16295 return nullptr;
16296
16297 return OMPFromClause::Create(
16298 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16299 MVLI.VarComponents, MVLI.UDMapperList,
16300 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
16301}
16302
16303OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
16304 const OMPVarListLocTy &Locs) {
16305 MappableVarListInfo MVLI(VarList);
16306 SmallVector<Expr *, 8> PrivateCopies;
16307 SmallVector<Expr *, 8> Inits;
16308
16309 for (Expr *RefExpr : VarList) {
16310 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.")((RefExpr && "NULL expr in OpenMP use_device_ptr clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP use_device_ptr clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16310, __PRETTY_FUNCTION__))
;
16311 SourceLocation ELoc;
16312 SourceRange ERange;
16313 Expr *SimpleRefExpr = RefExpr;
16314 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16315 if (Res.second) {
16316 // It will be analyzed later.
16317 MVLI.ProcessedVarList.push_back(RefExpr);
16318 PrivateCopies.push_back(nullptr);
16319 Inits.push_back(nullptr);
16320 }
16321 ValueDecl *D = Res.first;
16322 if (!D)
16323 continue;
16324
16325 QualType Type = D->getType();
16326 Type = Type.getNonReferenceType().getUnqualifiedType();
16327
16328 auto *VD = dyn_cast<VarDecl>(D);
16329
16330 // Item should be a pointer or reference to pointer.
16331 if (!Type->isPointerType()) {
16332 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
16333 << 0 << RefExpr->getSourceRange();
16334 continue;
16335 }
16336
16337 // Build the private variable and the expression that refers to it.
16338 auto VDPrivate =
16339 buildVarDecl(*this, ELoc, Type, D->getName(),
16340 D->hasAttrs() ? &D->getAttrs() : nullptr,
16341 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
16342 if (VDPrivate->isInvalidDecl())
16343 continue;
16344
16345 CurContext->addDecl(VDPrivate);
16346 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
16347 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16348
16349 // Add temporary variable to initialize the private copy of the pointer.
16350 VarDecl *VDInit =
16351 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
16352 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
16353 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
16354 AddInitializerToDecl(VDPrivate,
16355 DefaultLvalueConversion(VDInitRefExpr).get(),
16356 /*DirectInit=*/false);
16357
16358 // If required, build a capture to implement the privatization initialized
16359 // with the current list item value.
16360 DeclRefExpr *Ref = nullptr;
16361 if (!VD)
16362 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16363 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
16364 PrivateCopies.push_back(VDPrivateRefExpr);
16365 Inits.push_back(VDInitRefExpr);
16366
16367 // We need to add a data sharing attribute for this variable to make sure it
16368 // is correctly captured. A variable that shows up in a use_device_ptr has
16369 // similar properties of a first private variable.
16370 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16371
16372 // Create a mappable component for the list item. List items in this clause
16373 // only need a component.
16374 MVLI.VarBaseDeclarations.push_back(D);
16375 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16376 MVLI.VarComponents.back().push_back(
16377 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
16378 }
16379
16380 if (MVLI.ProcessedVarList.empty())
16381 return nullptr;
16382
16383 return OMPUseDevicePtrClause::Create(
16384 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
16385 MVLI.VarBaseDeclarations, MVLI.VarComponents);
16386}
16387
16388OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
16389 const OMPVarListLocTy &Locs) {
16390 MappableVarListInfo MVLI(VarList);
16391 for (Expr *RefExpr : VarList) {
16392 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.")((RefExpr && "NULL expr in OpenMP is_device_ptr clause."
) ? static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP is_device_ptr clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16392, __PRETTY_FUNCTION__))
;
16393 SourceLocation ELoc;
16394 SourceRange ERange;
16395 Expr *SimpleRefExpr = RefExpr;
16396 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16397 if (Res.second) {
16398 // It will be analyzed later.
16399 MVLI.ProcessedVarList.push_back(RefExpr);
16400 }
16401 ValueDecl *D = Res.first;
16402 if (!D)
16403 continue;
16404
16405 QualType Type = D->getType();
16406 // item should be a pointer or array or reference to pointer or array
16407 if (!Type.getNonReferenceType()->isPointerType() &&
16408 !Type.getNonReferenceType()->isArrayType()) {
16409 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
16410 << 0 << RefExpr->getSourceRange();
16411 continue;
16412 }
16413
16414 // Check if the declaration in the clause does not show up in any data
16415 // sharing attribute.
16416 DSAStackTy::DSAVarData DVar = DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getTopDSA(D, /*FromParent=*/false);
16417 if (isOpenMPPrivate(DVar.CKind)) {
16418 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16419 << getOpenMPClauseName(DVar.CKind)
16420 << getOpenMPClauseName(OMPC_is_device_ptr)
16421 << getOpenMPDirectiveName(DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getCurrentDirective());
16422 reportOriginalDsa(*this, DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
, D, DVar);
16423 continue;
16424 }
16425
16426 const Expr *ConflictExpr;
16427 if (DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->checkMappableExprComponentListsForDecl(
16428 D, /*CurrentRegionOnly=*/true,
16429 [&ConflictExpr](
16430 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
16431 OpenMPClauseKind) -> bool {
16432 ConflictExpr = R.front().getAssociatedExpression();
16433 return true;
16434 })) {
16435 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
16436 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
16437 << ConflictExpr->getSourceRange();
16438 continue;
16439 }
16440
16441 // Store the components in the stack so that they can be used to check
16442 // against other clauses later on.
16443 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
16444 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->addMappableExpressionComponents(
16445 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
16446
16447 // Record the expression we've just processed.
16448 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
16449
16450 // Create a mappable component for the list item. List items in this clause
16451 // only need a component. We use a null declaration to signal fields in
16452 // 'this'.
16453 assert((isa<DeclRefExpr>(SimpleRefExpr) ||(((isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr
>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
"Unexpected device pointer expression!") ? static_cast<void
> (0) : __assert_fail ("(isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && \"Unexpected device pointer expression!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16455, __PRETTY_FUNCTION__))
16454 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&(((isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr
>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
"Unexpected device pointer expression!") ? static_cast<void
> (0) : __assert_fail ("(isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && \"Unexpected device pointer expression!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16455, __PRETTY_FUNCTION__))
16455 "Unexpected device pointer expression!")(((isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr
>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
"Unexpected device pointer expression!") ? static_cast<void
> (0) : __assert_fail ("(isa<DeclRefExpr>(SimpleRefExpr) || isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && \"Unexpected device pointer expression!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16455, __PRETTY_FUNCTION__))
;
16456 MVLI.VarBaseDeclarations.push_back(
16457 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
16458 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16459 MVLI.VarComponents.back().push_back(MC);
16460 }
16461
16462 if (MVLI.ProcessedVarList.empty())
16463 return nullptr;
16464
16465 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
16466 MVLI.VarBaseDeclarations,
16467 MVLI.VarComponents);
16468}
16469
16470OMPClause *Sema::ActOnOpenMPAllocateClause(
16471 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16472 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16473 if (Allocator) {
16474 // OpenMP [2.11.4 allocate Clause, Description]
16475 // allocator is an expression of omp_allocator_handle_t type.
16476 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
))
16477 return nullptr;
16478
16479 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
16480 if (AllocatorRes.isInvalid())
16481 return nullptr;
16482 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
16483 DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->getOMPAllocatorHandleT(),
16484 Sema::AA_Initializing,
16485 /*AllowExplicit=*/true);
16486 if (AllocatorRes.isInvalid())
16487 return nullptr;
16488 Allocator = AllocatorRes.get();
16489 } else {
16490 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
16491 // allocate clauses that appear on a target construct or on constructs in a
16492 // target region must specify an allocator expression unless a requires
16493 // directive with the dynamic_allocators clause is present in the same
16494 // compilation unit.
16495 if (LangOpts.OpenMPIsDevice &&
16496 !DSAStackstatic_cast<DSAStackTy *>(VarDataSharingAttributesStack
)
->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
16497 targetDiag(StartLoc, diag::err_expected_allocator_expression);
16498 }
16499 // Analyze and build list of variables.
16500 SmallVector<Expr *, 8> Vars;
16501 for (Expr *RefExpr : VarList) {
16502 assert(RefExpr && "NULL expr in OpenMP private clause.")((RefExpr && "NULL expr in OpenMP private clause.") ?
static_cast<void> (0) : __assert_fail ("RefExpr && \"NULL expr in OpenMP private clause.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaOpenMP.cpp"
, 16502, __PRETTY_FUNCTION__))
;
16503 SourceLocation ELoc;
16504 SourceRange ERange;
16505 Expr *SimpleRefExpr = RefExpr;
16506 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16507 if (Res.second) {
16508 // It will be analyzed later.
16509 Vars.push_back(RefExpr);
16510 }
16511 ValueDecl *D = Res.first;
16512 if (!D)
16513 continue;
16514
16515 auto *VD = dyn_cast<VarDecl>(D);
16516 DeclRefExpr *Ref = nullptr;
16517 if (!VD && !CurContext->isDependentContext())
16518 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16519 Vars.push_back((VD || CurContext->isDependentContext())
16520 ? RefExpr->IgnoreParens()
16521 : Ref);
16522 }
16523
16524 if (Vars.empty())
16525 return nullptr;
16526
16527 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
16528 ColonLoc, EndLoc, Vars);
16529}