clang 24.0.0git
SemaOpenMP.cpp
Go to the documentation of this file.
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
16
17#include "TreeTransform.h"
20#include "clang/AST/Attr.h"
22#include "clang/AST/Decl.h"
23#include "clang/AST/DeclCXX.h"
28#include "clang/AST/Stmt.h"
29#include "clang/AST/StmtCXX.h"
38#include "clang/Sema/Lookup.h"
40#include "clang/Sema/Scope.h"
42#include "clang/Sema/Sema.h"
43#include "llvm/ADT/IndexedMap.h"
44#include "llvm/ADT/PointerEmbeddedInt.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/ADT/Sequence.h"
47#include "llvm/ADT/SetVector.h"
48#include "llvm/ADT/SmallSet.h"
49#include "llvm/ADT/StringExtras.h"
50#include "llvm/Frontend/OpenMP/OMPAssume.h"
51#include "llvm/Frontend/OpenMP/OMPConstants.h"
52#include "llvm/Frontend/OpenMP/OMPVersion.h"
53#include "llvm/IR/Assumptions.h"
54#include <limits>
55#include <optional>
56
57using namespace clang;
58using namespace llvm::omp;
59
60//===----------------------------------------------------------------------===//
61// Stack of data-sharing attributes for variables
62//===----------------------------------------------------------------------===//
63
65 Sema &SemaRef, Expr *E,
67 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose);
68
70
71namespace {
72/// Default data sharing attributes, which can be applied to directive.
73enum DefaultDataSharingAttributes {
74 DSA_unspecified = 0, /// Data sharing attribute not specified.
75 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
76 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
77 DSA_private = 1 << 2, /// Default data sharing attribute 'private'.
78 DSA_firstprivate = 1 << 3, /// Default data sharing attribute 'firstprivate'.
79};
80
81/// Variable Category attributes to restrict the modifier of the
82/// default clause (DefaultDataSharingAttributes)
83/// Not mentioning any Variable category attribute indicates
84/// the modifier (DefaultDataSharingAttributes) is for all variables.
85enum DefaultDataSharingVCAttributes {
86 DSA_VC_all = 0, /// for all variables.
87 DSA_VC_aggregate, /// for aggregate variables.
88 DSA_VC_pointer, /// for pointer variables.
89 DSA_VC_scalar, /// for scalar variables.
90};
91
92/// Stack for tracking declarations used in OpenMP directives and
93/// clauses and their data-sharing attributes.
94class DSAStackTy {
95public:
96 struct DSAVarData {
97 OpenMPDirectiveKind DKind = OMPD_unknown;
98 OpenMPClauseKind CKind = OMPC_unknown;
99 unsigned Modifier = 0;
100 const Expr *RefExpr = nullptr;
101 DeclRefExpr *PrivateCopy = nullptr;
102 SourceLocation ImplicitDSALoc;
103 bool AppliedToPointee = false;
104 DSAVarData() = default;
105 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
106 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
107 SourceLocation ImplicitDSALoc, unsigned Modifier,
108 bool AppliedToPointee)
109 : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
110 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
111 AppliedToPointee(AppliedToPointee) {}
112 };
113 using OperatorOffsetTy =
114 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
115 using DoacrossClauseMapTy = llvm::DenseMap<OMPClause *, OperatorOffsetTy>;
116 /// Kind of the declaration used in the uses_allocators clauses.
117 enum class UsesAllocatorsDeclKind {
118 /// Predefined allocator
119 PredefinedAllocator,
120 /// User-defined allocator
121 UserDefinedAllocator,
122 /// The declaration that represent allocator trait
123 AllocatorTrait,
124 };
125
126private:
127 struct DSAInfo {
128 OpenMPClauseKind Attributes = OMPC_unknown;
129 unsigned Modifier = 0;
130 /// Pointer to a reference expression and a flag which shows that the
131 /// variable is marked as lastprivate(true) or not (false).
132 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
133 DeclRefExpr *PrivateCopy = nullptr;
134 /// true if the attribute is applied to the pointee, not the variable
135 /// itself.
136 bool AppliedToPointee = false;
137 };
138 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
139 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
140 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
141 using LoopControlVariablesMapTy =
142 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
143 /// Struct that associates a component with the clause kind where they are
144 /// found.
145 struct MappedExprComponentTy {
147 OpenMPClauseKind Kind = OMPC_unknown;
148 };
149 using MappedExprComponentsTy =
150 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
151 using CriticalsWithHintsTy =
152 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
153 struct ReductionData {
154 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
155 SourceRange ReductionRange;
156 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
157 ReductionData() = default;
158 void set(BinaryOperatorKind BO, SourceRange RR) {
159 ReductionRange = RR;
160 ReductionOp = BO;
161 }
162 void set(const Expr *RefExpr, SourceRange RR) {
163 ReductionRange = RR;
164 ReductionOp = RefExpr;
165 }
166 };
167 using DeclReductionMapTy =
168 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
169 struct DefaultmapInfo {
170 OpenMPDefaultmapClauseModifier ImplicitBehavior =
172 SourceLocation SLoc;
173 DefaultmapInfo() = default;
174 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
175 : ImplicitBehavior(M), SLoc(Loc) {}
176 };
177
178 struct SharingMapTy {
179 DeclSAMapTy SharingMap;
180 DeclReductionMapTy ReductionMap;
181 UsedRefMapTy AlignedMap;
182 UsedRefMapTy NontemporalMap;
183 MappedExprComponentsTy MappedExprComponents;
184 LoopControlVariablesMapTy LCVMap;
185 /// Track DecompositionDecls and their data-sharing attributes to detect
186 /// conflicting clauses on bindings from the same decomposition.
187 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
188 SourceLocation DefaultAttrLoc;
189 DefaultDataSharingVCAttributes DefaultVCAttr = DSA_VC_all;
190 SourceLocation DefaultAttrVCLoc;
191 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown + 1];
192 OpenMPDirectiveKind Directive = OMPD_unknown;
193 DeclarationNameInfo DirectiveName;
194 Scope *CurScope = nullptr;
195 DeclContext *Context = nullptr;
196 SourceLocation ConstructLoc;
197 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
198 /// get the data (loop counters etc.) about enclosing loop-based construct.
199 /// This data is required during codegen.
200 DoacrossClauseMapTy DoacrossDepends;
201 /// First argument (Expr *) contains optional argument of the
202 /// 'ordered' clause, the second one is true if the regions has 'ordered'
203 /// clause, false otherwise.
204 std::optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
205 bool RegionHasOrderConcurrent = false;
206 unsigned AssociatedLoops = 1;
207 bool HasMutipleLoops = false;
208 const Decl *PossiblyLoopCounter = nullptr;
209 bool NowaitRegion = false;
210 bool UntiedRegion = false;
211 bool CancelRegion = false;
212 bool LoopStart = false;
213 bool BodyComplete = false;
214 SourceLocation PrevScanLocation;
215 SourceLocation PrevOrderedLocation;
216 SourceLocation InnerTeamsRegionLoc;
217 /// Reference to the taskgroup task_reduction reference expression.
218 Expr *TaskgroupReductionRef = nullptr;
219 llvm::DenseSet<QualType> MappedClassesQualTypes;
220 SmallVector<Expr *, 4> InnerUsedAllocators;
221 llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
222 /// List of globals marked as declare target link in this target region
223 /// (isOpenMPTargetExecutionDirective(Directive) == true).
224 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
225 /// List of decls used in inclusive/exclusive clauses of the scan directive.
226 llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
227 llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
228 UsesAllocatorsDecls;
229 /// Data is required on creating capture fields for implicit
230 /// default first|private clause.
231 struct ImplicitDefaultFDInfoTy {
232 /// Field decl.
233 const FieldDecl *FD = nullptr;
234 /// Nesting stack level
235 size_t StackLevel = 0;
236 /// Capture variable decl.
237 VarDecl *VD = nullptr;
238 ImplicitDefaultFDInfoTy(const FieldDecl *FD, size_t StackLevel,
239 VarDecl *VD)
240 : FD(FD), StackLevel(StackLevel), VD(VD) {}
241 };
242 /// List of captured fields
243 llvm::SmallVector<ImplicitDefaultFDInfoTy, 8>
244 ImplicitDefaultFirstprivateFDs;
245 Expr *DeclareMapperVar = nullptr;
246 SmallVector<VarDecl *, 16> IteratorVarDecls;
247 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
248 Scope *CurScope, SourceLocation Loc)
249 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
250 ConstructLoc(Loc) {}
251 SharingMapTy() = default;
252 };
253
254 using StackTy = SmallVector<SharingMapTy, 4>;
255
256 /// Stack of used declaration and their data-sharing attributes.
257 DeclSAMapTy Threadprivates;
258 DeclSAMapTy Groupprivates;
259 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
260 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
261 /// true, if check for DSA must be from parent directive, false, if
262 /// from current directive.
263 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
264 Sema &SemaRef;
265 bool ForceCapturing = false;
266 /// true if all the variables in the target executable directives must be
267 /// captured by reference.
268 bool ForceCaptureByReferenceInTargetExecutable = false;
269 CriticalsWithHintsTy Criticals;
270 unsigned IgnoredStackElements = 0;
271
272 /// Iterators over the stack iterate in order from innermost to outermost
273 /// directive.
274 using const_iterator = StackTy::const_reverse_iterator;
275 const_iterator begin() const {
276 return Stack.empty() ? const_iterator()
277 : Stack.back().first.rbegin() + IgnoredStackElements;
278 }
279 const_iterator end() const {
280 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
281 }
282 using iterator = StackTy::reverse_iterator;
283 iterator begin() {
284 return Stack.empty() ? iterator()
285 : Stack.back().first.rbegin() + IgnoredStackElements;
286 }
287 iterator end() {
288 return Stack.empty() ? iterator() : Stack.back().first.rend();
289 }
290
291 // Convenience operations to get at the elements of the stack.
292
293 bool isStackEmpty() const {
294 return Stack.empty() ||
295 Stack.back().second != CurrentNonCapturingFunctionScope ||
296 Stack.back().first.size() <= IgnoredStackElements;
297 }
298 size_t getStackSize() const {
299 return isStackEmpty() ? 0
300 : Stack.back().first.size() - IgnoredStackElements;
301 }
302
303 SharingMapTy *getTopOfStackOrNull() {
304 size_t Size = getStackSize();
305 if (Size == 0)
306 return nullptr;
307 return &Stack.back().first[Size - 1];
308 }
309 const SharingMapTy *getTopOfStackOrNull() const {
310 return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull();
311 }
312 SharingMapTy &getTopOfStack() {
313 assert(!isStackEmpty() && "no current directive");
314 return *getTopOfStackOrNull();
315 }
316 const SharingMapTy &getTopOfStack() const {
317 return const_cast<DSAStackTy &>(*this).getTopOfStack();
318 }
319
320 SharingMapTy *getSecondOnStackOrNull() {
321 size_t Size = getStackSize();
322 if (Size <= 1)
323 return nullptr;
324 return &Stack.back().first[Size - 2];
325 }
326 const SharingMapTy *getSecondOnStackOrNull() const {
327 return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull();
328 }
329
330 /// Get the stack element at a certain level (previously returned by
331 /// \c getNestingLevel).
332 ///
333 /// Note that nesting levels count from outermost to innermost, and this is
334 /// the reverse of our iteration order where new inner levels are pushed at
335 /// the front of the stack.
336 SharingMapTy &getStackElemAtLevel(unsigned Level) {
337 assert(Level < getStackSize() && "no such stack element");
338 return Stack.back().first[Level];
339 }
340 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
341 return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level);
342 }
343
344 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
345
346 /// Checks if the variable is a local for OpenMP region.
347 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
348
349 /// Vector of previously declared requires directives
350 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
351 /// omp_allocator_handle_t type.
352 QualType OMPAllocatorHandleT;
353 /// omp_depend_t type.
354 QualType OMPDependT;
355 /// omp_event_handle_t type.
356 QualType OMPEventHandleT;
357 /// omp_alloctrait_t type.
358 QualType OMPAlloctraitT;
359 /// Expression for the predefined allocators.
360 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
361 nullptr};
362 /// Vector of previously encountered target directives
363 SmallVector<SourceLocation, 2> TargetLocations;
364 SourceLocation AtomicLocation;
365 /// Vector of declare variant construct traits.
366 SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits;
367
368public:
369 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
370
371 /// Sets omp_allocator_handle_t type.
372 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
373 /// Gets omp_allocator_handle_t type.
374 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
375 /// Sets omp_alloctrait_t type.
376 void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
377 /// Gets omp_alloctrait_t type.
378 QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
379 /// Sets the given default allocator.
380 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
381 Expr *Allocator) {
382 OMPPredefinedAllocators[AllocatorKind] = Allocator;
383 }
384 /// Returns the specified default allocator.
385 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
386 return OMPPredefinedAllocators[AllocatorKind];
387 }
388 /// Sets omp_depend_t type.
389 void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
390 /// Gets omp_depend_t type.
391 QualType getOMPDependT() const { return OMPDependT; }
392
393 /// Sets omp_event_handle_t type.
394 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
395 /// Gets omp_event_handle_t type.
396 QualType getOMPEventHandleT() const { return OMPEventHandleT; }
397
398 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
399 OpenMPClauseKind getClauseParsingMode() const {
400 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
401 return ClauseKindMode;
402 }
403 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
404
405 bool isBodyComplete() const {
406 const SharingMapTy *Top = getTopOfStackOrNull();
407 return Top && Top->BodyComplete;
408 }
409 void setBodyComplete() { getTopOfStack().BodyComplete = true; }
410
411 bool isForceVarCapturing() const { return ForceCapturing; }
412 void setForceVarCapturing(bool V) { ForceCapturing = V; }
413
414 void setForceCaptureByReferenceInTargetExecutable(bool V) {
415 ForceCaptureByReferenceInTargetExecutable = V;
416 }
417 bool isForceCaptureByReferenceInTargetExecutable() const {
418 return ForceCaptureByReferenceInTargetExecutable;
419 }
420
421 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
422 Scope *CurScope, SourceLocation Loc) {
423 assert(!IgnoredStackElements &&
424 "cannot change stack while ignoring elements");
425 if (Stack.empty() ||
426 Stack.back().second != CurrentNonCapturingFunctionScope)
427 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
428 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
429 Stack.back().first.back().DefaultAttrLoc = Loc;
430 }
431
432 void pop() {
433 assert(!IgnoredStackElements &&
434 "cannot change stack while ignoring elements");
435 assert(!Stack.back().first.empty() &&
436 "Data-sharing attributes stack is empty!");
437 Stack.back().first.pop_back();
438 }
439
440 /// RAII object to temporarily leave the scope of a directive when we want to
441 /// logically operate in its parent.
442 class ParentDirectiveScope {
443 DSAStackTy &Self;
444 bool Active;
445
446 public:
447 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
448 : Self(Self), Active(false) {
449 if (Activate)
450 enable();
451 }
452 ~ParentDirectiveScope() { disable(); }
453 void disable() {
454 if (Active) {
455 --Self.IgnoredStackElements;
456 Active = false;
457 }
458 }
459 void enable() {
460 if (!Active) {
461 ++Self.IgnoredStackElements;
462 Active = true;
463 }
464 }
465 };
466
467 /// Marks that we're started loop parsing.
468 void loopInit() {
469 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
470 "Expected loop-based directive.");
471 getTopOfStack().LoopStart = true;
472 }
473 /// Start capturing of the variables in the loop context.
474 void loopStart() {
475 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
476 "Expected loop-based directive.");
477 getTopOfStack().LoopStart = false;
478 }
479 /// true, if variables are captured, false otherwise.
480 bool isLoopStarted() const {
481 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
482 "Expected loop-based directive.");
483 return !getTopOfStack().LoopStart;
484 }
485 /// Marks (or clears) declaration as possibly loop counter.
486 void resetPossibleLoopCounter(const Decl *D = nullptr) {
487 getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D;
488 }
489 /// Gets the possible loop counter decl.
490 const Decl *getPossiblyLoopCounter() const {
491 return getTopOfStack().PossiblyLoopCounter;
492 }
493 /// Start new OpenMP region stack in new non-capturing function.
494 void pushFunction() {
495 assert(!IgnoredStackElements &&
496 "cannot change stack while ignoring elements");
497 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
498 assert(!isa<CapturingScopeInfo>(CurFnScope));
499 CurrentNonCapturingFunctionScope = CurFnScope;
500 }
501 /// Pop region stack for non-capturing function.
502 void popFunction(const FunctionScopeInfo *OldFSI) {
503 assert(!IgnoredStackElements &&
504 "cannot change stack while ignoring elements");
505 if (!Stack.empty() && Stack.back().second == OldFSI) {
506 assert(Stack.back().first.empty());
507 Stack.pop_back();
508 }
509 CurrentNonCapturingFunctionScope = nullptr;
510 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
511 if (!isa<CapturingScopeInfo>(FSI)) {
512 CurrentNonCapturingFunctionScope = FSI;
513 break;
514 }
515 }
516 }
517
518 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
519 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
520 }
521 std::pair<const OMPCriticalDirective *, llvm::APSInt>
522 getCriticalWithHint(const DeclarationNameInfo &Name) const {
523 auto I = Criticals.find(Name.getAsString());
524 if (I != Criticals.end())
525 return I->second;
526 return std::make_pair(nullptr, llvm::APSInt());
527 }
528 /// If 'aligned' declaration for given variable \a D was not seen yet,
529 /// add it and return NULL; otherwise return previous occurrence's expression
530 /// for diagnostics.
531 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
532 /// If 'nontemporal' declaration for given variable \a D was not seen yet,
533 /// add it and return NULL; otherwise return previous occurrence's expression
534 /// for diagnostics.
535 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
536
537 /// Register specified variable as loop control variable.
538 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
539 /// Check if the specified variable is a loop control variable for
540 /// current region.
541 /// \return The index of the loop control variable in the list of associated
542 /// for-loops (from outer to inner).
543 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
544 /// Check if the specified variable is a loop control variable for
545 /// parent region.
546 /// \return The index of the loop control variable in the list of associated
547 /// for-loops (from outer to inner).
548 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
549 /// Check if the specified variable is a loop control variable for
550 /// current region.
551 /// \return The index of the loop control variable in the list of associated
552 /// for-loops (from outer to inner).
553 const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
554 unsigned Level) const;
555 /// Get the loop control variable for the I-th loop (or nullptr) in
556 /// parent directive.
557 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
558
559 /// Marks the specified decl \p D as used in scan directive.
560 void markDeclAsUsedInScanDirective(ValueDecl *D) {
561 if (SharingMapTy *Stack = getSecondOnStackOrNull())
562 Stack->UsedInScanDirective.insert(D);
563 }
564
565 /// Checks if the specified declaration was used in the inner scan directive.
566 bool isUsedInScanDirective(ValueDecl *D) const {
567 if (const SharingMapTy *Stack = getTopOfStackOrNull())
568 return Stack->UsedInScanDirective.contains(D);
569 return false;
570 }
571
572 /// Adds explicit data sharing attribute to the specified declaration.
573 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
574 DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
575 bool AppliedToPointee = false);
576
577 /// Adds additional information for the reduction items with the reduction id
578 /// represented as an operator.
579 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
581 /// Adds additional information for the reduction items with the reduction id
582 /// represented as reduction identifier.
583 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
584 const Expr *ReductionRef);
585 /// Returns the location and reduction operation from the innermost parent
586 /// region for the given \p D.
587 const DSAVarData
588 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
590 Expr *&TaskgroupDescriptor) const;
591 /// Returns the location and reduction operation from the innermost parent
592 /// region for the given \p D.
593 const DSAVarData
594 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
595 const Expr *&ReductionRef,
596 Expr *&TaskgroupDescriptor) const;
597 /// Return reduction reference expression for the current taskgroup or
598 /// parallel/worksharing directives with task reductions.
599 Expr *getTaskgroupReductionRef() const {
600 assert((getTopOfStack().Directive == OMPD_taskgroup ||
601 ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
602 isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
603 !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
604 "taskgroup reference expression requested for non taskgroup or "
605 "parallel/worksharing directive.");
606 return getTopOfStack().TaskgroupReductionRef;
607 }
608 /// Checks if the given \p VD declaration is actually a taskgroup reduction
609 /// descriptor variable at the \p Level of OpenMP regions.
610 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
611 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
612 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
613 ->getDecl() == VD;
614 }
615
616 /// Returns data sharing attributes from top of the stack for the
617 /// specified declaration.
618 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
619 /// Returns data-sharing attributes for the specified declaration.
620 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
621 /// Returns data-sharing attributes for the specified declaration.
622 const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
623 /// Checks if the specified variables has data-sharing attributes which
624 /// match specified \a CPred predicate in any directive which matches \a DPred
625 /// predicate.
626 const DSAVarData
627 hasDSA(ValueDecl *D,
628 const llvm::function_ref<bool(OpenMPClauseKind, bool,
629 DefaultDataSharingAttributes)>
630 CPred,
631 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
632 bool FromParent) const;
633 /// Checks if the specified variables has data-sharing attributes which
634 /// match specified \a CPred predicate in any innermost directive which
635 /// matches \a DPred predicate.
636 const DSAVarData
637 hasInnermostDSA(ValueDecl *D,
638 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
639 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
640 bool FromParent) const;
641 /// Checks if the specified variables has explicit data-sharing
642 /// attributes which match specified \a CPred predicate at the specified
643 /// OpenMP region.
644 bool
645 hasExplicitDSA(const ValueDecl *D,
646 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
647 unsigned Level, bool NotLastprivate = false) const;
648
649 /// Returns true if the directive at level \Level matches in the
650 /// specified \a DPred predicate.
651 bool hasExplicitDirective(
652 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
653 unsigned Level) const;
654
655 /// Finds a directive which matches specified \a DPred predicate.
656 bool hasDirective(
657 const llvm::function_ref<bool(
658 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
659 DPred,
660 bool FromParent) const;
661
662 /// Returns currently analyzed directive.
663 OpenMPDirectiveKind getCurrentDirective() const {
664 const SharingMapTy *Top = getTopOfStackOrNull();
665 return Top ? Top->Directive : OMPD_unknown;
666 }
667 /// Returns directive kind at specified level.
668 OpenMPDirectiveKind getDirective(unsigned Level) const {
669 assert(!isStackEmpty() && "No directive at specified level.");
670 return getStackElemAtLevel(Level).Directive;
671 }
672 /// Returns the capture region at the specified level.
673 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
674 unsigned OpenMPCaptureLevel) const {
675 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
676 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
677 return CaptureRegions[OpenMPCaptureLevel];
678 }
679 /// Returns parent directive.
680 OpenMPDirectiveKind getParentDirective() const {
681 const SharingMapTy *Parent = getSecondOnStackOrNull();
682 return Parent ? Parent->Directive : OMPD_unknown;
683 }
684
685 /// Add requires decl to internal vector
686 void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); }
687
688 ArrayRef<const OMPRequiresDecl *> getRequiresDecls() const {
689 return RequiresDecls;
690 }
691
692 /// Checks if the defined 'requires' directive has specified type of clause.
693 template <typename ClauseType> bool hasRequiresDeclWithClause() const {
694 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
695 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
696 return isa<ClauseType>(C);
697 });
698 });
699 }
700
701 /// Checks for a duplicate clause amongst previously declared requires
702 /// directives
703 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
704 bool IsDuplicate = false;
705 for (OMPClause *CNew : ClauseList) {
706 for (const OMPRequiresDecl *D : RequiresDecls) {
707 for (const OMPClause *CPrev : D->clauselists()) {
708 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
709 SemaRef.Diag(CNew->getBeginLoc(),
710 diag::err_omp_requires_clause_redeclaration)
711 << getOpenMPClauseNameForDiag(CNew->getClauseKind());
712 SemaRef.Diag(CPrev->getBeginLoc(),
713 diag::note_omp_requires_previous_clause)
714 << getOpenMPClauseNameForDiag(CPrev->getClauseKind());
715 IsDuplicate = true;
716 }
717 }
718 }
719 }
720 return IsDuplicate;
721 }
722
723 /// Add location of previously encountered target to internal vector
724 void addTargetDirLocation(SourceLocation LocStart) {
725 TargetLocations.push_back(LocStart);
726 }
727
728 /// Add location for the first encountered atomic directive.
729 void addAtomicDirectiveLoc(SourceLocation Loc) {
730 if (AtomicLocation.isInvalid())
731 AtomicLocation = Loc;
732 }
733
734 /// Returns the location of the first encountered atomic directive in the
735 /// module.
736 SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; }
737
738 // Return previously encountered target region locations.
739 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
740 return TargetLocations;
741 }
742
743 /// Set default data sharing attribute to none.
744 void setDefaultDSANone(SourceLocation Loc) {
745 getTopOfStack().DefaultAttr = DSA_none;
746 getTopOfStack().DefaultAttrLoc = Loc;
747 }
748 /// Set default data sharing attribute to shared.
749 void setDefaultDSAShared(SourceLocation Loc) {
750 getTopOfStack().DefaultAttr = DSA_shared;
751 getTopOfStack().DefaultAttrLoc = Loc;
752 }
753 /// Set default data sharing attribute to private.
754 void setDefaultDSAPrivate(SourceLocation Loc) {
755 getTopOfStack().DefaultAttr = DSA_private;
756 getTopOfStack().DefaultAttrLoc = Loc;
757 }
758 /// Set default data sharing attribute to firstprivate.
759 void setDefaultDSAFirstPrivate(SourceLocation Loc) {
760 getTopOfStack().DefaultAttr = DSA_firstprivate;
761 getTopOfStack().DefaultAttrLoc = Loc;
762 }
763 /// Set default data sharing variable category attribute to aggregate.
764 void setDefaultDSAVCAggregate(SourceLocation VCLoc) {
765 getTopOfStack().DefaultVCAttr = DSA_VC_aggregate;
766 getTopOfStack().DefaultAttrVCLoc = VCLoc;
767 }
768 /// Set default data sharing variable category attribute to all.
769 void setDefaultDSAVCAll(SourceLocation VCLoc) {
770 getTopOfStack().DefaultVCAttr = DSA_VC_all;
771 getTopOfStack().DefaultAttrVCLoc = VCLoc;
772 }
773 /// Set default data sharing variable category attribute to pointer.
774 void setDefaultDSAVCPointer(SourceLocation VCLoc) {
775 getTopOfStack().DefaultVCAttr = DSA_VC_pointer;
776 getTopOfStack().DefaultAttrVCLoc = VCLoc;
777 }
778 /// Set default data sharing variable category attribute to scalar.
779 void setDefaultDSAVCScalar(SourceLocation VCLoc) {
780 getTopOfStack().DefaultVCAttr = DSA_VC_scalar;
781 getTopOfStack().DefaultAttrVCLoc = VCLoc;
782 }
783 /// Set default data mapping attribute to Modifier:Kind
784 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
785 OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) {
786 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
787 DMI.ImplicitBehavior = M;
788 DMI.SLoc = Loc;
789 }
790 /// Check whether the implicit-behavior has been set in defaultmap
791 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
792 if (VariableCategory == OMPC_DEFAULTMAP_unknown)
793 return getTopOfStack()
794 .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
795 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
796 getTopOfStack()
797 .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
798 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
799 getTopOfStack()
800 .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
801 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
802 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
804 }
805
806 ArrayRef<llvm::omp::TraitProperty> getConstructTraits() {
807 return ConstructTraits;
808 }
809 void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits,
810 bool ScopeEntry) {
811 if (ScopeEntry)
812 ConstructTraits.append(Traits.begin(), Traits.end());
813 else
814 for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) {
815 llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val();
816 assert(Top == Trait && "Something left a trait on the stack!");
817 (void)Trait;
818 (void)Top;
819 }
820 }
821
822 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
823 return getStackSize() <= Level ? DSA_unspecified
824 : getStackElemAtLevel(Level).DefaultAttr;
825 }
826 DefaultDataSharingAttributes getDefaultDSA() const {
827 return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr;
828 }
829 SourceLocation getDefaultDSALocation() const {
830 return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc;
831 }
833 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
834 return isStackEmpty()
836 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
837 }
839 getDefaultmapModifierAtLevel(unsigned Level,
840 OpenMPDefaultmapClauseKind Kind) const {
841 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
842 }
843 bool isDefaultmapCapturedByRef(unsigned Level,
844 OpenMPDefaultmapClauseKind Kind) const {
846 getDefaultmapModifierAtLevel(Level, Kind);
847 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
848 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
849 (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
850 (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
851 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom) ||
852 (M == OMPC_DEFAULTMAP_MODIFIER_present) ||
853 (M == OMPC_DEFAULTMAP_MODIFIER_storage);
854 }
855 return true;
856 }
857 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
859 switch (Kind) {
860 case OMPC_DEFAULTMAP_scalar:
861 case OMPC_DEFAULTMAP_pointer:
862 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
863 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
864 (M == OMPC_DEFAULTMAP_MODIFIER_default);
865 case OMPC_DEFAULTMAP_aggregate:
866 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
867 default:
868 break;
869 }
870 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
871 }
872 bool mustBeFirstprivateAtLevel(unsigned Level,
873 OpenMPDefaultmapClauseKind Kind) const {
875 getDefaultmapModifierAtLevel(Level, Kind);
876 return mustBeFirstprivateBase(M, Kind);
877 }
878 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
879 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
880 return mustBeFirstprivateBase(M, Kind);
881 }
882
883 /// Checks if the specified variable is a threadprivate.
884 bool isThreadPrivate(VarDecl *D) {
885 const DSAVarData DVar = getTopDSA(D, false);
886 return isOpenMPThreadPrivate(DVar.CKind);
887 }
888
889 /// Marks current region as ordered (it has an 'ordered' clause).
890 void setOrderedRegion(bool IsOrdered, const Expr *Param,
891 OMPOrderedClause *Clause) {
892 if (IsOrdered)
893 getTopOfStack().OrderedRegion.emplace(Param, Clause);
894 else
895 getTopOfStack().OrderedRegion.reset();
896 }
897 /// Returns true, if region is ordered (has associated 'ordered' clause),
898 /// false - otherwise.
899 bool isOrderedRegion() const {
900 if (const SharingMapTy *Top = getTopOfStackOrNull())
901 return Top->OrderedRegion.has_value();
902 return false;
903 }
904 /// Returns optional parameter for the ordered region.
905 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
906 if (const SharingMapTy *Top = getTopOfStackOrNull())
907 if (Top->OrderedRegion)
908 return *Top->OrderedRegion;
909 return std::make_pair(nullptr, nullptr);
910 }
911 /// Returns true, if parent region is ordered (has associated
912 /// 'ordered' clause), false - otherwise.
913 bool isParentOrderedRegion() const {
914 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
915 return Parent->OrderedRegion.has_value();
916 return false;
917 }
918 /// Returns optional parameter for the ordered region.
919 std::pair<const Expr *, OMPOrderedClause *>
920 getParentOrderedRegionParam() const {
921 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
922 if (Parent->OrderedRegion)
923 return *Parent->OrderedRegion;
924 return std::make_pair(nullptr, nullptr);
925 }
926 /// Marks current region as having an 'order' clause.
927 void setRegionHasOrderConcurrent(bool HasOrderConcurrent) {
928 getTopOfStack().RegionHasOrderConcurrent = HasOrderConcurrent;
929 }
930 /// Returns true if the nearest enclosing directive that is not a
931 /// loop-transforming construct has an order(concurrent) clause.
932 bool isEnclosingOrderConcurrent() const {
933 for (const_iterator I = begin() + std::min<size_t>(1, getStackSize()),
934 E = end();
935 I != E; ++I) {
936 if (I->RegionHasOrderConcurrent)
937 return true;
938 if (!isOpenMPLoopTransformationDirective(I->Directive))
939 return false;
940 }
941 return false;
942 }
943 /// Returns true if the nearest enclosing directive that is not a
944 /// loop-transforming or ordered simd construct is a simd directive.
945 bool isInSimdRegion() const {
946 for (const_iterator I = begin() + std::min<size_t>(1, getStackSize()),
947 E = end();
948 I != E; ++I) {
949 if (isOpenMPSimdDirective(I->Directive))
950 return true;
951 if (!isOpenMPLoopTransformationDirective(I->Directive) &&
952 I->Directive != OMPD_ordered_blockassoc)
953 return false;
954 }
955 return false;
956 }
957 /// Marks current region as nowait (it has a 'nowait' clause).
958 void setNowaitRegion(bool IsNowait = true) {
959 getTopOfStack().NowaitRegion = IsNowait;
960 }
961 /// Returns true, if parent region is nowait (has associated
962 /// 'nowait' clause), false - otherwise.
963 bool isParentNowaitRegion() const {
964 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
965 return Parent->NowaitRegion;
966 return false;
967 }
968 /// Marks current region as untied (it has a 'untied' clause).
969 void setUntiedRegion(bool IsUntied = true) {
970 getTopOfStack().UntiedRegion = IsUntied;
971 }
972 /// Return true if current region is untied.
973 bool isUntiedRegion() const {
974 const SharingMapTy *Top = getTopOfStackOrNull();
975 return Top ? Top->UntiedRegion : false;
976 }
977 /// Marks parent region as cancel region.
978 void setParentCancelRegion(bool Cancel = true) {
979 if (SharingMapTy *Parent = getSecondOnStackOrNull())
980 Parent->CancelRegion |= Cancel;
981 }
982 /// Return true if current region has inner cancel construct.
983 bool isCancelRegion() const {
984 const SharingMapTy *Top = getTopOfStackOrNull();
985 return Top ? Top->CancelRegion : false;
986 }
987
988 /// Mark that parent region already has scan directive.
989 void setParentHasScanDirective(SourceLocation Loc) {
990 if (SharingMapTy *Parent = getSecondOnStackOrNull())
991 Parent->PrevScanLocation = Loc;
992 }
993 /// Return true if current region has inner cancel construct.
994 bool doesParentHasScanDirective() const {
995 const SharingMapTy *Top = getSecondOnStackOrNull();
996 return Top ? Top->PrevScanLocation.isValid() : false;
997 }
998 /// Return true if current region has inner cancel construct.
999 SourceLocation getParentScanDirectiveLoc() const {
1000 const SharingMapTy *Top = getSecondOnStackOrNull();
1001 return Top ? Top->PrevScanLocation : SourceLocation();
1002 }
1003 /// Mark that parent region already has ordered directive.
1004 void setParentHasOrderedDirective(SourceLocation Loc) {
1005 if (SharingMapTy *Parent = getSecondOnStackOrNull())
1006 Parent->PrevOrderedLocation = Loc;
1007 }
1008 /// Return true if current region has inner ordered construct.
1009 bool doesParentHasOrderedDirective() const {
1010 const SharingMapTy *Top = getSecondOnStackOrNull();
1011 return Top ? Top->PrevOrderedLocation.isValid() : false;
1012 }
1013 /// Returns the location of the previously specified ordered directive.
1014 SourceLocation getParentOrderedDirectiveLoc() const {
1015 const SharingMapTy *Top = getSecondOnStackOrNull();
1016 return Top ? Top->PrevOrderedLocation : SourceLocation();
1017 }
1018
1019 /// Set collapse value for the region.
1020 void setAssociatedLoops(unsigned Val) {
1021 getTopOfStack().AssociatedLoops = Val;
1022 if (Val > 1)
1023 getTopOfStack().HasMutipleLoops = true;
1024 }
1025 /// Return collapse value for region.
1026 unsigned getAssociatedLoops() const {
1027 const SharingMapTy *Top = getTopOfStackOrNull();
1028 return Top ? Top->AssociatedLoops : 0;
1029 }
1030 /// Returns true if the construct is associated with multiple loops.
1031 bool hasMutipleLoops() const {
1032 const SharingMapTy *Top = getTopOfStackOrNull();
1033 return Top ? Top->HasMutipleLoops : false;
1034 }
1035
1036 /// Marks current target region as one with closely nested teams
1037 /// region.
1038 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
1039 if (SharingMapTy *Parent = getSecondOnStackOrNull())
1040 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
1041 }
1042 /// Returns true, if current region has closely nested teams region.
1043 bool hasInnerTeamsRegion() const {
1044 return getInnerTeamsRegionLoc().isValid();
1045 }
1046 /// Returns location of the nested teams region (if any).
1047 SourceLocation getInnerTeamsRegionLoc() const {
1048 const SharingMapTy *Top = getTopOfStackOrNull();
1049 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
1050 }
1051
1052 Scope *getCurScope() const {
1053 const SharingMapTy *Top = getTopOfStackOrNull();
1054 return Top ? Top->CurScope : nullptr;
1055 }
1056 void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
1057 SourceLocation getConstructLoc() const {
1058 const SharingMapTy *Top = getTopOfStackOrNull();
1059 return Top ? Top->ConstructLoc : SourceLocation();
1060 }
1061
1062 /// Do the check specified in \a Check to all component lists and return true
1063 /// if any issue is found.
1064 bool checkMappableExprComponentListsForDecl(
1065 const ValueDecl *VD, bool CurrentRegionOnly,
1066 const llvm::function_ref<
1069 Check) const {
1070 if (isStackEmpty())
1071 return false;
1072 auto SI = begin();
1073 auto SE = end();
1074
1075 if (SI == SE)
1076 return false;
1077
1078 if (CurrentRegionOnly)
1079 SE = std::next(SI);
1080 else
1081 std::advance(SI, 1);
1082
1083 for (; SI != SE; ++SI) {
1084 auto MI = SI->MappedExprComponents.find(VD);
1085 if (MI != SI->MappedExprComponents.end())
1087 MI->second.Components)
1088 if (Check(L, MI->second.Kind))
1089 return true;
1090 }
1091 return false;
1092 }
1093
1094 /// Do the check specified in \a Check to all component lists at a given level
1095 /// and return true if any issue is found.
1096 bool checkMappableExprComponentListsForDeclAtLevel(
1097 const ValueDecl *VD, unsigned Level,
1098 const llvm::function_ref<
1101 Check) const {
1102 if (getStackSize() <= Level)
1103 return false;
1104
1105 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1106 auto MI = StackElem.MappedExprComponents.find(VD);
1107 if (MI != StackElem.MappedExprComponents.end())
1109 MI->second.Components)
1110 if (Check(L, MI->second.Kind))
1111 return true;
1112 return false;
1113 }
1114
1115 /// Create a new mappable expression component list associated with a given
1116 /// declaration and initialize it with the provided list of components.
1117 void addMappableExpressionComponents(
1118 const ValueDecl *VD,
1120 OpenMPClauseKind WhereFoundClauseKind) {
1121 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
1122 // Create new entry and append the new components there.
1123 MEC.Components.resize(MEC.Components.size() + 1);
1124 MEC.Components.back().append(Components.begin(), Components.end());
1125 MEC.Kind = WhereFoundClauseKind;
1126 }
1127
1128 unsigned getNestingLevel() const {
1129 assert(!isStackEmpty());
1130 return getStackSize() - 1;
1131 }
1132 void addDoacrossDependClause(OMPClause *C, const OperatorOffsetTy &OpsOffs) {
1133 SharingMapTy *Parent = getSecondOnStackOrNull();
1134 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
1135 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
1136 }
1137 llvm::iterator_range<DoacrossClauseMapTy::const_iterator>
1138 getDoacrossDependClauses() const {
1139 const SharingMapTy &StackElem = getTopOfStack();
1140 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
1141 const DoacrossClauseMapTy &Ref = StackElem.DoacrossDepends;
1142 return llvm::make_range(Ref.begin(), Ref.end());
1143 }
1144 return llvm::make_range(StackElem.DoacrossDepends.end(),
1145 StackElem.DoacrossDepends.end());
1146 }
1147
1148 // Store types of classes which have been explicitly mapped
1149 void addMappedClassesQualTypes(QualType QT) {
1150 SharingMapTy &StackElem = getTopOfStack();
1151 StackElem.MappedClassesQualTypes.insert(QT);
1152 }
1153
1154 // Return set of mapped classes types
1155 bool isClassPreviouslyMapped(QualType QT) const {
1156 const SharingMapTy &StackElem = getTopOfStack();
1157 return StackElem.MappedClassesQualTypes.contains(QT);
1158 }
1159
1160 /// Adds global declare target to the parent target region.
1161 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
1162 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1163 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
1164 "Expected declare target link global.");
1165 for (auto &Elem : *this) {
1166 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
1167 Elem.DeclareTargetLinkVarDecls.push_back(E);
1168 return;
1169 }
1170 }
1171 }
1172
1173 /// Returns the list of globals with declare target link if current directive
1174 /// is target.
1175 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
1176 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
1177 "Expected target executable directive.");
1178 return getTopOfStack().DeclareTargetLinkVarDecls;
1179 }
1180
1181 /// Adds list of allocators expressions.
1182 void addInnerAllocatorExpr(Expr *E) {
1183 getTopOfStack().InnerUsedAllocators.push_back(E);
1184 }
1185 /// Return list of used allocators.
1186 ArrayRef<Expr *> getInnerAllocators() const {
1187 return getTopOfStack().InnerUsedAllocators;
1188 }
1189 /// Marks the declaration as implicitly firstprivate nin the task-based
1190 /// regions.
1191 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
1192 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
1193 }
1194 /// Checks if the decl is implicitly firstprivate in the task-based region.
1195 bool isImplicitTaskFirstprivate(Decl *D) const {
1196 return getTopOfStack().ImplicitTaskFirstprivates.contains(D);
1197 }
1198
1199 /// Marks decl as used in uses_allocators clause as the allocator.
1200 void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
1201 getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
1202 }
1203 /// Checks if specified decl is used in uses allocator clause as the
1204 /// allocator.
1205 std::optional<UsesAllocatorsDeclKind>
1206 isUsesAllocatorsDecl(unsigned Level, const Decl *D) const {
1207 const SharingMapTy &StackElem = getTopOfStack();
1208 auto I = StackElem.UsesAllocatorsDecls.find(D);
1209 if (I == StackElem.UsesAllocatorsDecls.end())
1210 return std::nullopt;
1211 return I->getSecond();
1212 }
1213 std::optional<UsesAllocatorsDeclKind>
1214 isUsesAllocatorsDecl(const Decl *D) const {
1215 const SharingMapTy &StackElem = getTopOfStack();
1216 auto I = StackElem.UsesAllocatorsDecls.find(D);
1217 if (I == StackElem.UsesAllocatorsDecls.end())
1218 return std::nullopt;
1219 return I->getSecond();
1220 }
1221
1222 void addDeclareMapperVarRef(Expr *Ref) {
1223 SharingMapTy &StackElem = getTopOfStack();
1224 StackElem.DeclareMapperVar = Ref;
1225 }
1226 const Expr *getDeclareMapperVarRef() const {
1227 const SharingMapTy *Top = getTopOfStackOrNull();
1228 return Top ? Top->DeclareMapperVar : nullptr;
1229 }
1230
1231 /// Add a new iterator variable.
1232 void addIteratorVarDecl(VarDecl *VD) {
1233 SharingMapTy &StackElem = getTopOfStack();
1234 StackElem.IteratorVarDecls.push_back(VD->getCanonicalDecl());
1235 }
1236 /// Check if variable declaration is an iterator VarDecl.
1237 bool isIteratorVarDecl(const VarDecl *VD) const {
1238 const SharingMapTy *Top = getTopOfStackOrNull();
1239 if (!Top)
1240 return false;
1241
1242 return llvm::is_contained(Top->IteratorVarDecls, VD->getCanonicalDecl());
1243 }
1244 /// get captured field from ImplicitDefaultFirstprivateFDs
1245 VarDecl *getImplicitFDCapExprDecl(const FieldDecl *FD) const {
1246 const_iterator I = begin();
1247 const_iterator EndI = end();
1248 size_t StackLevel = getStackSize();
1249 for (; I != EndI; ++I) {
1250 if (I->DefaultAttr == DSA_firstprivate || I->DefaultAttr == DSA_private)
1251 break;
1252 StackLevel--;
1253 }
1254 assert((StackLevel > 0 && I != EndI) || (StackLevel == 0 && I == EndI));
1255 if (I == EndI)
1256 return nullptr;
1257 for (const auto &IFD : I->ImplicitDefaultFirstprivateFDs)
1258 if (IFD.FD == FD && IFD.StackLevel == StackLevel)
1259 return IFD.VD;
1260 return nullptr;
1261 }
1262 /// Check if capture decl is field captured in ImplicitDefaultFirstprivateFDs
1263 bool isImplicitDefaultFirstprivateFD(VarDecl *VD) const {
1264 const_iterator I = begin();
1265 const_iterator EndI = end();
1266 for (; I != EndI; ++I)
1267 if (I->DefaultAttr == DSA_firstprivate || I->DefaultAttr == DSA_private)
1268 break;
1269 if (I == EndI)
1270 return false;
1271 for (const auto &IFD : I->ImplicitDefaultFirstprivateFDs)
1272 if (IFD.VD == VD)
1273 return true;
1274 return false;
1275 }
1276 /// Store capture FD info in ImplicitDefaultFirstprivateFDs
1277 void addImplicitDefaultFirstprivateFD(const FieldDecl *FD, VarDecl *VD) {
1278 iterator I = begin();
1279 const_iterator EndI = end();
1280 size_t StackLevel = getStackSize();
1281 for (; I != EndI; ++I) {
1282 if (I->DefaultAttr == DSA_private || I->DefaultAttr == DSA_firstprivate) {
1283 I->ImplicitDefaultFirstprivateFDs.emplace_back(FD, StackLevel, VD);
1284 break;
1285 }
1286 StackLevel--;
1287 }
1288 assert((StackLevel > 0 && I != EndI) || (StackLevel == 0 && I == EndI));
1289 }
1290 void setOrderedToBlockAssociated() {
1291 assert(getCurrentDirective() == OMPD_ordered_standalone);
1292 getTopOfStack().Directive = OMPD_ordered_blockassoc;
1293 }
1294};
1295
1296bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1297 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
1298}
1299
1300bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
1301 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
1302 DKind == OMPD_unknown;
1303}
1304
1305} // namespace
1306
1307static const Expr *getExprAsWritten(const Expr *E) {
1308 if (const auto *FE = dyn_cast<FullExpr>(E))
1309 E = FE->getSubExpr();
1310
1311 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
1312 E = MTE->getSubExpr();
1313
1314 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1315 E = Binder->getSubExpr();
1316
1317 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
1318 E = ICE->getSubExprAsWritten();
1319 return E->IgnoreParens();
1320}
1321
1323 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
1324}
1325
1326static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
1327 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
1328 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
1329 D = ME->getMemberDecl();
1330
1332 return D;
1333}
1334
1336 return const_cast<ValueDecl *>(
1337 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
1338}
1339
1341 if (C == OMPC_threadprivate)
1342 return getOpenMPClauseName(C).str() + " or thread local";
1343 return getOpenMPClauseName(C).str();
1344}
1345
1346DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
1347 ValueDecl *D) const {
1348 D = getCanonicalDecl(D);
1349 auto *VD = dyn_cast<VarDecl>(D);
1350 const auto *FD = dyn_cast<FieldDecl>(D);
1351 DSAVarData DVar;
1352 if (Iter == end()) {
1353 // A tuple-like binding has the storage of the variable it decomposes.
1354 const VarDecl *StorageVD = VD;
1355 if (const auto *BD = dyn_cast<BindingDecl>(D); BD && BD->getHoldingVar())
1356 StorageVD = BD->getDecomposedDecl();
1357 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1358 // in a region but not in construct]
1359 // File-scope or namespace-scope variables referenced in called routines
1360 // in the region are shared unless they appear in a threadprivate
1361 // directive.
1362 if (StorageVD && !StorageVD->isFunctionOrMethodVarDecl() &&
1363 !isa<ParmVarDecl>(StorageVD))
1364 DVar.CKind = OMPC_shared;
1365
1366 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
1367 // in a region but not in construct]
1368 // Variables with static storage duration that are declared in called
1369 // routines in the region are shared.
1370 if (StorageVD && StorageVD->hasGlobalStorage())
1371 DVar.CKind = OMPC_shared;
1372
1373 // Non-static data members are shared by default.
1374 if (FD)
1375 DVar.CKind = OMPC_shared;
1376
1377 return DVar;
1378 }
1379
1380 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1381 // in a Construct, C/C++, predetermined, p.1]
1382 // Variables with automatic storage duration that are declared in a scope
1383 // inside the construct are private.
1384 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1385 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
1386 DVar.CKind = OMPC_private;
1387 return DVar;
1388 }
1389
1390 DVar.DKind = Iter->Directive;
1391 // Explicitly specified attributes and local variables with predetermined
1392 // attributes.
1393 if (Iter->SharingMap.count(D)) {
1394 const DSAInfo &Data = Iter->SharingMap.lookup(D);
1395 DVar.RefExpr = Data.RefExpr.getPointer();
1396 DVar.PrivateCopy = Data.PrivateCopy;
1397 DVar.CKind = Data.Attributes;
1398 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1399 DVar.Modifier = Data.Modifier;
1400 DVar.AppliedToPointee = Data.AppliedToPointee;
1401 // For BindingDecls with OMPC_unknown, fall through to implicit DSA logic
1402 // instead of treating them as explicitly specified.
1403 if (!(isa<BindingDecl>(D) && DVar.CKind == OMPC_unknown)) {
1404 return DVar;
1405 }
1406 }
1407
1408 DefaultDataSharingAttributes IterDA = Iter->DefaultAttr;
1409 switch (Iter->DefaultVCAttr) {
1410 case DSA_VC_aggregate:
1411 if (!D->getType()->isAggregateType())
1412 IterDA = DSA_none;
1413 break;
1414 case DSA_VC_pointer:
1415 if (!D->getType()->isPointerType())
1416 IterDA = DSA_none;
1417 break;
1418 case DSA_VC_scalar:
1419 if (!D->getType()->isScalarType())
1420 IterDA = DSA_none;
1421 break;
1422 case DSA_VC_all:
1423 break;
1424 }
1425
1426 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1427 // in a Construct, C/C++, implicitly determined, p.1]
1428 // In a parallel or task construct, the data-sharing attributes of these
1429 // variables are determined by the default clause, if present.
1430 switch (IterDA) {
1431 case DSA_shared:
1432 DVar.CKind = OMPC_shared;
1433 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1434 return DVar;
1435 case DSA_none:
1436 return DVar;
1437 case DSA_firstprivate:
1438 if (VD && VD->getStorageDuration() == SD_Static &&
1439 VD->getDeclContext()->isFileContext()) {
1440 DVar.CKind = OMPC_unknown;
1441 } else {
1442 DVar.CKind = OMPC_firstprivate;
1443 }
1444 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1445 return DVar;
1446 case DSA_private:
1447 // each variable with static storage duration that is declared
1448 // in a namespace or global scope and referenced in the construct,
1449 // and that does not have a predetermined data-sharing attribute
1450 if (VD && VD->getStorageDuration() == SD_Static &&
1451 VD->getDeclContext()->isFileContext()) {
1452 DVar.CKind = OMPC_unknown;
1453 } else {
1454 DVar.CKind = OMPC_private;
1455 }
1456 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1457 return DVar;
1458 case DSA_unspecified:
1459 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1460 // in a Construct, implicitly determined, p.2]
1461 // In a parallel construct, if no default clause is present, these
1462 // variables are shared.
1463 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
1464 if ((isOpenMPParallelDirective(DVar.DKind) &&
1465 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
1466 isOpenMPTeamsDirective(DVar.DKind)) {
1467 DVar.CKind = OMPC_shared;
1468 return DVar;
1469 }
1470
1471 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1472 // in a Construct, implicitly determined, p.4]
1473 // In a task construct, if no default clause is present, a variable that in
1474 // the enclosing context is determined to be shared by all implicit tasks
1475 // bound to the current team is shared.
1476 if (isOpenMPTaskingDirective(DVar.DKind)) {
1477 DSAVarData DVarTemp;
1478 const_iterator I = Iter, E = end();
1479 do {
1480 ++I;
1481 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
1482 // Referenced in a Construct, implicitly determined, p.6]
1483 // In a task construct, if no default clause is present, a variable
1484 // whose data-sharing attribute is not determined by the rules above is
1485 // firstprivate.
1486 DVarTemp = getDSA(I, D);
1487 if (DVarTemp.CKind != OMPC_shared) {
1488 DVar.RefExpr = nullptr;
1489 DVar.CKind = OMPC_firstprivate;
1490 return DVar;
1491 }
1492 } while (I != E && !isImplicitTaskingRegion(I->Directive));
1493 DVar.CKind =
1494 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
1495 return DVar;
1496 }
1497 }
1498 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1499 // in a Construct, implicitly determined, p.3]
1500 // For constructs other than task, if no default clause is present, these
1501 // variables inherit their data-sharing attributes from the enclosing
1502 // context.
1503 return getDSA(++Iter, D);
1504}
1505
1506const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1507 const Expr *NewDE) {
1508 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1509 D = getCanonicalDecl(D);
1510 SharingMapTy &StackElem = getTopOfStack();
1511 auto [It, Inserted] = StackElem.AlignedMap.try_emplace(D, NewDE);
1512 if (Inserted) {
1513 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1514 return nullptr;
1515 }
1516 assert(It->second && "Unexpected nullptr expr in the aligned map");
1517 return It->second;
1518}
1519
1520const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1521 const Expr *NewDE) {
1522 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1523 D = getCanonicalDecl(D);
1524 SharingMapTy &StackElem = getTopOfStack();
1525 auto [It, Inserted] = StackElem.NontemporalMap.try_emplace(D, NewDE);
1526 if (Inserted) {
1527 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1528 return nullptr;
1529 }
1530 assert(It->second && "Unexpected nullptr expr in the aligned map");
1531 return It->second;
1532}
1533
1534void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
1535 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1536 D = getCanonicalDecl(D);
1537 SharingMapTy &StackElem = getTopOfStack();
1538 StackElem.LCVMap.try_emplace(
1539 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
1540}
1541
1542const DSAStackTy::LCDeclInfo
1543DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
1544 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1545 D = getCanonicalDecl(D);
1546 const SharingMapTy &StackElem = getTopOfStack();
1547 auto It = StackElem.LCVMap.find(D);
1548 if (It != StackElem.LCVMap.end())
1549 return It->second;
1550 return {0, nullptr};
1551}
1552
1553const DSAStackTy::LCDeclInfo
1554DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
1555 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1556 D = getCanonicalDecl(D);
1557 for (unsigned I = Level + 1; I > 0; --I) {
1558 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
1559 auto It = StackElem.LCVMap.find(D);
1560 if (It != StackElem.LCVMap.end())
1561 return It->second;
1562 }
1563 return {0, nullptr};
1564}
1565
1566const DSAStackTy::LCDeclInfo
1567DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
1568 const SharingMapTy *Parent = getSecondOnStackOrNull();
1569 assert(Parent && "Data-sharing attributes stack is empty");
1570 D = getCanonicalDecl(D);
1571 auto It = Parent->LCVMap.find(D);
1572 if (It != Parent->LCVMap.end())
1573 return It->second;
1574 return {0, nullptr};
1575}
1576
1577const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
1578 const SharingMapTy *Parent = getSecondOnStackOrNull();
1579 assert(Parent && "Data-sharing attributes stack is empty");
1580 if (Parent->LCVMap.size() < I)
1581 return nullptr;
1582 for (const auto &Pair : Parent->LCVMap)
1583 if (Pair.second.first == I)
1584 return Pair.first;
1585 return nullptr;
1586}
1587
1588void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
1589 DeclRefExpr *PrivateCopy, unsigned Modifier,
1590 bool AppliedToPointee) {
1591 D = getCanonicalDecl(D);
1592 if (A == OMPC_threadprivate) {
1593 DSAInfo &Data = Threadprivates[D];
1594 Data.Attributes = A;
1595 Data.RefExpr.setPointer(E);
1596 Data.PrivateCopy = nullptr;
1597 Data.Modifier = Modifier;
1598 } else if (A == OMPC_groupprivate) {
1599 DSAInfo &Data = Groupprivates[D];
1600 Data.Attributes = A;
1601 Data.RefExpr.setPointer(E);
1602 Data.PrivateCopy = nullptr;
1603 Data.Modifier = Modifier;
1604 } else {
1605 DSAInfo &Data = getTopOfStack().SharingMap[D];
1606 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1607 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1608 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1609 (isLoopControlVariable(D).first && A == OMPC_private));
1610 Data.Modifier = Modifier;
1611 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1612 Data.RefExpr.setInt(/*IntVal=*/true);
1613 return;
1614 }
1615 const bool IsLastprivate =
1616 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1617 Data.Attributes = A;
1618 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1619 Data.PrivateCopy = PrivateCopy;
1620 Data.AppliedToPointee = AppliedToPointee;
1621 if (PrivateCopy) {
1622 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
1623 Data.Modifier = Modifier;
1624 Data.Attributes = A;
1625 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1626 Data.PrivateCopy = nullptr;
1627 Data.AppliedToPointee = AppliedToPointee;
1628 }
1629 }
1630}
1631
1632/// Build a variable declaration for OpenMP loop iteration variable.
1634 StringRef Name, const AttrVec *Attrs = nullptr,
1635 DeclRefExpr *OrigRef = nullptr) {
1636 DeclContext *DC = SemaRef.CurContext;
1637 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1638 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1639 auto *Decl =
1640 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1641 if (Attrs) {
1642 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1643 I != E; ++I)
1644 Decl->addAttr(*I);
1645 }
1646 Decl->setImplicit();
1647 if (OrigRef) {
1648 Decl->addAttr(
1649 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1650 }
1651 return Decl;
1652}
1653
1655 SourceLocation Loc,
1656 bool RefersToCapture = false) {
1657 D->setReferenced();
1658 D->markUsed(S.Context);
1660 SourceLocation(), D, RefersToCapture, Loc, Ty,
1661 VK_LValue);
1662}
1663
1664void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1665 BinaryOperatorKind BOK) {
1666 D = getCanonicalDecl(D);
1667 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1668 assert(
1669 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1670 "Additional reduction info may be specified only for reduction items.");
1671 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1672 assert(ReductionData.ReductionRange.isInvalid() &&
1673 (getTopOfStack().Directive == OMPD_taskgroup ||
1674 ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1675 isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1676 !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1677 "Additional reduction info may be specified only once for reduction "
1678 "items.");
1679 ReductionData.set(BOK, SR);
1680 Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1681 if (!TaskgroupReductionRef) {
1682 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1683 SemaRef.Context.VoidPtrTy, ".task_red.");
1684 TaskgroupReductionRef =
1685 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1686 }
1687}
1688
1689void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
1690 const Expr *ReductionRef) {
1691 D = getCanonicalDecl(D);
1692 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
1693 assert(
1694 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
1695 "Additional reduction info may be specified only for reduction items.");
1696 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
1697 assert(ReductionData.ReductionRange.isInvalid() &&
1698 (getTopOfStack().Directive == OMPD_taskgroup ||
1699 ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
1700 isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
1701 !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
1702 "Additional reduction info may be specified only once for reduction "
1703 "items.");
1704 ReductionData.set(ReductionRef, SR);
1705 Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
1706 if (!TaskgroupReductionRef) {
1707 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1708 SemaRef.Context.VoidPtrTy, ".task_red.");
1709 TaskgroupReductionRef =
1710 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1711 }
1712}
1713
1714const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1715 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1716 Expr *&TaskgroupDescriptor) const {
1717 D = getCanonicalDecl(D);
1718 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1719 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1720 const DSAInfo &Data = I->SharingMap.lookup(D);
1721 if (Data.Attributes != OMPC_reduction ||
1722 Data.Modifier != OMPC_REDUCTION_task)
1723 continue;
1724 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1725 if (!ReductionData.ReductionOp ||
1726 isa<const Expr *>(ReductionData.ReductionOp))
1727 return DSAVarData();
1728 SR = ReductionData.ReductionRange;
1729 BOK = cast<ReductionData::BOKPtrType>(ReductionData.ReductionOp);
1730 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1731 "expression for the descriptor is not "
1732 "set.");
1733 TaskgroupDescriptor = I->TaskgroupReductionRef;
1734 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1735 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1736 /*AppliedToPointee=*/false);
1737 }
1738 return DSAVarData();
1739}
1740
1741const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1742 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1743 Expr *&TaskgroupDescriptor) const {
1744 D = getCanonicalDecl(D);
1745 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1746 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
1747 const DSAInfo &Data = I->SharingMap.lookup(D);
1748 if (Data.Attributes != OMPC_reduction ||
1749 Data.Modifier != OMPC_REDUCTION_task)
1750 continue;
1751 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1752 if (!ReductionData.ReductionOp ||
1753 !isa<const Expr *>(ReductionData.ReductionOp))
1754 return DSAVarData();
1755 SR = ReductionData.ReductionRange;
1756 ReductionRef = cast<const Expr *>(ReductionData.ReductionOp);
1757 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1758 "expression for the descriptor is not "
1759 "set.");
1760 TaskgroupDescriptor = I->TaskgroupReductionRef;
1761 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
1762 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
1763 /*AppliedToPointee=*/false);
1764 }
1765 return DSAVarData();
1766}
1767
1768bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
1769 D = D->getCanonicalDecl();
1770 for (const_iterator E = end(); I != E; ++I) {
1771 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1772 isOpenMPTargetExecutionDirective(I->Directive)) {
1773 if (I->CurScope) {
1774 Scope *TopScope = I->CurScope->getParent();
1775 Scope *CurScope = getCurScope();
1776 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1777 CurScope = CurScope->getParent();
1778 return CurScope != TopScope;
1779 }
1780 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
1781 if (I->Context == DC)
1782 return true;
1783 return false;
1784 }
1785 }
1786 return false;
1787}
1788
1790 bool AcceptIfMutable = true,
1791 bool *IsClassType = nullptr) {
1792 ASTContext &Context = SemaRef.getASTContext();
1793 Type = Type.getNonReferenceType().getCanonicalType();
1794 bool IsConstant = Type.isConstant(Context);
1795 Type = Context.getBaseElementType(Type);
1796 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1798 : nullptr;
1799 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1800 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1801 RD = CTD->getTemplatedDecl();
1802 if (IsClassType)
1803 *IsClassType = RD;
1804 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1805 RD->hasDefinition() && RD->hasMutableFields());
1806}
1807
1808static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1810 SourceLocation ELoc,
1811 bool AcceptIfMutable = true,
1812 bool ListItemNotVar = false) {
1813 ASTContext &Context = SemaRef.getASTContext();
1814 bool IsClassType;
1815 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1816 unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item
1817 : IsClassType ? diag::err_omp_const_not_mutable_variable
1818 : diag::err_omp_const_variable;
1819 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseNameForDiag(CKind);
1820 if (!ListItemNotVar && D) {
1821 const VarDecl *VD = dyn_cast<VarDecl>(D);
1822 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1824 SemaRef.Diag(D->getLocation(),
1825 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1826 << D;
1827 }
1828 return true;
1829 }
1830 return false;
1831}
1832
1833const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1834 bool FromParent) {
1835 D = getCanonicalDecl(D);
1836 DSAVarData DVar;
1837
1838 auto *VD = dyn_cast<VarDecl>(D);
1839 auto TI = Threadprivates.find(D);
1840 if (TI != Threadprivates.end()) {
1841 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1842 DVar.CKind = OMPC_threadprivate;
1843 DVar.Modifier = TI->getSecond().Modifier;
1844 return DVar;
1845 }
1846 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1847 DVar.RefExpr = buildDeclRefExpr(
1848 SemaRef, VD, D->getType().getNonReferenceType(),
1849 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1850 DVar.CKind = OMPC_threadprivate;
1851 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1852 return DVar;
1853 }
1854 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1855 // in a Construct, C/C++, predetermined, p.1]
1856 // Variables appearing in threadprivate directives are threadprivate.
1857 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1858 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1859 SemaRef.getLangOpts().OpenMPUseTLS &&
1860 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1861 (VD && VD->getStorageClass() == SC_Register &&
1862 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1863 DVar.RefExpr = buildDeclRefExpr(
1864 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1865 DVar.CKind = OMPC_threadprivate;
1866 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1867 return DVar;
1868 }
1869 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1870 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1871 !isLoopControlVariable(D).first) {
1872 const_iterator IterTarget =
1873 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1874 return isOpenMPTargetExecutionDirective(Data.Directive);
1875 });
1876 if (IterTarget != end()) {
1877 const_iterator ParentIterTarget = IterTarget + 1;
1878 for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) {
1879 if (isOpenMPLocal(VD, Iter)) {
1880 DVar.RefExpr =
1881 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1882 D->getLocation());
1883 DVar.CKind = OMPC_threadprivate;
1884 return DVar;
1885 }
1886 }
1887 if (!isClauseParsingMode() || IterTarget != begin()) {
1888 auto DSAIter = IterTarget->SharingMap.find(D);
1889 if (DSAIter != IterTarget->SharingMap.end() &&
1890 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1891 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1892 DVar.CKind = OMPC_threadprivate;
1893 return DVar;
1894 }
1895 const_iterator End = end();
1896 if (!SemaRef.OpenMP().isOpenMPCapturedByRef(
1897 D, std::distance(ParentIterTarget, End),
1898 /*OpenMPCaptureLevel=*/0)) {
1899 DVar.RefExpr =
1900 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1901 IterTarget->ConstructLoc);
1902 DVar.CKind = OMPC_threadprivate;
1903 return DVar;
1904 }
1905 }
1906 }
1907 }
1908
1909 if (isStackEmpty())
1910 // Not in OpenMP execution region and top scope was already checked.
1911 return DVar;
1912
1913 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1914 // in a Construct, C/C++, predetermined, p.4]
1915 // Static data members are shared.
1916 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1917 // in a Construct, C/C++, predetermined, p.7]
1918 // Variables with static storage duration that are declared in a scope
1919 // inside the construct are shared.
1920 if (VD && VD->isStaticDataMember()) {
1921 // Check for explicitly specified attributes.
1922 const_iterator I = begin();
1923 const_iterator EndI = end();
1924 if (FromParent && I != EndI)
1925 ++I;
1926 if (I != EndI) {
1927 auto It = I->SharingMap.find(D);
1928 if (It != I->SharingMap.end()) {
1929 const DSAInfo &Data = It->getSecond();
1930 DVar.RefExpr = Data.RefExpr.getPointer();
1931 DVar.PrivateCopy = Data.PrivateCopy;
1932 DVar.CKind = Data.Attributes;
1933 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1934 DVar.DKind = I->Directive;
1935 DVar.Modifier = Data.Modifier;
1936 DVar.AppliedToPointee = Data.AppliedToPointee;
1937 return DVar;
1938 }
1939 }
1940
1941 DVar.CKind = OMPC_shared;
1942 return DVar;
1943 }
1944
1945 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1946 // The predetermined shared attribute for const-qualified types having no
1947 // mutable members was removed after OpenMP 3.1.
1948 if (SemaRef.LangOpts.OpenMP <= 31) {
1949 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1950 // in a Construct, C/C++, predetermined, p.6]
1951 // Variables with const qualified type having no mutable member are
1952 // shared.
1953 if (isConstNotMutableType(SemaRef, D->getType())) {
1954 // Variables with const-qualified type having no mutable member may be
1955 // listed in a firstprivate clause, even if they are static data members.
1956 DSAVarData DVarTemp = hasInnermostDSA(
1957 D,
1958 [](OpenMPClauseKind C, bool) {
1959 return C == OMPC_firstprivate || C == OMPC_shared;
1960 },
1961 MatchesAlways, FromParent);
1962 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1963 return DVarTemp;
1964
1965 DVar.CKind = OMPC_shared;
1966 return DVar;
1967 }
1968 }
1969
1970 // Explicitly specified attributes and local variables with predetermined
1971 // attributes.
1972 const_iterator I = begin();
1973 const_iterator EndI = end();
1974 if (FromParent && I != EndI)
1975 ++I;
1976 if (I == EndI)
1977 return DVar;
1978 auto It = I->SharingMap.find(D);
1979 if (It != I->SharingMap.end()) {
1980 const DSAInfo &Data = It->getSecond();
1981 DVar.RefExpr = Data.RefExpr.getPointer();
1982 DVar.PrivateCopy = Data.PrivateCopy;
1983 DVar.CKind = Data.Attributes;
1984 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1985 DVar.DKind = I->Directive;
1986 DVar.Modifier = Data.Modifier;
1987 DVar.AppliedToPointee = Data.AppliedToPointee;
1988 }
1989
1990 return DVar;
1991}
1992
1993const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1994 bool FromParent) const {
1995 if (isStackEmpty()) {
1996 const_iterator I;
1997 return getDSA(I, D);
1998 }
1999 D = getCanonicalDecl(D);
2000 const_iterator StartI = begin();
2001 const_iterator EndI = end();
2002 if (FromParent && StartI != EndI)
2003 ++StartI;
2004 return getDSA(StartI, D);
2005}
2006
2007const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
2008 unsigned Level) const {
2009 if (getStackSize() <= Level)
2010 return DSAVarData();
2011 D = getCanonicalDecl(D);
2012 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
2013 return getDSA(StartI, D);
2014}
2015
2016const DSAStackTy::DSAVarData
2017DSAStackTy::hasDSA(ValueDecl *D,
2018 const llvm::function_ref<bool(OpenMPClauseKind, bool,
2019 DefaultDataSharingAttributes)>
2020 CPred,
2021 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
2022 bool FromParent) const {
2023 if (isStackEmpty())
2024 return {};
2025 D = getCanonicalDecl(D);
2026 const_iterator I = begin();
2027 const_iterator EndI = end();
2028 if (FromParent && I != EndI)
2029 ++I;
2030 for (; I != EndI; ++I) {
2031 if (!DPred(I->Directive) &&
2032 !isImplicitOrExplicitTaskingRegion(I->Directive))
2033 continue;
2034 const_iterator NewI = I;
2035 DSAVarData DVar = getDSA(NewI, D);
2036 if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee, I->DefaultAttr))
2037 return DVar;
2038 }
2039 return {};
2040}
2041
2042const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
2043 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
2044 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
2045 bool FromParent) const {
2046 if (isStackEmpty())
2047 return {};
2048 D = getCanonicalDecl(D);
2049 const_iterator StartI = begin();
2050 const_iterator EndI = end();
2051 if (FromParent && StartI != EndI)
2052 ++StartI;
2053 if (StartI == EndI || !DPred(StartI->Directive))
2054 return {};
2055 const_iterator NewI = StartI;
2056 DSAVarData DVar = getDSA(NewI, D);
2057 return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
2058 ? DVar
2059 : DSAVarData();
2060}
2061
2062bool DSAStackTy::hasExplicitDSA(
2063 const ValueDecl *D,
2064 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
2065 unsigned Level, bool NotLastprivate) const {
2066 if (getStackSize() <= Level)
2067 return false;
2068 D = getCanonicalDecl(D);
2069 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
2070 auto I = StackElem.SharingMap.find(D);
2071 if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
2072 CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
2073 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
2074 return true;
2075 // Check predetermined rules for the loop control variables.
2076 auto LI = StackElem.LCVMap.find(D);
2077 if (LI != StackElem.LCVMap.end())
2078 return CPred(OMPC_private, /*AppliedToPointee=*/false);
2079 return false;
2080}
2081
2082bool DSAStackTy::hasExplicitDirective(
2083 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
2084 unsigned Level) const {
2085 if (getStackSize() <= Level)
2086 return false;
2087 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
2088 return DPred(StackElem.Directive);
2089}
2090
2091bool DSAStackTy::hasDirective(
2092 const llvm::function_ref<bool(OpenMPDirectiveKind,
2093 const DeclarationNameInfo &, SourceLocation)>
2094 DPred,
2095 bool FromParent) const {
2096 // We look only in the enclosing region.
2097 size_t Skip = FromParent ? 2 : 1;
2098 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
2099 I != E; ++I) {
2100 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
2101 return true;
2102 }
2103 return false;
2104}
2105
2106void SemaOpenMP::InitDataSharingAttributesStack() {
2107 VarDataSharingAttributesStack = new DSAStackTy(SemaRef);
2108}
2109
2110#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
2111
2113 DSAStack->addRequiresDecl(D);
2114}
2115
2117 return DSAStack->getRequiresDecls();
2118}
2119
2120void SemaOpenMP::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); }
2121
2122void SemaOpenMP::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
2123 DSAStack->popFunction(OldFSI);
2124}
2125
2127 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsTargetDevice &&
2128 "Expected OpenMP device compilation.");
2130}
2131
2132namespace {
2133/// Status of the function emission on the host/device.
2134enum class FunctionEmissionStatus {
2135 Emitted,
2136 Discarded,
2137 Unknown,
2138};
2139} // anonymous namespace
2140
2141SemaBase::SemaDiagnosticBuilder
2143 const FunctionDecl *FD) {
2144 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
2145 "Expected OpenMP device compilation.");
2146
2147 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
2148 if (FD) {
2149 Sema::FunctionEmissionStatus FES = SemaRef.getEmissionStatus(FD);
2150 switch (FES) {
2152 Kind = SemaDiagnosticBuilder::K_Immediate;
2153 break;
2155 // TODO: We should always delay diagnostics here in case a target
2156 // region is in a function we do not emit. However, as the
2157 // current diagnostics are associated with the function containing
2158 // the target region and we do not emit that one, we would miss out
2159 // on diagnostics for the target region itself. We need to anchor
2160 // the diagnostics with the new generated function *or* ensure we
2161 // emit diagnostics associated with the surrounding function.
2163 ? SemaDiagnosticBuilder::K_Deferred
2164 : SemaDiagnosticBuilder::K_Immediate;
2165 break;
2168 Kind = SemaDiagnosticBuilder::K_Nop;
2169 break;
2171 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
2172 break;
2173 }
2174 }
2175
2176 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, SemaRef);
2177}
2178
2181 const FunctionDecl *FD) {
2182 assert(getLangOpts().OpenMP && !getLangOpts().OpenMPIsTargetDevice &&
2183 "Expected OpenMP host compilation.");
2184
2185 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
2186 if (FD) {
2187 Sema::FunctionEmissionStatus FES = SemaRef.getEmissionStatus(FD);
2188 switch (FES) {
2190 Kind = SemaDiagnosticBuilder::K_Immediate;
2191 break;
2193 Kind = SemaDiagnosticBuilder::K_Deferred;
2194 break;
2198 Kind = SemaDiagnosticBuilder::K_Nop;
2199 break;
2200 }
2201 }
2202
2203 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, SemaRef);
2204}
2205
2208 if (LO.OpenMP <= 45) {
2210 return OMPC_DEFAULTMAP_scalar;
2211 return OMPC_DEFAULTMAP_aggregate;
2212 }
2214 return OMPC_DEFAULTMAP_pointer;
2216 return OMPC_DEFAULTMAP_scalar;
2217 return OMPC_DEFAULTMAP_aggregate;
2218}
2219
2220bool SemaOpenMP::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
2221 unsigned OpenMPCaptureLevel) const {
2222 assert(getLangOpts().OpenMP && "OpenMP is not allowed");
2223
2224 ASTContext &Ctx = getASTContext();
2225 bool IsByRef = true;
2226
2227 // Find the directive that is associated with the provided scope.
2229 QualType Ty = D->getType();
2230 if (const auto *BD = dyn_cast<BindingDecl>(D))
2231 Ty = BD->getDecomposedDecl()->getType();
2232
2233 bool IsVariableUsedInMapClause = false;
2234 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
2235 // This table summarizes how a given variable should be passed to the device
2236 // given its type and the clauses where it appears. This table is based on
2237 // the description in OpenMP 4.5 [2.10.4, target Construct] and
2238 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
2239 //
2240 // =========================================================================
2241 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
2242 // | |(tofrom:scalar)| | pvt | |has_dv_adr| |
2243 // =========================================================================
2244 // | scl | | | | - | | bycopy|
2245 // | scl | | - | x | - | - | bycopy|
2246 // | scl | | x | - | - | - | null |
2247 // | scl | x | | | - | | byref |
2248 // | scl | x | - | x | - | - | bycopy|
2249 // | scl | x | x | - | - | - | null |
2250 // | scl | | - | - | - | x | byref |
2251 // | scl | x | - | - | - | x | byref |
2252 //
2253 // | agg | n.a. | | | - | | byref |
2254 // | agg | n.a. | - | x | - | - | byref |
2255 // | agg | n.a. | x | - | - | - | null |
2256 // | agg | n.a. | - | - | - | x | byref |
2257 // | agg | n.a. | - | - | - | x[] | byref |
2258 //
2259 // | ptr | n.a. | | | - | | bycopy|
2260 // | ptr | n.a. | - | x | - | - | bycopy|
2261 // | ptr | n.a. | x | - | - | - | null |
2262 // | ptr | n.a. | - | - | - | x | byref |
2263 // | ptr | n.a. | - | - | - | x, x[] | bycopy|
2264 // | ptr | n.a. | - | - | - | x[] | bycopy|
2265 // | ptr | n.a. | - | - | x | | bycopy|
2266 // | ptr | n.a. | - | - | x | x | bycopy|
2267 // | ptr | n.a. | - | - | x | x[] | bycopy|
2268 // =========================================================================
2269 // Legend:
2270 // scl - scalar
2271 // ptr - pointer
2272 // agg - aggregate
2273 // x - applies
2274 // - - invalid in this combination
2275 // [] - mapped with an array section
2276 // byref - should be mapped by reference
2277 // byval - should be mapped by value
2278 // null - initialize a local variable to null on the device
2279 //
2280 // Observations:
2281 // - All scalar declarations that show up in a map clause have to be passed
2282 // by reference, because they may have been mapped in the enclosing data
2283 // environment.
2284 // - If the scalar value does not fit the size of uintptr, it has to be
2285 // passed by reference, regardless the result in the table above.
2286 // - For pointers mapped by value that have either an implicit map or an
2287 // array section, the runtime library may pass the NULL value to the
2288 // device instead of the value passed to it by the compiler.
2289 // - If both a pointer and a dereference of it are mapped, then the pointer
2290 // should be passed by reference.
2291
2292 if (Ty->isReferenceType())
2293 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
2294
2295 // Locate map clauses and see if the variable being captured is mapped by
2296 // itself, or referred to, in any of those clauses. Here we only care about
2297 // variables, not fields, because fields are part of aggregates.
2298 bool IsVariableAssociatedWithSection = false;
2299 bool IsVariableItselfMapped = false;
2300
2301 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2302 D, Level,
2303 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection,
2304 &IsVariableItselfMapped,
2306 MapExprComponents,
2307 OpenMPClauseKind WhereFoundClauseKind) {
2308 // Both map and has_device_addr clauses information influences how a
2309 // variable is captured. E.g. is_device_ptr does not require changing
2310 // the default behavior.
2311 if (WhereFoundClauseKind != OMPC_map &&
2312 WhereFoundClauseKind != OMPC_has_device_addr)
2313 return false;
2314
2315 auto EI = MapExprComponents.rbegin();
2316 auto EE = MapExprComponents.rend();
2317
2318 assert(EI != EE && "Invalid map expression!");
2319
2320 if (isa<DeclRefExpr>(EI->getAssociatedExpression()) &&
2321 EI->getAssociatedDeclaration() == D) {
2322 IsVariableUsedInMapClause = true;
2323
2324 // If the component list has only one element, it's for mapping the
2325 // variable itself, like map(p). This takes precedence in
2326 // determining how it's captured, so we don't need to look further
2327 // for any other maps that use the variable (like map(p[0]) etc.)
2328 if (MapExprComponents.size() == 1) {
2329 IsVariableItselfMapped = true;
2330 return true;
2331 }
2332 }
2333
2334 ++EI;
2335 if (EI == EE)
2336 return false;
2337 auto Last = std::prev(EE);
2338 const auto *UO =
2339 dyn_cast<UnaryOperator>(Last->getAssociatedExpression());
2340 if ((UO && UO->getOpcode() == UO_Deref) ||
2341 isa<ArraySubscriptExpr>(Last->getAssociatedExpression()) ||
2342 isa<ArraySectionExpr>(Last->getAssociatedExpression()) ||
2343 isa<MemberExpr>(EI->getAssociatedExpression()) ||
2344 isa<OMPArrayShapingExpr>(Last->getAssociatedExpression())) {
2345 IsVariableAssociatedWithSection = true;
2346 // We've found a case like map(p[0]) or map(p->a) or map(*p),
2347 // so we are done with this particular map, but we need to keep
2348 // looking in case we find a map(p).
2349 return false;
2350 }
2351
2352 // Keep looking for more map info.
2353 return false;
2354 });
2355
2356 if (IsVariableUsedInMapClause) {
2357 // If variable is identified in a map clause it is always captured by
2358 // reference except if it is a pointer that is dereferenced somehow, but
2359 // not itself mapped.
2360 //
2361 // OpenMP 6.0, 7.1.1: Data sharing attribute rules, variables referenced
2362 // in a construct::
2363 // If a list item in a has_device_addr clause or in a map clause on the
2364 // target construct has a base pointer, and the base pointer is a scalar
2365 // variable *that is not a list item in a map clause on the construct*,
2366 // the base pointer is firstprivate.
2367 //
2368 // OpenMP 4.5, 2.15.1.1: Data-sharing Attribute Rules for Variables
2369 // Referenced in a Construct:
2370 // If an array section is a list item in a map clause on the target
2371 // construct and the array section is derived from a variable for which
2372 // the type is pointer then that variable is firstprivate.
2373 IsByRef = IsVariableItselfMapped ||
2374 !(Ty->isPointerType() && IsVariableAssociatedWithSection);
2375 } else {
2376 // By default, all the data that has a scalar type is mapped by copy
2377 // (except for reduction variables).
2378 // Defaultmap scalar is mutual exclusive to defaultmap pointer
2379 IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
2380 !Ty->isAnyPointerType()) ||
2381 !Ty->isScalarType() ||
2382 DSAStack->isDefaultmapCapturedByRef(
2384 DSAStack->hasExplicitDSA(
2385 D,
2386 [](OpenMPClauseKind K, bool AppliedToPointee) {
2387 return K == OMPC_reduction && !AppliedToPointee;
2388 },
2389 Level);
2390 }
2391 }
2392
2393 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
2394 IsByRef =
2395 ((IsVariableUsedInMapClause &&
2396 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
2397 OMPD_target) ||
2398 !(DSAStack->hasExplicitDSA(
2399 D,
2400 [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
2401 return K == OMPC_firstprivate ||
2402 (K == OMPC_reduction && AppliedToPointee);
2403 },
2404 Level, /*NotLastprivate=*/true) ||
2405 DSAStack->isUsesAllocatorsDecl(Level, D))) &&
2406 // If the variable is artificial and must be captured by value - try to
2407 // capture by value.
2408 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
2409 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
2410 // If the variable is implicitly firstprivate and scalar - capture by
2411 // copy. Query the default data-sharing attribute at the capture level
2412 // being considered rather than at the innermost directive: a nested
2413 // default(firstprivate) or default(private) must not make an enclosing
2414 // region capture by copy and lose its writes.
2415 !((DSAStack->getDefaultDSA(Level) == DSA_firstprivate ||
2416 DSAStack->getDefaultDSA(Level) == DSA_private) &&
2417 !DSAStack->hasExplicitDSA(
2418 D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
2419 Level) &&
2420 !DSAStack->isLoopControlVariable(D, Level).first);
2421 }
2422
2423 // When passing data by copy, we need to make sure it fits the uintptr size
2424 // and alignment, because the runtime library only deals with uintptr types.
2425 // If it does not fit the uintptr size, we need to pass the data by reference
2426 // instead.
2427 if (!IsByRef && (Ctx.getTypeSizeInChars(Ty) >
2429 Ctx.getAlignOfGlobalVarInChars(Ty, dyn_cast<VarDecl>(D)) >
2430 Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
2431 IsByRef = true;
2432 }
2433
2434 return IsByRef;
2435}
2436
2437unsigned SemaOpenMP::getOpenMPNestingLevel() const {
2438 assert(getLangOpts().OpenMP);
2439 return DSAStack->getNestingLevel();
2440}
2441
2443 return isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2444 DSAStack->isUntiedRegion();
2445}
2446
2448 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
2449 !DSAStack->isClauseParsingMode()) ||
2450 DSAStack->hasDirective(
2452 SourceLocation) -> bool {
2454 },
2455 false);
2456}
2457
2459 // Only rebuild for Field.
2460 if (!isa<FieldDecl>(D))
2461 return false;
2462 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2463 D,
2464 [](OpenMPClauseKind C, bool AppliedToPointee,
2465 DefaultDataSharingAttributes DefaultAttr) {
2466 return isOpenMPPrivate(C) && !AppliedToPointee &&
2467 (DefaultAttr == DSA_firstprivate || DefaultAttr == DSA_private);
2468 },
2469 [](OpenMPDirectiveKind) { return true; },
2470 DSAStack->isClauseParsingMode());
2471 if (DVarPrivate.CKind != OMPC_unknown)
2472 return true;
2473 return false;
2474}
2475
2477 Expr *CaptureExpr, bool WithInit,
2478 DeclContext *CurContext,
2479 bool AsExpression);
2480
2482 unsigned StopAt) {
2483 assert(getLangOpts().OpenMP && "OpenMP is not allowed");
2484 D = getCanonicalDecl(D);
2485
2486 // A tuple-like binding has no private copy. A privatized one reports its
2487 // holding variable instead, so its uses still go through the capture checks.
2488 VarDecl *HoldingVar = nullptr;
2489 if (auto *BD = dyn_cast<BindingDecl>(D)) {
2490 HoldingVar = BD->getHoldingVar();
2491 if (!HoldingVar)
2492 D = cast<VarDecl>(BD->getDecomposedDecl());
2493 }
2494 auto *VD = dyn_cast<VarDecl>(D);
2495 // Do not capture constexpr variables.
2496 if (VD && VD->isConstexpr())
2497 return nullptr;
2498
2499 // If we want to determine whether the variable should be captured from the
2500 // perspective of the current capturing scope, and we've already left all the
2501 // capturing scopes of the top directive on the stack, check from the
2502 // perspective of its parent directive (if any) instead.
2503 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2504 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2505
2506 // If we are attempting to capture a global variable in a directive with
2507 // 'target' we return true so that this global is also mapped to the device.
2508 //
2509 if (VD && !VD->hasLocalStorage() &&
2510 (SemaRef.getCurCapturedRegion() || SemaRef.getCurBlock() ||
2511 SemaRef.getCurLambda())) {
2513 DSAStackTy::DSAVarData DVarTop =
2514 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2515 if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr)
2516 return VD;
2517 // If the declaration is enclosed in a 'declare target' directive,
2518 // then it should not be captured.
2519 //
2520 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2521 return nullptr;
2522 CapturedRegionScopeInfo *CSI = nullptr;
2523 for (FunctionScopeInfo *FSI : llvm::drop_begin(
2524 llvm::reverse(SemaRef.FunctionScopes),
2525 CheckScopeInfo ? (SemaRef.FunctionScopes.size() - (StopAt + 1))
2526 : 0)) {
2527 if (!isa<CapturingScopeInfo>(FSI))
2528 return nullptr;
2529 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2530 if (RSI->CapRegionKind == CR_OpenMP) {
2531 CSI = RSI;
2532 break;
2533 }
2534 }
2535 // Lambdas and blocks at namespace scope have no enclosing function scope.
2536 if (!CSI)
2537 return nullptr;
2540 DSAStack->getDirective(CSI->OpenMPLevel));
2541 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2542 return VD;
2543 }
2545 // Try to mark variable as declare target if it is used in capturing
2546 // regions.
2547 if (getLangOpts().OpenMP <= 45 &&
2548 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
2550 return nullptr;
2551 }
2552 }
2553
2554 if (CheckScopeInfo) {
2555 bool OpenMPFound = false;
2556 for (unsigned I = StopAt + 1; I > 0; --I) {
2557 FunctionScopeInfo *FSI = SemaRef.FunctionScopes[I - 1];
2558 if (!isa<CapturingScopeInfo>(FSI))
2559 return nullptr;
2560 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2561 if (RSI->CapRegionKind == CR_OpenMP) {
2562 OpenMPFound = true;
2563 break;
2564 }
2565 }
2566 if (!OpenMPFound)
2567 return nullptr;
2568 }
2569
2570 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2571 (!DSAStack->isClauseParsingMode() ||
2572 DSAStack->getParentDirective() != OMPD_unknown)) {
2573 auto &&Info = DSAStack->isLoopControlVariable(D);
2574 if (Info.first ||
2575 (VD && VD->hasLocalStorage() &&
2576 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
2577 (VD && DSAStack->isForceVarCapturing()))
2578 return VD ? VD : Info.second;
2579 DSAStackTy::DSAVarData DVarTop =
2580 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
2581 if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
2582 (!VD || VD->hasLocalStorage() ||
2583 !(DVarTop.AppliedToPointee && DVarTop.CKind != OMPC_reduction)))
2584 return VD ? VD
2585 : HoldingVar ? HoldingVar
2586 : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
2587 // Threadprivate variables must not be captured.
2588 if (isOpenMPThreadPrivate(DVarTop.CKind))
2589 return nullptr;
2590 // The variable is not private or it is the variable in the directive with
2591 // default(none) clause and not used in any clause.
2592 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2593 D,
2594 [](OpenMPClauseKind C, bool AppliedToPointee, bool) {
2595 return isOpenMPPrivate(C) && !AppliedToPointee;
2596 },
2597 [](OpenMPDirectiveKind) { return true; },
2598 DSAStack->isClauseParsingMode());
2599 // Global shared must not be captured.
2600 if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
2601 ((DSAStack->getDefaultDSA() != DSA_none &&
2602 DSAStack->getDefaultDSA() != DSA_private &&
2603 DSAStack->getDefaultDSA() != DSA_firstprivate) ||
2604 DVarTop.CKind == OMPC_shared))
2605 return nullptr;
2606 auto *FD = dyn_cast<FieldDecl>(D);
2607 if (DVarPrivate.CKind != OMPC_unknown && !VD && FD &&
2608 !DVarPrivate.PrivateCopy) {
2609 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2610 D,
2611 [](OpenMPClauseKind C, bool AppliedToPointee,
2612 DefaultDataSharingAttributes DefaultAttr) {
2613 return isOpenMPPrivate(C) && !AppliedToPointee &&
2614 (DefaultAttr == DSA_firstprivate ||
2615 DefaultAttr == DSA_private);
2616 },
2617 [](OpenMPDirectiveKind) { return true; },
2618 DSAStack->isClauseParsingMode());
2619 if (DVarPrivate.CKind == OMPC_unknown)
2620 return nullptr;
2621
2622 VarDecl *VD = DSAStack->getImplicitFDCapExprDecl(FD);
2623 if (VD)
2624 return VD;
2625 if (SemaRef.getCurrentThisType().isNull())
2626 return nullptr;
2627 Expr *ThisExpr = SemaRef.BuildCXXThisExpr(SourceLocation(),
2628 SemaRef.getCurrentThisType(),
2629 /*IsImplicit=*/true);
2630 Expr *ME = SemaRef.BuildMemberExpr(
2631 ThisExpr, /*IsArrow=*/true, SourceLocation(),
2634 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), FD->getType(),
2637 SemaRef, FD->getIdentifier(), ME, DVarPrivate.CKind != OMPC_private,
2638 SemaRef.CurContext->getParent(), /*AsExpression=*/false);
2639 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
2641 VD = cast<VarDecl>(VDPrivateRefExpr->getDecl());
2642 DSAStack->addImplicitDefaultFirstprivateFD(FD, VD);
2643 return VD;
2644 }
2645 if (DVarPrivate.CKind != OMPC_unknown ||
2646 (VD && (DSAStack->getDefaultDSA() == DSA_none ||
2647 DSAStack->getDefaultDSA() == DSA_private ||
2648 DSAStack->getDefaultDSA() == DSA_firstprivate)))
2649 return VD ? VD
2650 : HoldingVar ? HoldingVar
2651 : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
2652 }
2653 return nullptr;
2654}
2655
2656void SemaOpenMP::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2657 unsigned Level) const {
2658 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2659}
2660
2662 assert(getLangOpts().OpenMP && "OpenMP must be enabled.");
2663 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2664 DSAStack->loopInit();
2665}
2666
2668 assert(getLangOpts().OpenMP && "OpenMP must be enabled.");
2669 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2670 DSAStack->resetPossibleLoopCounter();
2671 DSAStack->loopStart();
2672 }
2673}
2674
2676 unsigned CapLevel) const {
2677 assert(getLangOpts().OpenMP && "OpenMP is not allowed");
2678 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2679 (!DSAStack->isClauseParsingMode() ||
2680 DSAStack->getParentDirective() != OMPD_unknown)) {
2681 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
2682 D,
2683 [](OpenMPClauseKind C, bool AppliedToPointee,
2684 DefaultDataSharingAttributes DefaultAttr) {
2685 return isOpenMPPrivate(C) && !AppliedToPointee &&
2686 DefaultAttr == DSA_private;
2687 },
2688 [](OpenMPDirectiveKind) { return true; },
2689 DSAStack->isClauseParsingMode());
2690 if (DVarPrivate.CKind == OMPC_private && isa<OMPCapturedExprDecl>(D) &&
2691 DSAStack->isImplicitDefaultFirstprivateFD(cast<VarDecl>(D)) &&
2692 !DSAStack->isLoopControlVariable(D).first)
2693 return OMPC_private;
2694 }
2695 if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) {
2696 bool IsTriviallyCopyable =
2698 getASTContext()) &&
2699 !D->getType()
2703 OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
2705 getOpenMPCaptureRegions(CaptureRegions, DKind);
2706 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
2707 (IsTriviallyCopyable ||
2708 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
2709 if (DSAStack->hasExplicitDSA(
2710 D,
2711 [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
2712 Level, /*NotLastprivate=*/true))
2713 return OMPC_firstprivate;
2714 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2715 if (DVar.CKind != OMPC_shared &&
2716 !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
2717 DSAStack->addImplicitTaskFirstprivate(Level, D);
2718 return OMPC_firstprivate;
2719 }
2720 }
2721 }
2722 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()) &&
2723 !isOpenMPLoopTransformationDirective(DSAStack->getCurrentDirective())) {
2724 if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) {
2725 DSAStack->resetPossibleLoopCounter(D);
2726 DSAStack->loopStart();
2727 return OMPC_private;
2728 }
2729 if ((DSAStack->getPossiblyLoopCounter() == D->getCanonicalDecl() ||
2730 DSAStack->isLoopControlVariable(D).first) &&
2731 !DSAStack->hasExplicitDSA(
2732 D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
2733 Level) &&
2734 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2735 return OMPC_private;
2736 }
2737 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2738 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2739 DSAStack->isForceVarCapturing() &&
2740 !DSAStack->hasExplicitDSA(
2741 D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
2742 Level))
2743 return OMPC_private;
2744 }
2745 // User-defined allocators are private since they must be defined in the
2746 // context of target region.
2747 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
2748 DSAStack->isUsesAllocatorsDecl(Level, D).value_or(
2749 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
2750 DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
2751 return OMPC_private;
2752 return (DSAStack->hasExplicitDSA(
2753 D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
2754 Level) ||
2755 (DSAStack->isClauseParsingMode() &&
2756 DSAStack->getClauseParsingMode() == OMPC_private) ||
2757 // Consider taskgroup reduction descriptor variable a private
2758 // to avoid possible capture in the region.
2759 (DSAStack->hasExplicitDirective(
2760 [](OpenMPDirectiveKind K) {
2761 return K == OMPD_taskgroup ||
2762 ((isOpenMPParallelDirective(K) ||
2763 isOpenMPWorksharingDirective(K)) &&
2764 !isOpenMPSimdDirective(K));
2765 },
2766 Level) &&
2767 DSAStack->isTaskgroupReductionRef(D, Level)))
2768 ? OMPC_private
2769 : OMPC_unknown;
2770}
2771
2773 unsigned Level) {
2774 assert(getLangOpts().OpenMP && "OpenMP is not allowed");
2775 D = getCanonicalDecl(D);
2776 OpenMPClauseKind OMPC = OMPC_unknown;
2777 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2778 const unsigned NewLevel = I - 1;
2779 if (DSAStack->hasExplicitDSA(
2780 D,
2781 [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
2782 if (isOpenMPPrivate(K) && !AppliedToPointee) {
2783 OMPC = K;
2784 return true;
2785 }
2786 return false;
2787 },
2788 NewLevel))
2789 break;
2790 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2791 D, NewLevel,
2793 OpenMPClauseKind) { return true; })) {
2794 OMPC = OMPC_map;
2795 break;
2796 }
2797 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2798 NewLevel)) {
2799 OMPC = OMPC_map;
2800 if (DSAStack->mustBeFirstprivateAtLevel(
2802 OMPC = OMPC_firstprivate;
2803 break;
2804 }
2805 }
2806 if (OMPC != OMPC_unknown)
2807 FD->addAttr(
2808 OMPCaptureKindAttr::CreateImplicit(getASTContext(), unsigned(OMPC)));
2809}
2810
2812 unsigned CaptureLevel) const {
2813 assert(getLangOpts().OpenMP && "OpenMP is not allowed");
2814 // Return true if the current level is no longer enclosed in a target region.
2815
2817 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2818 const auto *VD = dyn_cast<VarDecl>(D);
2819 return VD && !VD->hasLocalStorage() &&
2820 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2821 Level) &&
2822 Regions[CaptureLevel] != OMPD_task;
2823}
2824
2826 unsigned CaptureLevel) const {
2827 assert(getLangOpts().OpenMP && "OpenMP is not allowed");
2828 // Return true if the current level is no longer enclosed in a target region.
2829
2830 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2831 if (!VD->hasLocalStorage()) {
2833 return true;
2834 DSAStackTy::DSAVarData TopDVar =
2835 DSAStack->getTopDSA(D, /*FromParent=*/false);
2836 unsigned NumLevels =
2837 getOpenMPCaptureLevels(DSAStack->getDirective(Level));
2838 if (Level == 0)
2839 // non-file scope static variable with default(firstprivate)
2840 // should be global captured.
2841 return (NumLevels == CaptureLevel + 1 &&
2842 (TopDVar.CKind != OMPC_shared ||
2843 DSAStack->getDefaultDSA() == DSA_firstprivate));
2844 do {
2845 --Level;
2846 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
2847 if (DVar.CKind != OMPC_shared)
2848 return true;
2849 } while (Level > 0);
2850 }
2851 }
2852 return true;
2853}
2854
2855void SemaOpenMP::DestroyDataSharingAttributesStack() { delete DSAStack; }
2856
2858 OMPTraitInfo &TI) {
2859 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
2860}
2861
2864 "Not in OpenMP declare variant scope!");
2865
2866 OMPDeclareVariantScopes.pop_back();
2867}
2868
2870 const FunctionDecl *Callee,
2871 SourceLocation Loc) {
2872 assert(getLangOpts().OpenMP && "Expected OpenMP compilation mode.");
2873 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2874 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
2875 // Ignore host functions during device analysis.
2876 if (getLangOpts().OpenMPIsTargetDevice &&
2877 (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host))
2878 return;
2879 // Ignore nohost functions during host analysis.
2880 if (!getLangOpts().OpenMPIsTargetDevice && DevTy &&
2881 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2882 return;
2883 const FunctionDecl *FD = Callee->getMostRecentDecl();
2884 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
2885 if (getLangOpts().OpenMPIsTargetDevice && DevTy &&
2886 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2887 // Diagnose host function called during device codegen.
2888 StringRef HostDevTy =
2889 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
2890 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
2891 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2892 diag::note_omp_marked_device_type_here)
2893 << HostDevTy;
2894 return;
2895 }
2896 if (!getLangOpts().OpenMPIsTargetDevice &&
2897 !getLangOpts().OpenMPOffloadMandatory && DevTy &&
2898 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2899 // In OpenMP 5.2 or later, if the function has a host variant then allow
2900 // that to be called instead
2901 auto &&HasHostAttr = [](const FunctionDecl *Callee) {
2902 for (OMPDeclareVariantAttr *A :
2903 Callee->specific_attrs<OMPDeclareVariantAttr>()) {
2904 auto *DeclRefVariant = cast<DeclRefExpr>(A->getVariantFuncRef());
2905 auto *VariantFD = cast<FunctionDecl>(DeclRefVariant->getDecl());
2906 std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2907 OMPDeclareTargetDeclAttr::getDeviceType(
2908 VariantFD->getMostRecentDecl());
2909 if (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2910 return true;
2911 }
2912 return false;
2913 };
2914 if (getLangOpts().OpenMP >= 52 &&
2915 Callee->hasAttr<OMPDeclareVariantAttr>() && HasHostAttr(Callee))
2916 return;
2917 // Diagnose nohost function called during host codegen.
2918 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2919 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2920 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
2921 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
2922 diag::note_omp_marked_device_type_here)
2923 << NoHostDevTy;
2924 }
2925}
2926
2928 const DeclarationNameInfo &DirName,
2929 Scope *CurScope, SourceLocation Loc) {
2930 DSAStack->push(DKind, DirName, CurScope, Loc);
2931 SemaRef.PushExpressionEvaluationContext(
2933}
2934
2936 DSAStack->setClauseParsingMode(K);
2937}
2938
2940 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
2941 SemaRef.CleanupVarDeclMarking();
2942}
2943
2944static std::pair<ValueDecl *, bool>
2945getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2946 SourceRange &ERange, bool AllowArraySection = false,
2947 bool AllowAssumedSizeArray = false, StringRef DiagType = "");
2948
2949/// Check consistency of the reduction clauses.
2950static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
2951 ArrayRef<OMPClause *> Clauses) {
2952 bool InscanFound = false;
2953 SourceLocation InscanLoc;
2954 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
2955 // A reduction clause without the inscan reduction-modifier may not appear on
2956 // a construct on which a reduction clause with the inscan reduction-modifier
2957 // appears.
2958 for (OMPClause *C : Clauses) {
2959 if (C->getClauseKind() != OMPC_reduction)
2960 continue;
2961 auto *RC = cast<OMPReductionClause>(C);
2962 if (RC->getModifier() == OMPC_REDUCTION_inscan) {
2963 InscanFound = true;
2964 InscanLoc = RC->getModifierLoc();
2965 continue;
2966 }
2967 if (RC->getModifier() == OMPC_REDUCTION_task) {
2968 // OpenMP 5.0, 2.19.5.4 reduction Clause.
2969 // A reduction clause with the task reduction-modifier may only appear on
2970 // a parallel construct, a worksharing construct or a combined or
2971 // composite construct for which any of the aforementioned constructs is a
2972 // constituent construct and simd or loop are not constituent constructs.
2973 OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
2974 if (!(isOpenMPParallelDirective(CurDir) ||
2976 isOpenMPSimdDirective(CurDir))
2977 S.Diag(RC->getModifierLoc(),
2978 diag::err_omp_reduction_task_not_parallel_or_worksharing);
2979 continue;
2980 }
2981 }
2982 if (InscanFound) {
2983 for (OMPClause *C : Clauses) {
2984 if (C->getClauseKind() != OMPC_reduction)
2985 continue;
2986 auto *RC = cast<OMPReductionClause>(C);
2987 if (RC->getModifier() != OMPC_REDUCTION_inscan) {
2988 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
2989 ? RC->getBeginLoc()
2990 : RC->getModifierLoc(),
2991 diag::err_omp_inscan_reduction_expected);
2992 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
2993 continue;
2994 }
2995 for (Expr *Ref : RC->varlist()) {
2996 assert(Ref && "NULL expr in OpenMP reduction clause.");
2997 SourceLocation ELoc;
2998 SourceRange ERange;
2999 Expr *SimpleRefExpr = Ref;
3000 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
3001 /*AllowArraySection=*/true);
3002 ValueDecl *D = Res.first;
3003 if (!D)
3004 continue;
3005 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
3006 S.Diag(Ref->getExprLoc(),
3007 diag::err_omp_reduction_not_inclusive_exclusive)
3008 << Ref->getSourceRange();
3009 }
3010 }
3011 }
3012 }
3013}
3014
3015static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
3016 ArrayRef<OMPClause *> Clauses);
3017static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3018 bool WithInit);
3019
3020static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3021 const ValueDecl *D,
3022 const DSAStackTy::DSAVarData &DVar,
3023 bool IsLoopIterVar = false);
3024
3026 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
3027 // A variable of class type (or array thereof) that appears in a lastprivate
3028 // clause requires an accessible, unambiguous default constructor for the
3029 // class type, unless the list item is also specified in a firstprivate
3030 // clause.
3031
3032 auto FinalizeLastprivate = [&](OMPLastprivateClause *Clause) {
3033 SmallVector<Expr *, 8> PrivateCopies;
3034 for (Expr *DE : Clause->varlist()) {
3035 if (DE->isValueDependent() || DE->isTypeDependent()) {
3036 PrivateCopies.push_back(nullptr);
3037 continue;
3038 }
3039 // Data members are captured, and get private copies, on instantiation.
3040 if (isa<MemberExpr>(DE->IgnoreParens())) {
3041 assert(SemaRef.CurContext->isDependentContext() &&
3042 "uncaptured data member in a non-dependent context");
3043 PrivateCopies.push_back(nullptr);
3044 continue;
3045 }
3046 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
3047 auto *D = DRE->getDecl();
3048 if (auto *BD = dyn_cast<BindingDecl>(D)) {
3049 QualType Type = BD->getType().getNonReferenceType();
3050 const DSAStackTy::DSAVarData DVar =
3051 DSAStack->getTopDSA(BD, /*FromParent=*/false);
3052 if (DVar.CKind != OMPC_lastprivate) {
3053 // The variable is also a firstprivate, so initialization sequence
3054 // for private copy is generated already.
3055 PrivateCopies.push_back(nullptr);
3056 continue;
3057 }
3058 VarDecl *VDPrivate = buildVarDecl(
3059 SemaRef, DE->getExprLoc(), Type.getUnqualifiedType(), BD->getName(),
3060 BD->hasAttrs() ? &BD->getAttrs() : nullptr, DRE);
3061 SemaRef.ActOnUninitializedDecl(VDPrivate);
3062 if (VDPrivate->isInvalidDecl()) {
3063 PrivateCopies.push_back(nullptr);
3064 continue;
3065 }
3066 PrivateCopies.push_back(buildDeclRefExpr(
3067 SemaRef, VDPrivate, DE->getType(), DE->getExprLoc()));
3068 continue;
3069 }
3070 auto *VD = cast<VarDecl>(D);
3072 const DSAStackTy::DSAVarData DVar =
3073 DSAStack->getTopDSA(VD, /*FromParent=*/false);
3074 if (DVar.CKind != OMPC_lastprivate) {
3075 // The variable is also a firstprivate, so initialization sequence
3076 // for private copy is generated already.
3077 PrivateCopies.push_back(nullptr);
3078 continue;
3079 }
3080 // Generate helper private variable and initialize it with the
3081 // default value. The address of the original variable is replaced
3082 // by the address of the new private variable in CodeGen. This new
3083 // variable is not added to IdResolver, so the code in the OpenMP
3084 // region uses original variable for proper diagnostics.
3085 VarDecl *VDPrivate = buildVarDecl(
3086 SemaRef, DE->getExprLoc(), Type.getUnqualifiedType(), VD->getName(),
3087 VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
3088 SemaRef.ActOnUninitializedDecl(VDPrivate);
3089 if (VDPrivate->isInvalidDecl()) {
3090 PrivateCopies.push_back(nullptr);
3091 continue;
3092 }
3093 PrivateCopies.push_back(buildDeclRefExpr(
3094 SemaRef, VDPrivate, DE->getType(), DE->getExprLoc()));
3095 }
3096 Clause->setPrivateCopies(PrivateCopies);
3097 };
3098
3099 auto FinalizeNontemporal = [&](OMPNontemporalClause *Clause) {
3100 // Finalize nontemporal clause by handling private copies, if any.
3101 SmallVector<Expr *, 8> PrivateRefs;
3102 for (Expr *RefExpr : Clause->varlist()) {
3103 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
3104 SourceLocation ELoc;
3105 SourceRange ERange;
3106 Expr *SimpleRefExpr = RefExpr;
3107 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
3108 if (Res.second)
3109 // It will be analyzed later.
3110 PrivateRefs.push_back(RefExpr);
3111 ValueDecl *D = Res.first;
3112 if (!D)
3113 continue;
3114
3115 const DSAStackTy::DSAVarData DVar =
3116 DSAStack->getTopDSA(D, /*FromParent=*/false);
3117 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
3118 : SimpleRefExpr);
3119 }
3120 Clause->setPrivateRefs(PrivateRefs);
3121 };
3122
3123 auto FinalizeAllocators = [&](OMPUsesAllocatorsClause *Clause) {
3124 for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
3125 OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
3126 auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
3127 if (!DRE)
3128 continue;
3129 ValueDecl *VD = DRE->getDecl();
3130 if (!VD || !isa<VarDecl>(VD))
3131 continue;
3132 DSAStackTy::DSAVarData DVar =
3133 DSAStack->getTopDSA(VD, /*FromParent=*/false);
3134 // OpenMP [2.12.5, target Construct]
3135 // Memory allocators that appear in a uses_allocators clause cannot
3136 // appear in other data-sharing attribute clauses or data-mapping
3137 // attribute clauses in the same construct.
3138 Expr *MapExpr = nullptr;
3139 if (DVar.RefExpr ||
3140 DSAStack->checkMappableExprComponentListsForDecl(
3141 VD, /*CurrentRegionOnly=*/true,
3142 [VD, &MapExpr](
3144 MapExprComponents,
3146 auto MI = MapExprComponents.rbegin();
3147 auto ME = MapExprComponents.rend();
3148 if (MI != ME &&
3149 MI->getAssociatedDeclaration()->getCanonicalDecl() ==
3150 VD->getCanonicalDecl()) {
3151 MapExpr = MI->getAssociatedExpression();
3152 return true;
3153 }
3154 return false;
3155 })) {
3156 Diag(D.Allocator->getExprLoc(), diag::err_omp_allocator_used_in_clauses)
3157 << D.Allocator->getSourceRange();
3158 if (DVar.RefExpr)
3160 else
3161 Diag(MapExpr->getExprLoc(), diag::note_used_here)
3162 << MapExpr->getSourceRange();
3163 }
3164 }
3165 };
3166
3167 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
3168 for (OMPClause *C : D->clauses()) {
3169 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
3170 FinalizeLastprivate(Clause);
3171 } else if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
3172 FinalizeNontemporal(Clause);
3173 } else if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
3174 FinalizeAllocators(Clause);
3175 }
3176 }
3177 // Check allocate clauses.
3178 if (!SemaRef.CurContext->isDependentContext())
3179 checkAllocateClauses(SemaRef, DSAStack, D->clauses());
3180 checkReductionClauses(SemaRef, DSAStack, D->clauses());
3181 }
3182
3183 DSAStack->pop();
3186}
3187
3188static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
3189 Expr *NumIterations, Sema &SemaRef,
3190 Scope *S, DSAStackTy *Stack);
3191
3192static bool finishLinearClauses(Sema &SemaRef, ArrayRef<OMPClause *> Clauses,
3193 OMPLoopBasedDirective::HelperExprs &B,
3194 DSAStackTy *Stack) {
3195 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
3196 "loop exprs were not built");
3197
3198 if (SemaRef.CurContext->isDependentContext())
3199 return false;
3200
3201 // Finalize the clauses that need pre-built expressions for CodeGen.
3202 for (OMPClause *C : Clauses) {
3203 auto *LC = dyn_cast<OMPLinearClause>(C);
3204 if (!LC)
3205 continue;
3206 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
3207 B.NumIterations, SemaRef,
3208 SemaRef.getCurScope(), Stack))
3209 return true;
3210 }
3211
3212 return false;
3213}
3214
3215namespace {
3216
3217class VarDeclFilterCCC final : public CorrectionCandidateCallback {
3218private:
3219 Sema &SemaRef;
3220
3221public:
3222 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
3223 bool ValidateCandidate(const TypoCorrection &Candidate) override {
3224 NamedDecl *ND = Candidate.getCorrectionDecl();
3225 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
3226 return VD->hasGlobalStorage() &&
3227 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
3228 SemaRef.getCurScope());
3229 }
3230 return false;
3231 }
3232
3233 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3234 return std::make_unique<VarDeclFilterCCC>(*this);
3235 }
3236};
3237
3238class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
3239private:
3240 Sema &SemaRef;
3241
3242public:
3243 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
3244 bool ValidateCandidate(const TypoCorrection &Candidate) override {
3245 NamedDecl *ND = Candidate.getCorrectionDecl();
3246 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
3247 isa<FunctionDecl>(ND))) {
3248 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
3249 SemaRef.getCurScope());
3250 }
3251 return false;
3252 }
3253
3254 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3255 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
3256 }
3257};
3258
3259} // namespace
3260
3262 CXXScopeSpec &ScopeSpec,
3263 const DeclarationNameInfo &Id,
3264 OpenMPDirectiveKind Kind) {
3265 ASTContext &Context = getASTContext();
3266 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
3268 SemaRef.LookupParsedName(Lookup, CurScope, &ScopeSpec,
3269 /*ObjectType=*/QualType(),
3270 /*AllowBuiltinCreation=*/true);
3271
3272 if (Lookup.isAmbiguous())
3273 return ExprError();
3274
3275 VarDecl *VD;
3276 if (!Lookup.isSingleResult()) {
3277 VarDeclFilterCCC CCC(SemaRef);
3278 if (TypoCorrection Corrected =
3279 SemaRef.CorrectTypo(Id, Sema::LookupOrdinaryName, CurScope, nullptr,
3281 SemaRef.diagnoseTypo(
3282 Corrected,
3283 SemaRef.PDiag(Lookup.empty() ? diag::err_undeclared_var_use_suggest
3284 : diag::err_omp_expected_var_arg_suggest)
3285 << Id.getName());
3286 VD = Corrected.getCorrectionDeclAs<VarDecl>();
3287 } else {
3288 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
3289 : diag::err_omp_expected_var_arg)
3290 << Id.getName();
3291 return ExprError();
3292 }
3293 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
3294 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
3295 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
3296 return ExprError();
3297 }
3298 Lookup.suppressDiagnostics();
3299
3300 // OpenMP [2.9.2, Syntax, C/C++]
3301 // Variables must be file-scope, namespace-scope, or static block-scope.
3302 if ((Kind == OMPD_threadprivate || Kind == OMPD_groupprivate) &&
3303 !VD->hasGlobalStorage()) {
3304 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
3305 << getOpenMPDirectiveName(Kind, OMPVersion) << !VD->isStaticLocal();
3306 bool IsDecl =
3308 Diag(VD->getLocation(),
3309 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3310 << VD;
3311 return ExprError();
3312 }
3313
3314 VarDecl *CanonicalVD = VD->getCanonicalDecl();
3315 NamedDecl *ND = CanonicalVD;
3316 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
3317 // A threadprivate or groupprivate directive for file-scope variables must
3318 // appear outside any definition or declaration.
3319 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
3320 !SemaRef.getCurLexicalContext()->isTranslationUnit()) {
3321 Diag(Id.getLoc(), diag::err_omp_var_scope)
3322 << getOpenMPDirectiveName(Kind, OMPVersion) << VD;
3323 bool IsDecl =
3325 Diag(VD->getLocation(),
3326 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3327 << VD;
3328 return ExprError();
3329 }
3330 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
3331 // A threadprivate or groupprivate directive for static class member
3332 // variables must appear in the class definition, in the same scope in which
3333 // the member variables are declared.
3334 if (CanonicalVD->isStaticDataMember() &&
3335 !CanonicalVD->getDeclContext()->Equals(SemaRef.getCurLexicalContext())) {
3336 Diag(Id.getLoc(), diag::err_omp_var_scope)
3337 << getOpenMPDirectiveName(Kind, OMPVersion) << VD;
3338 bool IsDecl =
3340 Diag(VD->getLocation(),
3341 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3342 << VD;
3343 return ExprError();
3344 }
3345 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
3346 // A threadprivate or groupprivate directive for namespace-scope variables
3347 // must appear outside any definition or declaration other than the
3348 // namespace definition itself.
3349 if (CanonicalVD->getDeclContext()->isNamespace() &&
3350 (!SemaRef.getCurLexicalContext()->isFileContext() ||
3351 !SemaRef.getCurLexicalContext()->Encloses(
3352 CanonicalVD->getDeclContext()))) {
3353 Diag(Id.getLoc(), diag::err_omp_var_scope)
3354 << getOpenMPDirectiveName(Kind, OMPVersion) << VD;
3355 bool IsDecl =
3357 Diag(VD->getLocation(),
3358 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3359 << VD;
3360 return ExprError();
3361 }
3362 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
3363 // A threadprivate or groupprivate directive for static block-scope
3364 // variables must appear in the scope of the variable and not in a nested
3365 // scope.
3366 if (CanonicalVD->isLocalVarDecl() && CurScope &&
3367 !SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), CurScope)) {
3368 Diag(Id.getLoc(), diag::err_omp_var_scope)
3369 << getOpenMPDirectiveName(Kind, OMPVersion) << VD;
3370 bool IsDecl =
3372 Diag(VD->getLocation(),
3373 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3374 << VD;
3375 return ExprError();
3376 }
3377
3378 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
3379 // A threadprivate or groupprivate directive must lexically precede all
3380 // references to any of the variables in its list.
3381 if ((Kind == OMPD_threadprivate && VD->isUsed() &&
3382 !DSAStack->isThreadPrivate(VD)) ||
3383 (Kind == OMPD_groupprivate && VD->isUsed())) {
3384 Diag(Id.getLoc(), diag::err_omp_var_used)
3385 << getOpenMPDirectiveName(Kind, OMPVersion) << VD;
3386 return ExprError();
3387 }
3388
3389 QualType ExprType = VD->getType().getNonReferenceType();
3391 SourceLocation(), VD,
3392 /*RefersToEnclosingVariableOrCapture=*/false,
3393 Id.getLoc(), ExprType, VK_LValue);
3394}
3395
3398 ArrayRef<Expr *> VarList) {
3399 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
3400 SemaRef.CurContext->addDecl(D);
3402 }
3403 return nullptr;
3404}
3405
3408 ArrayRef<Expr *> VarList) {
3409 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
3410 if (!OMPVersion || OMPVersion < 60) {
3411 Diag(Loc, diag::err_omp_unexpected_directive)
3412 << getOpenMPDirectiveName(OMPD_groupprivate, OMPVersion);
3413 return nullptr;
3414 }
3415 if (OMPGroupPrivateDecl *D = CheckOMPGroupPrivateDecl(Loc, VarList)) {
3416 SemaRef.CurContext->addDecl(D);
3418 }
3419 return nullptr;
3420}
3421
3422namespace {
3423class LocalVarRefChecker final
3424 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
3425 Sema &SemaRef;
3426
3427public:
3428 bool VisitDeclRefExpr(const DeclRefExpr *E) {
3429 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
3430 if (VD->hasLocalStorage()) {
3431 SemaRef.Diag(E->getBeginLoc(),
3432 diag::err_omp_local_var_in_threadprivate_init)
3433 << E->getSourceRange();
3434 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
3435 << VD << VD->getSourceRange();
3436 return true;
3437 }
3438 }
3439 return false;
3440 }
3441 bool VisitStmt(const Stmt *S) {
3442 for (const Stmt *Child : S->children()) {
3443 if (Child && Visit(Child))
3444 return true;
3445 }
3446 return false;
3447 }
3448 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
3449};
3450} // namespace
3451
3452OMPThreadPrivateDecl *
3454 ArrayRef<Expr *> VarList) {
3455 ASTContext &Context = getASTContext();
3457 for (Expr *RefExpr : VarList) {
3458 auto *DE = cast<DeclRefExpr>(RefExpr);
3459 auto *VD = cast<VarDecl>(DE->getDecl());
3460 SourceLocation ILoc = DE->getExprLoc();
3461
3462 // Mark variable as used.
3463 VD->setReferenced();
3464 VD->markUsed(Context);
3465
3466 QualType QType = VD->getType();
3467 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
3468 // It will be analyzed later.
3469 Vars.push_back(DE);
3470 continue;
3471 }
3472
3473 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
3474 // A threadprivate variable must not have an incomplete type.
3475 if (SemaRef.RequireCompleteType(
3476 ILoc, VD->getType(), diag::err_omp_threadprivate_incomplete_type)) {
3477 continue;
3478 }
3479
3480 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
3481 // A threadprivate variable must not have a reference type.
3482 if (VD->getType()->isReferenceType()) {
3483 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
3484 Diag(ILoc, diag::err_omp_ref_type_arg)
3485 << getOpenMPDirectiveName(OMPD_threadprivate, OMPVersion)
3486 << VD->getType();
3487 bool IsDecl =
3489 Diag(VD->getLocation(),
3490 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3491 << VD;
3492 continue;
3493 }
3494
3495 // Check if this is a TLS variable. If TLS is not being supported, produce
3496 // the corresponding diagnostic.
3497 if ((VD->getTLSKind() != VarDecl::TLS_None &&
3498 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
3499 getLangOpts().OpenMPUseTLS &&
3500 getASTContext().getTargetInfo().isTLSSupported())) ||
3501 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3502 !VD->isLocalVarDecl())) {
3503 Diag(ILoc, diag::err_omp_var_thread_local)
3504 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
3505 bool IsDecl =
3507 Diag(VD->getLocation(),
3508 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3509 << VD;
3510 continue;
3511 }
3512
3513 // Check if initial value of threadprivate variable reference variable with
3514 // local storage (it is not supported by runtime).
3515 if (const Expr *Init = VD->getAnyInitializer()) {
3516 LocalVarRefChecker Checker(SemaRef);
3517 if (Checker.Visit(Init))
3518 continue;
3519 }
3520
3521 Vars.push_back(RefExpr);
3522 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
3523 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
3524 Context, SourceRange(Loc, Loc)));
3525 if (ASTMutationListener *ML = Context.getASTMutationListener())
3526 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
3527 }
3528 OMPThreadPrivateDecl *D = nullptr;
3529 if (!Vars.empty()) {
3530 D = OMPThreadPrivateDecl::Create(Context, SemaRef.getCurLexicalContext(),
3531 Loc, Vars);
3532 D->setAccess(AS_public);
3533 }
3534 return D;
3535}
3536
3539 ArrayRef<Expr *> VarList) {
3540 ASTContext &Context = getASTContext();
3542 for (Expr *RefExpr : VarList) {
3543 auto *DE = cast<DeclRefExpr>(RefExpr);
3544 auto *VD = cast<VarDecl>(DE->getDecl());
3545 SourceLocation ILoc = DE->getExprLoc();
3546
3547 // Mark variable as used.
3548 VD->setReferenced();
3549 VD->markUsed(Context);
3550
3551 QualType QType = VD->getType();
3552 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
3553 // It will be analyzed later.
3554 Vars.push_back(DE);
3555 continue;
3556 }
3557
3558 // OpenMP groupprivate restrictions:
3559 // A groupprivate variable must not have an incomplete type.
3560 if (SemaRef.RequireCompleteType(
3561 ILoc, VD->getType(), diag::err_omp_groupprivate_incomplete_type)) {
3562 continue;
3563 }
3564
3565 // A groupprivate variable must not have a reference type.
3566 if (VD->getType()->isReferenceType()) {
3567 Diag(ILoc, diag::err_omp_ref_type_arg)
3568 << getOpenMPDirectiveName(OMPD_groupprivate) << VD->getType();
3569 bool IsDecl =
3571 Diag(VD->getLocation(),
3572 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3573 << VD;
3574 continue;
3575 }
3576
3577 // A variable that is declared with an initializer must not appear in a
3578 // groupprivate directive.
3579 if (VD->getAnyInitializer()) {
3580 Diag(ILoc, diag::err_omp_groupprivate_with_initializer)
3581 << VD->getDeclName();
3582 bool IsDecl =
3584 Diag(VD->getLocation(),
3585 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3586 << VD;
3587 continue;
3588 }
3589
3590 Vars.push_back(RefExpr);
3591 DSAStack->addDSA(VD, DE, OMPC_groupprivate);
3592 VD->addAttr(OMPGroupPrivateDeclAttr::CreateImplicit(Context,
3593 SourceRange(Loc, Loc)));
3594 if (ASTMutationListener *ML = Context.getASTMutationListener())
3595 ML->DeclarationMarkedOpenMPGroupPrivate(VD);
3596 }
3597 OMPGroupPrivateDecl *D = nullptr;
3598 if (!Vars.empty()) {
3599 D = OMPGroupPrivateDecl::Create(Context, SemaRef.getCurLexicalContext(),
3600 Loc, Vars);
3601 D->setAccess(AS_public);
3602 }
3603 return D;
3604}
3605
3606static OMPAllocateDeclAttr::AllocatorTypeTy
3607getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
3608 if (!Allocator)
3609 return OMPAllocateDeclAttr::OMPNullMemAlloc;
3610 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3611 Allocator->isInstantiationDependent() ||
3613 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3614 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
3615 llvm::FoldingSetNodeID AEId;
3616 const Expr *AE = Allocator->IgnoreParenImpCasts();
3617 AE->IgnoreImpCasts()->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
3618 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
3619 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
3620 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
3621 llvm::FoldingSetNodeID DAEId;
3622 DefAllocator->IgnoreImpCasts()->Profile(DAEId, S.getASTContext(),
3623 /*Canonical=*/true);
3624 if (AEId == DAEId) {
3625 AllocatorKindRes = AllocatorKind;
3626 break;
3627 }
3628 }
3629 return AllocatorKindRes;
3630}
3631
3633 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
3634 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
3635 if (!VD->hasAttr<OMPAllocateDeclAttr>())
3636 return false;
3637 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
3638 Expr *PrevAllocator = A->getAllocator();
3639 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
3640 getAllocatorKind(S, Stack, PrevAllocator);
3641 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
3642 if (AllocatorsMatch &&
3643 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
3644 Allocator && PrevAllocator) {
3645 const Expr *AE = Allocator->IgnoreParenImpCasts();
3646 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
3647 llvm::FoldingSetNodeID AEId, PAEId;
3648 AE->Profile(AEId, S.Context, /*Canonical=*/true);
3649 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
3650 AllocatorsMatch = AEId == PAEId;
3651 }
3652 if (!AllocatorsMatch) {
3653 SmallString<256> AllocatorBuffer;
3654 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
3655 if (Allocator)
3656 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
3657 SmallString<256> PrevAllocatorBuffer;
3658 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
3659 if (PrevAllocator)
3660 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
3661 S.getPrintingPolicy());
3662
3663 SourceLocation AllocatorLoc =
3664 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
3665 SourceRange AllocatorRange =
3666 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
3667 SourceLocation PrevAllocatorLoc =
3668 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
3669 SourceRange PrevAllocatorRange =
3670 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
3671 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
3672 << (Allocator ? 1 : 0) << AllocatorStream.str()
3673 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
3674 << AllocatorRange;
3675 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
3676 << PrevAllocatorRange;
3677 return true;
3678 }
3679 return false;
3680}
3681
3682static void
3684 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
3685 Expr *Allocator, Expr *Alignment, SourceRange SR) {
3686 if (VD->hasAttr<OMPAllocateDeclAttr>())
3687 return;
3688 if (Alignment &&
3689 (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
3690 Alignment->isInstantiationDependent() ||
3691 Alignment->containsUnexpandedParameterPack()))
3692 // Apply later when we have a usable value.
3693 return;
3694 if (Allocator &&
3695 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
3696 Allocator->isInstantiationDependent() ||
3697 Allocator->containsUnexpandedParameterPack()))
3698 return;
3699 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
3700 Allocator, Alignment, SR);
3701 VD->addAttr(A);
3703 ML->DeclarationMarkedOpenMPAllocate(VD, A);
3704}
3705
3708 DeclContext *Owner) {
3709 assert(Clauses.size() <= 2 && "Expected at most two clauses.");
3710 Expr *Alignment = nullptr;
3711 Expr *Allocator = nullptr;
3712 if (Clauses.empty()) {
3713 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
3714 // allocate directives that appear in a target region must specify an
3715 // allocator clause unless a requires directive with the dynamic_allocators
3716 // clause is present in the same compilation unit.
3717 if (getLangOpts().OpenMPIsTargetDevice &&
3718 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
3719 SemaRef.targetDiag(Loc, diag::err_expected_allocator_clause);
3720 } else {
3721 for (const OMPClause *C : Clauses)
3722 if (const auto *AC = dyn_cast<OMPAllocatorClause>(C))
3723 Allocator = AC->getAllocator();
3724 else if (const auto *AC = dyn_cast<OMPAlignClause>(C))
3725 Alignment = AC->getAlignment();
3726 else
3727 llvm_unreachable("Unexpected clause on allocate directive");
3728 }
3729 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3730 getAllocatorKind(SemaRef, DSAStack, Allocator);
3732 for (Expr *RefExpr : VarList) {
3733 auto *DE = cast<DeclRefExpr>(RefExpr);
3734 auto *VD = cast<VarDecl>(DE->getDecl());
3735
3736 // Check if this is a TLS variable or global register.
3737 if (VD->getTLSKind() != VarDecl::TLS_None ||
3738 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
3739 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
3740 !VD->isLocalVarDecl()))
3741 continue;
3742
3743 // If the used several times in the allocate directive, the same allocator
3744 // must be used.
3746 AllocatorKind, Allocator))
3747 continue;
3748
3749 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
3750 // If a list item has a static storage type, the allocator expression in the
3751 // allocator clause must be a constant expression that evaluates to one of
3752 // the predefined memory allocator values.
3753 if (Allocator && VD->hasGlobalStorage()) {
3754 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
3755 Diag(Allocator->getExprLoc(),
3756 diag::err_omp_expected_predefined_allocator)
3757 << Allocator->getSourceRange();
3758 bool IsDecl = VD->isThisDeclarationADefinition(getASTContext()) ==
3760 Diag(VD->getLocation(),
3761 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
3762 << VD;
3763 continue;
3764 }
3765 }
3766
3767 Vars.push_back(RefExpr);
3768 applyOMPAllocateAttribute(SemaRef, VD, AllocatorKind, Allocator, Alignment,
3769 DE->getSourceRange());
3770 }
3771 if (Vars.empty())
3772 return nullptr;
3773 if (!Owner)
3774 Owner = SemaRef.getCurLexicalContext();
3775 auto *D = OMPAllocateDecl::Create(getASTContext(), Owner, Loc, Vars, Clauses);
3776 D->setAccess(AS_public);
3777 Owner->addDecl(D);
3779}
3780
3783 ArrayRef<OMPClause *> ClauseList) {
3784 OMPRequiresDecl *D = nullptr;
3785 if (!SemaRef.CurContext->isFileContext()) {
3786 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
3787 } else {
3788 D = CheckOMPRequiresDecl(Loc, ClauseList);
3789 if (D) {
3790 SemaRef.CurContext->addDecl(D);
3791 DSAStack->addRequiresDecl(D);
3792 }
3793 }
3795}
3796
3798 OpenMPDirectiveKind DKind,
3799 ArrayRef<std::string> Assumptions,
3800 bool SkippedClauses) {
3801 if (!SkippedClauses && Assumptions.empty()) {
3802 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
3803 Diag(Loc, diag::err_omp_no_clause_for_directive)
3804 << llvm::omp::getAllAssumeClauseOptions()
3805 << llvm::omp::getOpenMPDirectiveName(DKind, OMPVersion);
3806 }
3807
3808 auto *AA =
3809 OMPAssumeAttr::Create(getASTContext(), llvm::join(Assumptions, ","), Loc);
3810 if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
3811 OMPAssumeScoped.push_back(AA);
3812 return;
3813 }
3814
3815 // Global assumes without assumption clauses are ignored.
3816 if (Assumptions.empty())
3817 return;
3818
3819 assert(DKind == llvm::omp::Directive::OMPD_assumes &&
3820 "Unexpected omp assumption directive!");
3821 OMPAssumeGlobal.push_back(AA);
3822
3823 // The OMPAssumeGlobal scope above will take care of new declarations but
3824 // we also want to apply the assumption to existing ones, e.g., to
3825 // declarations in included headers. To this end, we traverse all existing
3826 // declaration contexts and annotate function declarations here.
3827 SmallVector<DeclContext *, 8> DeclContexts;
3828 auto *Ctx = SemaRef.CurContext;
3829 while (Ctx->getLexicalParent())
3830 Ctx = Ctx->getLexicalParent();
3831 DeclContexts.push_back(Ctx);
3832 while (!DeclContexts.empty()) {
3833 DeclContext *DC = DeclContexts.pop_back_val();
3834 for (auto *SubDC : DC->decls()) {
3835 if (SubDC->isInvalidDecl())
3836 continue;
3837 if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
3838 DeclContexts.push_back(CTD->getTemplatedDecl());
3839 llvm::append_range(DeclContexts, CTD->specializations());
3840 continue;
3841 }
3842 if (auto *DC = dyn_cast<DeclContext>(SubDC))
3843 DeclContexts.push_back(DC);
3844 if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
3845 F->addAttr(AA);
3846 continue;
3847 }
3848 }
3849 }
3850}
3851
3853 assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
3854 OMPAssumeScoped.pop_back();
3855}
3856
3858 Stmt *AStmt,
3859 SourceLocation StartLoc,
3860 SourceLocation EndLoc) {
3861 if (!AStmt)
3862 return StmtError();
3863
3864 return OMPAssumeDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses,
3865 AStmt);
3866}
3867
3869 SourceLocation StartLoc, SourceLocation EndLoc,
3870 ArrayRef<OMPTraitInfo *> TraitInfos, ArrayRef<Stmt *> Variants) {
3871 // Without an 'otherwise' clause, the last variant is the implicit one.
3872 bool HasImplicitOtherwise = Variants.size() == TraitInfos.size() + 1;
3873 assert((HasImplicitOtherwise || Variants.size() == TraitInfos.size()) &&
3874 "Expected one variant per metadirective clause");
3875 SmallVector<OMPTraitInfo *, 4> AllTraitInfos(TraitInfos);
3876 if (HasImplicitOtherwise)
3877 AllTraitInfos.push_back(&getASTContext().getNewOMPTraitInfo());
3878 // The user condition of each variant; null for 'otherwise'.
3879 SmallVector<Expr *, 4> Conditions;
3880 for (OMPTraitInfo *TI : AllTraitInfos) {
3881 Expr *Cond = nullptr;
3882 TI->anyScoreOrCondition([&](Expr *&E, bool IsScore) {
3883 if (!IsScore)
3884 Cond = E;
3885 return !IsScore;
3886 });
3887 if (Cond) {
3888 ExprResult Val = SemaRef.CheckBooleanCondition(Cond->getExprLoc(), Cond);
3889 if (Val.isInvalid())
3890 return StmtError();
3891 Cond = SemaRef.MakeFullExpr(Val.get()).get();
3892 }
3893 Conditions.push_back(Cond);
3894 }
3895 return OMPMetaDirective::Create(getASTContext(), StartLoc, EndLoc, Variants,
3896 Conditions, AllTraitInfos,
3897 HasImplicitOtherwise);
3898}
3899
3902 ArrayRef<OMPClause *> ClauseList) {
3903 /// For target specific clauses, the requires directive cannot be
3904 /// specified after the handling of any of the target regions in the
3905 /// current compilation unit.
3906 ArrayRef<SourceLocation> TargetLocations =
3907 DSAStack->getEncounteredTargetLocs();
3908 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
3909 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
3910 for (const OMPClause *CNew : ClauseList) {
3911 // Check if any of the requires clauses affect target regions.
3916 Diag(Loc, diag::err_omp_directive_before_requires)
3917 << "target" << getOpenMPClauseNameForDiag(CNew->getClauseKind());
3918 for (SourceLocation TargetLoc : TargetLocations) {
3919 Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
3920 << "target";
3921 }
3922 } else if (!AtomicLoc.isInvalid() &&
3924 Diag(Loc, diag::err_omp_directive_before_requires)
3925 << "atomic" << getOpenMPClauseNameForDiag(CNew->getClauseKind());
3926 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
3927 << "atomic";
3928 }
3929 }
3930 }
3931
3932 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
3934 getASTContext(), SemaRef.getCurLexicalContext(), Loc, ClauseList);
3935 return nullptr;
3936}
3937
3938static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
3939 const ValueDecl *D,
3940 const DSAStackTy::DSAVarData &DVar,
3941 bool IsLoopIterVar) {
3942 if (DVar.RefExpr) {
3943 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
3944 << getOpenMPClauseNameForDiag(DVar.CKind);
3945 return;
3946 }
3947 enum {
3948 PDSA_StaticMemberShared,
3949 PDSA_StaticLocalVarShared,
3950 PDSA_LoopIterVarPrivate,
3951 PDSA_LoopIterVarLinear,
3952 PDSA_LoopIterVarLastprivate,
3953 PDSA_ConstVarShared,
3954 PDSA_GlobalVarShared,
3955 PDSA_TaskVarFirstprivate,
3956 PDSA_LocalVarPrivate,
3957 PDSA_Implicit
3958 } Reason = PDSA_Implicit;
3959 bool ReportHint = false;
3960 auto ReportLoc = D->getLocation();
3961 auto *VD = dyn_cast<VarDecl>(D);
3962 if (IsLoopIterVar) {
3963 if (DVar.CKind == OMPC_private)
3964 Reason = PDSA_LoopIterVarPrivate;
3965 else if (DVar.CKind == OMPC_lastprivate)
3966 Reason = PDSA_LoopIterVarLastprivate;
3967 else
3968 Reason = PDSA_LoopIterVarLinear;
3969 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
3970 DVar.CKind == OMPC_firstprivate) {
3971 Reason = PDSA_TaskVarFirstprivate;
3972 ReportLoc = DVar.ImplicitDSALoc;
3973 } else if (VD && VD->isStaticLocal())
3974 Reason = PDSA_StaticLocalVarShared;
3975 else if (VD && VD->isStaticDataMember())
3976 Reason = PDSA_StaticMemberShared;
3977 else if (VD && VD->isFileVarDecl())
3978 Reason = PDSA_GlobalVarShared;
3979 else if (D->getType().isConstant(SemaRef.getASTContext()))
3980 Reason = PDSA_ConstVarShared;
3981 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
3982 ReportHint = true;
3983 Reason = PDSA_LocalVarPrivate;
3984 }
3985 if (Reason != PDSA_Implicit) {
3986 llvm::omp::Version OMPVersion = SemaRef.getLangOpts().getOpenMPVersion();
3987 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
3988 << Reason << ReportHint
3989 << getOpenMPDirectiveName(Stack->getCurrentDirective(), OMPVersion);
3990 } else if (DVar.ImplicitDSALoc.isValid()) {
3991 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
3992 << getOpenMPClauseNameForDiag(DVar.CKind);
3993 }
3994}
3995
3996namespace {
3997/// Visitor to collect variables used in a statement.
3998class VarUsageVisitor : public DynamicRecursiveASTVisitor {
3999 llvm::SmallPtrSet<const VarDecl *, 8> &UsedVars;
4000 llvm::SmallPtrSet<const BindingDecl *, 8> &UsedBindings;
4001
4002public:
4003 VarUsageVisitor(llvm::SmallPtrSet<const VarDecl *, 8> &UsedVars,
4004 llvm::SmallPtrSet<const BindingDecl *, 8> &UsedBindings)
4005 : UsedVars(UsedVars), UsedBindings(UsedBindings) {}
4006
4007 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
4008 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4009 UsedVars.insert(cast<VarDecl>(VD->getCanonicalDecl()));
4010 else if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
4011 UsedBindings.insert(cast<BindingDecl>(BD->getCanonicalDecl()));
4012 return true;
4013 }
4014};
4015} // namespace
4016
4017/// Check if bindings from the same structured binding have conflicting
4018/// capture kinds (by-ref vs by-copy). Bindings share the underlying
4019/// DecompositionDecl storage, so mixing by-ref and by-copy clauses on
4020/// different bindings from the same decomposition is not representable.
4021/// For example: map(a) creates by-ref, firstprivate(b) creates by-copy.
4023 Sema &SemaRef, OpenMPDirectiveKind DKind,
4024 llvm::SmallDenseMap<const DecompositionDecl *,
4025 std::pair<bool, SourceLocation>, 4> &SeenDecompositions,
4026 const ValueDecl *D, SourceLocation ELoc, OpenMPClauseKind ClauseKind) {
4027 const auto *BD = dyn_cast<BindingDecl>(D);
4028 if (!BD)
4029 return false;
4030
4031 const auto *DD = dyn_cast<DecompositionDecl>(BD->getDecomposedDecl());
4032 if (!DD)
4033 return false;
4034
4035 // Determine if this clause creates by-ref or by-copy capture.
4036 bool IsByRef = false;
4037 switch (ClauseKind) {
4038 case OMPC_map:
4039 case OMPC_shared:
4040 // Map and shared clauses are by-reference.
4041 IsByRef = true;
4042 break;
4043 case OMPC_firstprivate:
4044 case OMPC_private:
4045 case OMPC_lastprivate:
4046 // These are by-copy.
4047 IsByRef = false;
4048 break;
4049 default:
4050 // Other clauses don't create capture conflicts.
4051 return false;
4052 }
4053 auto [It, Inserted] = SeenDecompositions.insert({DD, {IsByRef, ELoc}});
4054 if (!Inserted && It->second.first != IsByRef) {
4055 // Conflict: same DecompositionDecl needs both by-ref and by-copy
4056 // Emit diagnostic showing the binding name, not the decomposition.
4057 SemaRef.Diag(ELoc,
4058 diag::err_omp_decomposition_bindings_different_capture_kinds)
4059 << BD;
4060 return true;
4061 }
4062 return false;
4063}
4064
4065/// Helper to check all clauses in a directive for structured binding
4066/// capture conflicts. Returns true if an error was found. If Body is
4067/// provided and the directive has default(shared), bindings used in the
4068/// body but not listed in explicit clauses are treated as implicit
4069/// shared (by-reference).
4071 OpenMPDirectiveKind DKind,
4072 ArrayRef<OMPClause *> Clauses,
4073 Stmt *Body = nullptr) {
4074 llvm::SmallDenseMap<const DecompositionDecl *,
4075 std::pair<bool, SourceLocation>, 4>
4076 SeenDecompositions;
4078 bool HasError = false;
4079 bool HasDefaultShared = false;
4080 SourceLocation DefaultSharedLoc;
4081 for (OMPClause *C : Clauses) {
4082 if (auto *DC = dyn_cast<OMPDefaultClause>(C)) {
4083 if (DC->getDefaultKind() == llvm::omp::DefaultKind::OMP_DEFAULT_shared) {
4084 HasDefaultShared = true;
4085 DefaultSharedLoc = DC->getBeginLoc();
4086 }
4087 continue;
4088 }
4089 OpenMPClauseKind CK = C->getClauseKind();
4090 if (CK != OMPC_map && CK != OMPC_firstprivate && CK != OMPC_private &&
4091 CK != OMPC_shared && CK != OMPC_lastprivate)
4092 continue;
4093 ArrayRef<Expr *> Varlist;
4094 if (auto *MPC = dyn_cast<OMPMapClause>(C))
4095 Varlist = MPC->varlist();
4096 else if (auto *FPC = dyn_cast<OMPFirstprivateClause>(C))
4097 Varlist = FPC->varlist();
4098 else if (auto *PC = dyn_cast<OMPPrivateClause>(C))
4099 Varlist = PC->varlist();
4100 else if (auto *SC = dyn_cast<OMPSharedClause>(C))
4101 Varlist = SC->varlist();
4102 else if (auto *LPC = dyn_cast<OMPLastprivateClause>(C))
4103 Varlist = LPC->varlist();
4104
4105 for (Expr *VE : Varlist) {
4106 if (auto *DRE = dyn_cast<DeclRefExpr>(VE->IgnoreParenImpCasts())) {
4107 ValueDecl *D = DRE->getDecl();
4108 // Look through OMPCapturedExprDecl (used when clauses reference
4109 // variables from an enclosing captured region) to find the
4110 // underlying BindingDecl.
4111 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) {
4112 if (auto *InitDRE =
4113 dyn_cast<DeclRefExpr>(CED->getInit()->IgnoreParenImpCasts()))
4114 D = InitDRE->getDecl();
4115 }
4116 if (auto *BD = dyn_cast<BindingDecl>(D))
4117 ExplicitBindings.insert(cast<BindingDecl>(BD->getCanonicalDecl()));
4119 SemaRef, DKind, SeenDecompositions, D, VE->getExprLoc(), CK))
4120 HasError = true;
4121 }
4122 }
4123 }
4124
4125 // With default(shared), bindings used in the body but not in an explicit
4126 // clause become implicit shared (by-reference). Check those for conflicts
4127 // with explicit by-copy clauses on the same decomposition.
4128 if (HasDefaultShared && Body) {
4131 VarUsageVisitor Visitor(UsedVars, UsedBindings);
4132 Visitor.TraverseStmt(Body);
4133 for (const BindingDecl *BD : UsedBindings) {
4134 if (ExplicitBindings.contains(BD))
4135 continue;
4136 if (checkDecompositionCaptureConflict(SemaRef, DKind, SeenDecompositions,
4137 BD, DefaultSharedLoc, OMPC_shared))
4138 HasError = true;
4139 }
4140 }
4141 return HasError;
4142}
4143
4144/// Check if original variable is explicitly mapped but only bindings are used.
4145/// Returns true if an error was found.
4147 Sema &SemaRef, ArrayRef<OMPClause *> Clauses, Stmt *Body) {
4148 llvm::SmallDenseMap<const VarDecl *, SourceLocation, 4> MappedOrigVars;
4149
4150 for (OMPClause *C : Clauses) {
4151 if (auto *MPC = dyn_cast<OMPMapClause>(C)) {
4152 for (Expr *VE : MPC->varlist()) {
4153 if (auto *DRE = dyn_cast<DeclRefExpr>(VE->IgnoreParenImpCasts())) {
4154 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
4155 MappedOrigVars[VD->getCanonicalDecl()] = VE->getExprLoc();
4156 }
4157 }
4158 }
4159 }
4160 }
4161 if (MappedOrigVars.empty())
4162 return false;
4163
4166 VarUsageVisitor Visitor(UsedVars, UsedBindings);
4167 Visitor.TraverseStmt(Body);
4168 bool HasError = false;
4169 for (const auto &Entry : MappedOrigVars) {
4170 const VarDecl *OrigVar = Entry.first;
4171 SourceLocation Loc = Entry.second;
4172
4173 // Check if this original variable has bindings that are used.
4174 // For reference bindings (`auto &[a, b] = p`), the bindings alias the
4175 // original variable, so mapping `p` covers them correctly.
4176 bool BindingsFromThisVarUsed = false;
4177 for (const BindingDecl *BD : UsedBindings) {
4178 if (auto *DD = dyn_cast<DecompositionDecl>(BD->getDecomposedDecl())) {
4179 if (DD->getType()->isReferenceType())
4180 continue;
4181 if (auto *OrigFromDD = DD->getOriginalVar().Var) {
4182 if (OrigFromDD->getCanonicalDecl() == OrigVar) {
4183 BindingsFromThisVarUsed = true;
4184 break;
4185 }
4186 }
4187 }
4188 }
4189
4190 // Error if: original is mapped, bindings are used, but original is not
4191 // used.
4192 if (BindingsFromThisVarUsed && !UsedVars.count(OrigVar)) {
4193 SemaRef.Diag(Loc, diag::err_omp_original_var_mapped_bindings_only_used)
4194 << OrigVar;
4195 HasError = true;
4196 }
4197 }
4198
4199 return HasError;
4200}
4201
4204 bool IsAggregateOrDeclareTarget,
4205 bool HasConstQualifier) {
4207 switch (M) {
4208 case OMPC_DEFAULTMAP_MODIFIER_alloc:
4209 case OMPC_DEFAULTMAP_MODIFIER_storage:
4210 Kind = OMPC_MAP_alloc;
4211 break;
4212 case OMPC_DEFAULTMAP_MODIFIER_to:
4213 Kind = OMPC_MAP_to;
4214 break;
4215 case OMPC_DEFAULTMAP_MODIFIER_from:
4216 Kind = OMPC_MAP_from;
4217 break;
4218 case OMPC_DEFAULTMAP_MODIFIER_tofrom:
4219 Kind = OMPC_MAP_tofrom;
4220 break;
4221 case OMPC_DEFAULTMAP_MODIFIER_present:
4222 // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
4223 // If implicit-behavior is present, each variable referenced in the
4224 // construct in the category specified by variable-category is treated as if
4225 // it had been listed in a map clause with the map-type of alloc and
4226 // map-type-modifier of present.
4227 Kind = OMPC_MAP_alloc;
4228 break;
4229 case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
4230 case OMPC_DEFAULTMAP_MODIFIER_private:
4232 llvm_unreachable("Unexpected defaultmap implicit behavior");
4233 case OMPC_DEFAULTMAP_MODIFIER_none:
4234 case OMPC_DEFAULTMAP_MODIFIER_default:
4236 // IsAggregateOrDeclareTarget could be true if:
4237 // 1. the implicit behavior for aggregate is tofrom
4238 // 2. it's a declare target link
4239 if (IsAggregateOrDeclareTarget) {
4240 if (HasConstQualifier)
4241 Kind = OMPC_MAP_to;
4242 else
4243 Kind = OMPC_MAP_tofrom;
4244 break;
4245 }
4246 llvm_unreachable("Unexpected defaultmap implicit behavior");
4247 }
4248 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
4249 return Kind;
4250}
4251
4252static bool hasNoMutableFields(const CXXRecordDecl *RD) {
4253 for (const auto *FD : RD->fields()) {
4254 if (FD->isMutable())
4255 return false;
4256 QualType FT = FD->getType();
4257 while (FT->isArrayType())
4259 if (const auto *NestedRD = FT->getAsCXXRecordDecl())
4260 if (!hasNoMutableFields(NestedRD))
4261 return false;
4262 }
4263 return true;
4264}
4265
4267 while (T->isArrayType())
4268 T = T->getAsArrayTypeUnsafe()->getElementType();
4269 if (!T.isConstQualified())
4270 return false;
4271 if (const auto *RD = T->getAsCXXRecordDecl())
4272 // TODO : Per OpenMP 6.0 p299 lines 3-4, non-mutable members of a
4273 // const-qualified struct should also be ignored for 'from'. This
4274 // requires per-member mapping granularity via compiler-generated
4275 // default mappers and a mechanism to ensure constness to the mapper.
4276 // For now we conservatively treat any struct with mutable members as
4277 // requiring full 'tofrom'.
4278 return hasNoMutableFields(RD);
4279 return true;
4280}
4281
4282namespace {
4283/// Try to extract the original variable from a DecompositionDecl.
4284/// If extraction fails, emit a diagnostic. Returns the original VarDecl* on
4285/// success, nullptr on failure.
4286static const VarDecl *getOriginalVarOrDiagnose(Sema &S,
4287 const DecompositionDecl *DD,
4288 SourceLocation Loc) {
4289 auto Result = DD->getOriginalVar();
4290 if (!Result.Var)
4291 S.Diag(Loc, diag::err_omp_unsupported_structured_binding_init)
4292 << Result.DiagKind;
4293 return Result.Var;
4294}
4295
4296struct VariableImplicitInfo {
4297 static const unsigned MapKindNum = OMPC_MAP_unknown;
4298 static const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_unknown + 1;
4299
4300 llvm::SetVector<Expr *> Privates;
4301 llvm::SetVector<Expr *> Firstprivates;
4302 llvm::SetVector<Expr *> Mappings[DefaultmapKindNum][MapKindNum];
4303 llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
4304 MapModifiers[DefaultmapKindNum];
4305};
4306
4307class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
4308 DSAStackTy *Stack;
4309 Sema &SemaRef;
4310 OpenMPDirectiveKind DKind = OMPD_unknown;
4311 bool ErrorFound = false;
4312 bool TryCaptureCXXThisMembers = false;
4313 CapturedStmt *CS = nullptr;
4314
4315 VariableImplicitInfo ImpInfo;
4316 SemaOpenMP::VarsWithInheritedDSAType VarsWithInheritedDSA;
4317 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
4318
4319 void VisitSubCaptures(OMPExecutableDirective *S) {
4320 // Check implicitly captured variables.
4321 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
4322 return;
4323 if (S->getDirectiveKind() == OMPD_atomic ||
4324 S->getDirectiveKind() == OMPD_critical ||
4325 S->getDirectiveKind() == OMPD_section ||
4326 S->getDirectiveKind() == OMPD_master ||
4327 S->getDirectiveKind() == OMPD_masked ||
4328 S->getDirectiveKind() == OMPD_scope ||
4329 S->getDirectiveKind() == OMPD_assume ||
4330 isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
4331 Visit(S->getAssociatedStmt());
4332 return;
4333 }
4334 visitSubCaptures(S->getInnermostCapturedStmt());
4335 // Try to capture inner this->member references to generate correct mappings
4336 // and diagnostics.
4337 if (TryCaptureCXXThisMembers ||
4339 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
4340 [](const CapturedStmt::Capture &C) {
4341 return C.capturesThis();
4342 }))) {
4343 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
4344 TryCaptureCXXThisMembers = true;
4345 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
4346 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
4347 }
4348 // In tasks firstprivates are not captured anymore, need to analyze them
4349 // explicitly.
4350 if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
4351 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
4352 for (OMPClause *C : S->clauses())
4353 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
4354 for (Expr *Ref : FC->varlist())
4355 Visit(Ref);
4356 }
4357 }
4358 }
4359
4360public:
4361 void VisitDeclRefExpr(DeclRefExpr *E) {
4362 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
4366 return;
4367 ValueDecl *D = const_cast<ValueDecl *>(E->getDecl());
4368 BindingDecl *BD = dyn_cast<BindingDecl>(D);
4369 if (BD)
4370 D = BD->getDecomposedDecl();
4371 if (auto *VD = dyn_cast<VarDecl>(D)) {
4372 // For BindingDecls, use the original binding for DSA lookups;
4373 // fall back to DecompositionDecl if lookup fails.
4374 ValueDecl *LookupDecl = BD ? static_cast<ValueDecl *>(BD) : VD;
4375 // Check the datasharing rules for the expressions in the clauses.
4376 if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) &&
4377 !Stack->getTopDSA(LookupDecl, /*FromParent=*/false).RefExpr &&
4378 !Stack->isImplicitDefaultFirstprivateFD(VD))) {
4379 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
4380 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
4381 Visit(const_cast<Expr *>(CED->getInit()));
4382 return;
4383 }
4384 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
4385 // Do not analyze internal variables and do not enclose them into
4386 // implicit clauses.
4387 if (!Stack->isImplicitDefaultFirstprivateFD(VD))
4388 return;
4389 VD = VD->getCanonicalDecl();
4390 // Skip DecompositionDecls (but not BindingDecls in DSA contexts) -
4391 // they should be handled through explicit mapping of the original
4392 // variable or as member expressions. When bindings are captured,
4393 // the original variable is what needs to be mapped, not the
4394 // decomposition itself. However, BindingDecls need DSA checking for
4395 // default(none)/private/firstprivate contexts, but NOT in target
4396 // offloading contexts (where map clause handles them).
4397 if (isa<DecompositionDecl>(VD)) {
4398 // For BindingDecls, continue checking only if:
4399 // - We are in a DSA context (tasking/parallel/worksharing/teams), or
4400 // - We are in a target context and the binding is scalar (implicit
4401 // firstprivate).
4402 bool InTargetAndScalar = BD &&
4404 BD->getType()->isScalarType();
4405 if (!BD ||
4406 (isOpenMPTargetExecutionDirective(DKind) && !InTargetAndScalar) ||
4407 (!InTargetAndScalar && !isImplicitOrExplicitTaskingRegion(DKind) &&
4408 !isOpenMPParallelDirective(DKind) &&
4410 !isOpenMPTeamsDirective(DKind)))
4411 return;
4412 }
4413 // Skip internally declared variables.
4414 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
4415 !Stack->isImplicitDefaultFirstprivateFD(VD) &&
4416 !Stack->isImplicitTaskFirstprivate(VD))
4417 return;
4418 // Skip allocators in uses_allocators clauses.
4419 if (Stack->isUsesAllocatorsDecl(VD))
4420 return;
4421
4422 DSAStackTy::DSAVarData DVar =
4423 Stack->getTopDSA(LookupDecl, /*FromParent=*/false);
4424 // If lookup on BindingDecl failed, try on DecompositionDecl.
4425 if (BD && !DVar.RefExpr)
4426 DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
4427 // Check if the variable has explicit DSA set and stop analysis if it so.
4428 if (DVar.RefExpr ||
4429 !ImplicitDeclarations
4430 .insert(cast<ValueDecl>(LookupDecl->getCanonicalDecl()))
4431 .second)
4432 return;
4433
4434 // Skip internally declared static variables.
4435 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
4436 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
4437 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
4438 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4439 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
4440 !Stack->isImplicitDefaultFirstprivateFD(VD) &&
4441 !Stack->isImplicitTaskFirstprivate(VD))
4442 return;
4443
4444 SourceLocation ELoc = E->getExprLoc();
4445 // The default(none) clause requires that each variable that is referenced
4446 // in the construct, and does not have a predetermined data-sharing
4447 // attribute, must have its data-sharing attribute explicitly determined
4448 // by being listed in a data-sharing attribute clause.
4449 if (DVar.CKind == OMPC_unknown &&
4450 (Stack->getDefaultDSA() == DSA_none ||
4451 Stack->getDefaultDSA() == DSA_private ||
4452 Stack->getDefaultDSA() == DSA_firstprivate) &&
4453 isImplicitOrExplicitTaskingRegion(DKind) &&
4454 VarsWithInheritedDSA.count(VD) == 0) {
4455 bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
4456 if (!InheritedDSA && (Stack->getDefaultDSA() == DSA_firstprivate ||
4457 Stack->getDefaultDSA() == DSA_private)) {
4458 DSAStackTy::DSAVarData DVar =
4459 Stack->getImplicitDSA(LookupDecl, /*FromParent=*/false);
4460 if (BD && DVar.CKind == OMPC_unknown)
4461 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
4462 InheritedDSA = DVar.CKind == OMPC_unknown;
4463 }
4464 if (InheritedDSA)
4465 VarsWithInheritedDSA[cast<ValueDecl>(
4466 LookupDecl->getCanonicalDecl())] = E;
4467 if (Stack->getDefaultDSA() == DSA_none)
4468 return;
4469 }
4470
4471 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
4472 // If implicit-behavior is none, each variable referenced in the
4473 // construct that does not have a predetermined data-sharing attribute
4474 // and does not appear in a to or link clause on a declare target
4475 // directive must be listed in a data-mapping attribute clause, a
4476 // data-sharing attribute clause (including a data-sharing attribute
4477 // clause on a combined construct where target. is one of the
4478 // constituent constructs), or an is_device_ptr clause.
4479 // For BindingDecls, use the binding's type to determine category.
4481 SemaRef.getLangOpts(), BD ? static_cast<const ValueDecl *>(BD)
4482 : static_cast<const ValueDecl *>(VD));
4483 if (SemaRef.getLangOpts().OpenMP >= 50) {
4484 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
4485 OMPC_DEFAULTMAP_MODIFIER_none;
4486 if (DVar.CKind == OMPC_unknown && IsModifierNone &&
4487 VarsWithInheritedDSA.count(VD) == 0 && !Res) {
4488 // Only check for data-mapping attribute and is_device_ptr here
4489 // since we have already make sure that the declaration does not
4490 // have a data-sharing attribute above
4491 if (!Stack->checkMappableExprComponentListsForDecl(
4492 VD, /*CurrentRegionOnly=*/true,
4494 MapExprComponents,
4496 auto MI = MapExprComponents.rbegin();
4497 auto ME = MapExprComponents.rend();
4498 return MI != ME && MI->getAssociatedDeclaration() == VD;
4499 })) {
4500 VarsWithInheritedDSA[cast<ValueDecl>(
4501 LookupDecl->getCanonicalDecl())] = E;
4502 return;
4503 }
4504 }
4505 }
4506 if (SemaRef.getLangOpts().OpenMP > 50) {
4507 bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
4508 OMPC_DEFAULTMAP_MODIFIER_present;
4509 if (IsModifierPresent) {
4510 if (!llvm::is_contained(ImpInfo.MapModifiers[ClauseKind],
4511 OMPC_MAP_MODIFIER_present)) {
4512 ImpInfo.MapModifiers[ClauseKind].push_back(
4513 OMPC_MAP_MODIFIER_present);
4514 }
4515 }
4516 }
4517
4519 !Stack->isLoopControlVariable(VD).first) {
4520 // Check if VD is already mapped. For DecompositionDecls, also check if
4521 // the original variable they decompose has been mapped (via BindingDecl
4522 // map clauses).
4523 bool AlreadyMapped = Stack->checkMappableExprComponentListsForDecl(
4524 VD, /*CurrentRegionOnly=*/true, [this](auto StackComponents, auto) {
4525 if (SemaRef.LangOpts.OpenMP >= 50)
4526 return !StackComponents.empty();
4527 // Variable is used if it has been marked as an array, array
4528 // section, array shaping or the variable itself.
4529 return StackComponents.size() == 1 ||
4530 llvm::all_of(
4531 llvm::drop_begin(llvm::reverse(StackComponents)),
4532 [](const auto &MC) {
4533 return MC.getAssociatedDeclaration() == nullptr &&
4535 MC.getAssociatedExpression()) ||
4537 MC.getAssociatedExpression()) ||
4539 MC.getAssociatedExpression()));
4540 });
4541 });
4542
4543 // For DecompositionDecls, check if the original variable has been
4544 // mapped.
4545 const auto *DD = dyn_cast<DecompositionDecl>(VD);
4546 if (!AlreadyMapped && DD) {
4547 // Don't diagnose here. Just check if we can extract the original
4548 // var. Diagnostics happen when processing explicit map clauses.
4549 if (const VarDecl *OrigVar = DD->getOriginalVar().Var) {
4550 AlreadyMapped = Stack->checkMappableExprComponentListsForDecl(
4551 OrigVar, /*CurrentRegionOnly=*/true,
4552 [this](auto StackComponents, auto) {
4553 if (SemaRef.LangOpts.OpenMP >= 50)
4554 return !StackComponents.empty();
4555 return StackComponents.size() == 1;
4556 });
4557 }
4558 }
4559 if (!AlreadyMapped) {
4560 bool IsFirstprivate = false;
4561 // By default lambdas are captured as firstprivates.
4562 QualType CheckType = BD ? BD->getType() : VD->getType();
4563 if (const auto *RD =
4565 IsFirstprivate = RD->isLambda();
4566 IsFirstprivate =
4567 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
4568 if (IsFirstprivate) {
4569 ImpInfo.Firstprivates.insert(E);
4570 } else {
4572 Stack->getDefaultmapModifier(ClauseKind);
4573 if (M == OMPC_DEFAULTMAP_MODIFIER_private) {
4574 ImpInfo.Privates.insert(E);
4575 } else {
4577 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res,
4579 ImpInfo.Mappings[ClauseKind][Kind].insert(E);
4580 }
4581 }
4582 return;
4583 }
4584 }
4585
4586 // OpenMP [2.9.3.6, Restrictions, p.2]
4587 // A list item that appears in a reduction clause of the innermost
4588 // enclosing worksharing or parallel construct may not be accessed in an
4589 // explicit task.
4590 DVar = Stack->hasInnermostDSA(
4591 LookupDecl,
4592 [](OpenMPClauseKind C, bool AppliedToPointee) {
4593 return C == OMPC_reduction && !AppliedToPointee;
4594 },
4595 [](OpenMPDirectiveKind K) {
4596 return isOpenMPParallelDirective(K) ||
4598 },
4599 /*FromParent=*/true);
4600 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
4601 ErrorFound = true;
4602 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
4603 reportOriginalDsa(SemaRef, Stack, BD ? LookupDecl : VD, DVar);
4604 return;
4605 }
4606
4607 // Define implicit data-sharing attributes for task.
4608 DVar = Stack->getImplicitDSA(LookupDecl, /*FromParent=*/false);
4609 if (BD && DVar.CKind == OMPC_unknown)
4610 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
4611 if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
4612 (((Stack->getDefaultDSA() == DSA_firstprivate &&
4613 DVar.CKind == OMPC_firstprivate) ||
4614 (Stack->getDefaultDSA() == DSA_private &&
4615 DVar.CKind == OMPC_private)) &&
4616 !DVar.RefExpr)) &&
4617 !Stack->isLoopControlVariable(VD).first) {
4618 if (Stack->getDefaultDSA() == DSA_private)
4619 ImpInfo.Privates.insert(E);
4620 else
4621 ImpInfo.Firstprivates.insert(E);
4622 return;
4623 }
4624
4625 // Store implicitly used globals with declare target link for parent
4626 // target.
4627 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
4628 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
4629 Stack->addToParentTargetRegionLinkGlobals(E);
4630 return;
4631 }
4632 }
4633 }
4634 void VisitMemberExpr(MemberExpr *E) {
4635 if (E->isTypeDependent() || E->isValueDependent() ||
4637 return;
4638 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4639 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
4640 if (!FD)
4641 return;
4642 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
4643 // Check if the variable has explicit DSA set and stop analysis if it
4644 // so.
4645 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
4646 return;
4647
4649 !Stack->isLoopControlVariable(FD).first &&
4650 !Stack->checkMappableExprComponentListsForDecl(
4651 FD, /*CurrentRegionOnly=*/true,
4653 StackComponents,
4655 return isa<CXXThisExpr>(
4656 cast<MemberExpr>(
4657 StackComponents.back().getAssociatedExpression())
4658 ->getBase()
4659 ->IgnoreParens());
4660 })) {
4661 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
4662 // A bit-field cannot appear in a map clause.
4663 //
4664 if (FD->isBitField())
4665 return;
4666
4667 // Check to see if the member expression is referencing a class that
4668 // has already been explicitly mapped
4669 if (Stack->isClassPreviouslyMapped(TE->getType()))
4670 return;
4671
4673 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
4674 OpenMPDefaultmapClauseKind ClauseKind =
4677 Modifier, /*IsAggregateOrDeclareTarget=*/true,
4678 /*HasConstQualifier=*/false);
4679 ImpInfo.Mappings[ClauseKind][Kind].insert(E);
4680 return;
4681 }
4682
4683 SourceLocation ELoc = E->getExprLoc();
4684 // OpenMP [2.9.3.6, Restrictions, p.2]
4685 // A list item that appears in a reduction clause of the innermost
4686 // enclosing worksharing or parallel construct may not be accessed in
4687 // an explicit task.
4688 DVar = Stack->hasInnermostDSA(
4689 FD,
4690 [](OpenMPClauseKind C, bool AppliedToPointee) {
4691 return C == OMPC_reduction && !AppliedToPointee;
4692 },
4693 [](OpenMPDirectiveKind K) {
4694 return isOpenMPParallelDirective(K) ||
4696 },
4697 /*FromParent=*/true);
4698 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
4699 ErrorFound = true;
4700 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
4701 reportOriginalDsa(SemaRef, Stack, FD, DVar);
4702 return;
4703 }
4704
4705 // Define implicit data-sharing attributes for task.
4706 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
4707 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
4708 !Stack->isLoopControlVariable(FD).first) {
4709 // Check if there is a captured expression for the current field in the
4710 // region. Do not mark it as firstprivate unless there is no captured
4711 // expression.
4712 // TODO: try to make it firstprivate.
4713 if (DVar.CKind != OMPC_unknown)
4714 ImpInfo.Firstprivates.insert(E);
4715 }
4716 return;
4717 }
4720 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
4721 DKind, /*NoDiagnose=*/true))
4722 return;
4723 const auto *VD = cast<ValueDecl>(
4724 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
4725 if (!Stack->checkMappableExprComponentListsForDecl(
4726 VD, /*CurrentRegionOnly=*/true,
4727 [&CurComponents](
4729 StackComponents,
4731 auto CCI = CurComponents.rbegin();
4732 auto CCE = CurComponents.rend();
4733 for (const auto &SC : llvm::reverse(StackComponents)) {
4734 // Do both expressions have the same kind?
4735 if (CCI->getAssociatedExpression()->getStmtClass() !=
4736 SC.getAssociatedExpression()->getStmtClass())
4737 if (!((isa<ArraySectionExpr>(
4738 SC.getAssociatedExpression()) ||
4739 isa<OMPArrayShapingExpr>(
4740 SC.getAssociatedExpression())) &&
4741 isa<ArraySubscriptExpr>(
4742 CCI->getAssociatedExpression())))
4743 return false;
4744
4745 const Decl *CCD = CCI->getAssociatedDeclaration();
4746 const Decl *SCD = SC.getAssociatedDeclaration();
4747 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
4748 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
4749 if (SCD != CCD)
4750 return false;
4751 std::advance(CCI, 1);
4752 if (CCI == CCE)
4753 break;
4754 }
4755 return true;
4756 })) {
4757 Visit(E->getBase());
4758 }
4759 } else if (!TryCaptureCXXThisMembers) {
4760 Visit(E->getBase());
4761 }
4762 }
4763 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
4764 for (OMPClause *C : S->clauses()) {
4765 // Skip analysis of arguments of private clauses for task|target
4766 // directives.
4767 if (isa_and_nonnull<OMPPrivateClause>(C))
4768 continue;
4769 // Skip analysis of arguments of implicitly defined firstprivate clause
4770 // for task|target directives.
4771 // Skip analysis of arguments of implicitly defined map clause for target
4772 // directives.
4774 C->isImplicit() && !isOpenMPTaskingDirective(DKind))) {
4775 for (Stmt *CC : C->children()) {
4776 if (CC)
4777 Visit(CC);
4778 }
4779 }
4780 }
4781 // Check implicitly captured variables.
4782 VisitSubCaptures(S);
4783 }
4784
4785 void VisitOMPCanonicalLoopNestTransformationDirective(
4786 OMPCanonicalLoopNestTransformationDirective *S) {
4787 // Loop transformation directives do not introduce data sharing
4788 VisitStmt(S);
4789 }
4790
4791 // A metadirective has no associated statement; visit its variants and
4792 // conditions.
4793 void VisitOMPMetaDirective(OMPMetaDirective *S) { VisitStmt(S); }
4794
4795 void VisitCallExpr(CallExpr *S) {
4796 for (Stmt *C : S->arguments()) {
4797 if (C) {
4798 // Check implicitly captured variables in the task-based directives to
4799 // check if they must be firstprivatized.
4800 Visit(C);
4801 }
4802 }
4803 if (Expr *Callee = S->getCallee()) {
4804 auto *CI = Callee->IgnoreParenImpCasts();
4805 if (auto *CE = dyn_cast<MemberExpr>(CI))
4806 Visit(CE->getBase());
4807 else if (auto *CE = dyn_cast<DeclRefExpr>(CI))
4808 Visit(CE);
4809 }
4810 }
4811 void VisitStmt(Stmt *S) {
4812 for (Stmt *C : S->children()) {
4813 if (C) {
4814 // Check implicitly captured variables in the task-based directives to
4815 // check if they must be firstprivatized.
4816 Visit(C);
4817 }
4818 }
4819 }
4820
4821 void visitSubCaptures(CapturedStmt *S) {
4822 for (const CapturedStmt::Capture &Cap : S->captures()) {
4823 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
4824 continue;
4825 VarDecl *VD = Cap.getCapturedVar();
4826 // Do not try to map the variable if it or its sub-component was mapped
4827 // already.
4829 Stack->checkMappableExprComponentListsForDecl(
4830 VD, /*CurrentRegionOnly=*/true,
4832 OpenMPClauseKind) { return true; }))
4833 continue;
4834 DeclRefExpr *DRE = buildDeclRefExpr(
4835 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
4836 Cap.getLocation(), /*RefersToCapture=*/true);
4837 Visit(DRE);
4838 }
4839 }
4840 bool isErrorFound() const { return ErrorFound; }
4841 const VariableImplicitInfo &getImplicitInfo() const { return ImpInfo; }
4842 const SemaOpenMP::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
4843 return VarsWithInheritedDSA;
4844 }
4845
4846 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
4847 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
4848 DKind = S->getCurrentDirective();
4849 // Process declare target link variables for the target directives.
4851 for (DeclRefExpr *E : Stack->getLinkGlobals())
4852 Visit(E);
4853 }
4854 }
4855};
4856} // namespace
4857
4858static void handleDeclareVariantConstructTrait(DSAStackTy *Stack,
4859 OpenMPDirectiveKind DKind,
4860 bool ScopeEntry) {
4863 Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target);
4864 if (DKind == OMPD_dispatch)
4865 Traits.emplace_back(llvm::omp::TraitProperty::construct_dispatch_dispatch);
4866 if (isOpenMPTeamsDirective(DKind))
4867 Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams);
4868 if (isOpenMPParallelDirective(DKind))
4869 Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel);
4871 Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for);
4872 if (isOpenMPSimdDirective(DKind))
4873 Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd);
4874 Stack->handleConstructTrait(Traits, ScopeEntry);
4875}
4876
4877static SmallVector<SemaOpenMP::CapturedParamNameType>
4878getParallelRegionParams(Sema &SemaRef, bool LoopBoundSharing) {
4879 ASTContext &Context = SemaRef.getASTContext();
4880 QualType KmpInt32Ty =
4881 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1).withConst();
4882 QualType KmpInt32PtrTy =
4883 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4885 std::make_pair(".global_tid.", KmpInt32PtrTy),
4886 std::make_pair(".bound_tid.", KmpInt32PtrTy),
4887 };
4888 if (LoopBoundSharing) {
4889 QualType KmpSizeTy = Context.getSizeType().withConst();
4890 Params.push_back(std::make_pair(".previous.lb.", KmpSizeTy));
4891 Params.push_back(std::make_pair(".previous.ub.", KmpSizeTy));
4892 }
4893
4894 // __context with shared vars
4895 Params.push_back(std::make_pair(StringRef(), QualType()));
4896 return Params;
4897}
4898
4899static SmallVector<SemaOpenMP::CapturedParamNameType>
4901 return getParallelRegionParams(SemaRef, /*LoopBoundSharing=*/false);
4902}
4903
4904static SmallVector<SemaOpenMP::CapturedParamNameType>
4906 ASTContext &Context = SemaRef.getASTContext();
4907 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
4908 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4909 QualType KmpInt32PtrTy =
4910 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4911 QualType Args[] = {VoidPtrTy};
4913 EPI.Variadic = true;
4914 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4916 std::make_pair(".global_tid.", KmpInt32Ty),
4917 std::make_pair(".part_id.", KmpInt32PtrTy),
4918 std::make_pair(".privates.", VoidPtrTy),
4919 std::make_pair(
4920 ".copy_fn.",
4921 Context.getPointerType(CopyFnType).withConst().withRestrict()),
4922 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4923 std::make_pair(StringRef(), QualType()) // __context with shared vars
4924 };
4925 return Params;
4926}
4927
4928static SmallVector<SemaOpenMP::CapturedParamNameType>
4930 ASTContext &Context = SemaRef.getASTContext();
4932 // __context with shared vars
4933 Params.push_back(std::make_pair(StringRef(), QualType()));
4934 // Implicit dyn_ptr argument, appended as the last parameter. Present on both
4935 // host and device so argument counts match without runtime manipulation.
4936 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4937 Params.push_back(std::make_pair(StringRef("dyn_ptr"), VoidPtrTy));
4938 return Params;
4939}
4940
4941static SmallVector<SemaOpenMP::CapturedParamNameType>
4944 std::make_pair(StringRef(), QualType()) // __context with shared vars
4945 };
4946 return Params;
4947}
4948
4949static SmallVector<SemaOpenMP::CapturedParamNameType>
4951 ASTContext &Context = SemaRef.getASTContext();
4952 QualType KmpInt32Ty =
4953 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1).withConst();
4954 QualType KmpUInt64Ty =
4955 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0).withConst();
4956 QualType KmpInt64Ty =
4957 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1).withConst();
4958 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
4959 QualType KmpInt32PtrTy =
4960 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
4961 QualType Args[] = {VoidPtrTy};
4963 EPI.Variadic = true;
4964 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
4966 std::make_pair(".global_tid.", KmpInt32Ty),
4967 std::make_pair(".part_id.", KmpInt32PtrTy),
4968 std::make_pair(".privates.", VoidPtrTy),
4969 std::make_pair(
4970 ".copy_fn.",
4971 Context.getPointerType(CopyFnType).withConst().withRestrict()),
4972 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
4973 std::make_pair(".lb.", KmpUInt64Ty),
4974 std::make_pair(".ub.", KmpUInt64Ty),
4975 std::make_pair(".st.", KmpInt64Ty),
4976 std::make_pair(".liter.", KmpInt32Ty),
4977 std::make_pair(".reductions.", VoidPtrTy),
4978 std::make_pair(StringRef(), QualType()) // __context with shared vars
4979 };
4980 return Params;
4981}
4982
4984 Scope *CurScope, SourceLocation Loc) {
4986 getOpenMPCaptureRegions(Regions, DKind);
4987
4988 bool LoopBoundSharing = isOpenMPLoopBoundSharingDirective(DKind);
4989
4990 auto MarkAsInlined = [&](CapturedRegionScopeInfo *CSI) {
4991 CSI->TheCapturedDecl->addAttr(AlwaysInlineAttr::CreateImplicit(
4992 SemaRef.getASTContext(), {}, AlwaysInlineAttr::Keyword_forceinline));
4993 };
4994
4995 for (auto [Level, RKind] : llvm::enumerate(Regions)) {
4996 switch (RKind) {
4997 // All region kinds that can be returned from `getOpenMPCaptureRegions`
4998 // are listed here.
4999 case OMPD_parallel:
5001 Loc, CurScope, CR_OpenMP,
5002 getParallelRegionParams(SemaRef, LoopBoundSharing), Level);
5003 break;
5004 case OMPD_teams:
5005 SemaRef.ActOnCapturedRegionStart(Loc, CurScope, CR_OpenMP,
5006 getTeamsRegionParams(SemaRef), Level);
5007 break;
5008 case OMPD_task:
5009 SemaRef.ActOnCapturedRegionStart(Loc, CurScope, CR_OpenMP,
5010 getTaskRegionParams(SemaRef), Level);
5011 // Mark this captured region as inlined, because we don't use outlined
5012 // function directly.
5013 MarkAsInlined(SemaRef.getCurCapturedRegion());
5014 break;
5015 case OMPD_taskloop:
5016 SemaRef.ActOnCapturedRegionStart(Loc, CurScope, CR_OpenMP,
5017 getTaskloopRegionParams(SemaRef), Level);
5018 // Mark this captured region as inlined, because we don't use outlined
5019 // function directly.
5020 MarkAsInlined(SemaRef.getCurCapturedRegion());
5021 break;
5022 case OMPD_target:
5023 SemaRef.ActOnCapturedRegionStart(Loc, CurScope, CR_OpenMP,
5024 getTargetRegionParams(SemaRef), Level);
5025 break;
5026 case OMPD_unknown:
5027 SemaRef.ActOnCapturedRegionStart(Loc, CurScope, CR_OpenMP,
5028 getUnknownRegionParams(SemaRef));
5029 break;
5030 case OMPD_metadirective:
5031 case OMPD_nothing:
5032 default:
5033 llvm_unreachable("Unexpected capture region");
5034 }
5035 }
5036}
5037
5039 Scope *CurScope) {
5040 if (DKind == OMPD_ordered_blockassoc &&
5041 DSAStack->getCurrentDirective() == OMPD_ordered_standalone) {
5042 DSAStack->setOrderedToBlockAssociated();
5043 }
5044 switch (DKind) {
5045 case OMPD_atomic:
5046 case OMPD_critical:
5047 case OMPD_masked:
5048 case OMPD_master:
5049 case OMPD_section:
5050 case OMPD_tile:
5051 case OMPD_stripe:
5052 case OMPD_unroll:
5053 case OMPD_reverse:
5054 case OMPD_split:
5055 case OMPD_interchange:
5056 case OMPD_flatten:
5057 case OMPD_fuse:
5058 case OMPD_assume:
5059 break;
5060 default:
5061 processCapturedRegions(SemaRef, DKind, CurScope,
5062 DSAStack->getConstructLoc());
5063 break;
5064 }
5065
5066 DSAStack->setContext(SemaRef.CurContext);
5067 handleDeclareVariantConstructTrait(DSAStack, DKind, /*ScopeEntry=*/true);
5068}
5069
5070int SemaOpenMP::getNumberOfConstructScopes(unsigned Level) const {
5071 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
5072}
5073
5076 getOpenMPCaptureRegions(CaptureRegions, DKind);
5077 return CaptureRegions.size();
5078}
5079
5081 Expr *CaptureExpr, bool WithInit,
5082 DeclContext *CurContext,
5083 bool AsExpression) {
5084 assert(CaptureExpr);
5085 ASTContext &C = S.getASTContext();
5086 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
5087 QualType Ty = Init->getType();
5088 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
5089 if (S.getLangOpts().CPlusPlus) {
5090 Ty = C.getLValueReferenceType(Ty);
5091 } else {
5092 Ty = C.getPointerType(Ty);
5093 ExprResult Res =
5094 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
5095 if (!Res.isUsable())
5096 return nullptr;
5097 Init = Res.get();
5098 }
5099 WithInit = true;
5100 }
5101 auto *CED = OMPCapturedExprDecl::Create(C, CurContext, Id, Ty,
5102 CaptureExpr->getBeginLoc());
5103 if (!WithInit)
5104 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
5105 CurContext->addHiddenDecl(CED);
5107 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
5108 return CED;
5109}
5110
5111static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
5112 bool WithInit) {
5114 // For BindingDecls, always create a new capture instead of reusing the
5115 // decomposed decl, since the decomposed decl is a regular VarDecl, not an
5116 // OMPCapturedExprDecl.
5117 if (!isa<BindingDecl>(D)) {
5118 if (VarDecl *VD = S.OpenMP().isOpenMPCapturedDecl(D))
5120 else
5121 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
5122 S.CurContext,
5123 /*AsExpression=*/false);
5124 } else {
5125 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
5126 S.CurContext,
5127 /*AsExpression=*/false);
5128 }
5129 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
5130 CaptureExpr->getExprLoc());
5131}
5132
5133static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref,
5134 StringRef Name) {
5135 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
5136 if (!Ref) {
5138 S, &S.getASTContext().Idents.get(Name), CaptureExpr,
5139 /*WithInit=*/true, S.CurContext, /*AsExpression=*/true);
5140 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
5141 CaptureExpr->getExprLoc());
5142 }
5143 ExprResult Res = Ref;
5144 if (!S.getLangOpts().CPlusPlus &&
5145 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
5146 Ref->getType()->isPointerType()) {
5147 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
5148 if (!Res.isUsable())
5149 return ExprError();
5150 }
5151 return S.DefaultLvalueConversion(Res.get());
5152}
5153
5154namespace {
5155// OpenMP directives parsed in this section are represented as a
5156// CapturedStatement with an associated statement. If a syntax error
5157// is detected during the parsing of the associated statement, the
5158// compiler must abort processing and close the CapturedStatement.
5159//
5160// Combined directives such as 'target parallel' have more than one
5161// nested CapturedStatements. This RAII ensures that we unwind out
5162// of all the nested CapturedStatements when an error is found.
5163class CaptureRegionUnwinderRAII {
5164private:
5165 Sema &S;
5166 bool &ErrorFound;
5167 OpenMPDirectiveKind DKind = OMPD_unknown;
5168
5169public:
5170 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
5171 OpenMPDirectiveKind DKind)
5172 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
5173 ~CaptureRegionUnwinderRAII() {
5174 if (ErrorFound) {
5175 int ThisCaptureLevel = S.OpenMP().getOpenMPCaptureLevels(DKind);
5176 while (--ThisCaptureLevel >= 0)
5178 }
5179 }
5180};
5181} // namespace
5182
5184 // Capture variables captured by reference in lambdas for target-based
5185 // directives.
5186 if (!SemaRef.CurContext->isDependentContext() &&
5187 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
5189 DSAStack->getCurrentDirective()))) {
5190 QualType Type = V->getType();
5191 if (const auto *RD = Type.getCanonicalType()
5192 .getNonReferenceType()
5193 ->getAsCXXRecordDecl()) {
5194 bool SavedForceCaptureByReferenceInTargetExecutable =
5195 DSAStack->isForceCaptureByReferenceInTargetExecutable();
5196 DSAStack->setForceCaptureByReferenceInTargetExecutable(
5197 /*V=*/true);
5198 if (RD->isLambda()) {
5199 llvm::DenseMap<const ValueDecl *, FieldDecl *> Captures;
5200 FieldDecl *ThisCapture;
5201 RD->getCaptureFields(Captures, ThisCapture);
5202 for (const LambdaCapture &LC : RD->captures()) {
5203 if (LC.getCaptureKind() == LCK_ByRef) {
5204 VarDecl *VD = cast<VarDecl>(LC.getCapturedVar());
5205 DeclContext *VDC = VD->getDeclContext();
5206 if (!VDC->Encloses(SemaRef.CurContext))
5207 continue;
5208 SemaRef.MarkVariableReferenced(LC.getLocation(), VD);
5209 } else if (LC.getCaptureKind() == LCK_This) {
5210 QualType ThisTy = SemaRef.getCurrentThisType();
5211 if (!ThisTy.isNull() && getASTContext().typesAreCompatible(
5212 ThisTy, ThisCapture->getType()))
5213 SemaRef.CheckCXXThisCapture(LC.getLocation());
5214 }
5215 }
5216 }
5217 DSAStack->setForceCaptureByReferenceInTargetExecutable(
5218 SavedForceCaptureByReferenceInTargetExecutable);
5219 }
5220 }
5221}
5222
5224 const ArrayRef<OMPClause *> Clauses) {
5225 const OMPOrderedClause *Ordered = nullptr;
5226 const OMPOrderClause *Order = nullptr;
5227
5228 for (const OMPClause *Clause : Clauses) {
5229 if (Clause->getClauseKind() == OMPC_ordered)
5230 Ordered = cast<OMPOrderedClause>(Clause);
5231 else if (Clause->getClauseKind() == OMPC_order) {
5232 Order = cast<OMPOrderClause>(Clause);
5233 if (Order->getKind() != OMPC_ORDER_concurrent)
5234 Order = nullptr;
5235 }
5236 if (Ordered && Order)
5237 break;
5238 }
5239
5240 if (Ordered && Order) {
5241 S.Diag(Order->getKindKwLoc(),
5242 diag::err_omp_simple_clause_incompatible_with_ordered)
5243 << getOpenMPClauseNameForDiag(OMPC_order)
5244 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
5245 << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
5246 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
5247 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
5248 return true;
5249 }
5250 return false;
5251}
5252
5254 ArrayRef<OMPClause *> Clauses) {
5256 /*ScopeEntry=*/false);
5257 if (!isOpenMPCapturingDirective(DSAStack->getCurrentDirective()))
5258 return S;
5259
5260 bool ErrorFound = false;
5261 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
5262 SemaRef, ErrorFound, DSAStack->getCurrentDirective());
5263 if (!S.isUsable()) {
5264 ErrorFound = true;
5265 return StmtError();
5266 }
5267
5269 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
5270 OMPOrderedClause *OC = nullptr;
5271 OMPScheduleClause *SC = nullptr;
5274 // This is required for proper codegen.
5275 for (OMPClause *Clause : Clauses) {
5276 if (!getLangOpts().OpenMPSimd &&
5277 (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) ||
5278 DSAStack->getCurrentDirective() == OMPD_target) &&
5279 Clause->getClauseKind() == OMPC_in_reduction) {
5280 // Capture taskgroup task_reduction descriptors inside the tasking regions
5281 // with the corresponding in_reduction items.
5282 auto *IRC = cast<OMPInReductionClause>(Clause);
5283 for (Expr *E : IRC->taskgroup_descriptors())
5284 if (E)
5285 SemaRef.MarkDeclarationsReferencedInExpr(E);
5286 }
5287 if (isOpenMPPrivate(Clause->getClauseKind()) ||
5288 Clause->getClauseKind() == OMPC_copyprivate ||
5289 (getLangOpts().OpenMPUseTLS &&
5290 getASTContext().getTargetInfo().isTLSSupported() &&
5291 Clause->getClauseKind() == OMPC_copyin)) {
5292 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
5293 // Mark all variables in private list clauses as used in inner region.
5294 for (Stmt *VarRef : Clause->children()) {
5295 if (auto *E = cast_or_null<Expr>(VarRef)) {
5296 SemaRef.MarkDeclarationsReferencedInExpr(E);
5297 }
5298 }
5299 DSAStack->setForceVarCapturing(/*V=*/false);
5300 } else if (CaptureRegions.size() > 1 ||
5301 CaptureRegions.back() != OMPD_unknown) {
5302 if (auto *C = OMPClauseWithPreInit::get(Clause))
5303 PICs.push_back(C);
5304 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
5305 if (Expr *E = C->getPostUpdateExpr())
5306 SemaRef.MarkDeclarationsReferencedInExpr(E);
5307 }
5308 }
5309 if (Clause->getClauseKind() == OMPC_schedule)
5310 SC = cast<OMPScheduleClause>(Clause);
5311 else if (Clause->getClauseKind() == OMPC_ordered)
5312 OC = cast<OMPOrderedClause>(Clause);
5313 else if (Clause->getClauseKind() == OMPC_linear)
5314 LCs.push_back(cast<OMPLinearClause>(Clause));
5315 }
5316 // Capture allocator expressions if used.
5317 for (Expr *E : DSAStack->getInnerAllocators())
5318 SemaRef.MarkDeclarationsReferencedInExpr(E);
5319 // OpenMP, 2.7.1 Loop Construct, Restrictions
5320 // The nonmonotonic modifier cannot be specified if an ordered clause is
5321 // specified.
5322 if (SC &&
5323 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
5324 SC->getSecondScheduleModifier() ==
5325 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
5326 OC) {
5327 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
5328 ? SC->getFirstScheduleModifierLoc()
5329 : SC->getSecondScheduleModifierLoc(),
5330 diag::err_omp_simple_clause_incompatible_with_ordered)
5331 << getOpenMPClauseNameForDiag(OMPC_schedule)
5332 << getOpenMPSimpleClauseTypeName(OMPC_schedule,
5333 OMPC_SCHEDULE_MODIFIER_nonmonotonic)
5334 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
5335 ErrorFound = true;
5336 }
5337 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
5338 // If an order(concurrent) clause is present, an ordered clause may not appear
5339 // on the same directive.
5340 if (checkOrderedOrderSpecified(SemaRef, Clauses))
5341 ErrorFound = true;
5342 if (!LCs.empty() && OC && OC->getNumForLoops()) {
5343 for (const OMPLinearClause *C : LCs) {
5344 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
5345 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
5346 }
5347 ErrorFound = true;
5348 }
5349 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
5350 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
5351 OC->getNumForLoops()) {
5352 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
5353 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
5354 << getOpenMPDirectiveName(DSAStack->getCurrentDirective(), OMPVersion);
5355 ErrorFound = true;
5356 }
5357 if (ErrorFound) {
5358 return StmtError();
5359 }
5360 StmtResult SR = S;
5361 unsigned CompletedRegions = 0;
5362 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
5363 // Mark all variables in private list clauses as used in inner region.
5364 // Required for proper codegen of combined directives.
5365 // TODO: add processing for other clauses.
5366 if (ThisCaptureRegion != OMPD_unknown) {
5367 for (const clang::OMPClauseWithPreInit *C : PICs) {
5368 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
5369 // Find the particular capture region for the clause if the
5370 // directive is a combined one with multiple capture regions.
5371 // If the directive is not a combined one, the capture region
5372 // associated with the clause is OMPD_unknown and is generated
5373 // only once.
5374 if (CaptureRegion == ThisCaptureRegion ||
5375 CaptureRegion == OMPD_unknown) {
5376 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
5377 for (Decl *D : DS->decls())
5378 SemaRef.MarkVariableReferenced(D->getLocation(),
5379 cast<VarDecl>(D));
5380 }
5381 }
5382 }
5383 }
5384 if (ThisCaptureRegion == OMPD_target) {
5385 // Capture allocator traits in the target region. They are used implicitly
5386 // and, thus, are not captured by default.
5387 for (OMPClause *C : Clauses) {
5388 if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
5389 for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
5390 ++I) {
5391 OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
5392 if (Expr *E = D.AllocatorTraits)
5393 SemaRef.MarkDeclarationsReferencedInExpr(E);
5394 }
5395 continue;
5396 }
5397 }
5398 }
5399 if (ThisCaptureRegion == OMPD_parallel) {
5400 // Capture temp arrays for inscan reductions and locals in aligned
5401 // clauses.
5402 for (OMPClause *C : Clauses) {
5403 if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
5404 if (RC->getModifier() != OMPC_REDUCTION_inscan)
5405 continue;
5406 for (Expr *E : RC->copy_array_temps())
5407 if (E)
5408 SemaRef.MarkDeclarationsReferencedInExpr(E);
5409 }
5410 if (auto *AC = dyn_cast<OMPAlignedClause>(C)) {
5411 for (Expr *E : AC->varlist())
5412 SemaRef.MarkDeclarationsReferencedInExpr(E);
5413 }
5414 }
5415 }
5416 if (++CompletedRegions == CaptureRegions.size())
5417 DSAStack->setBodyComplete();
5418 SR = SemaRef.ActOnCapturedRegionEnd(SR.get());
5419 }
5420 return SR;
5421}
5422
5423static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
5424 OpenMPDirectiveKind CancelRegion,
5425 SourceLocation StartLoc) {
5426 // CancelRegion is only needed for cancel and cancellation_point.
5427 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
5428 return false;
5429
5430 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
5431 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
5432 return false;
5433
5434 llvm::omp::Version OMPVersion = SemaRef.getLangOpts().getOpenMPVersion();
5435 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
5436 << getOpenMPDirectiveName(CancelRegion, OMPVersion);
5437 return true;
5438}
5439
5440static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
5441 OpenMPDirectiveKind CurrentRegion,
5442 const DeclarationNameInfo &CurrentName,
5443 OpenMPDirectiveKind CancelRegion,
5444 OpenMPBindClauseKind BindKind,
5445 SourceLocation StartLoc) {
5446 if (!Stack->getCurScope())
5447 return false;
5448
5449 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
5450 OpenMPDirectiveKind OffendingRegion = ParentRegion;
5451 bool NestingProhibited = false;
5452 bool CloseNesting = true;
5453 bool OrphanSeen = false;
5454 enum {
5455 NoRecommend,
5456 ShouldBeInParallelRegion,
5457 ShouldBeInOrderedRegion,
5458 ShouldBeInTargetRegion,
5459 ShouldBeInTeamsRegion,
5460 ShouldBeInLoopSimdRegion,
5461 } Recommend = NoRecommend;
5462
5465 getLeafOrCompositeConstructs(ParentRegion, LeafOrComposite);
5466 OpenMPDirectiveKind EnclosingConstruct = ParentLOC.back();
5467 llvm::omp::Version OMPVersion = SemaRef.getLangOpts().getOpenMPVersion();
5468
5469 if (OMPVersion >= 50 && Stack->isEnclosingOrderConcurrent() &&
5471 SemaRef.LangOpts)) {
5472 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_order)
5473 << getOpenMPDirectiveName(CurrentRegion, OMPVersion);
5474 return true;
5475 }
5476 // A construct nested in a loop-transforming or ordered construct is still
5477 // encountered during execution of an enclosing simd region.
5478 if (Stack->isInSimdRegion() &&
5479 ((OMPVersion <= 45 && CurrentRegion != OMPD_ordered_blockassoc) ||
5480 (OMPVersion >= 50 && !isOpenMPSimdizableDirective(
5481 CurrentRegion, BindKind, SemaRef.LangOpts)))) {
5482 // OpenMP [2.16, Nesting of Regions]
5483 // OpenMP constructs may not be nested inside a simd region.
5484 // OpenMP [2.8.1,simd Construct, Restrictions]
5485 // An ordered construct with the simd clause is the only OpenMP
5486 // construct that can appear in the simd region.
5487 // Allowing a SIMD construct nested in another SIMD construct is an
5488 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
5489 // message.
5490 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
5491 // The only OpenMP constructs that can be encountered during execution of
5492 // a simd region are the atomic construct, the loop construct, the simd
5493 // construct and the ordered construct with the simd clause.
5494 // OpenMP 5.2 [10.4, simd Construct, Restrictions]
5495 // Only simdizable constructs can be encountered during execution of a
5496 // simd region.
5497 // OpenMP 6.0 makes all loop-transforming constructs simdizable.
5498 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
5499 ? diag::err_omp_prohibited_region_simd
5500 : diag::warn_omp_nesting_simd)
5501 << (OMPVersion >= 60 ? 2
5502 : OMPVersion >= 50 ? 1
5503 : 0);
5504 return CurrentRegion != OMPD_simd;
5505 }
5506 if (EnclosingConstruct == OMPD_atomic) {
5507 // OpenMP [2.16, Nesting of Regions]
5508 // OpenMP constructs may not be nested inside an atomic region.
5509 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
5510 return true;
5511 }
5512 if (CurrentRegion == OMPD_section) {
5513 // OpenMP [2.7.2, sections Construct, Restrictions]
5514 // Orphaned section directives are prohibited. That is, the section
5515 // directives must appear within the sections construct and must not be
5516 // encountered elsewhere in the sections region.
5517 if (EnclosingConstruct != OMPD_sections) {
5518 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
5519 << (ParentRegion != OMPD_unknown)
5520 << getOpenMPDirectiveName(ParentRegion, OMPVersion);
5521 return true;
5522 }
5523 return false;
5524 }
5525 // Allow some constructs (except teams and cancellation constructs) to be
5526 // orphaned (they could be used in functions, called from OpenMP regions
5527 // with the required preconditions).
5528 if (ParentRegion == OMPD_unknown &&
5529 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
5530 CurrentRegion != OMPD_cancellation_point &&
5531 CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
5532 return false;
5533 // Checks needed for mapping "loop" construct. Please check mapLoopConstruct
5534 // for a detailed explanation
5535 if (OMPVersion >= 50 && CurrentRegion == OMPD_loop &&
5536 (BindKind == OMPC_BIND_parallel || BindKind == OMPC_BIND_teams) &&
5537 (isOpenMPWorksharingDirective(ParentRegion) ||
5538 EnclosingConstruct == OMPD_loop)) {
5539 int ErrorMsgNumber = (BindKind == OMPC_BIND_parallel) ? 1 : 4;
5540 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
5541 << true << getOpenMPDirectiveName(ParentRegion, OMPVersion)
5542 << ErrorMsgNumber << getOpenMPDirectiveName(CurrentRegion, OMPVersion);
5543 return true;
5544 }
5545 if (CurrentRegion == OMPD_cancellation_point ||
5546 CurrentRegion == OMPD_cancel) {
5547 // OpenMP [2.16, Nesting of Regions]
5548 // A cancellation point construct for which construct-type-clause is
5549 // taskgroup must be nested inside a task construct. A cancellation
5550 // point construct for which construct-type-clause is not taskgroup must
5551 // be closely nested inside an OpenMP construct that matches the type
5552 // specified in construct-type-clause.
5553 // A cancel construct for which construct-type-clause is taskgroup must be
5554 // nested inside a task construct. A cancel construct for which
5555 // construct-type-clause is not taskgroup must be closely nested inside an
5556 // OpenMP construct that matches the type specified in
5557 // construct-type-clause.
5558 ArrayRef<OpenMPDirectiveKind> Leafs = getLeafConstructsOrSelf(ParentRegion);
5559 if (CancelRegion == OMPD_taskgroup) {
5560 NestingProhibited =
5561 EnclosingConstruct != OMPD_task &&
5562 (OMPVersion < 50 || EnclosingConstruct != OMPD_taskloop);
5563 } else if (CancelRegion == OMPD_sections) {
5564 NestingProhibited = EnclosingConstruct != OMPD_section &&
5565 EnclosingConstruct != OMPD_sections;
5566 } else {
5567 NestingProhibited = CancelRegion != Leafs.back();
5568 }
5569 OrphanSeen = ParentRegion == OMPD_unknown;
5570 } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
5571 // OpenMP 5.1 [2.22, Nesting of Regions]
5572 // A masked region may not be closely nested inside a worksharing, loop,
5573 // atomic, task, or taskloop region.
5574 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
5575 isOpenMPGenericLoopDirective(ParentRegion) ||
5576 isOpenMPTaskingDirective(ParentRegion);
5577 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
5578 // OpenMP [2.16, Nesting of Regions]
5579 // A critical region may not be nested (closely or otherwise) inside a
5580 // critical region with the same name. Note that this restriction is not
5581 // sufficient to prevent deadlock.
5582 SourceLocation PreviousCriticalLoc;
5583 bool DeadLock = Stack->hasDirective(
5584 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
5585 const DeclarationNameInfo &DNI,
5586 SourceLocation Loc) {
5587 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
5588 PreviousCriticalLoc = Loc;
5589 return true;
5590 }
5591 return false;
5592 },
5593 false /* skip top directive */);
5594 if (DeadLock) {
5595 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_critical_same_name)
5596 << CurrentName.getName();
5597 if (PreviousCriticalLoc.isValid())
5598 SemaRef.Diag(PreviousCriticalLoc,
5599 diag::note_omp_previous_critical_region);
5600 return true;
5601 }
5602 } else if (CurrentRegion == OMPD_barrier || CurrentRegion == OMPD_scope) {
5603 // OpenMP 5.1 [2.22, Nesting of Regions]
5604 // A scope region may not be closely nested inside a worksharing, loop,
5605 // task, taskloop, critical, ordered, atomic, or masked region.
5606 // OpenMP 5.1 [2.22, Nesting of Regions]
5607 // A barrier region may not be closely nested inside a worksharing, loop,
5608 // task, taskloop, critical, ordered, atomic, or masked region.
5609 NestingProhibited =
5610 isOpenMPWorksharingDirective(ParentRegion) ||
5611 isOpenMPGenericLoopDirective(ParentRegion) ||
5612 isOpenMPTaskingDirective(ParentRegion) ||
5613 llvm::is_contained(
5614 {OMPD_masked, OMPD_master, OMPD_critical, OMPD_ordered_blockassoc},
5615 EnclosingConstruct);
5616 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
5617 !isOpenMPParallelDirective(CurrentRegion) &&
5618 !isOpenMPTeamsDirective(CurrentRegion)) {
5619 // OpenMP 5.1 [2.22, Nesting of Regions]
5620 // A loop region that binds to a parallel region or a worksharing region
5621 // may not be closely nested inside a worksharing, loop, task, taskloop,
5622 // critical, ordered, atomic, or masked region.
5623 NestingProhibited =
5624 isOpenMPWorksharingDirective(ParentRegion) ||
5625 isOpenMPGenericLoopDirective(ParentRegion) ||
5626 isOpenMPTaskingDirective(ParentRegion) ||
5627 llvm::is_contained(
5628 {OMPD_masked, OMPD_master, OMPD_critical, OMPD_ordered_blockassoc},
5629 EnclosingConstruct);
5630 Recommend = ShouldBeInParallelRegion;
5631 } else if (CurrentRegion == OMPD_ordered_blockassoc ||
5632 CurrentRegion == OMPD_ordered_standalone) {
5633 // OpenMP [2.16, Nesting of Regions]
5634 // An ordered region may not be closely nested inside a critical,
5635 // atomic, or explicit task region.
5636 // An ordered region must be closely nested inside a loop region (or
5637 // parallel loop region) with an ordered clause.
5638 // OpenMP [2.8.1,simd Construct, Restrictions]
5639 // An ordered construct with the simd clause is the only OpenMP construct
5640 // that can appear in the simd region.
5641 NestingProhibited = EnclosingConstruct == OMPD_critical ||
5642 isOpenMPTaskingDirective(ParentRegion) ||
5643 !(isOpenMPSimdDirective(ParentRegion) ||
5644 Stack->isParentOrderedRegion());
5645 Recommend = ShouldBeInOrderedRegion;
5646 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
5647 // OpenMP [2.16, Nesting of Regions]
5648 // If specified, a teams construct must be contained within a target
5649 // construct.
5650 NestingProhibited =
5651 (OMPVersion <= 45 && EnclosingConstruct != OMPD_target) ||
5652 (OMPVersion >= 50 && EnclosingConstruct != OMPD_unknown &&
5653 EnclosingConstruct != OMPD_target);
5654 OrphanSeen = ParentRegion == OMPD_unknown;
5655 Recommend = ShouldBeInTargetRegion;
5656 } else if (CurrentRegion == OMPD_scan) {
5657 if (OMPVersion >= 50) {
5658 // OpenMP spec 5.0 and 5.1 require scan to be directly enclosed by for,
5659 // simd, or for simd. This has to take into account combined directives.
5660 // In 5.2 this seems to be implied by the fact that the specified
5661 // separated constructs are do, for, and simd.
5662 NestingProhibited = !llvm::is_contained(
5663 {OMPD_for, OMPD_simd, OMPD_for_simd}, EnclosingConstruct);
5664 } else {
5665 NestingProhibited = true;
5666 }
5667 OrphanSeen = ParentRegion == OMPD_unknown;
5668 Recommend = ShouldBeInLoopSimdRegion;
5669 }
5670 if (!NestingProhibited && !isOpenMPTargetExecutionDirective(CurrentRegion) &&
5671 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
5672 EnclosingConstruct == OMPD_teams) {
5673 // OpenMP [5.1, 2.22, Nesting of Regions]
5674 // distribute, distribute simd, distribute parallel worksharing-loop,
5675 // distribute parallel worksharing-loop SIMD, loop, parallel regions,
5676 // including any parallel regions arising from combined constructs,
5677 // omp_get_num_teams() regions, and omp_get_team_num() regions are the
5678 // only OpenMP regions that may be strictly nested inside the teams
5679 // region.
5680 //
5681 // As an extension, we permit atomic within teams as well.
5682 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
5683 !isOpenMPDistributeDirective(CurrentRegion) &&
5684 CurrentRegion != OMPD_loop &&
5685 !(SemaRef.getLangOpts().OpenMPExtensions &&
5686 CurrentRegion == OMPD_atomic);
5687 Recommend = ShouldBeInParallelRegion;
5688 }
5689 if (!NestingProhibited && CurrentRegion == OMPD_loop) {
5690 // OpenMP [5.1, 2.11.7, loop Construct, Restrictions]
5691 // If the bind clause is present on the loop construct and binding is
5692 // teams then the corresponding loop region must be strictly nested inside
5693 // a teams region.
5694 NestingProhibited =
5695 BindKind == OMPC_BIND_teams && EnclosingConstruct != OMPD_teams;
5696 Recommend = ShouldBeInTeamsRegion;
5697 }
5698 if (!NestingProhibited && isOpenMPNestingDistributeDirective(CurrentRegion)) {
5699 // OpenMP 4.5 [2.17 Nesting of Regions]
5700 // The region associated with the distribute construct must be strictly
5701 // nested inside a teams region
5702 NestingProhibited = EnclosingConstruct != OMPD_teams;
5703 Recommend = ShouldBeInTeamsRegion;
5704 }
5705 if (!NestingProhibited &&
5706 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
5707 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
5708 // OpenMP 4.5 [2.17 Nesting of Regions]
5709 // If a target, target update, target data, target enter data, or
5710 // target exit data construct is encountered during execution of a
5711 // target region, the behavior is unspecified.
5712 NestingProhibited = Stack->hasDirective(
5713 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
5716 OffendingRegion = K;
5717 return true;
5718 }
5719 return false;
5720 },
5721 false /* don't skip top directive */);
5722 CloseNesting = false;
5723 }
5724 if (NestingProhibited) {
5725 if (OrphanSeen) {
5726 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
5727 << getOpenMPDirectiveName(CurrentRegion, OMPVersion) << Recommend;
5728 } else {
5729 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
5730 << CloseNesting << getOpenMPDirectiveName(OffendingRegion, OMPVersion)
5731 << Recommend << getOpenMPDirectiveName(CurrentRegion, OMPVersion);
5732 }
5733 return true;
5734 }
5735 return false;
5736}
5737
5743 ArrayRef<OMPClause *> Clauses,
5744 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
5745 bool ErrorFound = false;
5746 unsigned NamedModifiersNumber = 0;
5747 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
5748 FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
5749 SmallVector<SourceLocation, 4> NameModifierLoc;
5750 llvm::omp::Version OMPVersion = S.getLangOpts().getOpenMPVersion();
5751 for (const OMPClause *C : Clauses) {
5752 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
5753 // At most one if clause without a directive-name-modifier can appear on
5754 // the directive.
5755 OpenMPDirectiveKind CurNM = IC->getNameModifier();
5756 auto &FNM = FoundNameModifiers[CurNM];
5757 if (FNM) {
5758 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
5759 << getOpenMPDirectiveName(Kind, OMPVersion)
5760 << getOpenMPClauseNameForDiag(OMPC_if) << (CurNM != OMPD_unknown)
5761 << getOpenMPDirectiveName(CurNM, OMPVersion);
5762 ErrorFound = true;
5763 } else if (CurNM != OMPD_unknown) {
5764 NameModifierLoc.push_back(IC->getNameModifierLoc());
5765 ++NamedModifiersNumber;
5766 }
5767 FNM = IC;
5768 if (CurNM == OMPD_unknown)
5769 continue;
5770 // Check if the specified name modifier is allowed for the current
5771 // directive.
5772 // At most one if clause with the particular directive-name-modifier can
5773 // appear on the directive.
5774 if (!llvm::is_contained(AllowedNameModifiers, CurNM)) {
5775 S.Diag(IC->getNameModifierLoc(),
5776 diag::err_omp_wrong_if_directive_name_modifier)
5777 << getOpenMPDirectiveName(CurNM, OMPVersion)
5778 << getOpenMPDirectiveName(Kind, OMPVersion);
5779 ErrorFound = true;
5780 }
5781 }
5782 }
5783 // If any if clause on the directive includes a directive-name-modifier then
5784 // all if clauses on the directive must include a directive-name-modifier.
5785 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
5786 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
5787 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
5788 diag::err_omp_no_more_if_clause);
5789 } else {
5790 std::string Values;
5791 std::string Sep(", ");
5792 unsigned AllowedCnt = 0;
5793 unsigned TotalAllowedNum =
5794 AllowedNameModifiers.size() - NamedModifiersNumber;
5795 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
5796 ++Cnt) {
5797 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
5798 if (!FoundNameModifiers[NM]) {
5799 Values += "'";
5800 Values += getOpenMPDirectiveName(NM, OMPVersion);
5801 Values += "'";
5802 if (AllowedCnt + 2 == TotalAllowedNum)
5803 Values += " or ";
5804 else if (AllowedCnt + 1 != TotalAllowedNum)
5805 Values += Sep;
5806 ++AllowedCnt;
5807 }
5808 }
5809 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
5810 diag::err_omp_unnamed_if_clause)
5811 << (TotalAllowedNum > 1) << Values;
5812 }
5813 for (SourceLocation Loc : NameModifierLoc) {
5814 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
5815 }
5816 ErrorFound = true;
5817 }
5818 return ErrorFound;
5819}
5820
5821static std::pair<ValueDecl *, bool>
5823 SourceRange &ERange, bool AllowArraySection,
5824 bool AllowAssumedSizeArray, StringRef DiagType) {
5825 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
5827 return std::make_pair(nullptr, true);
5828
5829 // OpenMP [3.1, C/C++]
5830 // A list item is a variable name.
5831 // OpenMP [2.9.3.3, Restrictions, p.1]
5832 // A variable that is part of another variable (as an array or
5833 // structure element) cannot appear in a private clause.
5834 //
5835 // OpenMP [6.0]
5836 // 5.2.5 Array Sections, p. 166, L28-29
5837 // When the length is absent and the size of the dimension is not known,
5838 // the array section is an assumed-size array.
5839 // 2 Glossary, p. 23, L4-6
5840 // assumed-size array
5841 // For C/C++, an array section for which the length is absent and the
5842 // size of the dimensions is not known.
5843 // 5.2.5 Array Sections, p. 168, L11
5844 // An assumed-size array can appear only in clauses for which it is
5845 // explicitly allowed.
5846 // 7.4 List Item Privatization, Restrictions, p. 222, L15
5847 // Assumed-size arrays must not be privatized.
5848 RefExpr = RefExpr->IgnoreParens();
5849 enum {
5850 NoArrayExpr = -1,
5851 ArraySubscript = 0,
5852 OMPArraySection = 1
5853 } IsArrayExpr = NoArrayExpr;
5854 if (AllowArraySection) {
5855 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
5856 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
5857 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5858 Base = TempASE->getBase()->IgnoreParenImpCasts();
5859 RefExpr = Base;
5860 IsArrayExpr = ArraySubscript;
5861 } else if (auto *OASE = dyn_cast_or_null<ArraySectionExpr>(RefExpr)) {
5862 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
5863 if (S.getLangOpts().OpenMP >= 60 && !AllowAssumedSizeArray &&
5864 OASE->getColonLocFirst().isValid() && !OASE->getLength()) {
5866 if (BaseType.isNull() || (!BaseType->isConstantArrayType() &&
5867 !BaseType->isVariableArrayType())) {
5868 S.Diag(OASE->getColonLocFirst(),
5869 diag::err_omp_section_length_undefined)
5870 << (!BaseType.isNull() && BaseType->isArrayType());
5871 return std::make_pair(nullptr, false);
5872 }
5873 }
5874 while (auto *TempOASE = dyn_cast<ArraySectionExpr>(Base))
5875 Base = TempOASE->getBase()->IgnoreParenImpCasts();
5876 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
5877 Base = TempASE->getBase()->IgnoreParenImpCasts();
5878 RefExpr = Base;
5879 IsArrayExpr = OMPArraySection;
5880 }
5881 }
5882 ELoc = RefExpr->getExprLoc();
5883 ERange = RefExpr->getSourceRange();
5884 RefExpr = RefExpr->IgnoreParenImpCasts();
5885 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
5886 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
5887 if ((!DE || !isa<VarDecl, BindingDecl>(DE->getDecl())) &&
5888 (S.getCurrentThisType().isNull() || !ME ||
5889 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
5890 !isa<FieldDecl>(ME->getMemberDecl()))) {
5891 if (IsArrayExpr != NoArrayExpr) {
5892 S.Diag(ELoc, diag::err_omp_expected_base_var_name)
5893 << IsArrayExpr << ERange;
5894 } else if (!DiagType.empty()) {
5895 unsigned DiagSelect = S.getLangOpts().CPlusPlus
5896 ? (S.getCurrentThisType().isNull() ? 1 : 2)
5897 : 0;
5898 S.Diag(ELoc, diag::err_omp_expected_var_name_member_expr_with_type)
5899 << DiagSelect << DiagType << ERange;
5900 } else {
5901 S.Diag(ELoc,
5902 AllowArraySection
5903 ? diag::err_omp_expected_var_name_member_expr_or_array_item
5904 : diag::err_omp_expected_var_name_member_expr)
5905 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
5906 }
5907 return std::make_pair(nullptr, false);
5908 }
5909 return std::make_pair(
5910 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
5911}
5912
5913namespace {
5914/// Checks if the allocator is used in uses_allocators clause to be allowed in
5915/// target regions.
5916class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
5917 DSAStackTy *S = nullptr;
5918
5919public:
5920 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5921 return S->isUsesAllocatorsDecl(E->getDecl())
5922 .value_or(DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
5923 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
5924 }
5925 bool VisitStmt(const Stmt *S) {
5926 for (const Stmt *Child : S->children()) {
5927 if (Child && Visit(Child))
5928 return true;
5929 }
5930 return false;
5931 }
5932 explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
5933};
5934} // namespace
5935
5936static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
5937 ArrayRef<OMPClause *> Clauses) {
5938 assert(!S.CurContext->isDependentContext() &&
5939 "Expected non-dependent context.");
5940 auto AllocateRange =
5941 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
5942 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy;
5943 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
5944 return isOpenMPPrivate(C->getClauseKind());
5945 });
5946 for (OMPClause *Cl : PrivateRange) {
5948 if (Cl->getClauseKind() == OMPC_private) {
5949 auto *PC = cast<OMPPrivateClause>(Cl);
5950 I = PC->private_copies().begin();
5951 It = PC->varlist_begin();
5952 Et = PC->varlist_end();
5953 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
5954 auto *PC = cast<OMPFirstprivateClause>(Cl);
5955 I = PC->private_copies().begin();
5956 It = PC->varlist_begin();
5957 Et = PC->varlist_end();
5958 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
5959 auto *PC = cast<OMPLastprivateClause>(Cl);
5960 I = PC->private_copies().begin();
5961 It = PC->varlist_begin();
5962 Et = PC->varlist_end();
5963 } else if (Cl->getClauseKind() == OMPC_linear) {
5964 auto *PC = cast<OMPLinearClause>(Cl);
5965 I = PC->privates().begin();
5966 It = PC->varlist_begin();
5967 Et = PC->varlist_end();
5968 } else if (Cl->getClauseKind() == OMPC_reduction) {
5969 auto *PC = cast<OMPReductionClause>(Cl);
5970 I = PC->privates().begin();
5971 It = PC->varlist_begin();
5972 Et = PC->varlist_end();
5973 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
5974 auto *PC = cast<OMPTaskReductionClause>(Cl);
5975 I = PC->privates().begin();
5976 It = PC->varlist_begin();
5977 Et = PC->varlist_end();
5978 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
5979 auto *PC = cast<OMPInReductionClause>(Cl);
5980 I = PC->privates().begin();
5981 It = PC->varlist_begin();
5982 Et = PC->varlist_end();
5983 } else {
5984 llvm_unreachable("Expected private clause.");
5985 }
5986 for (Expr *E : llvm::make_range(It, Et)) {
5987 if (!*I) {
5988 ++I;
5989 continue;
5990 }
5991 SourceLocation ELoc;
5992 SourceRange ERange;
5993 Expr *SimpleRefExpr = E;
5994 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
5995 /*AllowArraySection=*/true);
5996 DeclToCopy.try_emplace(Res.first,
5997 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
5998 ++I;
5999 }
6000 }
6001 for (OMPClause *C : AllocateRange) {
6002 auto *AC = cast<OMPAllocateClause>(C);
6003 if (S.getLangOpts().OpenMP >= 50 &&
6004 !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
6005 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
6006 AC->getAllocator()) {
6007 Expr *Allocator = AC->getAllocator();
6008 // OpenMP, 2.12.5 target Construct
6009 // Memory allocators that do not appear in a uses_allocators clause cannot
6010 // appear as an allocator in an allocate clause or be used in the target
6011 // region unless a requires directive with the dynamic_allocators clause
6012 // is present in the same compilation unit.
6013 AllocatorChecker Checker(Stack);
6014 if (Checker.Visit(Allocator))
6015 S.Diag(Allocator->getExprLoc(),
6016 diag::err_omp_allocator_not_in_uses_allocators)
6017 << Allocator->getSourceRange();
6018 }
6019 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
6020 getAllocatorKind(S, Stack, AC->getAllocator());
6021 // OpenMP, 2.11.4 allocate Clause, Restrictions.
6022 // For task, taskloop or target directives, allocation requests to memory
6023 // allocators with the trait access set to thread result in unspecified
6024 // behavior.
6025 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
6026 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
6027 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
6028 llvm::omp::Version OMPVersion = S.getLangOpts().getOpenMPVersion();
6029 S.Diag(AC->getAllocator()->getExprLoc(),
6030 diag::warn_omp_allocate_thread_on_task_target_directive)
6031 << getOpenMPDirectiveName(Stack->getCurrentDirective(), OMPVersion);
6032 }
6033 for (Expr *E : AC->varlist()) {
6034 SourceLocation ELoc;
6035 SourceRange ERange;
6036 Expr *SimpleRefExpr = E;
6037 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
6038 ValueDecl *VD = Res.first;
6039 if (!VD)
6040 continue;
6041 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
6042 if (!isOpenMPPrivate(Data.CKind)) {
6043 S.Diag(E->getExprLoc(),
6044 diag::err_omp_expected_private_copy_for_allocate);
6045 continue;
6046 }
6047 VarDecl *PrivateVD = DeclToCopy[VD];
6048 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
6049 AllocatorKind, AC->getAllocator()))
6050 continue;
6051 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
6052 AC->getAlignment(), E->getSourceRange());
6053 }
6054 }
6055}
6056
6057namespace {
6058/// Rewrite statements and expressions for Sema \p Actions CurContext.
6059///
6060/// Used to wrap already parsed statements/expressions into a new CapturedStmt
6061/// context. DeclRefExpr used inside the new context are changed to refer to the
6062/// captured variable instead.
6063class CaptureVars : public TreeTransform<CaptureVars> {
6064 using BaseTransform = TreeTransform<CaptureVars>;
6065
6066public:
6067 CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
6068
6069 bool AlwaysRebuild() { return true; }
6070};
6071} // namespace
6072
6073/// Like ASTContext::getIntTypeForBitwidth, but falls back to a _BitInt type
6074/// when no standard integer type has the requested width.
6076 bool Signed) {
6077 QualType Ty = C.getIntTypeForBitwidth(Bits, Signed);
6078 if (Ty.isNull())
6079 Ty = C.getBitIntType(/*IsUnsigned=*/!Signed, Bits);
6080 return Ty;
6081}
6082
6083static Expr *buildInitListValue(Sema &SemaRef, Expr *E) {
6084 auto *ILE = dyn_cast<InitListExpr>(E->IgnoreImplicit());
6085 if (!ILE)
6086 return E;
6087 if (ILE->isTransparent())
6088 return buildInitListValue(SemaRef, ILE->getInit(0));
6089 QualType Ty = ILE->getType();
6090 bool IsEmptyScalar = ILE->getNumInits() == 0 && Ty->isScalarType();
6091 SourceLocation LBrace = ILE->getLBraceLoc();
6092 if (!SemaRef.getLangOpts().CPlusPlus) {
6093 if (!IsEmptyScalar)
6094 return E;
6096 SemaRef.ActOnIntegerConstant(LBrace, 0).get(), Ty,
6098 return Zero.isUsable() ? Zero.get() : E;
6099 }
6100 Expr *Syntactic = ILE->getSyntacticForm();
6101 if ((!IsEmptyScalar && !Ty->isRecordType()) || !Syntactic)
6102 return E;
6103 Sema::TentativeAnalysisScope Trap(SemaRef);
6105 SemaRef.Context.getTrivialTypeSourceInfo(Ty, LBrace), LBrace, Syntactic,
6106 ILE->getRBraceLoc(), /*ListInitialization=*/true);
6107 return Value.isUsable() ? Value.get() : E;
6108}
6109
6110static VarDecl *precomputeExpr(Sema &Actions,
6111 SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
6112 StringRef Name) {
6113 Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
6114 VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
6115 dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
6116 auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
6117 Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
6118 Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
6119 BodyStmts.push_back(NewDeclStmt);
6120 return NewVar;
6121}
6122
6123/// Create a closure that computes the number of iterations of a loop.
6124///
6125/// \param Actions The Sema object.
6126/// \param LogicalTy Type for the logical iteration number.
6127/// \param Rel Comparison operator of the loop condition.
6128/// \param StartExpr Value of the loop counter at the first iteration.
6129/// \param StopExpr Expression the loop counter is compared against in the loop
6130/// condition. \param StepExpr Amount of increment after each iteration.
6131///
6132/// \return Closure (CapturedStmt) of the distance calculation.
6133static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
6135 Expr *StartExpr, Expr *StopExpr,
6136 Expr *StepExpr) {
6137 ASTContext &Ctx = Actions.getASTContext();
6138 TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
6139
6140 // Captured regions currently don't support return values, we use an
6141 // out-parameter instead. All inputs are implicit captures.
6142 // TODO: Instead of capturing each DeclRefExpr occurring in
6143 // StartExpr/StopExpr/Step, these could also be passed as a value capture.
6144 QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
6145 Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
6146 {StringRef(), QualType()}};
6147 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
6148
6149 Stmt *Body;
6150 {
6151 Sema::CompoundScopeRAII CompoundScope(Actions);
6153
6154 // Get the LValue expression for the result.
6155 ImplicitParamDecl *DistParam = CS->getParam(0);
6156 DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
6157 DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
6158
6159 SmallVector<Stmt *, 4> BodyStmts;
6160
6161 // Capture all referenced variable references.
6162 // TODO: Instead of computing NewStart/NewStop/NewStep inside the
6163 // CapturedStmt, we could compute them before and capture the result, to be
6164 // used jointly with the LoopVar function.
6165 VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
6166 VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
6167 VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
6168 auto BuildVarRef = [&](VarDecl *VD) {
6169 return buildDeclRefExpr(Actions, VD, VD->getType(), {});
6170 };
6171
6173 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
6175 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
6176 Expr *Dist;
6177 if (Rel == BO_NE) {
6178 // When using a != comparison, the increment can be +1 or -1. This can be
6179 // dynamic at runtime, so we need to check for the direction.
6180 Expr *IsNegStep = AssertSuccess(
6181 Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
6182
6183 // Positive increment.
6184 Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
6185 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
6186 ForwardRange = AssertSuccess(
6187 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
6188 Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
6189 nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
6190
6191 // Negative increment.
6192 Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
6193 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
6194 BackwardRange = AssertSuccess(
6195 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
6196 Expr *NegIncAmount = AssertSuccess(
6197 Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
6198 Expr *BackwardDist = AssertSuccess(
6199 Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
6200
6201 // Use the appropriate case.
6202 Dist = AssertSuccess(Actions.ActOnConditionalOp(
6203 {}, {}, IsNegStep, BackwardDist, ForwardDist));
6204 } else {
6205 assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
6206 "Expected one of these relational operators");
6207
6208 // We can derive the direction from any other comparison operator. It is
6209 // non well-formed OpenMP if Step increments/decrements in the other
6210 // directions. Whether at least the first iteration passes the loop
6211 // condition.
6212 Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
6213 nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
6214
6215 // Compute the range between first and last counter value.
6216 Expr *Range;
6217 if (Rel == BO_GE || Rel == BO_GT)
6218 Range = AssertSuccess(Actions.BuildBinOp(
6219 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
6220 else
6221 Range = AssertSuccess(Actions.BuildBinOp(
6222 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
6223
6224 // Ensure unsigned range space.
6225 Range =
6226 AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
6227
6228 if (Rel == BO_LE || Rel == BO_GE) {
6229 // Add one to the range if the relational operator is inclusive.
6230 Range =
6231 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, Range, One));
6232 }
6233
6234 // Divide by the absolute step amount. If the range is not a multiple of
6235 // the step size, rounding-up the effective upper bound ensures that the
6236 // last iteration is included.
6237 // Note that the rounding-up may cause an overflow in a temporary that
6238 // could be avoided, but would have occurred in a C-style for-loop as
6239 // well.
6240 Expr *Divisor = BuildVarRef(NewStep);
6241 if (Rel == BO_GE || Rel == BO_GT)
6242 Divisor =
6243 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
6244 Expr *DivisorMinusOne =
6245 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Sub, Divisor, One));
6246 Expr *RangeRoundUp = AssertSuccess(
6247 Actions.BuildBinOp(nullptr, {}, BO_Add, Range, DivisorMinusOne));
6248 Dist = AssertSuccess(
6249 Actions.BuildBinOp(nullptr, {}, BO_Div, RangeRoundUp, Divisor));
6250
6251 // If there is not at least one iteration, the range contains garbage. Fix
6252 // to zero in this case.
6253 Dist = AssertSuccess(
6254 Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
6255 }
6256
6257 // Assign the result to the out-parameter.
6258 Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
6259 Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
6260 BodyStmts.push_back(ResultAssign);
6261
6262 Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
6263 }
6264
6265 return cast<CapturedStmt>(
6266 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
6267}
6268
6269/// Create a closure that computes the loop variable from the logical iteration
6270/// number.
6271///
6272/// \param Actions The Sema object.
6273/// \param LoopVarTy Type for the loop variable used for result value.
6274/// \param LogicalTy Type for the logical iteration number.
6275/// \param StartExpr Value of the loop counter at the first iteration.
6276/// \param Step Amount of increment after each iteration.
6277/// \param Deref Whether the loop variable is a dereference of the loop
6278/// counter variable.
6279///
6280/// \return Closure (CapturedStmt) of the loop value calculation.
6281static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
6282 QualType LogicalTy,
6283 DeclRefExpr *StartExpr, Expr *Step,
6284 bool Deref) {
6285 ASTContext &Ctx = Actions.getASTContext();
6286
6287 // Pass the result as an out-parameter. Passing as return value would require
6288 // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
6289 // invoke a copy constructor.
6290 QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
6291 SemaOpenMP::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
6292 {"Logical", LogicalTy},
6293 {StringRef(), QualType()}};
6294 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
6295
6296 // Capture the initial iterator which represents the LoopVar value at the
6297 // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
6298 // it in every iteration, capture it by value before it is modified.
6299 VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
6300 bool Invalid = Actions.tryCaptureVariable(StartVar, {},
6302 (void)Invalid;
6303 assert(!Invalid && "Expecting capture-by-value to work.");
6304
6305 Expr *Body;
6306 {
6307 Sema::CompoundScopeRAII CompoundScope(Actions);
6308 auto *CS = cast<CapturedDecl>(Actions.CurContext);
6309
6310 ImplicitParamDecl *TargetParam = CS->getParam(0);
6311 DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
6312 TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
6313 ImplicitParamDecl *IndvarParam = CS->getParam(1);
6314 DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
6315 IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
6316
6317 // Capture the Start expression.
6318 CaptureVars Recap(Actions);
6319 Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
6320 Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
6321
6323 Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
6324 // TODO: Explicitly cast to the iterator's difference_type instead of
6325 // relying on implicit conversion.
6326 Expr *Advanced =
6327 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
6328
6329 if (Deref) {
6330 // For range-based for-loops convert the loop counter value to a concrete
6331 // loop variable value by dereferencing the iterator.
6332 Advanced =
6333 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
6334 }
6335
6336 // Assign the result to the output parameter.
6337 Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
6338 BO_Assign, TargetRef, Advanced));
6339 }
6340 return cast<CapturedStmt>(
6341 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
6342}
6343
6345 ASTContext &Ctx = getASTContext();
6346
6347 // Extract the common elements of ForStmt and CXXForRangeStmt:
6348 // Loop variable, repeat condition, increment
6349 Expr *Cond, *Inc;
6350 VarDecl *LIVDecl, *LUVDecl;
6351 if (auto *For = dyn_cast<ForStmt>(AStmt)) {
6352 Stmt *Init = For->getInit();
6353 if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
6354 // For statement declares loop variable.
6355 LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
6356 } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
6357 // For statement reuses variable.
6358 assert(LCAssign->getOpcode() == BO_Assign &&
6359 "init part must be a loop variable assignment");
6360 auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
6361 LIVDecl = cast<VarDecl>(CounterRef->getDecl());
6362 } else
6363 llvm_unreachable("Cannot determine loop variable");
6364 LUVDecl = LIVDecl;
6365
6366 Cond = For->getCond();
6367 Inc = For->getInc();
6368 } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
6369 DeclStmt *BeginStmt = RangeFor->getBeginStmt();
6370 LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
6371 LUVDecl = RangeFor->getLoopVariable();
6372
6373 Cond = RangeFor->getCond();
6374 Inc = RangeFor->getInc();
6375 } else
6376 llvm_unreachable("unhandled kind of loop");
6377
6378 QualType CounterTy = LIVDecl->getType();
6379 QualType LVTy = LUVDecl->getType();
6380
6381 // Analyze the loop condition.
6382 Expr *LHS, *RHS;
6383 BinaryOperator::Opcode CondRel;
6384 Cond = Cond->IgnoreImplicit();
6385 if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
6386 LHS = CondBinExpr->getLHS();
6387 RHS = CondBinExpr->getRHS();
6388 CondRel = CondBinExpr->getOpcode();
6389 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
6390 assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
6391 LHS = CondCXXOp->getArg(0);
6392 RHS = CondCXXOp->getArg(1);
6393 switch (CondCXXOp->getOperator()) {
6394 case OO_ExclaimEqual:
6395 CondRel = BO_NE;
6396 break;
6397 case OO_Less:
6398 CondRel = BO_LT;
6399 break;
6400 case OO_LessEqual:
6401 CondRel = BO_LE;
6402 break;
6403 case OO_Greater:
6404 CondRel = BO_GT;
6405 break;
6406 case OO_GreaterEqual:
6407 CondRel = BO_GE;
6408 break;
6409 default:
6410 llvm_unreachable("unexpected iterator operator");
6411 }
6412 } else
6413 llvm_unreachable("unexpected loop condition");
6414
6415 // Normalize such that the loop counter is on the LHS.
6416 if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
6417 cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
6418 std::swap(LHS, RHS);
6419 CondRel = BinaryOperator::reverseComparisonOp(CondRel);
6420 }
6421 auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
6422
6423 // Decide the bit width for the logical iteration counter. By default use the
6424 // unsigned ptrdiff_t integer size (for iterators and pointers).
6425 // TODO: For iterators, use iterator::difference_type,
6426 // std::iterator_traits<>::difference_type or decltype(it - end).
6427 QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
6428 if (CounterTy->isIntegerType()) {
6429 unsigned BitWidth = Ctx.getIntWidth(CounterTy);
6430 LogicalTy = getIntTypeForBitwidthOrBitInt(Ctx, BitWidth, /*Signed=*/false);
6431 }
6432
6433 // Analyze the loop increment.
6434 Expr *Step;
6435 if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
6436 int Direction;
6437 switch (IncUn->getOpcode()) {
6438 case UO_PreInc:
6439 case UO_PostInc:
6440 Direction = 1;
6441 break;
6442 case UO_PreDec:
6443 case UO_PostDec:
6444 Direction = -1;
6445 break;
6446 default:
6447 llvm_unreachable("unhandled unary increment operator");
6448 }
6450 Ctx,
6451 llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction, /*isSigned=*/true),
6452 LogicalTy, {});
6453 } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
6454 Expr *IncRHS = buildInitListValue(SemaRef, IncBin->getRHS());
6455 if (IncBin->getOpcode() == BO_AddAssign) {
6456 Step = IncRHS;
6457 } else if (IncBin->getOpcode() == BO_SubAssign) {
6458 Step = AssertSuccess(SemaRef.BuildUnaryOp(nullptr, {}, UO_Minus, IncRHS));
6459 } else
6460 llvm_unreachable("unhandled binary increment operator");
6461 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
6462 switch (CondCXXOp->getOperator()) {
6463 case OO_PlusPlus:
6465 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
6466 break;
6467 case OO_MinusMinus:
6469 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
6470 break;
6471 case OO_PlusEqual:
6472 Step = buildInitListValue(SemaRef, CondCXXOp->getArg(1));
6473 break;
6474 case OO_MinusEqual:
6475 Step = AssertSuccess(SemaRef.BuildUnaryOp(
6476 nullptr, {}, UO_Minus,
6477 buildInitListValue(SemaRef, CondCXXOp->getArg(1))));
6478 break;
6479 default:
6480 llvm_unreachable("unhandled overloaded increment operator");
6481 }
6482 } else
6483 llvm_unreachable("unknown increment expression");
6484
6485 CapturedStmt *DistanceFunc =
6486 buildDistanceFunc(SemaRef, LogicalTy, CondRel, LHS, RHS, Step);
6487 CapturedStmt *LoopVarFunc = buildLoopVarFunc(
6488 SemaRef, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
6489 DeclRefExpr *LVRef =
6490 SemaRef.BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue, {},
6491 nullptr, nullptr, {}, nullptr);
6492 return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
6493 LoopVarFunc, LVRef);
6494}
6495
6497 // Handle a literal loop.
6498 if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt))
6499 return ActOnOpenMPCanonicalLoop(AStmt);
6500
6501 // If not a literal loop, it must be the result of a loop transformation.
6503 assert(
6504 isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) &&
6505 "Loop transformation directive expected");
6506 return LoopTransform;
6507}
6508
6510 CXXScopeSpec &MapperIdScopeSpec,
6511 const DeclarationNameInfo &MapperId,
6512 QualType Type,
6513 Expr *UnresolvedMapper,
6514 SourceLocation ItemLoc);
6515
6516/// Perform DFS through the structure/class data members trying to find
6517/// member(s) with user-defined 'default' mapper and generate implicit map
6518/// clauses for such members with the found 'default' mapper.
6519static void
6522 // Check for the default mapper for data members.
6523 if (S.getLangOpts().OpenMP < 50)
6524 return;
6525 for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
6526 auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
6527 if (!C)
6528 continue;
6529 SmallVector<Expr *, 4> SubExprs;
6530 auto *MI = C->mapperlist_begin();
6531 for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
6532 ++I, ++MI) {
6533 // Expression is mapped using mapper - skip it.
6534 if (*MI)
6535 continue;
6536 Expr *E = *I;
6537 // Expression is dependent - skip it, build the mapper when it gets
6538 // instantiated.
6539 if (E->isTypeDependent() || E->isValueDependent() ||
6541 continue;
6542 // Array section - need to check for the mapping of the array section
6543 // element.
6544 QualType CanonType = E->getType().getCanonicalType();
6545 if (CanonType->isSpecificBuiltinType(BuiltinType::ArraySection)) {
6546 const auto *OASE = cast<ArraySectionExpr>(E->IgnoreParenImpCasts());
6547 QualType BaseType =
6549 QualType ElemType;
6550 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
6551 ElemType = ATy->getElementType();
6552 else
6553 ElemType = BaseType->getPointeeType();
6554 CanonType = ElemType;
6555 }
6556
6557 // DFS over data members in structures/classes.
6559 1, {CanonType, nullptr});
6560 llvm::DenseMap<const Type *, Expr *> Visited;
6562 1, {nullptr, 1});
6563 while (!Types.empty()) {
6564 QualType BaseType;
6565 FieldDecl *CurFD;
6566 std::tie(BaseType, CurFD) = Types.pop_back_val();
6567 while (ParentChain.back().second == 0)
6568 ParentChain.pop_back();
6569 --ParentChain.back().second;
6570 if (BaseType.isNull())
6571 continue;
6572 // Only structs/classes are allowed to have mappers.
6573 const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
6574 if (!RD)
6575 continue;
6576 auto It = Visited.find(BaseType.getTypePtr());
6577 if (It == Visited.end()) {
6578 // Try to find the associated user-defined mapper.
6579 CXXScopeSpec MapperIdScopeSpec;
6580 DeclarationNameInfo DefaultMapperId;
6582 &S.Context.Idents.get("default")));
6583 DefaultMapperId.setLoc(E->getExprLoc());
6585 S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
6586 BaseType, /*UnresolvedMapper=*/nullptr, E->getExprLoc());
6587 if (ER.isInvalid())
6588 continue;
6589 It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
6590 }
6591 // Found default mapper.
6592 if (It->second) {
6593 auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
6595 OE->setIsUnique(/*V=*/true);
6596 Expr *BaseExpr = OE;
6597 for (const auto &P : ParentChain) {
6598 if (P.first) {
6599 BaseExpr = S.BuildMemberExpr(
6600 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
6602 DeclAccessPair::make(P.first, P.first->getAccess()),
6603 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
6604 P.first->getType(), VK_LValue, OK_Ordinary);
6605 BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
6606 }
6607 }
6608 if (CurFD)
6609 BaseExpr = S.BuildMemberExpr(
6610 BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
6612 DeclAccessPair::make(CurFD, CurFD->getAccess()),
6613 /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
6614 CurFD->getType(), VK_LValue, OK_Ordinary);
6615 SubExprs.push_back(BaseExpr);
6616 continue;
6617 }
6618 // Check for the "default" mapper for data members.
6619 bool FirstIter = true;
6620 for (FieldDecl *FD : RD->fields()) {
6621 if (!FD)
6622 continue;
6623 QualType FieldTy = FD->getType();
6624 if (FieldTy.isNull() ||
6625 !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
6626 continue;
6627 if (FirstIter) {
6628 FirstIter = false;
6629 ParentChain.emplace_back(CurFD, 1);
6630 } else {
6631 ++ParentChain.back().second;
6632 }
6633 Types.emplace_back(FieldTy, FD);
6634 }
6635 }
6636 }
6637 if (SubExprs.empty())
6638 continue;
6639 CXXScopeSpec MapperIdScopeSpec;
6640 DeclarationNameInfo MapperId;
6641 if (OMPClause *NewClause = S.OpenMP().ActOnOpenMPMapClause(
6642 nullptr, C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
6643 MapperIdScopeSpec, MapperId, C->getMapType(),
6644 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
6645 SubExprs, OMPVarListLocTy()))
6646 Clauses.push_back(NewClause);
6647 }
6648}
6649
6650namespace {
6651/// A 'teams loop' with a nested 'loop bind(parallel)' or generic function
6652/// call in the associated loop-nest cannot be a 'parallel for'.
6653class TeamsLoopChecker final : public ConstStmtVisitor<TeamsLoopChecker> {
6654 Sema &SemaRef;
6655
6656public:
6657 bool teamsLoopCanBeParallelFor() const { return TeamsLoopCanBeParallelFor; }
6658
6659 // Is there a nested OpenMP loop bind(parallel)
6660 void VisitOMPExecutableDirective(const OMPExecutableDirective *D) {
6661 if (D->getDirectiveKind() == llvm::omp::Directive::OMPD_loop) {
6662 if (const auto *C = D->getSingleClause<OMPBindClause>())
6663 if (C->getBindKind() == OMPC_BIND_parallel) {
6664 TeamsLoopCanBeParallelFor = false;
6665 // No need to continue visiting any more
6666 return;
6667 }
6668 }
6669 for (const Stmt *Child : D->children())
6670 if (Child)
6671 Visit(Child);
6672 }
6673
6674 void VisitCallExpr(const CallExpr *C) {
6675 // Function calls inhibit parallel loop translation of 'target teams loop'
6676 // unless the assume-no-nested-parallelism flag has been specified.
6677 // OpenMP API runtime library calls do not inhibit parallel loop
6678 // translation, regardless of the assume-no-nested-parallelism.
6679 bool IsOpenMPAPI = false;
6680 auto *FD = dyn_cast_or_null<FunctionDecl>(C->getCalleeDecl());
6681 if (FD) {
6682 std::string Name = FD->getNameInfo().getAsString();
6683 IsOpenMPAPI = Name.find("omp_") == 0;
6684 }
6685 TeamsLoopCanBeParallelFor =
6686 IsOpenMPAPI || SemaRef.getLangOpts().OpenMPNoNestedParallelism;
6687 if (!TeamsLoopCanBeParallelFor)
6688 return;
6689
6690 for (const Stmt *Child : C->children())
6691 if (Child)
6692 Visit(Child);
6693 }
6694
6695 void VisitCapturedStmt(const CapturedStmt *S) {
6696 if (!S)
6697 return;
6698 Visit(S->getCapturedDecl()->getBody());
6699 }
6700
6701 void VisitStmt(const Stmt *S) {
6702 if (!S)
6703 return;
6704 for (const Stmt *Child : S->children())
6705 if (Child)
6706 Visit(Child);
6707 }
6708 explicit TeamsLoopChecker(Sema &SemaRef)
6709 : SemaRef(SemaRef), TeamsLoopCanBeParallelFor(true) {}
6710
6711private:
6712 bool TeamsLoopCanBeParallelFor;
6713};
6714} // namespace
6715
6716static bool teamsLoopCanBeParallelFor(Stmt *AStmt, Sema &SemaRef) {
6717 TeamsLoopChecker Checker(SemaRef);
6718 Checker.Visit(AStmt);
6719 return Checker.teamsLoopCanBeParallelFor();
6720}
6721
6723 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
6724 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
6725 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
6726 assert(isOpenMPExecutableDirective(Kind) && "Unexpected directive category");
6727
6728 StmtResult Res = StmtError();
6730 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
6731
6732 if (const OMPBindClause *BC =
6733 OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses))
6734 BindKind = BC->getBindKind();
6735
6736 if (Kind == OMPD_loop && BindKind == OMPC_BIND_unknown) {
6737 const OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
6738
6739 // Setting the enclosing teams or parallel construct for the loop
6740 // directive without bind clause.
6741 // [5.0:129:25-28] If the bind clause is not present on the construct and
6742 // the loop construct is closely nested inside a teams or parallel
6743 // construct, the binding region is the corresponding teams or parallel
6744 // region. If none of those conditions hold, the binding region is not
6745 // defined.
6746 BindKind = OMPC_BIND_thread; // Default bind(thread) if binding is unknown
6747 ArrayRef<OpenMPDirectiveKind> ParentLeafs =
6748 getLeafConstructsOrSelf(ParentDirective);
6749
6750 if (ParentDirective == OMPD_unknown) {
6751 Diag(DSAStack->getDefaultDSALocation(),
6752 diag::err_omp_bind_required_on_loop);
6753 } else if (ParentLeafs.back() == OMPD_parallel) {
6754 BindKind = OMPC_BIND_parallel;
6755 } else if (ParentLeafs.back() == OMPD_teams) {
6756 BindKind = OMPC_BIND_teams;
6757 }
6758
6759 assert(BindKind != OMPC_BIND_unknown && "Expecting BindKind");
6760
6761 OMPClause *C =
6764 ClausesWithImplicit.push_back(C);
6765 }
6766
6767 // Diagnose "loop bind(teams)" with "reduction".
6768 if (Kind == OMPD_loop && BindKind == OMPC_BIND_teams) {
6769 for (OMPClause *C : Clauses) {
6770 if (C->getClauseKind() == OMPC_reduction)
6771 Diag(DSAStack->getDefaultDSALocation(),
6772 diag::err_omp_loop_reduction_clause);
6773 }
6774 }
6775
6776 // First check CancelRegion which is then used in checkNestingOfRegions.
6777 if (checkCancelRegion(SemaRef, Kind, CancelRegion, StartLoc) ||
6778 checkNestingOfRegions(SemaRef, DSAStack, Kind, DirName, CancelRegion,
6779 BindKind, StartLoc)) {
6780 return StmtError();
6781 }
6782
6783 // Report affected OpenMP target offloading behavior when in HIP lang-mode.
6786 Diag(StartLoc, diag::warn_hip_omp_target_directives);
6787
6788 VarsWithInheritedDSAType VarsWithInheritedDSA;
6789 bool ErrorFound = false;
6790 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
6791
6792 if (AStmt && !SemaRef.CurContext->isDependentContext() &&
6794 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6795
6796 // Check default data sharing attributes for referenced variables.
6797 DSAAttrChecker DSAChecker(DSAStack, SemaRef, cast<CapturedStmt>(AStmt));
6798 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
6799 Stmt *S = AStmt;
6800 while (--ThisCaptureLevel >= 0)
6801 S = cast<CapturedStmt>(S)->getCapturedStmt();
6802 DSAChecker.Visit(S);
6804 !isOpenMPTaskingDirective(Kind)) {
6805 // Visit subcaptures to generate implicit clauses for captured vars.
6806 auto *CS = cast<CapturedStmt>(AStmt);
6808 getOpenMPCaptureRegions(CaptureRegions, Kind);
6809 // Ignore outer tasking regions for target directives.
6810 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
6812 DSAChecker.visitSubCaptures(CS);
6813 }
6814 if (DSAChecker.isErrorFound())
6815 return StmtError();
6816 // Generate list of implicitly defined firstprivate variables.
6817 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
6818 VariableImplicitInfo ImpInfo = DSAChecker.getImplicitInfo();
6819
6821 ImplicitMapModifiersLoc[VariableImplicitInfo::DefaultmapKindNum];
6822 // Get the original location of present modifier from Defaultmap clause.
6823 SourceLocation PresentModifierLocs[VariableImplicitInfo::DefaultmapKindNum];
6824 for (OMPClause *C : Clauses) {
6825 if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
6826 if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
6827 PresentModifierLocs[DMC->getDefaultmapKind()] =
6828 DMC->getDefaultmapModifierLoc();
6829 }
6830
6832 llvm::enum_seq_inclusive<OpenMPDefaultmapClauseKind>(
6834 std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[K]),
6835 ImpInfo.MapModifiers[K].size(), PresentModifierLocs[K]);
6836 }
6837 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
6838 for (OMPClause *C : Clauses) {
6839 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
6840 for (Expr *E : IRC->taskgroup_descriptors())
6841 if (E)
6842 ImpInfo.Firstprivates.insert(E);
6843 }
6844 // OpenMP 5.0, 2.10.1 task Construct
6845 // [detach clause]... The event-handle will be considered as if it was
6846 // specified on a firstprivate clause.
6847 if (auto *DC = dyn_cast<OMPDetachClause>(C))
6848 ImpInfo.Firstprivates.insert(DC->getEventHandler());
6849 }
6850 if (!ImpInfo.Firstprivates.empty()) {
6852 ImpInfo.Firstprivates.getArrayRef(), SourceLocation(),
6854 ClausesWithImplicit.push_back(Implicit);
6855 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
6856 ImpInfo.Firstprivates.size();
6857 } else {
6858 ErrorFound = true;
6859 }
6860 }
6861 if (!ImpInfo.Privates.empty()) {
6863 ImpInfo.Privates.getArrayRef(), SourceLocation(),
6865 ClausesWithImplicit.push_back(Implicit);
6866 ErrorFound = cast<OMPPrivateClause>(Implicit)->varlist_size() !=
6867 ImpInfo.Privates.size();
6868 } else {
6869 ErrorFound = true;
6870 }
6871 }
6872 // OpenMP 5.0 [2.19.7]
6873 // If a list item appears in a reduction, lastprivate or linear
6874 // clause on a combined target construct then it is treated as
6875 // if it also appears in a map clause with a map-type of tofrom
6876 if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target &&
6878 SmallVector<Expr *, 4> ImplicitExprs;
6879 for (OMPClause *C : Clauses) {
6880 if (auto *RC = dyn_cast<OMPReductionClause>(C))
6881 for (Expr *E : RC->varlist())
6883 ImplicitExprs.emplace_back(E);
6884 }
6885 if (!ImplicitExprs.empty()) {
6886 ArrayRef<Expr *> Exprs = ImplicitExprs;
6887 CXXScopeSpec MapperIdScopeSpec;
6888 DeclarationNameInfo MapperId;
6891 MapperIdScopeSpec, MapperId, OMPC_MAP_tofrom,
6892 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
6893 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true))
6894 ClausesWithImplicit.emplace_back(Implicit);
6895 }
6896 }
6897 for (unsigned I = 0; I < VariableImplicitInfo::DefaultmapKindNum; ++I) {
6898 int ClauseKindCnt = -1;
6899 for (unsigned J = 0; J < VariableImplicitInfo::MapKindNum; ++J) {
6900 ArrayRef<Expr *> ImplicitMap = ImpInfo.Mappings[I][J].getArrayRef();
6901 ++ClauseKindCnt;
6902 if (ImplicitMap.empty())
6903 continue;
6904 CXXScopeSpec MapperIdScopeSpec;
6905 DeclarationNameInfo MapperId;
6906 auto K = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
6908 nullptr, ImpInfo.MapModifiers[I], ImplicitMapModifiersLoc[I],
6909 MapperIdScopeSpec, MapperId, K, /*IsMapTypeImplicit=*/true,
6910 SourceLocation(), SourceLocation(), ImplicitMap,
6911 OMPVarListLocTy())) {
6912 ClausesWithImplicit.emplace_back(Implicit);
6913 ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
6914 ImplicitMap.size();
6915 } else {
6916 ErrorFound = true;
6917 }
6918 }
6919 }
6920 // Build expressions for implicit maps of data members with 'default'
6921 // mappers.
6922 if (getLangOpts().OpenMP >= 50)
6924 ClausesWithImplicit);
6925 }
6926
6927 switch (Kind) {
6928 case OMPD_parallel:
6929 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
6930 EndLoc);
6931 break;
6932 case OMPD_simd:
6933 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
6934 VarsWithInheritedDSA);
6935 break;
6936 case OMPD_tile:
6937 Res =
6938 ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6939 break;
6940 case OMPD_stripe:
6941 Res = ActOnOpenMPStripeDirective(ClausesWithImplicit, AStmt, StartLoc,
6942 EndLoc);
6943 break;
6944 case OMPD_unroll:
6945 Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
6946 EndLoc);
6947 break;
6948 case OMPD_reverse:
6949 assert(ClausesWithImplicit.empty() &&
6950 "reverse directive does not support any clauses");
6951 Res = ActOnOpenMPReverseDirective(AStmt, StartLoc, EndLoc);
6952 break;
6953 case OMPD_split:
6954 Res =
6955 ActOnOpenMPSplitDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6956 break;
6957 case OMPD_interchange:
6958 Res = ActOnOpenMPInterchangeDirective(ClausesWithImplicit, AStmt, StartLoc,
6959 EndLoc);
6960 break;
6961 case OMPD_flatten:
6962 Res = ActOnOpenMPFlattenDirective(ClausesWithImplicit, AStmt, StartLoc,
6963 EndLoc);
6964 break;
6965 case OMPD_fuse:
6966 Res =
6967 ActOnOpenMPFuseDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
6968 break;
6969 case OMPD_for:
6970 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
6971 VarsWithInheritedDSA);
6972 break;
6973 case OMPD_for_simd:
6974 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
6975 EndLoc, VarsWithInheritedDSA);
6976 break;
6977 case OMPD_sections:
6978 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
6979 EndLoc);
6980 break;
6981 case OMPD_section:
6982 assert(ClausesWithImplicit.empty() &&
6983 "No clauses are allowed for 'omp section' directive");
6984 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
6985 break;
6986 case OMPD_single:
6987 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
6988 EndLoc);
6989 break;
6990 case OMPD_master:
6991 assert(ClausesWithImplicit.empty() &&
6992 "No clauses are allowed for 'omp master' directive");
6993 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
6994 break;
6995 case OMPD_masked:
6996 Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
6997 EndLoc);
6998 break;
6999 case OMPD_critical:
7000 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
7001 StartLoc, EndLoc);
7002 break;
7003 case OMPD_parallel_for:
7004 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
7005 EndLoc, VarsWithInheritedDSA);
7006 break;
7007 case OMPD_parallel_for_simd:
7009 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7010 break;
7011 case OMPD_scope:
7012 Res =
7013 ActOnOpenMPScopeDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
7014 break;
7015 case OMPD_parallel_master:
7016 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
7017 StartLoc, EndLoc);
7018 break;
7019 case OMPD_parallel_masked:
7020 Res = ActOnOpenMPParallelMaskedDirective(ClausesWithImplicit, AStmt,
7021 StartLoc, EndLoc);
7022 break;
7023 case OMPD_parallel_sections:
7024 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
7025 StartLoc, EndLoc);
7026 break;
7027 case OMPD_task:
7028 Res =
7029 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
7030 break;
7031 case OMPD_taskyield:
7032 assert(ClausesWithImplicit.empty() &&
7033 "No clauses are allowed for 'omp taskyield' directive");
7034 assert(AStmt == nullptr &&
7035 "No associated statement allowed for 'omp taskyield' directive");
7036 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
7037 break;
7038 case OMPD_error:
7039 assert(AStmt == nullptr &&
7040 "No associated statement allowed for 'omp error' directive");
7041 Res = ActOnOpenMPErrorDirective(ClausesWithImplicit, StartLoc, EndLoc);
7042 break;
7043 case OMPD_barrier:
7044 assert(ClausesWithImplicit.empty() &&
7045 "No clauses are allowed for 'omp barrier' directive");
7046 assert(AStmt == nullptr &&
7047 "No associated statement allowed for 'omp barrier' directive");
7048 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
7049 break;
7050 case OMPD_taskwait:
7051 assert(AStmt == nullptr &&
7052 "No associated statement allowed for 'omp taskwait' directive");
7053 Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc);
7054 break;
7055 case OMPD_taskgroup:
7056 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
7057 EndLoc);
7058 break;
7059 case OMPD_flush:
7060 assert(AStmt == nullptr &&
7061 "No associated statement allowed for 'omp flush' directive");
7062 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
7063 break;
7064 case OMPD_depobj:
7065 assert(AStmt == nullptr &&
7066 "No associated statement allowed for 'omp depobj' directive");
7067 Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
7068 break;
7069 case OMPD_scan:
7070 assert(AStmt == nullptr &&
7071 "No associated statement allowed for 'omp scan' directive");
7072 Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
7073 break;
7074 case OMPD_ordered_blockassoc:
7075 case OMPD_ordered_standalone:
7076 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
7077 EndLoc);
7078 break;
7079 case OMPD_atomic:
7080 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
7081 EndLoc);
7082 break;
7083 case OMPD_teams:
7084 Res =
7085 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
7086 break;
7087 case OMPD_target:
7088 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
7089 EndLoc);
7090 break;
7091 case OMPD_target_parallel:
7092 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
7093 StartLoc, EndLoc);
7094 break;
7095 case OMPD_target_parallel_for:
7097 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7098 break;
7099 case OMPD_cancellation_point:
7100 assert(ClausesWithImplicit.empty() &&
7101 "No clauses are allowed for 'omp cancellation point' directive");
7102 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
7103 "cancellation point' directive");
7104 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
7105 break;
7106 case OMPD_cancel:
7107 assert(AStmt == nullptr &&
7108 "No associated statement allowed for 'omp cancel' directive");
7109 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
7110 CancelRegion);
7111 break;
7112 case OMPD_target_data:
7113 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
7114 EndLoc);
7115 break;
7116 case OMPD_target_enter_data:
7117 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
7118 EndLoc, AStmt);
7119 break;
7120 case OMPD_target_exit_data:
7121 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
7122 EndLoc, AStmt);
7123 break;
7124 case OMPD_taskloop:
7125 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
7126 EndLoc, VarsWithInheritedDSA);
7127 break;
7128 case OMPD_taskloop_simd:
7129 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
7130 EndLoc, VarsWithInheritedDSA);
7131 break;
7132 case OMPD_master_taskloop:
7134 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7135 break;
7136 case OMPD_masked_taskloop:
7138 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7139 break;
7140 case OMPD_master_taskloop_simd:
7142 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7143 break;
7144 case OMPD_masked_taskloop_simd:
7146 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7147 break;
7148 case OMPD_parallel_master_taskloop:
7150 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7151 break;
7152 case OMPD_parallel_masked_taskloop:
7154 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7155 break;
7156 case OMPD_parallel_master_taskloop_simd:
7158 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7159 break;
7160 case OMPD_parallel_masked_taskloop_simd:
7162 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7163 break;
7164 case OMPD_distribute:
7165 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
7166 EndLoc, VarsWithInheritedDSA);
7167 break;
7168 case OMPD_target_update:
7169 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
7170 EndLoc, AStmt);
7171 break;
7172 case OMPD_distribute_parallel_for:
7174 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7175 break;
7176 case OMPD_distribute_parallel_for_simd:
7178 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7179 break;
7180 case OMPD_distribute_simd:
7182 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7183 break;
7184 case OMPD_target_parallel_for_simd:
7186 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7187 break;
7188 case OMPD_target_simd:
7189 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
7190 EndLoc, VarsWithInheritedDSA);
7191 break;
7192 case OMPD_teams_distribute:
7194 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7195 break;
7196 case OMPD_teams_distribute_simd:
7198 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7199 break;
7200 case OMPD_teams_distribute_parallel_for_simd:
7202 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7203 break;
7204 case OMPD_teams_distribute_parallel_for:
7206 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7207 break;
7208 case OMPD_target_teams:
7209 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
7210 EndLoc);
7211 break;
7212 case OMPD_target_teams_distribute:
7214 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7215 break;
7216 case OMPD_target_teams_distribute_parallel_for:
7218 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7219 break;
7220 case OMPD_target_teams_distribute_parallel_for_simd:
7222 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7223 break;
7224 case OMPD_target_teams_distribute_simd:
7226 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7227 break;
7228 case OMPD_interop:
7229 assert(AStmt == nullptr &&
7230 "No associated statement allowed for 'omp interop' directive");
7231 Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
7232 break;
7233 case OMPD_dispatch:
7234 Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
7235 EndLoc);
7236 break;
7237 case OMPD_loop:
7238 Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
7239 EndLoc, VarsWithInheritedDSA);
7240 break;
7241 case OMPD_teams_loop:
7243 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7244 break;
7245 case OMPD_target_teams_loop:
7247 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7248 break;
7249 case OMPD_parallel_loop:
7251 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7252 break;
7253 case OMPD_target_parallel_loop:
7255 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7256 break;
7257 case OMPD_target_loop:
7259 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
7260 break;
7261 case OMPD_declare_target:
7262 case OMPD_end_declare_target:
7263 case OMPD_threadprivate:
7264 case OMPD_allocate:
7265 case OMPD_declare_reduction:
7266 case OMPD_declare_mapper:
7267 case OMPD_declare_simd:
7268 case OMPD_requires:
7269 case OMPD_declare_variant:
7270 case OMPD_begin_declare_variant:
7271 case OMPD_end_declare_variant:
7272 llvm_unreachable("OpenMP Directive is not allowed");
7273 case OMPD_taskgraph:
7274 Diag(StartLoc, diag::err_omp_unexpected_directive)
7275 << 1 << getOpenMPDirectiveName(OMPD_taskgraph);
7276 return StmtError();
7277 case OMPD_unknown:
7278 default:
7279 llvm_unreachable("Unknown OpenMP directive");
7280 }
7281
7282 ErrorFound = Res.isInvalid() || ErrorFound;
7283
7284 // Check variables in the clauses if default(none) or
7285 // default(firstprivate) was specified.
7286 if (DSAStack->getDefaultDSA() == DSA_none ||
7287 DSAStack->getDefaultDSA() == DSA_private ||
7288 DSAStack->getDefaultDSA() == DSA_firstprivate) {
7289 DSAAttrChecker DSAChecker(DSAStack, SemaRef, nullptr);
7290 for (OMPClause *C : Clauses) {
7291 switch (C->getClauseKind()) {
7292 case OMPC_num_threads:
7293 case OMPC_dist_schedule:
7294 // Do not analyze if no parent teams directive.
7295 if (isOpenMPTeamsDirective(Kind))
7296 break;
7297 continue;
7298 case OMPC_if:
7299 if (isOpenMPTeamsDirective(Kind) &&
7300 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
7301 break;
7302 if (isOpenMPParallelDirective(Kind) &&
7304 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
7305 break;
7306 continue;
7307 case OMPC_schedule:
7308 case OMPC_detach:
7309 break;
7310 case OMPC_grainsize:
7311 case OMPC_num_tasks:
7312 case OMPC_final:
7313 case OMPC_priority:
7314 case OMPC_novariants:
7315 case OMPC_nocontext:
7316 // Do not analyze if no parent parallel directive.
7317 if (isOpenMPParallelDirective(Kind))
7318 break;
7319 continue;
7320 case OMPC_ordered:
7321 case OMPC_device:
7322 case OMPC_num_teams:
7323 case OMPC_thread_limit:
7324 case OMPC_hint:
7325 case OMPC_collapse:
7326 case OMPC_safelen:
7327 case OMPC_simdlen:
7328 case OMPC_sizes:
7329 case OMPC_depth:
7330 case OMPC_default:
7331 case OMPC_proc_bind:
7332 case OMPC_private:
7333 case OMPC_firstprivate:
7334 case OMPC_lastprivate:
7335 case OMPC_shared:
7336 case OMPC_reduction:
7337 case OMPC_task_reduction:
7338 case OMPC_in_reduction:
7339 case OMPC_linear:
7340 case OMPC_aligned:
7341 case OMPC_copyin:
7342 case OMPC_copyprivate:
7343 case OMPC_nowait:
7344 case OMPC_untied:
7345 case OMPC_mergeable:
7346 case OMPC_allocate:
7347 case OMPC_read:
7348 case OMPC_write:
7349 case OMPC_update:
7350 case OMPC_capture:
7351 case OMPC_compare:
7352 case OMPC_seq_cst:
7353 case OMPC_acq_rel:
7354 case OMPC_acquire:
7355 case OMPC_release:
7356 case OMPC_relaxed:
7357 case OMPC_depend:
7358 case OMPC_threads:
7359 case OMPC_simd:
7360 case OMPC_map:
7361 case OMPC_nogroup:
7362 case OMPC_defaultmap:
7363 case OMPC_to:
7364 case OMPC_from:
7365 case OMPC_use_device_ptr:
7366 case OMPC_use_device_addr:
7367 case OMPC_is_device_ptr:
7368 case OMPC_has_device_addr:
7369 case OMPC_nontemporal:
7370 case OMPC_order:
7371 case OMPC_destroy:
7372 case OMPC_inclusive:
7373 case OMPC_exclusive:
7374 case OMPC_uses_allocators:
7375 case OMPC_affinity:
7376 case OMPC_bind:
7377 case OMPC_filter:
7378 case OMPC_severity:
7379 case OMPC_message:
7380 continue;
7381 case OMPC_allocator:
7382 case OMPC_flush:
7383 case OMPC_depobj:
7384 case OMPC_threadprivate:
7385 case OMPC_groupprivate:
7386 case OMPC_uniform:
7387 case OMPC_unknown:
7388 case OMPC_unified_address:
7389 case OMPC_unified_shared_memory:
7390 case OMPC_reverse_offload:
7391 case OMPC_dynamic_allocators:
7392 case OMPC_atomic_default_mem_order:
7393 case OMPC_self_maps:
7394 case OMPC_device_type:
7395 case OMPC_match:
7396 case OMPC_when:
7397 case OMPC_at:
7398 default:
7399 llvm_unreachable("Unexpected clause");
7400 }
7401 for (Stmt *CC : C->children()) {
7402 if (CC)
7403 DSAChecker.Visit(CC);
7404 }
7405 }
7406 for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
7407 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
7408 }
7409 for (const auto &P : VarsWithInheritedDSA) {
7410 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
7411 continue;
7412 ErrorFound = true;
7413 if (DSAStack->getDefaultDSA() == DSA_none ||
7414 DSAStack->getDefaultDSA() == DSA_private ||
7415 DSAStack->getDefaultDSA() == DSA_firstprivate) {
7416 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
7417 << P.first << P.second->getSourceRange();
7418 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
7419 } else if (getLangOpts().OpenMP >= 50) {
7420 Diag(P.second->getExprLoc(),
7421 diag::err_omp_defaultmap_no_attr_for_variable)
7422 << P.first << P.second->getSourceRange();
7423 Diag(DSAStack->getDefaultDSALocation(),
7424 diag::note_omp_defaultmap_attr_none);
7425 }
7426 }
7427
7428 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
7429 for (OpenMPDirectiveKind D : getLeafConstructsOrSelf(Kind)) {
7430 if (isAllowedClauseForDirective(D, OMPC_if,
7431 getLangOpts().getOpenMPVersion()))
7432 AllowedNameModifiers.push_back(D);
7433 }
7434 if (!AllowedNameModifiers.empty())
7435 ErrorFound = checkIfClauses(SemaRef, Kind, Clauses, AllowedNameModifiers) ||
7436 ErrorFound;
7437
7438 if (ErrorFound)
7439 return StmtError();
7440
7441 if (!SemaRef.CurContext->isDependentContext() &&
7443 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
7444 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
7445 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
7446 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
7447 // Register target to DSA Stack.
7448 DSAStack->addTargetDirLocation(StartLoc);
7449 }
7450
7451 return Res;
7452}
7453
7455 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
7456 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
7457 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
7458 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
7459 assert(Aligneds.size() == Alignments.size());
7460 assert(Linears.size() == LinModifiers.size());
7461 assert(Linears.size() == Steps.size());
7462 if (!DG || DG.get().isNull())
7463 return DeclGroupPtrTy();
7464
7465 const int SimdId = 0;
7466 if (!DG.get().isSingleDecl()) {
7467 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
7468 << SimdId;
7469 return DG;
7470 }
7471 Decl *ADecl = DG.get().getSingleDecl();
7472 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
7473 ADecl = FTD->getTemplatedDecl();
7474
7475 auto *FD = dyn_cast<FunctionDecl>(ADecl);
7476 if (!FD) {
7477 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
7478 return DeclGroupPtrTy();
7479 }
7480
7481 // OpenMP [2.8.2, declare simd construct, Description]
7482 // The parameter of the simdlen clause must be a constant positive integer
7483 // expression.
7484 ExprResult SL;
7485 if (Simdlen)
7486 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
7487 // OpenMP [2.8.2, declare simd construct, Description]
7488 // The special this pointer can be used as if was one of the arguments to the
7489 // function in any of the linear, aligned, or uniform clauses.
7490 // The uniform clause declares one or more arguments to have an invariant
7491 // value for all concurrent invocations of the function in the execution of a
7492 // single SIMD loop.
7493 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
7494 const Expr *UniformedLinearThis = nullptr;
7495 for (const Expr *E : Uniforms) {
7496 E = E->IgnoreParenImpCasts();
7497 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
7498 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
7499 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
7500 FD->getParamDecl(PVD->getFunctionScopeIndex())
7501 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
7502 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
7503 continue;
7504 }
7505 if (isa<CXXThisExpr>(E)) {
7506 UniformedLinearThis = E;
7507 continue;
7508 }
7509 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
7510 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
7511 }
7512 // OpenMP [2.8.2, declare simd construct, Description]
7513 // The aligned clause declares that the object to which each list item points
7514 // is aligned to the number of bytes expressed in the optional parameter of
7515 // the aligned clause.
7516 // The special this pointer can be used as if was one of the arguments to the
7517 // function in any of the linear, aligned, or uniform clauses.
7518 // The type of list items appearing in the aligned clause must be array,
7519 // pointer, reference to array, or reference to pointer.
7520 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
7521 const Expr *AlignedThis = nullptr;
7522 for (const Expr *E : Aligneds) {
7523 E = E->IgnoreParenImpCasts();
7524 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
7525 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
7526 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
7527 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
7528 FD->getParamDecl(PVD->getFunctionScopeIndex())
7529 ->getCanonicalDecl() == CanonPVD) {
7530 // OpenMP [2.8.1, simd construct, Restrictions]
7531 // A list-item cannot appear in more than one aligned clause.
7532 auto [It, Inserted] = AlignedArgs.try_emplace(CanonPVD, E);
7533 if (!Inserted) {
7534 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
7535 << 1 << getOpenMPClauseNameForDiag(OMPC_aligned)
7536 << E->getSourceRange();
7537 Diag(It->second->getExprLoc(), diag::note_omp_explicit_dsa)
7538 << getOpenMPClauseNameForDiag(OMPC_aligned);
7539 continue;
7540 }
7541 QualType QTy = PVD->getType()
7542 .getNonReferenceType()
7543 .getUnqualifiedType()
7544 .getCanonicalType();
7545 const Type *Ty = QTy.getTypePtrOrNull();
7546 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
7547 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
7548 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
7549 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
7550 }
7551 continue;
7552 }
7553 }
7554 if (isa<CXXThisExpr>(E)) {
7555 if (AlignedThis) {
7556 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
7557 << 2 << getOpenMPClauseNameForDiag(OMPC_aligned)
7558 << E->getSourceRange();
7559 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
7560 << getOpenMPClauseNameForDiag(OMPC_aligned);
7561 }
7562 AlignedThis = E;
7563 continue;
7564 }
7565 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
7566 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
7567 }
7568 // The optional parameter of the aligned clause, alignment, must be a constant
7569 // positive integer expression. If no optional parameter is specified,
7570 // implementation-defined default alignments for SIMD instructions on the
7571 // target platforms are assumed.
7573 for (Expr *E : Alignments) {
7574 ExprResult Align;
7575 if (E)
7576 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
7577 NewAligns.push_back(Align.get());
7578 }
7579 // OpenMP [2.8.2, declare simd construct, Description]
7580 // The linear clause declares one or more list items to be private to a SIMD
7581 // lane and to have a linear relationship with respect to the iteration space
7582 // of a loop.
7583 // The special this pointer can be used as if was one of the arguments to the
7584 // function in any of the linear, aligned, or uniform clauses.
7585 // When a linear-step expression is specified in a linear clause it must be
7586 // either a constant integer expression or an integer-typed parameter that is
7587 // specified in a uniform clause on the directive.
7588 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
7589 const bool IsUniformedThis = UniformedLinearThis != nullptr;
7590 auto MI = LinModifiers.begin();
7591 for (const Expr *E : Linears) {
7592 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
7593 ++MI;
7594 E = E->IgnoreParenImpCasts();
7595 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
7596 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
7597 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
7598 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
7599 FD->getParamDecl(PVD->getFunctionScopeIndex())
7600 ->getCanonicalDecl() == CanonPVD) {
7601 // OpenMP [2.15.3.7, linear Clause, Restrictions]
7602 // A list-item cannot appear in more than one linear clause.
7603 if (auto It = LinearArgs.find(CanonPVD); It != LinearArgs.end()) {
7604 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
7605 << getOpenMPClauseNameForDiag(OMPC_linear)
7606 << getOpenMPClauseNameForDiag(OMPC_linear)
7607 << E->getSourceRange();
7608 Diag(It->second->getExprLoc(), diag::note_omp_explicit_dsa)
7609 << getOpenMPClauseNameForDiag(OMPC_linear);
7610 continue;
7611 }
7612 // Each argument can appear in at most one uniform or linear clause.
7613 if (auto It = UniformedArgs.find(CanonPVD);
7614 It != UniformedArgs.end()) {
7615 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
7616 << getOpenMPClauseNameForDiag(OMPC_linear)
7617 << getOpenMPClauseNameForDiag(OMPC_uniform)
7618 << E->getSourceRange();
7619 Diag(It->second->getExprLoc(), diag::note_omp_explicit_dsa)
7620 << getOpenMPClauseNameForDiag(OMPC_uniform);
7621 continue;
7622 }
7623 LinearArgs[CanonPVD] = E;
7624 if (E->isValueDependent() || E->isTypeDependent() ||
7627 continue;
7628 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
7629 PVD->getOriginalType(),
7630 /*IsDeclareSimd=*/true);
7631 continue;
7632 }
7633 }
7634 if (isa<CXXThisExpr>(E)) {
7635 if (UniformedLinearThis) {
7636 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
7637 << getOpenMPClauseNameForDiag(OMPC_linear)
7638 << getOpenMPClauseNameForDiag(IsUniformedThis ? OMPC_uniform
7639 : OMPC_linear)
7640 << E->getSourceRange();
7641 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
7642 << getOpenMPClauseNameForDiag(IsUniformedThis ? OMPC_uniform
7643 : OMPC_linear);
7644 continue;
7645 }
7646 UniformedLinearThis = E;
7647 if (E->isValueDependent() || E->isTypeDependent() ||
7649 continue;
7650 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
7651 E->getType(), /*IsDeclareSimd=*/true);
7652 continue;
7653 }
7654 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
7655 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
7656 }
7657 Expr *Step = nullptr;
7658 Expr *NewStep = nullptr;
7659 SmallVector<Expr *, 4> NewSteps;
7660 for (Expr *E : Steps) {
7661 // Skip the same step expression, it was checked already.
7662 if (Step == E || !E) {
7663 NewSteps.push_back(E ? NewStep : nullptr);
7664 continue;
7665 }
7666 Step = E;
7667 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
7668 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
7669 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
7670 if (UniformedArgs.count(CanonPVD) == 0) {
7671 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
7672 << Step->getSourceRange();
7673 } else if (E->isValueDependent() || E->isTypeDependent() ||
7676 CanonPVD->getType()->hasIntegerRepresentation()) {
7677 NewSteps.push_back(Step);
7678 } else {
7679 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
7680 << Step->getSourceRange();
7681 }
7682 continue;
7683 }
7684 NewStep = Step;
7685 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
7686 !Step->isInstantiationDependent() &&
7688 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
7689 .get();
7690 if (NewStep)
7691 NewStep = SemaRef
7692 .VerifyIntegerConstantExpression(
7693 NewStep, /*FIXME*/ AllowFoldKind::Allow)
7694 .get();
7695 }
7696 NewSteps.push_back(NewStep);
7697 }
7698 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
7699 getASTContext(), BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
7700 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
7701 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
7702 const_cast<Expr **>(Linears.data()), Linears.size(),
7703 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
7704 NewSteps.data(), NewSteps.size(), SR);
7705 ADecl->addAttr(NewAttr);
7706 return DG;
7707}
7708
7710 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
7711 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7712 SourceLocation EndLoc) {
7713 assert(isOpenMPInformationalDirective(Kind) &&
7714 "Unexpected directive category");
7715
7716 StmtResult Res = StmtError();
7717
7718 switch (Kind) {
7719 case OMPD_assume:
7720 Res = ActOnOpenMPAssumeDirective(Clauses, AStmt, StartLoc, EndLoc);
7721 break;
7722 default:
7723 llvm_unreachable("Unknown OpenMP directive");
7724 }
7725
7726 return Res;
7727}
7728
7729static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
7730 QualType NewType) {
7731 assert(NewType->isFunctionProtoType() &&
7732 "Expected function type with prototype.");
7733 assert(FD->getType()->isFunctionNoProtoType() &&
7734 "Expected function with type with no prototype.");
7735 assert(FDWithProto->getType()->isFunctionProtoType() &&
7736 "Expected function with prototype.");
7737 // Synthesize parameters with the same types.
7738 FD->setType(NewType);
7740 for (const ParmVarDecl *P : FDWithProto->parameters()) {
7741 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
7742 SourceLocation(), nullptr, P->getType(),
7743 /*TInfo=*/nullptr, SC_None, nullptr);
7744 Param->setScopeInfo(0, Params.size());
7745 Param->setImplicit();
7746 Params.push_back(Param);
7747 }
7748
7749 FD->setParams(Params);
7750}
7751
7753 if (D->isInvalidDecl())
7754 return;
7755 FunctionDecl *FD = nullptr;
7756 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
7757 FD = UTemplDecl->getTemplatedDecl();
7758 else
7759 FD = cast<FunctionDecl>(D);
7760 assert(FD && "Expected a function declaration!");
7761
7762 // If we are instantiating templates we do *not* apply scoped assumptions but
7763 // only global ones. We apply scoped assumption to the template definition
7764 // though.
7765 if (!SemaRef.inTemplateInstantiation()) {
7766 for (OMPAssumeAttr *AA : OMPAssumeScoped)
7767 FD->addAttr(AA);
7768 }
7769 for (OMPAssumeAttr *AA : OMPAssumeGlobal)
7770 FD->addAttr(AA);
7771}
7772
7773SemaOpenMP::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
7774 : TI(&TI), NameSuffix(TI.getMangledName()) {}
7775
7777 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
7779 if (!D.getIdentifier())
7780 return;
7781
7782 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
7783
7784 // Template specialization is an extension, check if we do it.
7785 bool IsTemplated = !TemplateParamLists.empty();
7786 if (IsTemplated &&
7787 !DVScope.TI->isExtensionActive(
7788 llvm::omp::TraitProperty::implementation_extension_allow_templates))
7789 return;
7790
7791 const IdentifierInfo *BaseII = D.getIdentifier();
7794 SemaRef.LookupParsedName(Lookup, S, &D.getCXXScopeSpec(),
7795 /*ObjectType=*/QualType());
7796
7797 TypeSourceInfo *TInfo = SemaRef.GetTypeForDeclarator(D);
7798 QualType FType = TInfo->getType();
7799
7800 bool IsConstexpr =
7802 bool IsConsteval =
7804
7805 for (auto *Candidate : Lookup) {
7806 auto *CandidateDecl = Candidate->getUnderlyingDecl();
7807 FunctionDecl *UDecl = nullptr;
7808 if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) {
7809 auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl);
7810 // FIXME: Should this compare the template parameter lists on all levels?
7811 if (SemaRef.Context.isSameTemplateParameterList(
7812 FTD->getTemplateParameters(), TemplateParamLists.back()))
7813 UDecl = FTD->getTemplatedDecl();
7814 } else if (!IsTemplated)
7815 UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
7816 if (!UDecl)
7817 continue;
7818
7819 // Don't specialize constexpr/consteval functions with
7820 // non-constexpr/consteval functions.
7821 if (UDecl->isConstexpr() && !IsConstexpr)
7822 continue;
7823 if (UDecl->isConsteval() && !IsConsteval)
7824 continue;
7825
7826 QualType UDeclTy = UDecl->getType();
7827 if (!UDeclTy->isDependentType()) {
7829 FType, UDeclTy, /*OfBlockPointer=*/false,
7830 /*Unqualified=*/false, /*AllowCXX=*/true);
7831 if (NewType.isNull())
7832 continue;
7833 }
7834
7835 // Found a base!
7836 Bases.push_back(UDecl);
7837 }
7838
7839 bool UseImplicitBase = !DVScope.TI->isExtensionActive(
7840 llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
7841 // If no base was found we create a declaration that we use as base.
7842 if (Bases.empty() && UseImplicitBase) {
7844 Decl *BaseD = SemaRef.HandleDeclarator(S, D, TemplateParamLists);
7845 BaseD->setImplicit(true);
7846 if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
7847 Bases.push_back(BaseTemplD->getTemplatedDecl());
7848 else
7849 Bases.push_back(cast<FunctionDecl>(BaseD));
7850 }
7851
7852 std::string MangledName;
7853 MangledName += D.getIdentifier()->getName();
7854 MangledName += getOpenMPVariantManglingSeparatorStr();
7855 MangledName += DVScope.NameSuffix;
7856 IdentifierInfo &VariantII = getASTContext().Idents.get(MangledName);
7857
7858 VariantII.setMangledOpenMPVariantName(true);
7859 D.SetIdentifier(&VariantII, D.getBeginLoc());
7860}
7861
7864 // Do not mark function as is used to prevent its emission if this is the
7865 // only place where it is used.
7868
7869 FunctionDecl *FD = nullptr;
7870 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
7871 FD = UTemplDecl->getTemplatedDecl();
7872 else
7873 FD = cast<FunctionDecl>(D);
7874 auto *VariantFuncRef = DeclRefExpr::Create(
7876 /*RefersToEnclosingVariableOrCapture=*/false,
7877 /*NameLoc=*/FD->getLocation(), FD->getType(), ExprValueKind::VK_PRValue);
7878
7879 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
7880 auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
7881 getASTContext(), VariantFuncRef, DVScope.TI,
7882 /*AdjustArgs=*/nullptr, /*AdjustArgsSize=*/0,
7883 /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0);
7884 for (FunctionDecl *BaseFD : Bases)
7885 BaseFD->addAttr(OMPDeclareVariantA);
7886}
7887
7889 SourceLocation LParenLoc,
7890 MultiExprArg ArgExprs,
7891 SourceLocation RParenLoc,
7892 Expr *ExecConfig) {
7893 // The common case is a regular call we do not want to specialize at all. Try
7894 // to make that case fast by bailing early.
7895 CallExpr *CE = dyn_cast<CallExpr>(Call.get());
7896 if (!CE)
7897 return Call;
7898
7899 FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
7900
7901 // Mark indirect calls inside target regions, to allow for insertion of
7902 // __llvm_omp_indirect_call_lookup calls during codegen.
7903 if (!CalleeFnDecl) {
7905 Expr *E = CE->getCallee()->IgnoreParenImpCasts();
7906 DeclRefExpr *DRE = nullptr;
7907 while (E) {
7908 if ((DRE = dyn_cast<DeclRefExpr>(E)))
7909 break;
7910 if (auto *ME = dyn_cast<MemberExpr>(E))
7911 E = ME->getBase()->IgnoreParenImpCasts();
7912 else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
7913 E = ASE->getBase()->IgnoreParenImpCasts();
7914 else
7915 break;
7916 }
7917 VarDecl *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
7918 if (VD && !VD->hasAttr<OMPTargetIndirectCallAttr>()) {
7919 VD->addAttr(OMPTargetIndirectCallAttr::CreateImplicit(getASTContext()));
7920 if (ASTMutationListener *ML = getASTContext().getASTMutationListener())
7921 ML->DeclarationMarkedOpenMPIndirectCall(VD);
7922 }
7923 }
7924
7925 return Call;
7926 }
7927
7928 if (getLangOpts().OpenMP >= 50 && getLangOpts().OpenMP <= 60 &&
7929 CalleeFnDecl->getIdentifier() &&
7930 CalleeFnDecl->getName().starts_with_insensitive("omp_")) {
7931 // checking for any calls inside an Order region
7933 Diag(LParenLoc, diag::err_omp_unexpected_call_to_omp_runtime_api);
7934 }
7935
7936 if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
7937 return Call;
7938
7939 ASTContext &Context = getASTContext();
7940 std::function<void(StringRef)> DiagUnknownTrait = [this,
7941 CE](StringRef ISATrait) {
7942 // TODO Track the selector locations in a way that is accessible here to
7943 // improve the diagnostic location.
7944 Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
7945 << ISATrait;
7946 };
7947 TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
7948 SemaRef.getCurFunctionDecl(),
7949 DSAStack->getConstructTraits(), getOpenMPDeviceNum());
7950
7951 QualType CalleeFnType = CalleeFnDecl->getType();
7952
7955 while (CalleeFnDecl) {
7956 for (OMPDeclareVariantAttr *A :
7957 CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
7958 Expr *VariantRef = A->getVariantFuncRef();
7959
7960 VariantMatchInfo VMI;
7961 OMPTraitInfo &TI = A->getTraitInfo();
7962 TI.getAsVariantMatchInfo(Context, VMI);
7963 if (!isVariantApplicableInContext(VMI, OMPCtx,
7964 /*DeviceSetOnly=*/false))
7965 continue;
7966
7967 VMIs.push_back(VMI);
7968 Exprs.push_back(VariantRef);
7969 }
7970
7971 CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
7972 }
7973
7974 ExprResult NewCall;
7975 do {
7976 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
7977 if (BestIdx < 0)
7978 return Call;
7979 Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
7980 Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
7981
7982 {
7983 // Try to build a (member) call expression for the current best applicable
7984 // variant expression. We allow this to fail in which case we continue
7985 // with the next best variant expression. The fail case is part of the
7986 // implementation defined behavior in the OpenMP standard when it talks
7987 // about what differences in the function prototypes: "Any differences
7988 // that the specific OpenMP context requires in the prototype of the
7989 // variant from the base function prototype are implementation defined."
7990 // This wording is there to allow the specialized variant to have a
7991 // different type than the base function. This is intended and OK but if
7992 // we cannot create a call the difference is not in the "implementation
7993 // defined range" we allow.
7995
7996 if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
7997 auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
7998 BestExpr = MemberExpr::CreateImplicit(
7999 Context, MemberCall->getImplicitObjectArgument(),
8000 /*IsArrow=*/false, SpecializedMethod, Context.BoundMemberTy,
8001 MemberCall->getValueKind(), MemberCall->getObjectKind());
8002 }
8003 NewCall = SemaRef.BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs,
8004 RParenLoc, ExecConfig);
8005 if (NewCall.isUsable()) {
8006 if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
8007 FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
8009 CalleeFnType, NewCalleeFnDecl->getType(),
8010 /*OfBlockPointer=*/false,
8011 /*Unqualified=*/false, /*AllowCXX=*/true);
8012 if (!NewType.isNull())
8013 break;
8014 // Don't use the call if the function type was not compatible.
8015 NewCall = nullptr;
8016 }
8017 }
8018 }
8019
8020 VMIs.erase(VMIs.begin() + BestIdx);
8021 Exprs.erase(Exprs.begin() + BestIdx);
8022 } while (!VMIs.empty());
8023
8024 if (!NewCall.isUsable())
8025 return Call;
8026 return PseudoObjectExpr::Create(getASTContext(), CE, {NewCall.get()}, 0);
8027}
8028
8029std::optional<std::pair<FunctionDecl *, Expr *>>
8031 Expr *VariantRef,
8032 OMPTraitInfo &TI,
8033 unsigned NumAppendArgs,
8034 SourceRange SR) {
8035 ASTContext &Context = getASTContext();
8036 if (!DG || DG.get().isNull())
8037 return std::nullopt;
8038
8039 const int VariantId = 1;
8040 // Must be applied only to single decl.
8041 if (!DG.get().isSingleDecl()) {
8042 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
8043 << VariantId << SR;
8044 return std::nullopt;
8045 }
8046 Decl *ADecl = DG.get().getSingleDecl();
8047 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
8048 ADecl = FTD->getTemplatedDecl();
8049
8050 // Decl must be a function.
8051 auto *FD = dyn_cast<FunctionDecl>(ADecl);
8052 if (!FD) {
8053 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
8054 << VariantId << SR;
8055 return std::nullopt;
8056 }
8057
8058 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
8059 // The 'target' attribute needs to be separately checked because it does
8060 // not always signify a multiversion function declaration.
8061 return FD->isMultiVersion() || FD->hasAttr<TargetAttr>();
8062 };
8063 // OpenMP is not compatible with multiversion function attributes.
8064 if (HasMultiVersionAttributes(FD)) {
8065 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
8066 << SR;
8067 return std::nullopt;
8068 }
8069
8070 // Allow #pragma omp declare variant only if the function is not used.
8071 if (FD->isUsed(false))
8072 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
8073 << FD->getLocation();
8074
8075 // Check if the function was emitted already.
8076 const FunctionDecl *Definition;
8077 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
8078 (getLangOpts().EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
8079 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
8080 << FD->getLocation();
8081
8082 // The VariantRef must point to function.
8083 if (!VariantRef) {
8084 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
8085 return std::nullopt;
8086 }
8087
8088 auto ShouldDelayChecks = [](Expr *&E, bool) {
8089 return E && (E->isTypeDependent() || E->isValueDependent() ||
8092 };
8093 // Do not check templates, wait until instantiation.
8094 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
8095 TI.anyScoreOrCondition(ShouldDelayChecks))
8096 return std::make_pair(FD, VariantRef);
8097
8098 // Deal with non-constant score and user condition expressions.
8099 auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
8100 bool IsScore) -> bool {
8101 if (!E || E->isIntegerConstantExpr(getASTContext()))
8102 return false;
8103
8104 if (IsScore) {
8105 // We warn on non-constant scores and pretend they were not present.
8106 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
8107 << E;
8108 E = nullptr;
8109 } else {
8110 // We could replace a non-constant user condition with "false" but we
8111 // will soon need to handle these anyway for the dynamic version of
8112 // OpenMP context selectors.
8113 Diag(E->getExprLoc(),
8114 diag::err_omp_declare_variant_user_condition_not_constant)
8115 << E;
8116 }
8117 return true;
8118 };
8119 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
8120 return std::nullopt;
8121
8122 QualType AdjustedFnType = FD->getType();
8123 if (NumAppendArgs) {
8124 const auto *PTy = AdjustedFnType->getAsAdjusted<FunctionProtoType>();
8125 if (!PTy) {
8126 Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required)
8127 << SR;
8128 return std::nullopt;
8129 }
8130 // Adjust the function type to account for an extra omp_interop_t for each
8131 // specified in the append_args clause.
8132 const TypeDecl *TD = nullptr;
8133 LookupResult Result(SemaRef, &Context.Idents.get("omp_interop_t"),
8135 if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
8136 NamedDecl *ND = Result.getFoundDecl();
8137 TD = dyn_cast_or_null<TypeDecl>(ND);
8138 }
8139 if (!TD) {
8140 Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR;
8141 return std::nullopt;
8142 }
8143 QualType InteropType =
8144 Context.getTypeDeclType(ElaboratedTypeKeyword::None,
8145 /*Qualifier=*/std::nullopt, TD);
8146 if (PTy->isVariadic()) {
8147 Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR;
8148 return std::nullopt;
8149 }
8151 Params.append(PTy->param_type_begin(), PTy->param_type_end());
8152 Params.insert(Params.end(), NumAppendArgs, InteropType);
8153 AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params,
8154 PTy->getExtProtoInfo());
8155 }
8156
8157 // Convert VariantRef expression to the type of the original function to
8158 // resolve possible conflicts.
8159 ExprResult VariantRefCast = VariantRef;
8160 if (getLangOpts().CPlusPlus) {
8161 QualType FnPtrType;
8162 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8163 if (Method && !Method->isStatic()) {
8164 FnPtrType = Context.getMemberPointerType(
8165 AdjustedFnType, /*Qualifier=*/std::nullopt, Method->getParent());
8166 ExprResult ER;
8167 {
8168 // Build addr_of unary op to correctly handle type checks for member
8169 // functions.
8171 ER = SemaRef.CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
8172 VariantRef);
8173 }
8174 if (!ER.isUsable()) {
8175 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
8176 << VariantId << VariantRef->getSourceRange();
8177 return std::nullopt;
8178 }
8179 VariantRef = ER.get();
8180 } else {
8181 FnPtrType = Context.getPointerType(AdjustedFnType);
8182 }
8183 QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
8184 if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
8185 ImplicitConversionSequence ICS = SemaRef.TryImplicitConversion(
8186 VariantRef, FnPtrType.getUnqualifiedType(),
8187 /*SuppressUserConversions=*/false, Sema::AllowedExplicit::None,
8188 /*InOverloadResolution=*/false,
8189 /*CStyle=*/false,
8190 /*AllowObjCWritebackConversion=*/false);
8191 if (ICS.isFailure()) {
8192 Diag(VariantRef->getExprLoc(),
8193 diag::err_omp_declare_variant_incompat_types)
8194 << VariantRef->getType()
8195 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
8196 << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange();
8197 return std::nullopt;
8198 }
8199 VariantRefCast = SemaRef.PerformImplicitConversion(
8200 VariantRef, FnPtrType.getUnqualifiedType(),
8202 if (!VariantRefCast.isUsable())
8203 return std::nullopt;
8204 }
8205 // Drop previously built artificial addr_of unary op for member functions.
8206 if (Method && !Method->isStatic()) {
8207 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
8208 if (auto *UO = dyn_cast<UnaryOperator>(
8209 PossibleAddrOfVariantRef->IgnoreImplicit()))
8210 VariantRefCast = UO->getSubExpr();
8211 }
8212 }
8213
8214 ExprResult ER = SemaRef.CheckPlaceholderExpr(VariantRefCast.get());
8215 if (!ER.isUsable() ||
8217 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
8218 << VariantId << VariantRef->getSourceRange();
8219 return std::nullopt;
8220 }
8221
8222 // The VariantRef must point to function.
8223 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
8224 if (!DRE) {
8225 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
8226 << VariantId << VariantRef->getSourceRange();
8227 return std::nullopt;
8228 }
8229 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
8230 if (!NewFD) {
8231 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
8232 << VariantId << VariantRef->getSourceRange();
8233 return std::nullopt;
8234 }
8235
8236 if (FD->getCanonicalDecl() == NewFD->getCanonicalDecl()) {
8237 Diag(VariantRef->getExprLoc(),
8238 diag::err_omp_declare_variant_same_base_function)
8239 << VariantRef->getSourceRange();
8240 return std::nullopt;
8241 }
8242
8243 // Check if function types are compatible in C.
8244 if (!getLangOpts().CPlusPlus) {
8245 QualType NewType =
8246 Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType());
8247 if (NewType.isNull()) {
8248 Diag(VariantRef->getExprLoc(),
8249 diag::err_omp_declare_variant_incompat_types)
8250 << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0)
8251 << VariantRef->getSourceRange();
8252 return std::nullopt;
8253 }
8254 if (NewType->isFunctionProtoType()) {
8255 if (FD->getType()->isFunctionNoProtoType())
8256 setPrototype(SemaRef, FD, NewFD, NewType);
8257 else if (NewFD->getType()->isFunctionNoProtoType())
8258 setPrototype(SemaRef, NewFD, FD, NewType);
8259 }
8260 }
8261
8262 // Check if variant function is not marked with declare variant directive.
8263 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
8264 Diag(VariantRef->getExprLoc(),
8265 diag::warn_omp_declare_variant_marked_as_declare_variant)
8266 << VariantRef->getSourceRange();
8267 SourceRange SR =
8268 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
8269 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
8270 return std::nullopt;
8271 }
8272
8273 enum DoesntSupport {
8274 VirtFuncs = 1,
8275 Constructors = 3,
8276 Destructors = 4,
8277 DeletedFuncs = 5,
8278 DefaultedFuncs = 6,
8279 ConstexprFuncs = 7,
8280 ConstevalFuncs = 8,
8281 };
8282 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
8283 if (CXXFD->isVirtual()) {
8284 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
8285 << VirtFuncs;
8286 return std::nullopt;
8287 }
8288
8289 if (isa<CXXConstructorDecl>(FD)) {
8290 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
8291 << Constructors;
8292 return std::nullopt;
8293 }
8294
8295 if (isa<CXXDestructorDecl>(FD)) {
8296 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
8297 << Destructors;
8298 return std::nullopt;
8299 }
8300 }
8301
8302 if (FD->isDeleted()) {
8303 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
8304 << DeletedFuncs;
8305 return std::nullopt;
8306 }
8307
8308 if (FD->isDefaulted()) {
8309 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
8310 << DefaultedFuncs;
8311 return std::nullopt;
8312 }
8313
8314 if (FD->isConstexpr()) {
8315 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
8316 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
8317 return std::nullopt;
8318 }
8319
8320 // Check general compatibility.
8321 if (SemaRef.areMultiversionVariantFunctionsCompatible(
8326 VariantRef->getExprLoc(),
8327 SemaRef.PDiag(diag::err_omp_declare_variant_doesnt_support)),
8328 PartialDiagnosticAt(VariantRef->getExprLoc(),
8329 SemaRef.PDiag(diag::err_omp_declare_variant_diff)
8330 << FD->getLocation()),
8331 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
8332 /*CLinkageMayDiffer=*/true))
8333 return std::nullopt;
8334 return std::make_pair(FD, cast<Expr>(DRE));
8335}
8336
8337/// Validate prefer_type fr() and attr() arguments in an OMPInteropInfo.
8338/// fr() must be a string literal or constant integer expression.
8339/// attr() must be a string literal starting with "ompx_" and containing no
8340/// commas. Returns true if valid; emits diagnostic and returns false on first
8341/// error.
8342static bool checkPreferTypeArgs(SemaOpenMP &S, const OMPInteropInfo &Info) {
8343 auto isDependent = [](const Expr *E) {
8344 return E->isValueDependent() || E->isTypeDependent() ||
8347 };
8348 for (const OMPInteropPref &P : Info.Prefs) {
8349 const Expr *E = P.Fr;
8350 if (!E) {
8351 assert(Info.HasPreferAttrs && "null Fr requires OMP 6.0 syntax");
8352 } else if (!isDependent(E)) {
8353 if (!E->isIntegerConstantExpr(S.getASTContext()) &&
8354 !isa<StringLiteral>(E)) {
8355 S.Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
8356 return false;
8357 }
8358 }
8359 for (const Expr *A : P.Attrs) {
8360 if (isDependent(A))
8361 continue;
8362 const auto *SL = dyn_cast<StringLiteral>(A);
8363 if (!SL) {
8364 S.Diag(A->getExprLoc(), diag::err_omp_interop_attr_not_string);
8365 return false;
8366 }
8367 StringRef Str = SL->getString();
8368 if (!Str.starts_with("ompx_")) {
8369 S.Diag(A->getExprLoc(), diag::err_omp_interop_attr_missing_ompx_prefix)
8370 << Str;
8371 return false;
8372 }
8373 if (Str.contains(',')) {
8374 S.Diag(A->getExprLoc(), diag::err_omp_interop_attr_contains_comma)
8375 << Str;
8376 return false;
8377 }
8378 }
8379 }
8380 return true;
8381}
8382
8384
8385/// Check one 'adjust_args' integer expression for the constant property plus
8386/// either the positive or the non-negative property (OpenMP 6.0 [5.2.1]).
8388 bool StrictlyPositive,
8389 llvm::APSInt &Result) {
8390 if (E->isInstantiationDependent())
8391 return OMPAdjustArgsVal::Dependent; // re-checked on instantiation
8393 return OMPAdjustArgsVal::Invalid; // already diagnosed
8394 if (StrictlyPositive ? !Result.isStrictlyPositive() : Result.isNegative()) {
8395 S.Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
8396 << getOpenMPClauseNameForDiag(OMPC_adjust_args)
8397 << (StrictlyPositive ? 1 : 0) << E->getSourceRange();
8399 }
8400 if (!Result.isRepresentableByInt64()) {
8401 S.Diag(E->getExprLoc(), diag::err_omp_large_expression_in_clause)
8402 << getOpenMPClauseNameForDiag(OMPC_adjust_args) << E->getSourceRange();
8404 }
8406}
8407
8408/// Check one bound of a parameter range 'lb:ub' (OpenMP 6.0 [5.2.1]).
8409/// A plain bound has the positive property, checked via
8410/// checkOMPAdjustArgsValue. An 'omp_num_args' bound's logical_offset has the
8411/// non-negative property instead, so it is checked with a different lower
8412/// bound.
8414 const OMPAdjustArgsItem::Bound &Bound) {
8416 return true;
8417 if (Bound.Kind == OMPAdjustArgsItem::Bound::NumArgs && !Bound.E)
8418 return true;
8419
8420 assert((Bound.Kind == OMPAdjustArgsItem::Bound::Expression ||
8422 Bound.E && "expected an adjust_args bound expression");
8423 llvm::APSInt Result;
8424 bool StrictlyPositive = Bound.Kind == OMPAdjustArgsItem::Bound::Expression;
8425 return checkOMPAdjustArgsValue(S, Bound.E, StrictlyPositive, Result) !=
8427}
8428
8430 const OMPAdjustArgsItem &Range) {
8431 assert(Range.Kind == OMPAdjustArgsItem::Range &&
8432 "expected an adjust_args range");
8433 return checkOMPAdjustArgsBound(S, Range.Lower) &&
8434 checkOMPAdjustArgsBound(S, Range.Upper);
8435}
8436
8438 SourceLocation FallbackLoc) {
8439 if (Item.E)
8440 return Item.E->getExprLoc();
8441 if (Item.Lower.E)
8442 return Item.Lower.E->getExprLoc();
8443 if (Item.Upper.E)
8444 return Item.Upper.E->getExprLoc();
8445 return FallbackLoc;
8446}
8447
8449 OpenMPAdjustArgsOpKind AdjustOp,
8450 OpenMPNeedDevicePtrModifier NeedDevicePtrModifier,
8452 // OpenMP 6.0 [9.6.2]: the fallback modifier is only valid with
8453 // need_device_ptr.
8454 if (NeedDevicePtrModifier != OMPC_NEED_DEVICE_PTR_unknown &&
8455 AdjustOp != OMPC_ADJUST_ARGS_need_device_ptr) {
8456 Diag(Loc, diag::err_omp_unexpected_clause_modifier)
8457 << getOpenMPClauseName(OMPC_adjust_args);
8458 return nullptr;
8459 }
8461 NeedDevicePtrModifier, Items);
8462}
8463
8465 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
8467 ArrayRef<OMPInteropInfo> AppendArgs, SourceLocation AdjustArgsLoc,
8468 SourceLocation AppendArgsLoc, SourceRange SR) {
8469
8470 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
8471 // An adjust_args clause or append_args clause can only be specified if the
8472 // dispatch selector of the construct selector set appears in the match
8473 // clause.
8474
8475 if (!AdjustArgs.empty() || !AppendArgs.empty()) {
8476 VariantMatchInfo VMI;
8478 if (!llvm::is_contained(
8479 VMI.ConstructTraits,
8480 llvm::omp::TraitProperty::construct_dispatch_dispatch)) {
8481 if (!AdjustArgs.empty())
8482 Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
8483 << getOpenMPClauseNameForDiag(OMPC_adjust_args);
8484 if (!AppendArgs.empty())
8485 Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
8486 << getOpenMPClauseNameForDiag(OMPC_append_args);
8487 return;
8488 }
8489 }
8490
8491 // OpenMP 6.0 [5.2.1]: each parameter list item may be specified only once
8492 // across all clauses of the same type in a directive. A range has the effect
8493 // of specifying each of its parameter positions individually.
8494 llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars; // named items
8495 llvm::SmallSet<uint64_t, 4> AdjustPositions; // positions, including ranges
8496
8497 for (const OMPAdjustArgsDescriptor *Desc : AdjustArgs) {
8498 for (const OMPAdjustArgsItem &ItemInfo : Desc->items()) {
8499 if (ItemInfo.Kind == OMPAdjustArgsItem::Range) {
8500 if (!checkOMPAdjustArgsRange(*this, ItemInfo))
8501 continue;
8502 SmallVector<unsigned, 8> Positions;
8503 if (resolveOMPAdjustArgsItem(ItemInfo, FD, FD->getNumParams(),
8504 getASTContext(), Positions)) {
8505 for (unsigned Pos : Positions) {
8506 if (!AdjustPositions.insert(Pos).second) {
8507 Diag(getOMPAdjustArgsItemLoc(ItemInfo, AdjustArgsLoc),
8508 diag::err_omp_adjust_arg_multiple_clauses)
8509 << Pos;
8510 return;
8511 }
8512 }
8513 }
8514 continue;
8515 }
8516
8517 assert(ItemInfo.E && "expected an adjust_args expression");
8518 Expr *Item = ItemInfo.E->IgnoreParenImpCasts();
8519
8520 // A named parameter list item — unchanged from OpenMP 5.1.
8521 if (const auto *DRE = dyn_cast<DeclRefExpr>(Item)) {
8522 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
8523 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
8524 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
8525 FD->getParamDecl(PVD->getFunctionScopeIndex())
8526 ->getCanonicalDecl() == CanonPVD) {
8527 if (!AdjustVars.insert(CanonPVD).second) {
8528 Diag(DRE->getLocation(),
8529 diag::err_omp_adjust_arg_multiple_clauses)
8530 << PVD;
8531 return;
8532 }
8533 continue;
8534 }
8535 }
8536 }
8537
8538 if (getLangOpts().OpenMP < 60) {
8539 // Anything that is not a function parameter is an error before 6.0.
8540 Diag(Item->getExprLoc(), diag::err_omp_param_or_this_in_clause)
8541 << FD << 0;
8542 return;
8543 }
8544
8545 // OpenMP 6.0 [5.2.1]: the position of a parameter, given as a
8546 // positive constant integer expression. A dependent item is skipped
8547 // here and rechecked when the template is instantiated.
8548 if (Item->isTypeDependent() || Item->getType()->isIntegerType()) {
8549 llvm::APSInt Pos;
8550 switch (checkOMPAdjustArgsValue(*this, Item,
8551 /*StrictlyPositive=*/true, Pos)) {
8553 return;
8555 continue;
8557 if (!AdjustPositions.insert(Pos.getZExtValue()).second) {
8558 Diag(Item->getExprLoc(), diag::err_omp_adjust_arg_multiple_clauses)
8559 << Pos;
8560 return;
8561 }
8562 continue;
8563 }
8564 }
8565
8566 if (isa<DeclRefExpr>(Item)) {
8567 Diag(Item->getExprLoc(), diag::err_omp_param_or_this_in_clause)
8568 << FD << 0;
8569 return;
8570 }
8571
8572 // Not a name or a position: neither form OpenMP 6.0 allows for a
8573 // non-range item.
8574 Diag(Item->getExprLoc(), diag::err_omp_adjust_args_invalid_item);
8575 return;
8576 }
8577 }
8578
8579 // OpenMP 6.0 [9.6.2]: if the need_device_addr adjust-op modifier
8580 // is present, each list item that appears in the clause must refer to an
8581 // argument in the declaration of the function variant that has a reference
8582 // type. Unlike the need_device_ptr restriction, this one is not scoped to
8583 // named items ("that refers to a specific named argument" is absent here),
8584 // so positions and ranges are checked too, via the shared item-to-positions
8585 // resolver.
8586 if (getLangOpts().OpenMP >= 60) {
8587 for (const OMPAdjustArgsDescriptor *Desc : AdjustArgs) {
8588 if (Desc->AdjustOp != OMPC_ADJUST_ARGS_need_device_addr)
8589 continue;
8590 for (const OMPAdjustArgsItem &Item : Desc->items()) {
8591 SmallVector<unsigned, 8> Positions;
8592 // With no call site in hand, 'omp_num_args' is the declared parameter
8593 // count (OpenMP 6.0 [20.1]). Positions past it denote variadic
8594 // actuals, which have no declared parameter to check against, and are
8595 // dropped by the resolver (OpenMP 6.0 [9.6.2]).
8597 Positions);
8598 for (unsigned Pos : Positions) {
8599 QualType ParamTy = FD->getParamDecl(Pos - 1)->getType();
8600 if (ParamTy->isReferenceType() || ParamTy->isDependentType())
8601 continue;
8602 Diag(getOMPAdjustArgsItemLoc(Item, AdjustArgsLoc.isValid()
8603 ? AdjustArgsLoc
8604 : SR.getBegin()),
8605 diag::err_omp_non_by_ref_need_device_addr_modifier_argument);
8606 break; // One diagnostic per written item.
8607 }
8608 }
8609 }
8610 }
8611
8612 // OpenMP 6.0 [16.1.3] Check prefer_type fr()/attr() arguments in
8613 // append_args.
8614 for (const OMPInteropInfo &Info : AppendArgs) {
8615 if (!checkPreferTypeArgs(*this, Info))
8616 return;
8617 }
8618
8619 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
8620 getASTContext(), VariantRef, &TI,
8621 const_cast<OMPAdjustArgsDescriptor **>(AdjustArgs.data()),
8622 AdjustArgs.size(), const_cast<OMPInteropInfo *>(AppendArgs.data()),
8623 AppendArgs.size(), SR);
8624 FD->addAttr(NewAttr);
8625}
8626
8627static CapturedStmt *
8629 auto *CS = dyn_cast<CapturedStmt>(AStmt);
8630 assert(CS && "Captured statement expected");
8631 // 1.2.2 OpenMP Language Terminology
8632 // Structured block - An executable statement with a single entry at the
8633 // top and a single exit at the bottom.
8634 // The point of exit cannot be a branch out of the structured block.
8635 // longjmp() and throw() must not violate the entry/exit criteria.
8636 CS->getCapturedDecl()->setNothrow();
8637
8638 for (int ThisCaptureLevel = SemaRef.OpenMP().getOpenMPCaptureLevels(DKind);
8639 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8641 // 1.2.2 OpenMP Language Terminology
8642 // Structured block - An executable statement with a single entry at the
8643 // top and a single exit at the bottom.
8644 // The point of exit cannot be a branch out of the structured block.
8645 // longjmp() and throw() must not violate the entry/exit criteria.
8646 CS->getCapturedDecl()->setNothrow();
8647 }
8649 return CS;
8650}
8651
8654 Stmt *AStmt, SourceLocation StartLoc,
8655 SourceLocation EndLoc) {
8656 if (!AStmt)
8657 return StmtError();
8658
8659 // Check for conflicting capture kinds on structured bindings.
8660 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_parallel, Clauses,
8661 AStmt))
8662 return StmtError();
8663
8664 setBranchProtectedScope(SemaRef, OMPD_parallel, AStmt);
8665
8666 return OMPParallelDirective::Create(
8667 getASTContext(), StartLoc, EndLoc, Clauses, AStmt,
8668 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
8669}
8670
8671namespace {
8672/// Iteration space of a single for loop.
8673struct LoopIterationSpace final {
8674 /// True if the condition operator is the strict compare operator (<, > or
8675 /// !=).
8676 bool IsStrictCompare = false;
8677 /// Condition of the loop.
8678 Expr *PreCond = nullptr;
8679 /// This expression calculates the number of iterations in the loop.
8680 /// It is always possible to calculate it before starting the loop.
8681 Expr *NumIterations = nullptr;
8682 /// The loop counter variable.
8683 Expr *CounterVar = nullptr;
8684 /// Private loop counter variable.
8685 Expr *PrivateCounterVar = nullptr;
8686 /// This is initializer for the initial value of #CounterVar.
8687 Expr *CounterInit = nullptr;
8688 /// This is step for the #CounterVar used to generate its update:
8689 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
8690 Expr *CounterStep = nullptr;
8691 /// Should step be subtracted?
8692 bool Subtract = false;
8693 /// Source range of the loop init.
8694 SourceRange InitSrcRange;
8695 /// Source range of the loop condition.
8696 SourceRange CondSrcRange;
8697 /// Source range of the loop increment.
8698 SourceRange IncSrcRange;
8699 /// Minimum value that can have the loop control variable. Used to support
8700 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
8701 /// since only such variables can be used in non-loop invariant expressions.
8702 Expr *MinValue = nullptr;
8703 /// Maximum value that can have the loop control variable. Used to support
8704 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
8705 /// since only such variables can be used in non-loop invariant expressions.
8706 Expr *MaxValue = nullptr;
8707 /// true, if the lower bound depends on the outer loop control var.
8708 bool IsNonRectangularLB = false;
8709 /// true, if the upper bound depends on the outer loop control var.
8710 bool IsNonRectangularUB = false;
8711 /// Index of the loop this loop depends on and forms non-rectangular loop
8712 /// nest.
8713 unsigned LoopDependentIdx = 0;
8714 /// Final condition for the non-rectangular loop nest support. It is used to
8715 /// check that the number of iterations for this particular counter must be
8716 /// finished.
8717 Expr *FinalCondition = nullptr;
8718};
8719
8720/// Scan an AST subtree, checking that no decls in the CollapsedLoopVarDecls
8721/// set are referenced. Used for verifying loop nest structure before
8722/// performing a loop collapse operation.
8723class ForSubExprChecker : public DynamicRecursiveASTVisitor {
8724 const llvm::SmallPtrSetImpl<const Decl *> &CollapsedLoopVarDecls;
8725 VarDecl *ForbiddenVar = nullptr;
8726 SourceRange ErrLoc;
8727
8728public:
8729 explicit ForSubExprChecker(
8730 const llvm::SmallPtrSetImpl<const Decl *> &CollapsedLoopVarDecls)
8731 : CollapsedLoopVarDecls(CollapsedLoopVarDecls) {
8732 // We want to visit implicit code, i.e. synthetic initialisation statements
8733 // created during range-for lowering.
8734 ShouldVisitImplicitCode = true;
8735 }
8736
8737 bool VisitDeclRefExpr(DeclRefExpr *E) override {
8738 ValueDecl *VD = E->getDecl();
8740 return true;
8741 VarDecl *V = VD->getPotentiallyDecomposedVarDecl();
8742 if (V->getType()->isReferenceType()) {
8743 VarDecl *VD = V->getDefinition();
8744 if (VD && VD->hasInit()) {
8745 Expr *I = VD->getInit();
8746 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(I);
8747 if (!DRE)
8748 return true;
8750 }
8751 }
8752 Decl *Canon = V->getCanonicalDecl();
8753 if (CollapsedLoopVarDecls.contains(Canon)) {
8754 ForbiddenVar = V;
8755 ErrLoc = E->getSourceRange();
8756 return false;
8757 }
8758
8759 return true;
8760 }
8761
8762 VarDecl *getForbiddenVar() const { return ForbiddenVar; }
8763 SourceRange getErrRange() const { return ErrLoc; }
8764};
8765
8766/// Helper class for checking canonical form of the OpenMP loops and
8767/// extracting iteration space of each loop in the loop nest, that will be used
8768/// for IR generation.
8769class OpenMPIterationSpaceChecker {
8770 /// Reference to Sema.
8771 Sema &SemaRef;
8772 /// Does the loop associated directive support non-rectangular loops?
8773 bool SupportsNonRectangular;
8774 /// Data-sharing stack.
8775 DSAStackTy &Stack;
8776 /// A location for diagnostics (when there is no some better location).
8777 SourceLocation DefaultLoc;
8778 /// A location for diagnostics (when increment is not compatible).
8779 SourceLocation ConditionLoc;
8780 /// The set of variables declared within the (to be collapsed) loop nest.
8781 const llvm::SmallPtrSetImpl<const Decl *> &CollapsedLoopVarDecls;
8782 /// The set of induction variables from outer collapsed loops.
8783 llvm::SmallPtrSetImpl<const Decl *> &CollapsedLoopInductionVars;
8784 /// A source location for referring to loop init later.
8785 SourceRange InitSrcRange;
8786 /// A source location for referring to condition later.
8787 SourceRange ConditionSrcRange;
8788 /// A source location for referring to increment later.
8789 SourceRange IncrementSrcRange;
8790 /// Loop variable.
8791 ValueDecl *LCDecl = nullptr;
8792 /// Reference to loop variable.
8793 Expr *LCRef = nullptr;
8794 /// Lower bound (initializer for the var).
8795 Expr *LB = nullptr;
8796 /// Upper bound.
8797 Expr *UB = nullptr;
8798 /// Loop step (increment).
8799 Expr *Step = nullptr;
8800 /// This flag is true when condition is one of:
8801 /// Var < UB
8802 /// Var <= UB
8803 /// UB > Var
8804 /// UB >= Var
8805 /// This will have no value when the condition is !=
8806 std::optional<bool> TestIsLessOp;
8807 /// This flag is true when condition is strict ( < or > ).
8808 bool TestIsStrictOp = false;
8809 /// This flag is true when step is subtracted on each iteration.
8810 bool SubtractStep = false;
8811 /// The outer loop counter this loop depends on (if any).
8812 const ValueDecl *DepDecl = nullptr;
8813 /// Contains number of loop (starts from 1) on which loop counter init
8814 /// expression of this loop depends on.
8815 std::optional<unsigned> InitDependOnLC;
8816 /// Contains number of loop (starts from 1) on which loop counter condition
8817 /// expression of this loop depends on.
8818 std::optional<unsigned> CondDependOnLC;
8819 /// Checks if the provide statement depends on the loop counter.
8820 std::optional<unsigned> doesDependOnLoopCounter(const Stmt *S,
8821 bool IsInitializer);
8822 /// Original condition required for checking of the exit condition for
8823 /// non-rectangular loop.
8824 Expr *Condition = nullptr;
8825
8826public:
8827 OpenMPIterationSpaceChecker(
8828 Sema &SemaRef, bool SupportsNonRectangular, DSAStackTy &Stack,
8829 SourceLocation DefaultLoc,
8830 const llvm::SmallPtrSetImpl<const Decl *> &CollapsedLoopDecls,
8831 llvm::SmallPtrSetImpl<const Decl *> &CollapsedLoopInductionVars)
8832 : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
8833 Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
8834 CollapsedLoopVarDecls(CollapsedLoopDecls),
8835 CollapsedLoopInductionVars(CollapsedLoopInductionVars) {}
8836 /// Check init-expr for canonical loop form and save loop counter
8837 /// variable - #Var and its initialization value - #LB.
8838 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
8839 /// Check test-expr for canonical form, save upper-bound (#UB), flags
8840 /// for less/greater and for strict/non-strict comparison.
8841 bool checkAndSetCond(Expr *S);
8842 /// Check incr-expr for canonical loop form and return true if it
8843 /// does not conform, otherwise save loop step (#Step).
8844 bool checkAndSetInc(Expr *S);
8845 /// Return the loop counter variable.
8846 ValueDecl *getLoopDecl() const { return LCDecl; }
8847 /// Return the reference expression to loop counter variable.
8848 Expr *getLoopDeclRefExpr() const { return LCRef; }
8849 /// Source range of the loop init.
8850 SourceRange getInitSrcRange() const { return InitSrcRange; }
8851 /// Source range of the loop condition.
8852 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
8853 /// Source range of the loop increment.
8854 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
8855 /// True if the step should be subtracted.
8856 bool shouldSubtractStep() const { return SubtractStep; }
8857 /// True, if the compare operator is strict (<, > or !=).
8858 bool isStrictTestOp() const { return TestIsStrictOp; }
8859 /// Build the expression to calculate the number of iterations.
8860 Expr *buildNumIterations(
8861 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
8862 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
8863 /// Build the precondition expression for the loops.
8864 Expr *
8865 buildPreCond(Scope *S, Expr *Cond,
8866 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
8867 /// Build reference expression to the counter be used for codegen.
8868 DeclRefExpr *
8869 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8870 DSAStackTy &DSA) const;
8871 /// Build reference expression to the private counter be used for
8872 /// codegen.
8873 Expr *buildPrivateCounterVar() const;
8874 /// Build initialization of the counter be used for codegen.
8875 Expr *buildCounterInit() const;
8876 /// Build step of the counter be used for codegen.
8877 Expr *buildCounterStep() const;
8878 /// Build loop data with counter value for depend clauses in ordered
8879 /// directives.
8880 Expr *
8881 buildOrderedLoopData(Scope *S, Expr *Counter,
8882 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
8883 SourceLocation Loc, Expr *Inc = nullptr,
8884 OverloadedOperatorKind OOK = OO_Amp);
8885 /// Builds the minimum value for the loop counter.
8886 std::pair<Expr *, Expr *> buildMinMaxValues(
8887 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
8888 /// Builds final condition for the non-rectangular loops.
8889 Expr *buildFinalCondition(Scope *S) const;
8890 /// Return true if any expression is dependent.
8891 bool dependent() const;
8892 /// Returns true if the initializer forms non-rectangular loop.
8893 bool doesInitDependOnLC() const { return InitDependOnLC.has_value(); }
8894 /// Returns true if the condition forms non-rectangular loop.
8895 bool doesCondDependOnLC() const { return CondDependOnLC.has_value(); }
8896 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
8897 unsigned getLoopDependentIdx() const {
8898 return InitDependOnLC.value_or(CondDependOnLC.value_or(0));
8899 }
8900
8901private:
8902 /// Check the right-hand side of an assignment in the increment
8903 /// expression.
8904 bool checkAndSetIncRHS(Expr *RHS);
8905 /// Helper to set loop counter variable and its initializer.
8906 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
8907 bool EmitDiags);
8908 /// Helper to set upper bound.
8909 bool setUB(Expr *NewUB, std::optional<bool> LessOp, bool StrictOp,
8910 SourceRange SR, SourceLocation SL);
8911 /// Helper to set loop increment.
8912 bool setStep(Expr *NewStep, bool Subtract);
8913 /// Diagnose a statement expression in a bound of a non-rectangular loop.
8914 bool checkNonRectangularBound(const Expr *E, bool IsInitializer) const;
8915};
8916
8917bool OpenMPIterationSpaceChecker::dependent() const {
8918 if (!LCDecl) {
8919 assert(!LB && !UB && !Step);
8920 return false;
8921 }
8922 return LCDecl->getType()->isDependentType() ||
8923 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
8924 (Step && Step->isValueDependent());
8925}
8926
8927/// Find a statement expression in \p E.
8928static const StmtExpr *findStmtExpr(const Expr *E) {
8929 SmallVector<const Stmt *, 8> Worklist{E};
8930 while (!Worklist.empty()) {
8931 const Stmt *S = Worklist.pop_back_val();
8932 if (!S)
8933 continue;
8934 if (const auto *SE = dyn_cast<StmtExpr>(S))
8935 return SE;
8936 llvm::append_range(Worklist, S->children());
8937 }
8938 return nullptr;
8939}
8940
8941bool OpenMPIterationSpaceChecker::checkNonRectangularBound(
8942 const Expr *E, bool IsInitializer) const {
8943 // Such a bound is emitted at every use, its declarations cannot be.
8944 const StmtExpr *SE = findStmtExpr(E);
8945 if (!SE)
8946 return false;
8947 SemaRef.Diag(SE->getBeginLoc(),
8948 diag::err_omp_stmt_expr_in_non_rectangular_loop)
8949 << (IsInitializer ? 0 : 1);
8950 return true;
8951}
8952
8953bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
8954 Expr *NewLCRefExpr,
8955 Expr *NewLB, bool EmitDiags) {
8956 // State consistency checking to ensure correct usage.
8957 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
8958 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
8959 if (!NewLCDecl || !NewLB || NewLB->containsErrors())
8960 return true;
8961 NewLB = buildInitListValue(SemaRef, NewLB);
8962 LCDecl = getCanonicalDecl(NewLCDecl);
8963 LCRef = NewLCRefExpr;
8964 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
8965 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
8966 if ((Ctor->isCopyOrMoveConstructor() ||
8967 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
8968 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
8969 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
8970 LB = NewLB;
8971 if (EmitDiags) {
8972 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
8973 if (InitDependOnLC && checkNonRectangularBound(LB, /*IsInitializer=*/true))
8974 return true;
8975 }
8976 return false;
8977}
8978
8979bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, std::optional<bool> LessOp,
8980 bool StrictOp, SourceRange SR,
8981 SourceLocation SL) {
8982 // State consistency checking to ensure correct usage.
8983 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
8984 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
8985 if (!NewUB || NewUB->containsErrors())
8986 return true;
8987 UB = NewUB;
8988 if (LessOp)
8989 TestIsLessOp = LessOp;
8990 TestIsStrictOp = StrictOp;
8991 ConditionSrcRange = SR;
8992 ConditionLoc = SL;
8993 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
8994 // The condition is also emitted as the body guard of a non-rectangular loop.
8995 if ((InitDependOnLC || CondDependOnLC) &&
8996 checkNonRectangularBound(UB, /*IsInitializer=*/false))
8997 return true;
8998 return false;
8999}
9000
9001bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
9002 // State consistency checking to ensure correct usage.
9003 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
9004 if (!NewStep || NewStep->containsErrors())
9005 return true;
9006 NewStep = buildInitListValue(SemaRef, NewStep);
9007 if (!NewStep->isValueDependent()) {
9008 // Check that the step is integer expression.
9009 SourceLocation StepLoc = NewStep->getBeginLoc();
9011 StepLoc, getExprAsWritten(NewStep));
9012 if (Val.isInvalid())
9013 return true;
9014 NewStep = Val.get();
9015
9016 // OpenMP [2.6, Canonical Loop Form, Restrictions]
9017 // If test-expr is of form var relational-op b and relational-op is < or
9018 // <= then incr-expr must cause var to increase on each iteration of the
9019 // loop. If test-expr is of form var relational-op b and relational-op is
9020 // > or >= then incr-expr must cause var to decrease on each iteration of
9021 // the loop.
9022 // If test-expr is of form b relational-op var and relational-op is < or
9023 // <= then incr-expr must cause var to decrease on each iteration of the
9024 // loop. If test-expr is of form b relational-op var and relational-op is
9025 // > or >= then incr-expr must cause var to increase on each iteration of
9026 // the loop.
9027 std::optional<llvm::APSInt> Result =
9028 NewStep->getIntegerConstantExpr(SemaRef.Context);
9029 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
9030 bool IsConstNeg =
9031 Result && Result->isSigned() && (Subtract != Result->isNegative());
9032 bool IsConstPos =
9033 Result && Result->isSigned() && (Subtract == Result->isNegative());
9034 bool IsConstZero = Result && !Result->getBoolValue();
9035
9036 // != with increment is treated as <; != with decrement is treated as >
9037 if (!TestIsLessOp)
9038 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
9039 if (UB && (IsConstZero ||
9040 (*TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
9041 : (IsConstPos || (IsUnsigned && !Subtract))))) {
9042 SemaRef.Diag(NewStep->getExprLoc(),
9043 diag::err_omp_loop_incr_not_compatible)
9044 << LCDecl << *TestIsLessOp << NewStep->getSourceRange();
9045 SemaRef.Diag(ConditionLoc,
9046 diag::note_omp_loop_cond_requires_compatible_incr)
9047 << *TestIsLessOp << ConditionSrcRange;
9048 return true;
9049 }
9050 if (*TestIsLessOp == Subtract) {
9051 NewStep =
9052 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
9053 .get();
9054 Subtract = !Subtract;
9055 }
9056 }
9057
9058 Step = NewStep;
9059 SubtractStep = Subtract;
9060 return false;
9061}
9062
9063namespace {
9064/// Checker for the non-rectangular loops. Checks if the initializer or
9065/// condition expression references loop counter variable.
9066class LoopCounterRefChecker final
9067 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
9068 Sema &SemaRef;
9069 DSAStackTy &Stack;
9070 const ValueDecl *CurLCDecl = nullptr;
9071 const ValueDecl *DepDecl = nullptr;
9072 const ValueDecl *PrevDepDecl = nullptr;
9073 bool IsInitializer = true;
9074 bool SupportsNonRectangular;
9075 unsigned BaseLoopId = 0;
9076 bool checkDecl(const Expr *E, const ValueDecl *VD) {
9077 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
9078 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
9079 << (IsInitializer ? 0 : 1);
9080 return false;
9081 }
9082 const auto &&Data = Stack.isLoopControlVariable(VD);
9083 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
9084 // The type of the loop iterator on which we depend may not have a random
9085 // access iterator type.
9086 if (Data.first && VD->getType()->isRecordType()) {
9087 SmallString<128> Name;
9088 llvm::raw_svector_ostream OS(Name);
9089 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
9090 /*Qualified=*/true);
9091 SemaRef.Diag(E->getExprLoc(),
9092 diag::err_omp_wrong_dependency_iterator_type)
9093 << OS.str();
9094 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
9095 return false;
9096 }
9097 if (Data.first && !SupportsNonRectangular) {
9098 SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
9099 return false;
9100 }
9101 if (Data.first &&
9102 (DepDecl || (PrevDepDecl &&
9103 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
9104 if (!DepDecl && PrevDepDecl)
9105 DepDecl = PrevDepDecl;
9106 SmallString<128> Name;
9107 llvm::raw_svector_ostream OS(Name);
9108 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
9109 /*Qualified=*/true);
9110 SemaRef.Diag(E->getExprLoc(),
9111 diag::err_omp_invariant_or_linear_dependency)
9112 << OS.str();
9113 return false;
9114 }
9115 if (Data.first) {
9116 DepDecl = VD;
9117 BaseLoopId = Data.first;
9118 }
9119 return Data.first;
9120 }
9121
9122public:
9123 bool VisitDeclRefExpr(const DeclRefExpr *E) {
9124 const ValueDecl *VD = E->getDecl();
9125 if (isa<VarDecl>(VD))
9126 return checkDecl(E, VD);
9127 return false;
9128 }
9129 bool VisitMemberExpr(const MemberExpr *E) {
9130 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
9131 const ValueDecl *VD = E->getMemberDecl();
9132 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
9133 return checkDecl(E, VD);
9134 }
9135 return false;
9136 }
9137 bool VisitStmt(const Stmt *S) {
9138 bool Res = false;
9139 for (const Stmt *Child : S->children())
9140 Res = (Child && Visit(Child)) || Res;
9141 return Res;
9142 }
9143 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
9144 const ValueDecl *CurLCDecl, bool IsInitializer,
9145 const ValueDecl *PrevDepDecl = nullptr,
9146 bool SupportsNonRectangular = true)
9147 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
9148 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
9149 SupportsNonRectangular(SupportsNonRectangular) {}
9150 unsigned getBaseLoopId() const {
9151 assert(CurLCDecl && "Expected loop dependency.");
9152 return BaseLoopId;
9153 }
9154 const ValueDecl *getDepDecl() const {
9155 assert(CurLCDecl && "Expected loop dependency.");
9156 return DepDecl;
9157 }
9158};
9159} // namespace
9160
9161std::optional<unsigned>
9162OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
9163 bool IsInitializer) {
9164 // Check for the non-rectangular loops.
9165 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
9166 DepDecl, SupportsNonRectangular);
9167 if (LoopStmtChecker.Visit(S)) {
9168 DepDecl = LoopStmtChecker.getDepDecl();
9169 return LoopStmtChecker.getBaseLoopId();
9170 }
9171 return std::nullopt;
9172}
9173
9174bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
9175 // Check init-expr for canonical loop form and save loop counter
9176 // variable - #Var and its initialization value - #LB.
9177 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
9178 // var = lb
9179 // integer-type var = lb
9180 // random-access-iterator-type var = lb
9181 // pointer-type var = lb
9182 //
9183 if (!S) {
9184 if (EmitDiags) {
9185 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
9186 }
9187 return true;
9188 }
9189 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
9190 if (!ExprTemp->cleanupsHaveSideEffects())
9191 S = ExprTemp->getSubExpr();
9192
9193 if (!CollapsedLoopVarDecls.empty()) {
9194 ForSubExprChecker FSEC{CollapsedLoopVarDecls};
9195 if (!FSEC.TraverseStmt(S)) {
9196 SourceRange Range = FSEC.getErrRange();
9197 SemaRef.Diag(Range.getBegin(), diag::err_omp_loop_bad_collapse_var)
9198 << Range.getEnd() << 0 << FSEC.getForbiddenVar();
9199 return true;
9200 }
9201 }
9202
9203 // Helper lambda to reject structured bindings used as OpenMP loop
9204 // control variables. Loop counters are implicitly private, but bindings
9205 // share storage with their decomposition, so this is not representable.
9206 auto CheckBindingAsLoopVar = [&](ValueDecl *LoopVar,
9207 SourceLocation Loc) -> bool {
9208 if (!isa<BindingDecl>(LoopVar))
9209 return false;
9210 if (EmitDiags)
9211 SemaRef.Diag(Loc, diag::err_omp_loop_var_is_structured_binding)
9212 << LoopVar;
9213 return true;
9214 };
9215
9216 // Helper lambda to check if a loop variable is already used in an outer
9217 // loop.
9218 auto CheckLoopVarReuse = [&](ValueDecl *LoopVar, SourceLocation Loc) -> bool {
9219 if (EmitDiags &&
9220 CollapsedLoopInductionVars.count(LoopVar->getCanonicalDecl())) {
9221 SemaRef.Diag(Loc, diag::err_omp_loop_var_reused_in_collapsed_loop)
9222 << LoopVar;
9223 return true;
9224 }
9225 return false;
9226 };
9227
9228 InitSrcRange = S->getSourceRange();
9229 if (Expr *E = dyn_cast<Expr>(S))
9230 S = E->IgnoreParens();
9231 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
9232 if (BO->getOpcode() == BO_Assign) {
9233 Expr *LHS = BO->getLHS()->IgnoreParens();
9234 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
9235 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
9236 if (auto *ME =
9237 dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) {
9238 ValueDecl *LoopVar = ME->getMemberDecl();
9239 if (CheckLoopVarReuse(LoopVar, DRE->getLocation()))
9240 return true;
9241 return setLCDeclAndLB(LoopVar, ME, BO->getRHS(), EmitDiags);
9242 }
9243 ValueDecl *LoopVar = DRE->getDecl();
9244 if (CheckBindingAsLoopVar(LoopVar, DRE->getLocation()))
9245 return true;
9246 if (CheckLoopVarReuse(LoopVar, DRE->getLocation()))
9247 return true;
9248 return setLCDeclAndLB(LoopVar, DRE, BO->getRHS(), EmitDiags);
9249 }
9250 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
9251 if (ME->isArrow() &&
9252 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) {
9253 ValueDecl *LoopVar = ME->getMemberDecl();
9254 if (CheckLoopVarReuse(LoopVar, LHS->getBeginLoc()))
9255 return true;
9256 return setLCDeclAndLB(LoopVar, ME, BO->getRHS(), EmitDiags);
9257 }
9258 }
9259 }
9260 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
9261 if (DS->isSingleDecl()) {
9262 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
9263 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
9264 // Accept non-canonical init form here but emit ext. warning.
9265 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
9266 SemaRef.Diag(S->getBeginLoc(),
9267 diag::ext_omp_loop_not_canonical_init)
9268 << S->getSourceRange();
9269 if (CheckLoopVarReuse(Var, Var->getLocation()))
9270 return true;
9271 return setLCDeclAndLB(
9272 Var,
9273 buildDeclRefExpr(SemaRef, Var,
9274 Var->getType().getNonReferenceType(),
9275 DS->getBeginLoc()),
9276 Var->getInit(), EmitDiags);
9277 }
9278 }
9279 }
9280 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
9281 if (CE->getOperator() == OO_Equal) {
9282 Expr *LHS = CE->getArg(0);
9283 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
9284 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
9285 if (auto *ME =
9286 dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) {
9287 ValueDecl *LoopVar = ME->getMemberDecl();
9288 if (CheckLoopVarReuse(LoopVar, DRE->getLocation()))
9289 return true;
9290 return setLCDeclAndLB(LoopVar, ME, CE->getArg(1), EmitDiags);
9291 }
9292 ValueDecl *LoopVar = DRE->getDecl();
9293 if (CheckBindingAsLoopVar(LoopVar, DRE->getLocation()))
9294 return true;
9295 if (CheckLoopVarReuse(LoopVar, DRE->getLocation()))
9296 return true;
9297 return setLCDeclAndLB(LoopVar, DRE, CE->getArg(1), EmitDiags);
9298 }
9299 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
9300 if (ME->isArrow() &&
9301 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) {
9302 ValueDecl *LoopVar = ME->getMemberDecl();
9303 if (CheckLoopVarReuse(LoopVar, LHS->getBeginLoc()))
9304 return true;
9305 return setLCDeclAndLB(LoopVar, ME, CE->getArg(1), EmitDiags);
9306 }
9307 }
9308 }
9309 }
9310
9311 if (dependent() || SemaRef.CurContext->isDependentContext())
9312 return false;
9313 if (EmitDiags) {
9314 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
9315 << S->getSourceRange();
9316 }
9317 return true;
9318}
9319
9320/// Ignore parenthesizes, implicit casts, copy constructor and return the
9321/// variable (which may be the loop variable) if possible.
9322static const ValueDecl *getInitLCDecl(const Expr *E) {
9323 if (!E)
9324 return nullptr;
9325 E = getExprAsWritten(E);
9326 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
9327 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
9328 if ((Ctor->isCopyOrMoveConstructor() ||
9329 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
9330 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
9331 E = CE->getArg(0)->IgnoreParenImpCasts();
9332 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
9333 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
9334 return getCanonicalDecl(VD);
9335 }
9336 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
9337 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
9338 return getCanonicalDecl(ME->getMemberDecl());
9339 return nullptr;
9340}
9341
9342bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
9343 // Check test-expr for canonical form, save upper-bound UB, flags for
9344 // less/greater and for strict/non-strict comparison.
9345 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
9346 // var relational-op b
9347 // b relational-op var
9348 //
9349 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
9350 if (!S) {
9351 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
9352 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
9353 return true;
9354 }
9355 Condition = S;
9356 S = getExprAsWritten(S);
9357
9358 if (!CollapsedLoopVarDecls.empty()) {
9359 ForSubExprChecker FSEC{CollapsedLoopVarDecls};
9360 if (!FSEC.TraverseStmt(S)) {
9361 SourceRange Range = FSEC.getErrRange();
9362 SemaRef.Diag(Range.getBegin(), diag::err_omp_loop_bad_collapse_var)
9363 << Range.getEnd() << 1 << FSEC.getForbiddenVar();
9364 return true;
9365 }
9366 }
9367
9368 SourceLocation CondLoc = S->getBeginLoc();
9369 auto &&CheckAndSetCond =
9370 [this, IneqCondIsCanonical](BinaryOperatorKind Opcode, const Expr *LHS,
9371 const Expr *RHS, SourceRange SR,
9372 SourceLocation OpLoc) -> std::optional<bool> {
9373 if (BinaryOperator::isRelationalOp(Opcode)) {
9374 if (getInitLCDecl(LHS) == LCDecl)
9375 return setUB(const_cast<Expr *>(RHS),
9376 (Opcode == BO_LT || Opcode == BO_LE),
9377 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
9378 if (getInitLCDecl(RHS) == LCDecl)
9379 return setUB(const_cast<Expr *>(LHS),
9380 (Opcode == BO_GT || Opcode == BO_GE),
9381 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
9382 } else if (IneqCondIsCanonical && Opcode == BO_NE) {
9383 return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
9384 /*LessOp=*/std::nullopt,
9385 /*StrictOp=*/true, SR, OpLoc);
9386 }
9387 return std::nullopt;
9388 };
9389 std::optional<bool> Res;
9390 if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
9391 CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
9392 Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
9393 RBO->getOperatorLoc());
9394 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
9395 Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
9396 BO->getSourceRange(), BO->getOperatorLoc());
9397 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
9398 if (CE->getNumArgs() == 2) {
9399 Res = CheckAndSetCond(
9400 BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
9401 CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
9402 }
9403 }
9404 if (Res)
9405 return *Res;
9406 if (dependent() || SemaRef.CurContext->isDependentContext())
9407 return false;
9408 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
9409 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
9410 return true;
9411}
9412
9413bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
9414 // RHS of canonical loop form increment can be:
9415 // var + incr
9416 // incr + var
9417 // var - incr
9418 //
9419 RHS = RHS->IgnoreParenImpCasts();
9420 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
9421 if (BO->isAdditiveOp()) {
9422 bool IsAdd = BO->getOpcode() == BO_Add;
9423 if (getInitLCDecl(BO->getLHS()) == LCDecl)
9424 return setStep(BO->getRHS(), !IsAdd);
9425 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
9426 return setStep(BO->getLHS(), /*Subtract=*/false);
9427 }
9428 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
9429 bool IsAdd = CE->getOperator() == OO_Plus;
9430 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
9431 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
9432 return setStep(CE->getArg(1), !IsAdd);
9433 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
9434 return setStep(CE->getArg(0), /*Subtract=*/false);
9435 }
9436 }
9437 if (dependent() || SemaRef.CurContext->isDependentContext())
9438 return false;
9439 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
9440 << RHS->getSourceRange() << LCDecl;
9441 return true;
9442}
9443
9444bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
9445 // Check incr-expr for canonical loop form and return true if it
9446 // does not conform.
9447 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
9448 // ++var
9449 // var++
9450 // --var
9451 // var--
9452 // var += incr
9453 // var -= incr
9454 // var = var + incr
9455 // var = incr + var
9456 // var = var - incr
9457 //
9458 if (!S) {
9459 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
9460 return true;
9461 }
9462 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
9463 if (!ExprTemp->cleanupsHaveSideEffects())
9464 S = ExprTemp->getSubExpr();
9465
9466 if (!CollapsedLoopVarDecls.empty()) {
9467 ForSubExprChecker FSEC{CollapsedLoopVarDecls};
9468 if (!FSEC.TraverseStmt(S)) {
9469 SourceRange Range = FSEC.getErrRange();
9470 SemaRef.Diag(Range.getBegin(), diag::err_omp_loop_bad_collapse_var)
9471 << Range.getEnd() << 2 << FSEC.getForbiddenVar();
9472 return true;
9473 }
9474 }
9475
9476 IncrementSrcRange = S->getSourceRange();
9477 S = S->IgnoreParens();
9478 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
9479 if (UO->isIncrementDecrementOp() &&
9480 getInitLCDecl(UO->getSubExpr()) == LCDecl)
9481 return setStep(SemaRef
9482 .ActOnIntegerConstant(UO->getBeginLoc(),
9483 (UO->isDecrementOp() ? -1 : 1))
9484 .get(),
9485 /*Subtract=*/false);
9486 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
9487 switch (BO->getOpcode()) {
9488 case BO_AddAssign:
9489 case BO_SubAssign:
9490 if (getInitLCDecl(BO->getLHS()) == LCDecl)
9491 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
9492 break;
9493 case BO_Assign:
9494 if (getInitLCDecl(BO->getLHS()) == LCDecl)
9495 return checkAndSetIncRHS(BO->getRHS());
9496 break;
9497 default:
9498 break;
9499 }
9500 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
9501 switch (CE->getOperator()) {
9502 case OO_PlusPlus:
9503 case OO_MinusMinus:
9504 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
9505 return setStep(SemaRef
9506 .ActOnIntegerConstant(
9507 CE->getBeginLoc(),
9508 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
9509 .get(),
9510 /*Subtract=*/false);
9511 break;
9512 case OO_PlusEqual:
9513 case OO_MinusEqual:
9514 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
9515 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
9516 break;
9517 case OO_Equal:
9518 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
9519 return checkAndSetIncRHS(CE->getArg(1));
9520 break;
9521 default:
9522 break;
9523 }
9524 }
9525 if (dependent() || SemaRef.CurContext->isDependentContext())
9526 return false;
9527 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
9528 << S->getSourceRange() << LCDecl;
9529 return true;
9530}
9531
9532static ExprResult
9533tryBuildCapture(Sema &SemaRef, Expr *Capture,
9534 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
9535 StringRef Name = ".capture_expr.") {
9536 if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
9537 return Capture;
9538 // A statement expression must be captured even if it is constant, since the
9539 // declarations inside it can only be emitted once.
9540 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects) &&
9541 !findStmtExpr(Capture))
9542 return SemaRef.PerformImplicitConversion(Capture->IgnoreImpCasts(),
9543 Capture->getType(),
9545 /*AllowExplicit=*/true);
9546 auto I = Captures.find(Capture);
9547 if (I != Captures.end())
9548 return buildCapture(SemaRef, Capture, I->second, Name);
9549 DeclRefExpr *Ref = nullptr;
9550 ExprResult Res = buildCapture(SemaRef, Capture, Ref, Name);
9551 Captures[Capture] = Ref;
9552 return Res;
9553}
9554
9555/// Calculate number of iterations, transforming to unsigned, if number of
9556/// iterations may be larger than the original type.
9557static Expr *
9558calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
9559 Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
9560 bool TestIsStrictOp, bool RoundToStep,
9561 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
9562 std::optional<unsigned> InitDependOnLC,
9563 std::optional<unsigned> CondDependOnLC) {
9564 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures, ".new_step");
9565 if (!NewStep.isUsable())
9566 return nullptr;
9567 llvm::APSInt LRes, SRes;
9568 bool IsLowerConst = false, IsStepConst = false;
9569 if (std::optional<llvm::APSInt> Res =
9570 Lower->getIntegerConstantExpr(SemaRef.Context)) {
9571 LRes = *Res;
9572 IsLowerConst = true;
9573 }
9574 if (std::optional<llvm::APSInt> Res =
9575 Step->getIntegerConstantExpr(SemaRef.Context)) {
9576 SRes = *Res;
9577 IsStepConst = true;
9578 }
9579 bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
9580 ((!TestIsStrictOp && LRes.isNonNegative()) ||
9581 (TestIsStrictOp && LRes.isStrictlyPositive()));
9582 bool NeedToReorganize = false;
9583 // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
9584 if (!NoNeedToConvert && IsLowerConst &&
9585 (TestIsStrictOp || (RoundToStep && IsStepConst))) {
9586 NoNeedToConvert = true;
9587 if (RoundToStep) {
9588 unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
9589 ? LRes.getBitWidth()
9590 : SRes.getBitWidth();
9591 LRes = LRes.extend(BW + 1);
9592 LRes.setIsSigned(true);
9593 SRes = SRes.extend(BW + 1);
9594 SRes.setIsSigned(true);
9595 LRes -= SRes;
9596 NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
9597 LRes = LRes.trunc(BW);
9598 }
9599 if (TestIsStrictOp) {
9600 unsigned BW = LRes.getBitWidth();
9601 LRes = LRes.extend(BW + 1);
9602 LRes.setIsSigned(true);
9603 ++LRes;
9604 NoNeedToConvert =
9605 NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
9606 // truncate to the original bitwidth.
9607 LRes = LRes.trunc(BW);
9608 }
9609 NeedToReorganize = NoNeedToConvert;
9610 }
9611 llvm::APSInt URes;
9612 bool IsUpperConst = false;
9613 if (std::optional<llvm::APSInt> Res =
9614 Upper->getIntegerConstantExpr(SemaRef.Context)) {
9615 URes = *Res;
9616 IsUpperConst = true;
9617 }
9618 if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
9619 (!RoundToStep || IsStepConst)) {
9620 unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
9621 : URes.getBitWidth();
9622 LRes = LRes.extend(BW + 1);
9623 LRes.setIsSigned(true);
9624 URes = URes.extend(BW + 1);
9625 URes.setIsSigned(true);
9626 URes -= LRes;
9627 NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
9628 NeedToReorganize = NoNeedToConvert;
9629 }
9630 // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
9631 // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
9632 // unsigned.
9633 if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
9634 !LCTy->isDependentType() && LCTy->isIntegerType()) {
9635 QualType LowerTy = Lower->getType();
9636 QualType UpperTy = Upper->getType();
9637 uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
9638 uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
9639 if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
9640 (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
9642 SemaRef.Context, LowerSize > UpperSize ? LowerSize : UpperSize,
9643 /*Signed=*/false);
9644 Upper =
9645 SemaRef
9647 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
9649 .get();
9650 Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
9651 NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
9652 }
9653 }
9654 if (!Lower || !Upper || NewStep.isInvalid())
9655 return nullptr;
9656
9657 ExprResult Diff;
9658
9659 // For nested triangular loops (depth >= 2), use already computed Upper and
9660 // Lower bounds to calculate the number of iterations: Upper - Lower + 1.
9661 // Don't apply to first-level triangular loops as the standard formula handles
9662 // those correctly.
9663 if (TestIsStrictOp && InitDependOnLC.has_value() &&
9664 InitDependOnLC.value() >= 2 && !CondDependOnLC.has_value()) {
9665 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
9666 if (!Diff.isUsable())
9667 return nullptr;
9668
9669 Diff =
9670 SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(),
9671 SemaRef.ActOnIntegerConstant(DefaultLoc, 1).get());
9672 if (!Diff.isUsable())
9673 return nullptr;
9674
9675 return Diff.get();
9676 }
9677
9678 // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
9679 // 1]).
9680 if (NeedToReorganize) {
9681 Diff = Lower;
9682
9683 // (Lower - Step [+ 1]) may be negative. Compute it in at least Upper's
9684 // width: in a narrower unsigned type it would wrap around and then be
9685 // zero-extended in the subtraction from Upper, giving a wrong number of
9686 // iterations, e.g. for
9687 // for (unsigned i = 0; i < (size_t)N; i += 2)
9688 QualType LowerTy = Lower->getType();
9689 QualType UpperTy = Upper->getType();
9690 if (!LowerTy->isDependentType() && !UpperTy->isDependentType() &&
9691 LowerTy->isIntegerType() && UpperTy->isIntegerType() &&
9692 SemaRef.Context.getTypeSize(LowerTy) <
9693 SemaRef.Context.getTypeSize(UpperTy)) {
9695 SemaRef.Context, SemaRef.Context.getTypeSize(UpperTy),
9697 Diff = SemaRef.PerformImplicitConversion(Lower, WideTy,
9699 if (!Diff.isUsable())
9700 return nullptr;
9701 }
9702
9703 if (RoundToStep) {
9704 // Lower - Step
9705 Diff =
9706 SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
9707 if (!Diff.isUsable())
9708 return nullptr;
9709 }
9710
9711 // Lower - Step [+ 1]
9712 if (TestIsStrictOp)
9713 Diff = SemaRef.BuildBinOp(
9714 S, DefaultLoc, BO_Add, Diff.get(),
9715 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9716 if (!Diff.isUsable())
9717 return nullptr;
9718
9719 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
9720 if (!Diff.isUsable())
9721 return nullptr;
9722
9723 // Upper - (Lower - Step [+ 1]).
9724 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
9725 if (!Diff.isUsable())
9726 return nullptr;
9727 } else {
9728 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
9729
9730 if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
9731 // BuildBinOp already emitted error, this one is to point user to upper
9732 // and lower bound, and to tell what is passed to 'operator-'.
9733 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
9734 << Upper->getSourceRange() << Lower->getSourceRange();
9735 return nullptr;
9736 }
9737
9738 if (!Diff.isUsable())
9739 return nullptr;
9740
9741 // Upper - Lower [- 1]
9742 if (TestIsStrictOp)
9743 Diff = SemaRef.BuildBinOp(
9744 S, DefaultLoc, BO_Sub, Diff.get(),
9745 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
9746 if (!Diff.isUsable())
9747 return nullptr;
9748
9749 if (RoundToStep) {
9750 // Upper - Lower [- 1] + Step
9751 Diff =
9752 SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
9753 if (!Diff.isUsable())
9754 return nullptr;
9755 }
9756 }
9757
9758 // Parentheses (for dumping/debugging purposes only).
9759 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
9760 if (!Diff.isUsable())
9761 return nullptr;
9762
9763 // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
9764 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
9765 if (!Diff.isUsable())
9766 return nullptr;
9767
9768 return Diff.get();
9769}
9770
9771/// Build the expression to calculate the number of iterations.
9772Expr *OpenMPIterationSpaceChecker::buildNumIterations(
9773 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
9774 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
9775 QualType VarType = LCDecl->getType().getNonReferenceType();
9776 if (!VarType->isIntegerType() && !VarType->isPointerType() &&
9777 !SemaRef.getLangOpts().CPlusPlus)
9778 return nullptr;
9779 Expr *LBVal = LB;
9780 Expr *UBVal = UB;
9781 // OuterVar = (LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
9782 // max(LB(MinVal), LB(MaxVal)))
9783 if (InitDependOnLC) {
9784 const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
9785 if (!IS.MinValue || !IS.MaxValue)
9786 return nullptr;
9787 // OuterVar = Min
9788 ExprResult MinValue =
9789 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
9790 if (!MinValue.isUsable())
9791 return nullptr;
9792
9793 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
9794 IS.CounterVar, MinValue.get());
9795 if (!LBMinVal.isUsable())
9796 return nullptr;
9797 // OuterVar = Min, LBVal
9798 LBMinVal =
9799 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
9800 if (!LBMinVal.isUsable())
9801 return nullptr;
9802 // (OuterVar = Min, LBVal)
9803 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
9804 if (!LBMinVal.isUsable())
9805 return nullptr;
9806
9807 // OuterVar = Max
9808 ExprResult MaxValue =
9809 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
9810 if (!MaxValue.isUsable())
9811 return nullptr;
9812
9813 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
9814 IS.CounterVar, MaxValue.get());
9815 if (!LBMaxVal.isUsable())
9816 return nullptr;
9817 // OuterVar = Max, LBVal
9818 LBMaxVal =
9819 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
9820 if (!LBMaxVal.isUsable())
9821 return nullptr;
9822 // (OuterVar = Max, LBVal)
9823 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
9824 if (!LBMaxVal.isUsable())
9825 return nullptr;
9826
9827 Expr *LBMin =
9828 tryBuildCapture(SemaRef, LBMinVal.get(), Captures, ".lb_min").get();
9829 Expr *LBMax =
9830 tryBuildCapture(SemaRef, LBMaxVal.get(), Captures, ".lb_max").get();
9831 if (!LBMin || !LBMax)
9832 return nullptr;
9833 // LB(MinVal) < LB(MaxVal)
9834 ExprResult MinLessMaxRes =
9835 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
9836 if (!MinLessMaxRes.isUsable())
9837 return nullptr;
9838 Expr *MinLessMax =
9839 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures, ".min_less_max")
9840 .get();
9841 if (!MinLessMax)
9842 return nullptr;
9843 if (*TestIsLessOp) {
9844 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
9845 // LB(MaxVal))
9846 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
9847 MinLessMax, LBMin, LBMax);
9848 if (!MinLB.isUsable())
9849 return nullptr;
9850 LBVal = MinLB.get();
9851 } else {
9852 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
9853 // LB(MaxVal))
9854 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
9855 MinLessMax, LBMax, LBMin);
9856 if (!MaxLB.isUsable())
9857 return nullptr;
9858 LBVal = MaxLB.get();
9859 }
9860 // OuterVar = LB
9861 LBMinVal =
9862 SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, IS.CounterVar, LBVal);
9863 if (!LBMinVal.isUsable())
9864 return nullptr;
9865 LBVal = LBMinVal.get();
9866 }
9867 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
9868 // min(UB(MinVal), UB(MaxVal))
9869 if (CondDependOnLC) {
9870 const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
9871 if (!IS.MinValue || !IS.MaxValue)
9872 return nullptr;
9873 // OuterVar = Min
9874 ExprResult MinValue =
9875 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
9876 if (!MinValue.isUsable())
9877 return nullptr;
9878
9879 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
9880 IS.CounterVar, MinValue.get());
9881 if (!UBMinVal.isUsable())
9882 return nullptr;
9883 // OuterVar = Min, UBVal
9884 UBMinVal =
9885 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
9886 if (!UBMinVal.isUsable())
9887 return nullptr;
9888 // (OuterVar = Min, UBVal)
9889 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
9890 if (!UBMinVal.isUsable())
9891 return nullptr;
9892
9893 // OuterVar = Max
9894 ExprResult MaxValue =
9895 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
9896 if (!MaxValue.isUsable())
9897 return nullptr;
9898
9899 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
9900 IS.CounterVar, MaxValue.get());
9901 if (!UBMaxVal.isUsable())
9902 return nullptr;
9903 // OuterVar = Max, UBVal
9904 UBMaxVal =
9905 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
9906 if (!UBMaxVal.isUsable())
9907 return nullptr;
9908 // (OuterVar = Max, UBVal)
9909 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
9910 if (!UBMaxVal.isUsable())
9911 return nullptr;
9912
9913 Expr *UBMin =
9914 tryBuildCapture(SemaRef, UBMinVal.get(), Captures, ".ub_min").get();
9915 Expr *UBMax =
9916 tryBuildCapture(SemaRef, UBMaxVal.get(), Captures, ".ub_max").get();
9917 if (!UBMin || !UBMax)
9918 return nullptr;
9919 // UB(MinVal) > UB(MaxVal)
9920 ExprResult MinGreaterMaxRes =
9921 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
9922 if (!MinGreaterMaxRes.isUsable())
9923 return nullptr;
9924 Expr *MinGreaterMax = tryBuildCapture(SemaRef, MinGreaterMaxRes.get(),
9925 Captures, ".min_greater_max")
9926 .get();
9927 if (!MinGreaterMax)
9928 return nullptr;
9929 if (*TestIsLessOp) {
9930 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
9931 // UB(MaxVal))
9932 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
9933 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
9934 if (!MaxUB.isUsable())
9935 return nullptr;
9936 UBVal = MaxUB.get();
9937 } else {
9938 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
9939 // UB(MaxVal))
9940 ExprResult MinUB = SemaRef.ActOnConditionalOp(
9941 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
9942 if (!MinUB.isUsable())
9943 return nullptr;
9944 UBVal = MinUB.get();
9945 }
9946 }
9947 Expr *UBExpr = *TestIsLessOp ? UBVal : LBVal;
9948 Expr *LBExpr = *TestIsLessOp ? LBVal : UBVal;
9949 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures, ".upper").get();
9950 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures, ".lower").get();
9951 if (!Upper || !Lower)
9952 return nullptr;
9953
9954 ExprResult Diff = calculateNumIters(
9955 SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, TestIsStrictOp,
9956 /*RoundToStep=*/true, Captures, InitDependOnLC, CondDependOnLC);
9957 if (!Diff.isUsable())
9958 return nullptr;
9959
9960 // OpenMP runtime requires 32-bit or 64-bit loop variables.
9961 QualType Type = Diff.get()->getType();
9962 ASTContext &C = SemaRef.Context;
9963 bool UseVarType = VarType->hasIntegerRepresentation() &&
9964 C.getTypeSize(Type) > C.getTypeSize(VarType);
9965 if (!Type->isIntegerType() || UseVarType) {
9966 unsigned NewSize =
9967 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
9968 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
9970 Type = getIntTypeForBitwidthOrBitInt(C, NewSize, IsSigned);
9971 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
9972 Diff = SemaRef.PerformImplicitConversion(Diff.get(), Type,
9974 /*AllowExplicit=*/true);
9975 if (!Diff.isUsable())
9976 return nullptr;
9977 }
9978 }
9979 if (LimitedType) {
9980 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
9981 if (NewSize != C.getTypeSize(Type)) {
9982 if (NewSize < C.getTypeSize(Type)) {
9983 assert(NewSize == 64 && "incorrect loop var size");
9984 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
9985 << InitSrcRange << ConditionSrcRange;
9986 }
9987 QualType NewType = C.getIntTypeForBitwidth(
9989 C.getTypeSize(Type) < NewSize);
9990 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
9991 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
9993 /*AllowExplicit=*/true);
9994 if (!Diff.isUsable())
9995 return nullptr;
9996 }
9997 }
9998 }
9999
10000 return Diff.get();
10001}
10002
10003std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
10004 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
10005 // Do not build for iterators, they cannot be used in non-rectangular loop
10006 // nests.
10007 if (LCDecl->getType()->isRecordType())
10008 return std::make_pair(nullptr, nullptr);
10009 // If we subtract, the min is in the condition, otherwise the min is in the
10010 // init value.
10011 Expr *MinExpr = nullptr;
10012 Expr *MaxExpr = nullptr;
10013 Expr *LBExpr = *TestIsLessOp ? LB : UB;
10014 Expr *UBExpr = *TestIsLessOp ? UB : LB;
10015 bool LBNonRect =
10016 *TestIsLessOp ? InitDependOnLC.has_value() : CondDependOnLC.has_value();
10017 bool UBNonRect =
10018 *TestIsLessOp ? CondDependOnLC.has_value() : InitDependOnLC.has_value();
10019 Expr *Lower =
10020 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
10021 Expr *Upper =
10022 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
10023 if (!Upper || !Lower)
10024 return std::make_pair(nullptr, nullptr);
10025
10026 if (*TestIsLessOp)
10027 MinExpr = Lower;
10028 else
10029 MaxExpr = Upper;
10030
10031 // Build minimum/maximum value based on number of iterations.
10032 QualType VarType = LCDecl->getType().getNonReferenceType();
10033
10034 ExprResult Diff = calculateNumIters(
10035 SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, TestIsStrictOp,
10036 /*RoundToStep=*/false, Captures, InitDependOnLC, CondDependOnLC);
10037
10038 if (!Diff.isUsable())
10039 return std::make_pair(nullptr, nullptr);
10040
10041 // ((Upper - Lower [- 1]) / Step) * Step
10042 // Parentheses (for dumping/debugging purposes only).
10043 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
10044 if (!Diff.isUsable())
10045 return std::make_pair(nullptr, nullptr);
10046
10047 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures, ".new_step");
10048 if (!NewStep.isUsable())
10049 return std::make_pair(nullptr, nullptr);
10050 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
10051 if (!Diff.isUsable())
10052 return std::make_pair(nullptr, nullptr);
10053
10054 // Parentheses (for dumping/debugging purposes only).
10055 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
10056 if (!Diff.isUsable())
10057 return std::make_pair(nullptr, nullptr);
10058
10059 // Convert to the ptrdiff_t, if original type is pointer.
10060 if (VarType->isAnyPointerType() &&
10061 !SemaRef.Context.hasSameType(
10062 Diff.get()->getType(),
10064 Diff = SemaRef.PerformImplicitConversion(
10065 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
10066 AssignmentAction::Converting, /*AllowExplicit=*/true);
10067 }
10068 if (!Diff.isUsable())
10069 return std::make_pair(nullptr, nullptr);
10070
10071 if (*TestIsLessOp) {
10072 // MinExpr = Lower;
10073 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
10074 Diff = SemaRef.BuildBinOp(
10075 S, DefaultLoc, BO_Add,
10076 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
10077 Diff.get());
10078 if (!Diff.isUsable())
10079 return std::make_pair(nullptr, nullptr);
10080 } else {
10081 // MaxExpr = Upper;
10082 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
10083 Diff = SemaRef.BuildBinOp(
10084 S, DefaultLoc, BO_Sub,
10085 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
10086 Diff.get());
10087 if (!Diff.isUsable())
10088 return std::make_pair(nullptr, nullptr);
10089 }
10090
10091 // Convert to the original type.
10092 if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
10093 Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
10095 /*AllowExplicit=*/true);
10096 if (!Diff.isUsable())
10097 return std::make_pair(nullptr, nullptr);
10098
10099 Sema::TentativeAnalysisScope Trap(SemaRef);
10100 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
10101 if (!Diff.isUsable())
10102 return std::make_pair(nullptr, nullptr);
10103
10104 if (*TestIsLessOp)
10105 MaxExpr = Diff.get();
10106 else
10107 MinExpr = Diff.get();
10108
10109 return std::make_pair(MinExpr, MaxExpr);
10110}
10111
10112Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
10113 if (InitDependOnLC || CondDependOnLC)
10114 return Condition;
10115 return nullptr;
10116}
10117
10118Expr *OpenMPIterationSpaceChecker::buildPreCond(
10119 Scope *S, Expr *Cond,
10120 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
10121 // Do not build a precondition when the condition/initialization is dependent
10122 // to prevent pessimistic early loop exit.
10123 // TODO: this can be improved by calculating min/max values but not sure that
10124 // it will be very effective.
10125 if (CondDependOnLC || InitDependOnLC)
10126 return SemaRef
10128 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
10129 SemaRef.Context.BoolTy, /*Action=*/AssignmentAction::Casting,
10130 /*AllowExplicit=*/true)
10131 .get();
10132
10133 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
10134 Sema::TentativeAnalysisScope Trap(SemaRef);
10135
10136 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
10137 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
10138 if (!NewLB.isUsable() || !NewUB.isUsable())
10139 return nullptr;
10140
10141 ExprResult CondExpr =
10142 SemaRef.BuildBinOp(S, DefaultLoc,
10143 *TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
10144 : (TestIsStrictOp ? BO_GT : BO_GE),
10145 NewLB.get(), NewUB.get());
10146 if (CondExpr.isUsable()) {
10147 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
10148 SemaRef.Context.BoolTy))
10149 CondExpr = SemaRef.PerformImplicitConversion(
10150 CondExpr.get(), SemaRef.Context.BoolTy,
10151 /*Action=*/AssignmentAction::Casting,
10152 /*AllowExplicit=*/true);
10153 }
10154
10155 // Otherwise use original loop condition and evaluate it in runtime.
10156 return CondExpr.isUsable() ? CondExpr.get() : Cond;
10157}
10158
10159/// Build reference expression to the counter be used for codegen.
10160DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
10161 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
10162 DSAStackTy &DSA) const {
10163 auto *VD = dyn_cast<VarDecl>(LCDecl);
10164 if (!VD) {
10165 VD = SemaRef.OpenMP().isOpenMPCapturedDecl(LCDecl);
10167 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
10168 const DSAStackTy::DSAVarData Data =
10169 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
10170 // If the loop control decl is explicitly marked as private, do not mark it
10171 // as captured again.
10172 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
10173 Captures.insert(std::make_pair(LCRef, Ref));
10174 return Ref;
10175 }
10176 return cast<DeclRefExpr>(LCRef);
10177}
10178
10179Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
10180 if (LCDecl && !LCDecl->isInvalidDecl()) {
10182 VarDecl *PrivateVar = buildVarDecl(
10183 SemaRef, DefaultLoc, Type, LCDecl->getName(),
10184 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
10185 isa<VarDecl>(LCDecl)
10186 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
10187 : nullptr);
10188 if (PrivateVar->isInvalidDecl())
10189 return nullptr;
10190 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
10191 }
10192 return nullptr;
10193}
10194
10195/// Build initialization of the counter to be used for codegen.
10196Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
10197
10198/// Build step of the counter be used for codegen.
10199Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
10200
10201Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
10202 Scope *S, Expr *Counter,
10203 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
10204 Expr *Inc, OverloadedOperatorKind OOK) {
10205 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
10206 if (!Cnt)
10207 return nullptr;
10208 if (Inc) {
10209 assert((OOK == OO_Plus || OOK == OO_Minus) &&
10210 "Expected only + or - operations for depend clauses.");
10211 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
10212 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
10213 if (!Cnt)
10214 return nullptr;
10215 }
10216 QualType VarType = LCDecl->getType().getNonReferenceType();
10217 if (!VarType->isIntegerType() && !VarType->isPointerType() &&
10218 !SemaRef.getLangOpts().CPlusPlus)
10219 return nullptr;
10220 // Upper - Lower
10221 Expr *Upper =
10222 *TestIsLessOp ? Cnt : tryBuildCapture(SemaRef, LB, Captures).get();
10223 Expr *Lower =
10224 *TestIsLessOp ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt;
10225 if (!Upper || !Lower)
10226 return nullptr;
10227
10228 ExprResult Diff =
10229 calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
10230 /*TestIsStrictOp=*/false, /*RoundToStep=*/false,
10231 Captures, InitDependOnLC, CondDependOnLC);
10232 if (!Diff.isUsable())
10233 return nullptr;
10234
10235 return Diff.get();
10236}
10237} // namespace
10238
10240 Stmt *Init) {
10241 assert(getLangOpts().OpenMP && "OpenMP is not active.");
10242 assert(Init && "Expected loop in canonical form.");
10243 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
10244 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10245 if (AssociatedLoops == 0 || !isOpenMPLoopDirective(DKind))
10246 return;
10247
10248 DSAStack->loopStart();
10250 OpenMPIterationSpaceChecker ISC(SemaRef, /*SupportsNonRectangular=*/true,
10251 *DSAStack, ForLoc, EmptyDeclSet,
10252 EmptyDeclSet);
10253 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
10254 if (ValueDecl *D = ISC.getLoopDecl()) {
10255 auto *VD = dyn_cast<VarDecl>(D);
10256 DeclRefExpr *PrivateRef = nullptr;
10257 if (!VD) {
10259 VD = Private;
10260 } else {
10261 PrivateRef = buildCapture(SemaRef, D, ISC.getLoopDeclRefExpr(),
10262 /*WithInit=*/false);
10263 VD = cast<VarDecl>(PrivateRef->getDecl());
10264 }
10265 }
10266 DSAStack->addLoopControlVariable(D, VD);
10267 const Decl *LD = DSAStack->getPossiblyLoopCounter();
10268 if (LD != D->getCanonicalDecl()) {
10269 DSAStack->resetPossibleLoopCounter();
10270 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
10271 SemaRef.MarkDeclarationsReferencedInExpr(buildDeclRefExpr(
10272 SemaRef, const_cast<VarDecl *>(Var),
10273 Var->getType().getNonLValueExprType(getASTContext()), ForLoc,
10274 /*RefersToCapture=*/true));
10275 }
10276 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
10277 // Referenced in a Construct, C/C++]. The loop iteration variable in the
10278 // associated for-loop of a simd construct with just one associated
10279 // for-loop may be listed in a linear clause with a constant-linear-step
10280 // that is the increment of the associated for-loop. The loop iteration
10281 // variable(s) in the associated for-loop(s) of a for or parallel for
10282 // construct may be listed in a private or lastprivate clause.
10283 DSAStackTy::DSAVarData DVar =
10284 DSAStack->getTopDSA(D, /*FromParent=*/false);
10285 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
10286 // is declared in the loop and it is predetermined as a private.
10287 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
10288 OpenMPClauseKind PredeterminedCKind =
10290 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
10291 : OMPC_private;
10292 auto IsOpenMPTaskloopDirective = [](OpenMPDirectiveKind DK) {
10293 return getLeafConstructsOrSelf(DK).back() == OMPD_taskloop;
10294 };
10295 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
10296 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
10297 (getLangOpts().OpenMP <= 45 ||
10298 (DVar.CKind != OMPC_lastprivate && DVar.CKind != OMPC_private))) ||
10300 IsOpenMPTaskloopDirective(DKind) ||
10302 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
10303 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
10304 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
10305 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
10306 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
10307 << getOpenMPClauseNameForDiag(DVar.CKind)
10308 << getOpenMPDirectiveName(DKind, OMPVersion)
10309 << getOpenMPClauseNameForDiag(PredeterminedCKind);
10310 if (DVar.RefExpr == nullptr)
10311 DVar.CKind = PredeterminedCKind;
10312 reportOriginalDsa(SemaRef, DSAStack, D, DVar, /*IsLoopIterVar=*/true);
10313 } else if (LoopDeclRefExpr) {
10314 // Make the loop iteration variable private (for worksharing
10315 // constructs), linear (for simd directives with the only one
10316 // associated loop) or lastprivate (for simd directives with several
10317 // collapsed or ordered loops).
10318 if (DVar.CKind == OMPC_unknown)
10319 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind, PrivateRef);
10320 }
10321 }
10322 }
10323 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
10324}
10325
10326namespace {
10327// Utility for OpenMP doacross clause kind
10328class OMPDoacrossKind {
10329public:
10330 bool isSource(const OMPDoacrossClause *C) {
10331 return C->getDependenceType() == OMPC_DOACROSS_source ||
10332 C->getDependenceType() == OMPC_DOACROSS_source_omp_cur_iteration;
10333 }
10334 bool isSink(const OMPDoacrossClause *C) {
10335 return C->getDependenceType() == OMPC_DOACROSS_sink;
10336 }
10337 bool isSinkIter(const OMPDoacrossClause *C) {
10338 return C->getDependenceType() == OMPC_DOACROSS_sink_omp_cur_iteration;
10339 }
10340};
10341} // namespace
10342/// Called on a for stmt to check and extract its iteration space
10343/// for further processing (such as collapsing).
10345 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
10346 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
10347 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
10348 Expr *OrderedLoopCountExpr,
10349 SemaOpenMP::VarsWithInheritedDSAType &VarsWithImplicitDSA,
10351 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
10352 const llvm::SmallPtrSetImpl<const Decl *> &CollapsedLoopVarDecls,
10353 llvm::SmallPtrSetImpl<const Decl *> &CollapsedLoopInductionVars) {
10354 bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
10355
10356 // See the tile reinterpretation design note in ActOnOpenMPTileDirective.
10357 // If the loop carries the hint, analyze its rectangular form instead.
10358 //
10359 // Only directives that emit the per-iteration body guard (i.e. those going
10360 // through EmitOMPLoopBody's finals-conditions handling) may reinterpret the
10361 // loop; a loop transformation such as an enclosing 'tile' has nowhere to put
10362 // the overshoot guard, so for those the stored min-bounded form is analyzed
10363 // exactly as it is on a build without this hint.
10364 // OpenMP [2.9.1, Canonical Loop Form]
10365 // for (init-expr; test-expr; incr-expr) structured-block
10366 // for (range-decl: range-expr) structured-block
10367 if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
10368 S = CanonLoop->getLoopStmt();
10369 const OMPInvariantPredicateBoundAttr *IntraTileHint =
10370 OMPLoopBasedDirective::getIntraTileHint(S);
10371 if (IntraTileHint)
10372 S = OMPLoopBasedDirective::ignoreIntraTileHint(S);
10373 Expr *TileRectCond = nullptr;
10374 Expr *TileBodyPredicate = nullptr;
10375 Expr *TileTripCount = nullptr;
10376 if (IntraTileHint && !isOpenMPLoopTransformationDirective(DKind)) {
10377 TileRectCond = IntraTileHint->getRectCond();
10378 TileBodyPredicate = IntraTileHint->getPredicate();
10379 TileTripCount = IntraTileHint->getTileSize();
10380 }
10381 auto *For = dyn_cast_or_null<ForStmt>(S);
10382 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
10383 // Ranged for is supported only in OpenMP 5.0.
10384 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
10385 llvm::omp::Version OMPVersion = SemaRef.getLangOpts().getOpenMPVersion();
10386 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
10387 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
10388 << getOpenMPDirectiveName(DKind, OMPVersion) << TotalNestedLoopCount
10389 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
10390 if (TotalNestedLoopCount > 1) {
10391 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
10392 SemaRef.Diag(DSA.getConstructLoc(),
10393 diag::note_omp_collapse_ordered_expr)
10394 << 2 << CollapseLoopCountExpr->getSourceRange()
10395 << OrderedLoopCountExpr->getSourceRange();
10396 else if (CollapseLoopCountExpr)
10397 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
10398 diag::note_omp_collapse_ordered_expr)
10399 << 0 << CollapseLoopCountExpr->getSourceRange();
10400 else if (OrderedLoopCountExpr)
10401 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
10402 diag::note_omp_collapse_ordered_expr)
10403 << 1 << OrderedLoopCountExpr->getSourceRange();
10404 }
10405 return true;
10406 }
10407 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
10408 "No loop body.");
10409 // Postpone analysis in dependent contexts for ranged for loops.
10410 if (CXXFor && SemaRef.CurContext->isDependentContext())
10411 return false;
10412
10413 OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
10414 For ? For->getForLoc() : CXXFor->getForLoc(),
10415 CollapsedLoopVarDecls,
10416 CollapsedLoopInductionVars);
10417
10418 // Check init.
10419 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
10420 if (ISC.checkAndSetInit(Init))
10421 return true;
10422
10423 bool HasErrors = false;
10424
10425 // Condition used for iteration-space analysis: the rectangular hint when
10426 // reinterpreting an intra-tile loop, otherwise the loop's own condition.
10427 Expr *EffectiveCond =
10428 TileRectCond ? TileRectCond : (For ? For->getCond() : CXXFor->getCond());
10429
10430 // Check loop variable's type.
10431 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
10432 // OpenMP [2.6, Canonical Loop Form]
10433 // Var is one of the following:
10434 // A variable of signed or unsigned integer type.
10435 // For C++, a variable of a random access iterator type.
10436 // For C, a variable of a pointer type.
10437 QualType VarType = LCDecl->getType().getNonReferenceType();
10438 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
10439 !VarType->isPointerType() &&
10440 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
10441 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
10442 << SemaRef.getLangOpts().CPlusPlus;
10443 HasErrors = true;
10444 }
10445
10446 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
10447 // a Construct
10448 // The loop iteration variable(s) in the associated for-loop(s) of a for or
10449 // parallel for construct is (are) private.
10450 // The loop iteration variable in the associated for-loop of a simd
10451 // construct with just one associated for-loop is linear with a
10452 // constant-linear-step that is the increment of the associated for-loop.
10453 // Exclude loop var from the list of variables with implicitly defined data
10454 // sharing attributes.
10455 VarsWithImplicitDSA.erase(LCDecl);
10456
10457 assert((isOpenMPLoopDirective(DKind) ||
10459 "DSA for non-loop vars");
10460
10461 // Check test-expr.
10462 HasErrors |= ISC.checkAndSetCond(EffectiveCond);
10463
10464 // Check incr-expr.
10465 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
10466 }
10467
10468 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
10469 return HasErrors;
10470
10471 // Build the loop's iteration space representation.
10472 //
10473 // A reinterpreted intra-tile loop takes all three of these from the hint
10474 // instead of deriving them: the precondition is trivially true (the floor
10475 // loop's own precondition already covers an empty iteration space), the trip
10476 // count is the constant tile size, and any overshoot on the remainder tile
10477 // is handled by the body guard.
10478 if (TileRectCond) {
10479 ResultIterSpaces[CurrentNestedLoopCount].PreCond =
10480 SemaRef
10482 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
10484 /*AllowExplicit=*/true)
10485 .get();
10486 ResultIterSpaces[CurrentNestedLoopCount].NumIterations = TileTripCount;
10487 } else {
10488 ResultIterSpaces[CurrentNestedLoopCount].PreCond =
10489 ISC.buildPreCond(DSA.getCurScope(), EffectiveCond, Captures);
10490 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
10491 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
10497 Captures);
10498 }
10499 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
10500 ISC.buildCounterVar(Captures, DSA);
10501 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
10502 ISC.buildPrivateCounterVar();
10503 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
10504 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
10505 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
10506 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
10507 ISC.getConditionSrcRange();
10508 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
10509 ISC.getIncrementSrcRange();
10510 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
10511 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
10512 ISC.isStrictTestOp();
10513 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
10514 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
10515 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
10516 if (TileRectCond) {
10517 // Floor is not a registered loop-control variable, so this helper is null.
10518 // Use the overshoot guard only (null when N % T == 0).
10519 assert(!ISC.buildFinalCondition(DSA.getCurScope()) &&
10520 "intra-tile floor is not a registered loop-control variable");
10521 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition = TileBodyPredicate;
10522
10523 // Re-read .floor.iv each outer trip. Match it to an outer collapsed
10524 // counter.
10525 bool FoundFloor = false;
10526 if (Expr *InitExpr = ResultIterSpaces[CurrentNestedLoopCount].CounterInit) {
10527 if (const auto *LBRef =
10528 dyn_cast<DeclRefExpr>(InitExpr->IgnoreParenImpCasts())) {
10529 const Decl *FloorDecl = LBRef->getDecl()->getCanonicalDecl();
10530 for (unsigned K = 0; K < CurrentNestedLoopCount; ++K) {
10531 const auto *CV =
10532 dyn_cast_or_null<DeclRefExpr>(ResultIterSpaces[K].CounterVar);
10533 if (CV && CV->getDecl()->getCanonicalDecl() == FloorDecl) {
10534 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB = true;
10535 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx = K + 1;
10536 FoundFloor = true;
10537 break;
10538 }
10539 }
10540 }
10541 }
10542 if (!FoundFloor) {
10543 // The floor this intra-tile loop starts from is not one of the
10544 // collapsed counters: it is assigned in the body of an enclosing
10545 // transformed loop, so the collapsed nest would read a stale value
10546 // instead of recomputing it per iteration. Diagnose to avoid silently
10547 // producing the wrong iteration space.
10548 SemaRef.Diag(ISC.getInitSrcRange().getBegin(),
10549 diag::err_omp_collapse_stacked_tile)
10550 << /*Collapse=*/0;
10551 return true;
10552 }
10553 } else {
10554 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
10555 ISC.buildFinalCondition(DSA.getCurScope());
10556 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
10557 ISC.doesInitDependOnLC();
10558 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
10559 ISC.doesCondDependOnLC();
10560 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
10561 ISC.getLoopDependentIdx();
10562 }
10563
10564 HasErrors |=
10565 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
10566 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
10567 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
10568 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
10569 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
10570 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
10571 if (!HasErrors && DSA.isOrderedRegion()) {
10572 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
10573 if (CurrentNestedLoopCount <
10574 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
10575 DSA.getOrderedRegionParam().second->setLoopNumIterations(
10576 CurrentNestedLoopCount,
10577 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
10578 DSA.getOrderedRegionParam().second->setLoopCounter(
10579 CurrentNestedLoopCount,
10580 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
10581 }
10582 }
10583 for (auto &Pair : DSA.getDoacrossDependClauses()) {
10584 auto *DependC = dyn_cast<OMPDependClause>(Pair.first);
10585 auto *DoacrossC = dyn_cast<OMPDoacrossClause>(Pair.first);
10586 unsigned NumLoops =
10587 DependC ? DependC->getNumLoops() : DoacrossC->getNumLoops();
10588 if (CurrentNestedLoopCount >= NumLoops) {
10589 // Erroneous case - clause has some problems.
10590 continue;
10591 }
10592 if (DependC && DependC->getDependencyKind() == OMPC_DEPEND_sink &&
10593 Pair.second.size() <= CurrentNestedLoopCount) {
10594 // Erroneous case - clause has some problems.
10595 DependC->setLoopData(CurrentNestedLoopCount, nullptr);
10596 continue;
10597 }
10598 OMPDoacrossKind ODK;
10599 if (DoacrossC && ODK.isSink(DoacrossC) &&
10600 Pair.second.size() <= CurrentNestedLoopCount) {
10601 // Erroneous case - clause has some problems.
10602 DoacrossC->setLoopData(CurrentNestedLoopCount, nullptr);
10603 continue;
10604 }
10605 Expr *CntValue;
10606 SourceLocation DepLoc =
10607 DependC ? DependC->getDependencyLoc() : DoacrossC->getDependenceLoc();
10608 if ((DependC && DependC->getDependencyKind() == OMPC_DEPEND_source) ||
10609 (DoacrossC && ODK.isSource(DoacrossC)))
10610 CntValue = ISC.buildOrderedLoopData(
10611 DSA.getCurScope(),
10612 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
10613 DepLoc);
10614 else if (DoacrossC && ODK.isSinkIter(DoacrossC)) {
10615 Expr *Cnt = SemaRef
10617 ResultIterSpaces[CurrentNestedLoopCount].CounterVar)
10618 .get();
10619 if (!Cnt)
10620 continue;
10621 // build CounterVar - 1
10622 Expr *Inc =
10623 SemaRef.ActOnIntegerConstant(DoacrossC->getColonLoc(), /*Val=*/1)
10624 .get();
10625 CntValue = ISC.buildOrderedLoopData(
10626 DSA.getCurScope(),
10627 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
10628 DepLoc, Inc, clang::OO_Minus);
10629 } else
10630 CntValue = ISC.buildOrderedLoopData(
10631 DSA.getCurScope(),
10632 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
10633 DepLoc, Pair.second[CurrentNestedLoopCount].first,
10634 Pair.second[CurrentNestedLoopCount].second);
10635 if (DependC)
10636 DependC->setLoopData(CurrentNestedLoopCount, CntValue);
10637 else
10638 DoacrossC->setLoopData(CurrentNestedLoopCount, CntValue);
10639 }
10640 }
10641 // Record the loop induction variable for nested loop reuse checking.
10642 if (CurrentNestedLoopCount < NestedLoopCount && !HasErrors) {
10643 if (const ValueDecl *LCDecl = ISC.getLoopDecl())
10644 CollapsedLoopInductionVars.insert(LCDecl->getCanonicalDecl());
10645 }
10646 return HasErrors;
10647}
10648
10649/// Build 'VarRef = Start.
10650static ExprResult
10652 ExprResult Start, bool IsNonRectangularLB,
10653 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
10654 // Build 'VarRef = Start.
10655 ExprResult NewStart = IsNonRectangularLB
10656 ? Start.get()
10657 : tryBuildCapture(SemaRef, Start.get(), Captures);
10658 if (!NewStart.isUsable())
10659 return ExprError();
10660 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
10661 VarRef.get()->getType())) {
10662 NewStart = SemaRef.PerformImplicitConversion(
10663 NewStart.get(), VarRef.get()->getType(), AssignmentAction::Converting,
10664 /*AllowExplicit=*/true);
10665 if (!NewStart.isUsable())
10666 return ExprError();
10667 }
10668
10670 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
10671 return Init;
10672}
10673
10674/// Build 'VarRef = Start + Iter * Step'.
10676 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
10677 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
10678 bool IsNonRectangularLB,
10679 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
10680 // Add parentheses (for debugging purposes only).
10681 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
10682 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
10683 !Step.isUsable())
10684 return ExprError();
10685
10686 ExprResult NewStep = Step;
10687 if (Captures)
10688 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
10689 if (NewStep.isInvalid())
10690 return ExprError();
10692 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
10693 if (!Update.isUsable())
10694 return ExprError();
10695
10696 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
10697 // 'VarRef = Start (+|-) Iter * Step'.
10698 if (!Start.isUsable())
10699 return ExprError();
10700 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
10701 if (!NewStart.isUsable())
10702 return ExprError();
10703 if (Captures && !IsNonRectangularLB)
10704 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
10705 if (NewStart.isInvalid())
10706 return ExprError();
10707
10708 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
10709 ExprResult SavedUpdate = Update;
10710 ExprResult UpdateVal;
10711 if (VarRef.get()->getType()->isOverloadableType() ||
10712 NewStart.get()->getType()->isOverloadableType() ||
10713 Update.get()->getType()->isOverloadableType()) {
10714 Sema::TentativeAnalysisScope Trap(SemaRef);
10715
10716 Update =
10717 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
10718 if (Update.isUsable()) {
10719 UpdateVal =
10720 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
10721 VarRef.get(), SavedUpdate.get());
10722 if (UpdateVal.isUsable()) {
10723 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
10724 UpdateVal.get());
10725 }
10726 }
10727 }
10728
10729 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
10730 if (!Update.isUsable() || !UpdateVal.isUsable()) {
10731 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
10732 NewStart.get(), SavedUpdate.get());
10733 if (!Update.isUsable())
10734 return ExprError();
10735
10736 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
10737 VarRef.get()->getType())) {
10739 Update.get(), VarRef.get()->getType(), AssignmentAction::Converting,
10740 /*AllowExplicit=*/true);
10741 if (!Update.isUsable())
10742 return ExprError();
10743 }
10744
10745 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
10746 }
10747 return Update;
10748}
10749
10750/// Convert integer expression \a E to make it have at least \a Bits
10751/// bits.
10752static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
10753 if (E == nullptr)
10754 return ExprError();
10755 ASTContext &C = SemaRef.Context;
10756 QualType OldType = E->getType();
10757 unsigned HasBits = C.getTypeSize(OldType);
10758 if (HasBits >= Bits)
10759 return ExprResult(E);
10760 // OK to convert to signed, because new type has more bits than old.
10761 QualType NewType = C.getIntTypeForBitwidth(Bits, /*Signed=*/true);
10762 return SemaRef.PerformImplicitConversion(
10763 E, NewType, AssignmentAction::Converting, /*AllowExplicit=*/true);
10764}
10765
10766/// Check if the given expression \a E is a constant integer that fits
10767/// into \a Bits bits.
10768static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
10769 if (E == nullptr)
10770 return false;
10771 if (std::optional<llvm::APSInt> Result =
10772 E->getIntegerConstantExpr(SemaRef.Context))
10773 return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
10774 return false;
10775}
10776
10777/// Build preinits statement for the given declarations.
10779 MutableArrayRef<Decl *> PreInits) {
10780 if (!PreInits.empty()) {
10781 return new (Context) DeclStmt(
10782 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
10784 }
10785 return nullptr;
10786}
10787
10788/// Append the \p Item or the content of a CompoundStmt to the list \p
10789/// TargetList.
10790///
10791/// A CompoundStmt is used as container in case multiple statements need to be
10792/// stored in lieu of using an explicit list. Flattening is necessary because
10793/// contained DeclStmts need to be visible after the execution of the list. Used
10794/// for OpenMP pre-init declarations/statements.
10796 Stmt *Item) {
10797 // nullptr represents an empty list.
10798 if (!Item)
10799 return;
10800
10801 if (auto *CS = dyn_cast<CompoundStmt>(Item))
10802 llvm::append_range(TargetList, CS->body());
10803 else
10804 TargetList.push_back(Item);
10805}
10806
10807/// Build preinits statement for the given declarations.
10808static Stmt *
10810 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
10811 if (!Captures.empty()) {
10812 SmallVector<Decl *, 16> PreInits;
10813 for (const auto &Pair : Captures)
10814 PreInits.push_back(Pair.second->getDecl());
10815 return buildPreInits(Context, PreInits);
10816 }
10817 return nullptr;
10818}
10819
10820/// Build pre-init statement for the given statements.
10821static Stmt *buildPreInits(ASTContext &Context, ArrayRef<Stmt *> PreInits) {
10822 if (PreInits.empty())
10823 return nullptr;
10824
10825 SmallVector<Stmt *> Stmts;
10826 for (Stmt *S : PreInits)
10827 appendFlattenedStmtList(Stmts, S);
10828 return CompoundStmt::Create(Context, PreInits, FPOptionsOverride(), {}, {});
10829}
10830
10831/// Build postupdate expression for the given list of postupdates expressions.
10832static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
10833 Expr *PostUpdate = nullptr;
10834 if (!PostUpdates.empty()) {
10835 for (Expr *E : PostUpdates) {
10836 Expr *ConvE = S.BuildCStyleCastExpr(
10837 E->getExprLoc(),
10839 E->getExprLoc(), E)
10840 .get();
10841 PostUpdate = PostUpdate
10842 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
10843 PostUpdate, ConvE)
10844 .get()
10845 : ConvE;
10846 }
10847 }
10848 return PostUpdate;
10849}
10850
10851/// Look for variables declared in the body parts of a for-loop nest. Used
10852/// for verifying loop nest structure before performing a loop collapse
10853/// operation.
10855 int NestingDepth = 0;
10856 llvm::SmallPtrSetImpl<const Decl *> &VarDecls;
10857
10858public:
10859 explicit ForVarDeclFinder(llvm::SmallPtrSetImpl<const Decl *> &VD)
10860 : VarDecls(VD) {}
10861
10862 bool VisitForStmt(ForStmt *F) override {
10863 ++NestingDepth;
10864 TraverseStmt(F->getBody());
10865 --NestingDepth;
10866 return false;
10867 }
10868
10870 ++NestingDepth;
10871 TraverseStmt(RF->getBody());
10872 --NestingDepth;
10873 return false;
10874 }
10875
10876 bool VisitVarDecl(VarDecl *D) override {
10877 Decl *C = D->getCanonicalDecl();
10878 if (NestingDepth > 0)
10879 VarDecls.insert(C);
10880 return true;
10881 }
10882};
10883
10884/// Called on a for stmt to check itself and nested loops (if any).
10885/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
10886/// number of collapsed loops otherwise.
10887static unsigned
10888checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
10889 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
10890 DSAStackTy &DSA,
10891 SemaOpenMP::VarsWithInheritedDSAType &VarsWithImplicitDSA,
10892 OMPLoopBasedDirective::HelperExprs &Built) {
10893 // If either of the loop expressions exist and contain errors, we bail out
10894 // early because diagnostics have already been emitted and we can't reliably
10895 // check more about the loop.
10896 if ((CollapseLoopCountExpr && CollapseLoopCountExpr->containsErrors()) ||
10897 (OrderedLoopCountExpr && OrderedLoopCountExpr->containsErrors()))
10898 return 0;
10899
10900 unsigned NestedLoopCount = 1;
10901 bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
10903 llvm::SmallPtrSet<const Decl *, 4> CollapsedLoopVarDecls;
10904 llvm::SmallPtrSet<const Decl *, 4> CollapsedLoopInductionVars;
10905
10906 if (CollapseLoopCountExpr) {
10907 // Found 'collapse' clause - calculate collapse number.
10909 if (!CollapseLoopCountExpr->isInstantiationDependent() &&
10910 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
10911 NestedLoopCount = Result.Val.getInt().getLimitedValue();
10912
10913 ForVarDeclFinder FVDF{CollapsedLoopVarDecls};
10914 FVDF.TraverseStmt(AStmt);
10915 } else {
10916 Built.clear(/*Size=*/1);
10917 return 1;
10918 }
10919 }
10920 unsigned OrderedLoopCount = 1;
10921 if (OrderedLoopCountExpr) {
10922 // Found 'ordered' clause - calculate collapse number.
10923 Expr::EvalResult EVResult;
10924 if (!OrderedLoopCountExpr->isInstantiationDependent() &&
10925 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
10926 SemaRef.getASTContext())) {
10927 llvm::APSInt Result = EVResult.Val.getInt();
10928 if (Result.getLimitedValue() < NestedLoopCount) {
10929 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
10930 diag::err_omp_wrong_ordered_loop_count)
10931 << OrderedLoopCountExpr->getSourceRange();
10932 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
10933 diag::note_collapse_loop_count)
10934 << CollapseLoopCountExpr->getSourceRange();
10935 }
10936 OrderedLoopCount = Result.getLimitedValue();
10937 } else {
10938 Built.clear(/*Size=*/1);
10939 return 1;
10940 }
10941 }
10942 // This is helper routine for loop directives (e.g., 'for', 'simd',
10943 // 'for simd', etc.).
10944 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
10945 unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
10946 SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
10947 if (!OMPLoopBasedDirective::doForAllLoops(
10948 AStmt->IgnoreContainers(
10950 SupportsNonPerfectlyNested, NumLoops,
10951 [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
10952 CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
10953 &IterSpaces, &Captures, &CollapsedLoopVarDecls,
10954 &CollapsedLoopInductionVars](unsigned Cnt, Stmt *Loop,
10955 Stmt *HintWrapper) {
10956 Stmt *CurStmt = HintWrapper ? HintWrapper : Loop;
10958 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
10959 NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
10960 VarsWithImplicitDSA, IterSpaces, Captures,
10961 CollapsedLoopVarDecls, CollapsedLoopInductionVars))
10962 return true;
10963 if (Cnt > 0 && Cnt >= NestedLoopCount &&
10964 IterSpaces[Cnt].CounterVar) {
10965 // Handle initialization of captured loop iterator variables.
10966 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
10967 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
10968 Captures[DRE] = DRE;
10969 }
10970 }
10971 return false;
10972 },
10973 [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) {
10974 Stmt *DependentPreInits = Transform->getPreInits();
10975 if (!DependentPreInits)
10976 return;
10977
10978 // Search for pre-init declared variables that need to be captured
10979 // to be referenceable inside the directive.
10980 SmallVector<Stmt *> Constituents;
10981 appendFlattenedStmtList(Constituents, DependentPreInits);
10982 for (Stmt *S : Constituents) {
10983 if (auto *DC = dyn_cast<DeclStmt>(S)) {
10984 for (Decl *C : DC->decls()) {
10985 auto *D = cast<VarDecl>(C);
10987 SemaRef, D, D->getType().getNonReferenceType(),
10988 cast<OMPExecutableDirective>(Transform->getDirective())
10989 ->getBeginLoc());
10990 Captures[Ref] = Ref;
10991 }
10992 }
10993 }
10994 }))
10995 return 0;
10996
10997 Built.clear(/*size=*/NestedLoopCount);
10998
10999 if (SemaRef.CurContext->isDependentContext())
11000 return NestedLoopCount;
11001
11002 // An example of what is generated for the following code:
11003 //
11004 // #pragma omp simd collapse(2) ordered(2)
11005 // for (i = 0; i < NI; ++i)
11006 // for (k = 0; k < NK; ++k)
11007 // for (j = J0; j < NJ; j+=2) {
11008 // <loop body>
11009 // }
11010 //
11011 // We generate the code below.
11012 // Note: the loop body may be outlined in CodeGen.
11013 // Note: some counters may be C++ classes, operator- is used to find number of
11014 // iterations and operator+= to calculate counter value.
11015 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
11016 // or i64 is currently supported).
11017 //
11018 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
11019 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
11020 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
11021 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
11022 // // similar updates for vars in clauses (e.g. 'linear')
11023 // <loop body (using local i and j)>
11024 // }
11025 // i = NI; // assign final values of counters
11026 // j = NJ;
11027 //
11028
11029 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
11030 // the iteration counts of the collapsed for loops.
11031 // Precondition tests if there is at least one iteration (all conditions are
11032 // true).
11033 auto PreCond = ExprResult(IterSpaces[0].PreCond);
11034 ASTContext &C = SemaRef.Context;
11035 unsigned FirstCountBits =
11036 C.getTypeSize(IterSpaces[0].NumIterations->getType());
11037 bool AllCountsNeedLessThan32Bits = FirstCountBits < 32;
11038
11039 Scope *CurScope = DSA.getCurScope();
11040 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
11041 if (PreCond.isUsable()) {
11042 PreCond =
11043 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
11044 PreCond.get(), IterSpaces[Cnt].PreCond);
11045 }
11046 Expr *N = IterSpaces[Cnt].NumIterations;
11047 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
11048 }
11049
11050 auto BuildLastIteration = [&](unsigned Bits) -> ExprResult {
11052 for (unsigned Cnt : llvm::seq<unsigned>(NestedLoopCount)) {
11053 Expr *N = IterSpaces[Cnt].NumIterations;
11055 Bits,
11056 SemaRef
11057 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
11059 /*AllowExplicit=*/true)
11060 .get(),
11061 SemaRef);
11062 if (!Count.isUsable())
11063 return ExprError();
11064 if (Cnt == 0)
11065 Result = Count;
11066 else
11067 Result = SemaRef.BuildBinOp(CurScope, N->getExprLoc(), BO_Mul,
11068 Result.get(), Count.get());
11069 if (!Result.isUsable())
11070 return ExprError();
11071 }
11072 return Result;
11073 };
11074
11075 // Build the 32-bit tree immediately only when it is always selected.
11076 // Otherwise, build the 64-bit tree first and build the 32-bit tree only when
11077 // the constant product may fit.
11078 ExprResult LastIteration;
11079 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
11080 AllCountsNeedLessThan32Bits ||
11081 (NestedLoopCount == 1 && FirstCountBits == 32)) {
11082 LastIteration = BuildLastIteration(/*Bits=*/32);
11083 } else {
11084 ExprResult LastIteration64 = BuildLastIteration(/*Bits=*/64);
11085 if (!LastIteration64.isUsable())
11086 return NestedLoopCount;
11087 LastIteration = LastIteration64;
11088 if (LastIteration64.get()->isIntegerConstantExpr(C)) {
11089 ExprResult LastIteration32 = BuildLastIteration(/*Bits=*/32);
11090 if (LastIteration32.isUsable() &&
11091 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
11092 fitsInto(
11093 /*Bits=*/32,
11094 LastIteration32.get()
11095 ->getType()
11097 LastIteration64.get(), SemaRef))
11098 LastIteration = LastIteration32;
11099 }
11100 }
11101 if (!LastIteration.isUsable())
11102 return NestedLoopCount;
11103
11104 QualType VType = LastIteration.get()->getType();
11105 QualType RealVType = VType;
11106 QualType StrideVType = VType;
11107 if (isOpenMPTaskLoopDirective(DKind)) {
11108 VType =
11109 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
11110 StrideVType =
11111 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
11112 }
11113
11114 // Save the number of iterations.
11115 ExprResult NumIterations = LastIteration;
11116 {
11117 LastIteration = SemaRef.BuildBinOp(
11118 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
11119 LastIteration.get(),
11120 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
11121 if (!LastIteration.isUsable())
11122 return 0;
11123 }
11124
11125 // Calculate the last iteration number beforehand instead of doing this on
11126 // each iteration. Do not do this if the number of iterations may be kfold-ed.
11127 bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
11128 ExprResult CalcLastIteration;
11129 if (!IsConstant) {
11130 ExprResult SaveRef =
11131 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
11132 LastIteration = SaveRef;
11133
11134 // Prepare SaveRef + 1.
11135 NumIterations = SemaRef.BuildBinOp(
11136 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
11137 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
11138 if (!NumIterations.isUsable())
11139 return 0;
11140 }
11141
11142 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
11143
11144 // Build variables passed into runtime, necessary for worksharing directives.
11145 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
11150 // Lower bound variable, initialized with zero.
11151 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
11152 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
11153 SemaRef.AddInitializerToDecl(LBDecl,
11154 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
11155 /*DirectInit=*/false);
11156
11157 // Upper bound variable, initialized with last iteration number.
11158 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
11159 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
11160 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
11161 /*DirectInit=*/false);
11162
11163 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
11164 // This will be used to implement clause 'lastprivate'.
11165 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
11166 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
11167 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
11168 SemaRef.AddInitializerToDecl(ILDecl,
11169 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
11170 /*DirectInit=*/false);
11171
11172 // Stride variable returned by runtime (we initialize it to 1 by default).
11173 VarDecl *STDecl =
11174 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
11175 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
11176 SemaRef.AddInitializerToDecl(STDecl,
11177 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
11178 /*DirectInit=*/false);
11179
11180 // Build expression: UB = min(UB, LastIteration)
11181 // It is necessary for CodeGen of directives with static scheduling.
11182 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
11183 UB.get(), LastIteration.get());
11184 ExprResult CondOp = SemaRef.ActOnConditionalOp(
11185 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
11186 LastIteration.get(), UB.get());
11187 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
11188 CondOp.get());
11189 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue=*/false);
11190
11191 // If we have a combined directive that combines 'distribute', 'for' or
11192 // 'simd' we need to be able to access the bounds of the schedule of the
11193 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
11194 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
11196 // Lower bound variable, initialized with zero.
11197 VarDecl *CombLBDecl =
11198 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
11199 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
11200 SemaRef.AddInitializerToDecl(
11201 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
11202 /*DirectInit=*/false);
11203
11204 // Upper bound variable, initialized with last iteration number.
11205 VarDecl *CombUBDecl =
11206 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
11207 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
11208 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
11209 /*DirectInit=*/false);
11210
11211 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
11212 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
11213 ExprResult CombCondOp =
11214 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
11215 LastIteration.get(), CombUB.get());
11216 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
11217 CombCondOp.get());
11218 CombEUB =
11219 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue=*/false);
11220
11221 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
11222 // We expect to have at least 2 more parameters than the 'parallel'
11223 // directive does - the lower and upper bounds of the previous schedule.
11224 assert(CD->getNumParams() >= 4 &&
11225 "Unexpected number of parameters in loop combined directive");
11226
11227 // Set the proper type for the bounds given what we learned from the
11228 // enclosed loops.
11229 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
11230 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
11231
11232 // Previous lower and upper bounds are obtained from the region
11233 // parameters.
11234 PrevLB =
11235 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
11236 PrevUB =
11237 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
11238 }
11239 }
11240
11241 // Build the iteration variable and its initialization before loop.
11242 ExprResult IV;
11243 ExprResult Init, CombInit;
11244 {
11245 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
11246 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
11247 Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
11252 ? LB.get()
11253 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
11254 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
11255 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue=*/false);
11256
11258 Expr *CombRHS =
11263 ? CombLB.get()
11264 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
11265 CombInit =
11266 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
11267 CombInit =
11268 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue=*/false);
11269 }
11270 }
11271
11272 bool UseStrictCompare =
11273 RealVType->hasUnsignedIntegerRepresentation() &&
11274 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
11275 return LIS.IsStrictCompare;
11276 });
11277 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
11278 // unsigned IV)) for worksharing loops.
11279 SourceLocation CondLoc = AStmt->getBeginLoc();
11280 Expr *BoundUB = UB.get();
11281 if (UseStrictCompare) {
11282 BoundUB =
11283 SemaRef
11284 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
11285 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
11286 .get();
11287 BoundUB =
11288 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue=*/false).get();
11289 }
11290 ExprResult Cond =
11295 ? SemaRef.BuildBinOp(CurScope, CondLoc,
11296 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
11297 BoundUB)
11298 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
11299 NumIterations.get());
11300 ExprResult CombDistCond;
11302 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
11303 NumIterations.get());
11304 }
11305
11306 ExprResult CombCond;
11308 Expr *BoundCombUB = CombUB.get();
11309 if (UseStrictCompare) {
11310 BoundCombUB =
11311 SemaRef
11312 .BuildBinOp(
11313 CurScope, CondLoc, BO_Add, BoundCombUB,
11314 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
11315 .get();
11316 BoundCombUB =
11317 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue=*/false)
11318 .get();
11319 }
11320 CombCond =
11321 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
11322 IV.get(), BoundCombUB);
11323 }
11324 // Loop increment (IV = IV + 1)
11325 SourceLocation IncLoc = AStmt->getBeginLoc();
11326 ExprResult Inc =
11327 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
11328 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
11329 if (!Inc.isUsable())
11330 return 0;
11331 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
11332 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue=*/false);
11333 if (!Inc.isUsable())
11334 return 0;
11335
11336 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
11337 // Used for directives with static scheduling.
11338 // In combined construct, add combined version that use CombLB and CombUB
11339 // base variables for the update
11340 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
11345 // LB + ST
11346 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
11347 if (!NextLB.isUsable())
11348 return 0;
11349 // LB = LB + ST
11350 NextLB =
11351 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
11352 NextLB =
11353 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue=*/false);
11354 if (!NextLB.isUsable())
11355 return 0;
11356 // UB + ST
11357 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
11358 if (!NextUB.isUsable())
11359 return 0;
11360 // UB = UB + ST
11361 NextUB =
11362 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
11363 NextUB =
11364 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue=*/false);
11365 if (!NextUB.isUsable())
11366 return 0;
11368 CombNextLB =
11369 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
11370 if (!NextLB.isUsable())
11371 return 0;
11372 // LB = LB + ST
11373 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
11374 CombNextLB.get());
11375 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
11376 /*DiscardedValue=*/false);
11377 if (!CombNextLB.isUsable())
11378 return 0;
11379 // UB + ST
11380 CombNextUB =
11381 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
11382 if (!CombNextUB.isUsable())
11383 return 0;
11384 // UB = UB + ST
11385 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
11386 CombNextUB.get());
11387 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
11388 /*DiscardedValue=*/false);
11389 if (!CombNextUB.isUsable())
11390 return 0;
11391 }
11392 }
11393
11394 // Create increment expression for distribute loop when combined in a same
11395 // directive with for as IV = IV + ST; ensure upper bound expression based
11396 // on PrevUB instead of NumIterations - used to implement 'for' when found
11397 // in combination with 'distribute', like in 'distribute parallel for'
11398 SourceLocation DistIncLoc = AStmt->getBeginLoc();
11399 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
11401 DistCond = SemaRef.BuildBinOp(
11402 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
11403 assert(DistCond.isUsable() && "distribute cond expr was not built");
11404
11405 DistInc =
11406 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
11407 assert(DistInc.isUsable() && "distribute inc expr was not built");
11408 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
11409 DistInc.get());
11410 DistInc =
11411 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue=*/false);
11412 assert(DistInc.isUsable() && "distribute inc expr was not built");
11413
11414 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
11415 // construct
11416 ExprResult NewPrevUB = PrevUB;
11417 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
11418 if (!SemaRef.Context.hasSameType(UB.get()->getType(),
11419 PrevUB.get()->getType())) {
11420 NewPrevUB = SemaRef.BuildCStyleCastExpr(
11421 DistEUBLoc,
11423 DistEUBLoc, NewPrevUB.get());
11424 if (!NewPrevUB.isUsable())
11425 return 0;
11426 }
11427 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT,
11428 UB.get(), NewPrevUB.get());
11429 ExprResult CondOp = SemaRef.ActOnConditionalOp(
11430 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get());
11431 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
11432 CondOp.get());
11433 PrevEUB =
11434 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue=*/false);
11435
11436 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
11437 // parallel for is in combination with a distribute directive with
11438 // schedule(static, 1)
11439 Expr *BoundPrevUB = PrevUB.get();
11440 if (UseStrictCompare) {
11441 BoundPrevUB =
11442 SemaRef
11443 .BuildBinOp(
11444 CurScope, CondLoc, BO_Add, BoundPrevUB,
11445 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
11446 .get();
11447 BoundPrevUB =
11448 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue=*/false)
11449 .get();
11450 }
11451 ParForInDistCond =
11452 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
11453 IV.get(), BoundPrevUB);
11454 }
11455
11456 // Build updates and final values of the loop counters.
11457 bool HasErrors = false;
11458 Built.Counters.resize(NestedLoopCount);
11459 Built.Inits.resize(NestedLoopCount);
11460 Built.Updates.resize(NestedLoopCount);
11461 Built.Finals.resize(NestedLoopCount);
11462 Built.DependentCounters.resize(NestedLoopCount);
11463 Built.DependentInits.resize(NestedLoopCount);
11464 Built.FinalsConditions.resize(NestedLoopCount);
11465 {
11466 // We implement the following algorithm for obtaining the
11467 // original loop iteration variable values based on the
11468 // value of the collapsed loop iteration variable IV.
11469 //
11470 // Let n+1 be the number of collapsed loops in the nest.
11471 // Iteration variables (I0, I1, .... In)
11472 // Iteration counts (N0, N1, ... Nn)
11473 //
11474 // Acc = IV;
11475 //
11476 // To compute Ik for loop k, 0 <= k <= n, generate:
11477 // Prod = N(k+1) * N(k+2) * ... * Nn;
11478 // Ik = Acc / Prod;
11479 // Acc -= Ik * Prod;
11480 //
11481 ExprResult Acc = IV;
11482 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
11483 LoopIterationSpace &IS = IterSpaces[Cnt];
11484 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
11485 ExprResult Iter;
11486
11487 // Compute prod
11488 ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
11489 for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K)
11490 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
11491 IterSpaces[K].NumIterations);
11492
11493 // Iter = Acc / Prod
11494 // If there is at least one more inner loop to avoid
11495 // multiplication by 1.
11496 if (Cnt + 1 < NestedLoopCount)
11497 Iter =
11498 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get());
11499 else
11500 Iter = Acc;
11501 if (!Iter.isUsable()) {
11502 HasErrors = true;
11503 break;
11504 }
11505
11506 // Update Acc:
11507 // Acc -= Iter * Prod
11508 // Check if there is at least one more inner loop to avoid
11509 // multiplication by 1.
11510 if (Cnt + 1 < NestedLoopCount)
11511 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(),
11512 Prod.get());
11513 else
11514 Prod = Iter;
11515 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get());
11516
11517 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
11518 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
11519 DeclRefExpr *CounterVar = buildDeclRefExpr(
11520 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
11521 /*RefersToCapture=*/true);
11523 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
11524 IS.CounterInit, IS.IsNonRectangularLB, Captures);
11525 if (!Init.isUsable()) {
11526 HasErrors = true;
11527 break;
11528 }
11530 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
11531 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
11532 if (!Update.isUsable()) {
11533 HasErrors = true;
11534 break;
11535 }
11536
11537 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
11538 ExprResult Final =
11539 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
11540 IS.CounterInit, IS.NumIterations, IS.CounterStep,
11541 IS.Subtract, IS.IsNonRectangularLB, &Captures);
11542 if (!Final.isUsable()) {
11543 HasErrors = true;
11544 break;
11545 }
11546
11547 if (!Update.isUsable() || !Final.isUsable()) {
11548 HasErrors = true;
11549 break;
11550 }
11551 // Save results
11552 Built.Counters[Cnt] = IS.CounterVar;
11553 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
11554 Built.Inits[Cnt] = Init.get();
11555 Built.Updates[Cnt] = Update.get();
11556 Built.Finals[Cnt] = Final.get();
11557 Built.DependentCounters[Cnt] = nullptr;
11558 Built.DependentInits[Cnt] = nullptr;
11559 // Transfer the body-guard condition: the loop condition for
11560 // non-rectangular loops, the overshoot predicate for reinterpreted tiles,
11561 // null otherwise.
11562 Built.FinalsConditions[Cnt] = IS.FinalCondition;
11563 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
11564 Built.DependentCounters[Cnt] = Built.Counters[IS.LoopDependentIdx - 1];
11565 Built.DependentInits[Cnt] = Built.Inits[IS.LoopDependentIdx - 1];
11566 }
11567 }
11568 }
11569
11570 if (HasErrors)
11571 return 0;
11572
11573 // Save results
11574 Built.IterationVarRef = IV.get();
11575 Built.LastIteration = LastIteration.get();
11576 Built.NumIterations = NumIterations.get();
11577 Built.CalcLastIteration = SemaRef
11578 .ActOnFinishFullExpr(CalcLastIteration.get(),
11579 /*DiscardedValue=*/false)
11580 .get();
11581 Built.PreCond = PreCond.get();
11582 Built.PreInits = buildPreInits(C, Captures);
11583 Built.Cond = Cond.get();
11584 Built.Init = Init.get();
11585 Built.Inc = Inc.get();
11586 Built.LB = LB.get();
11587 Built.UB = UB.get();
11588 Built.IL = IL.get();
11589 Built.ST = ST.get();
11590 Built.EUB = EUB.get();
11591 Built.NLB = NextLB.get();
11592 Built.NUB = NextUB.get();
11593 Built.PrevLB = PrevLB.get();
11594 Built.PrevUB = PrevUB.get();
11595 Built.DistInc = DistInc.get();
11596 Built.PrevEUB = PrevEUB.get();
11597 Built.DistCombinedFields.LB = CombLB.get();
11598 Built.DistCombinedFields.UB = CombUB.get();
11599 Built.DistCombinedFields.EUB = CombEUB.get();
11600 Built.DistCombinedFields.Init = CombInit.get();
11601 Built.DistCombinedFields.Cond = CombCond.get();
11602 Built.DistCombinedFields.NLB = CombNextLB.get();
11603 Built.DistCombinedFields.NUB = CombNextUB.get();
11604 Built.DistCombinedFields.DistCond = CombDistCond.get();
11605 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
11606
11607 return NestedLoopCount;
11608}
11609
11611 auto CollapseClauses =
11612 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
11613 if (CollapseClauses.begin() != CollapseClauses.end())
11614 return (*CollapseClauses.begin())->getNumForLoops();
11615 return nullptr;
11616}
11617
11619 auto OrderedClauses =
11620 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
11621 if (OrderedClauses.begin() != OrderedClauses.end())
11622 return (*OrderedClauses.begin())->getNumForLoops();
11623 return nullptr;
11624}
11625
11627 const ArrayRef<OMPClause *> Clauses) {
11628 const OMPSafelenClause *Safelen = nullptr;
11629 const OMPSimdlenClause *Simdlen = nullptr;
11630
11631 for (const OMPClause *Clause : Clauses) {
11632 if (Clause->getClauseKind() == OMPC_safelen)
11633 Safelen = cast<OMPSafelenClause>(Clause);
11634 else if (Clause->getClauseKind() == OMPC_simdlen)
11635 Simdlen = cast<OMPSimdlenClause>(Clause);
11636 if (Safelen && Simdlen)
11637 break;
11638 }
11639
11640 if (Simdlen && Safelen) {
11641 const Expr *SimdlenLength = Simdlen->getSimdlen();
11642 const Expr *SafelenLength = Safelen->getSafelen();
11643 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
11644 SimdlenLength->isInstantiationDependent() ||
11645 SimdlenLength->containsUnexpandedParameterPack())
11646 return false;
11647 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
11648 SafelenLength->isInstantiationDependent() ||
11649 SafelenLength->containsUnexpandedParameterPack())
11650 return false;
11651 Expr::EvalResult SimdlenResult, SafelenResult;
11652 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
11653 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
11654 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
11655 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
11656 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
11657 // If both simdlen and safelen clauses are specified, the value of the
11658 // simdlen parameter must be less than or equal to the value of the safelen
11659 // parameter.
11660 if (llvm::APSInt::compareValues(SimdlenRes, SafelenRes) > 0) {
11661 S.Diag(SimdlenLength->getExprLoc(),
11662 diag::err_omp_wrong_simdlen_safelen_values)
11663 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
11664 return true;
11665 }
11666 }
11667 return false;
11668}
11669
11671 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11672 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11673 if (!AStmt)
11674 return StmtError();
11675
11676 CapturedStmt *CS = setBranchProtectedScope(SemaRef, OMPD_simd, AStmt);
11677
11678 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11679 OMPLoopBasedDirective::HelperExprs B;
11680 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11681 // define the nested loops number.
11682 unsigned NestedLoopCount = checkOpenMPLoop(
11683 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
11684 CS, SemaRef, *DSAStack, VarsWithImplicitDSA, B);
11685 if (NestedLoopCount == 0)
11686 return StmtError();
11687
11688 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
11689 return StmtError();
11690
11692 return StmtError();
11693
11694 auto *SimdDirective = OMPSimdDirective::Create(
11695 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
11696 return SimdDirective;
11697}
11698
11700 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11701 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11702 if (!AStmt)
11703 return StmtError();
11704
11705 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11706 OMPLoopBasedDirective::HelperExprs B;
11707 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11708 // define the nested loops number.
11709 unsigned NestedLoopCount = checkOpenMPLoop(
11710 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
11711 AStmt, SemaRef, *DSAStack, VarsWithImplicitDSA, B);
11712 if (NestedLoopCount == 0)
11713 return StmtError();
11714
11715 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
11716 return StmtError();
11717
11718 auto *ForDirective = OMPForDirective::Create(
11719 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
11720 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11721 return ForDirective;
11722}
11723
11725 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11726 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11727 if (!AStmt)
11728 return StmtError();
11729
11730 CapturedStmt *CS = setBranchProtectedScope(SemaRef, OMPD_for_simd, AStmt);
11731
11732 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11733 OMPLoopBasedDirective::HelperExprs B;
11734 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
11735 // define the nested loops number.
11736 unsigned NestedLoopCount =
11737 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
11738 getOrderedNumberExpr(Clauses), CS, SemaRef, *DSAStack,
11739 VarsWithImplicitDSA, B);
11740 if (NestedLoopCount == 0)
11741 return StmtError();
11742
11743 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
11744 return StmtError();
11745
11747 return StmtError();
11748
11749 return OMPForSimdDirective::Create(getASTContext(), StartLoc, EndLoc,
11750 NestedLoopCount, Clauses, AStmt, B);
11751}
11752
11754 Stmt *AStmt, DSAStackTy *Stack) {
11755 if (!AStmt)
11756 return true;
11757
11758 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
11759 llvm::omp::Version OMPVersion = SemaRef.getLangOpts().getOpenMPVersion();
11760 auto BaseStmt = AStmt;
11761 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
11762 BaseStmt = CS->getCapturedStmt();
11763 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
11764 auto S = C->children();
11765 if (S.begin() == S.end())
11766 return true;
11767 // All associated statements must be '#pragma omp section' except for
11768 // the first one.
11769 for (Stmt *SectionStmt : llvm::drop_begin(S)) {
11770 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
11771 if (SectionStmt)
11772 SemaRef.Diag(SectionStmt->getBeginLoc(),
11773 diag::err_omp_sections_substmt_not_section)
11774 << getOpenMPDirectiveName(DKind, OMPVersion);
11775 return true;
11776 }
11777 cast<OMPSectionDirective>(SectionStmt)
11778 ->setHasCancel(Stack->isCancelRegion());
11779 }
11780 } else {
11781 SemaRef.Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt)
11782 << getOpenMPDirectiveName(DKind, OMPVersion);
11783 return true;
11784 }
11785 return false;
11786}
11787
11790 Stmt *AStmt, SourceLocation StartLoc,
11791 SourceLocation EndLoc) {
11792 if (checkSectionsDirective(SemaRef, OMPD_sections, AStmt, DSAStack))
11793 return StmtError();
11794
11795 SemaRef.setFunctionHasBranchProtectedScope();
11796
11798 getASTContext(), StartLoc, EndLoc, Clauses, AStmt,
11799 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
11800}
11801
11803 SourceLocation StartLoc,
11804 SourceLocation EndLoc) {
11805 if (!AStmt)
11806 return StmtError();
11807
11808 SemaRef.setFunctionHasBranchProtectedScope();
11809 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
11810
11811 return OMPSectionDirective::Create(getASTContext(), StartLoc, EndLoc, AStmt,
11812 DSAStack->isCancelRegion());
11813}
11814
11816 E = E->IgnoreParenCasts()->IgnoreImplicit();
11817 // A call replaced by a declare variant keeps the original call.
11818 if (auto *POE = dyn_cast<PseudoObjectExpr>(E))
11819 E = POE->getSyntacticForm()->IgnoreImpCasts();
11820 if (auto *CE = dyn_cast<CallExpr>(E))
11821 if (CE->getDirectCallee())
11822 return E;
11823 return nullptr;
11824}
11825
11828 Stmt *AStmt, SourceLocation StartLoc,
11829 SourceLocation EndLoc) {
11830 if (!AStmt)
11831 return StmtError();
11832
11833 Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
11834
11835 // 5.1 OpenMP
11836 // expression-stmt : an expression statement with one of the following forms:
11837 // expression = target-call ( [expression-list] );
11838 // target-call ( [expression-list] );
11839
11840 SourceLocation TargetCallLoc;
11841
11842 if (!SemaRef.CurContext->isDependentContext()) {
11843 Expr *TargetCall = nullptr;
11844
11845 auto *E = dyn_cast<Expr>(S);
11846 if (!E) {
11847 Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
11848 return StmtError();
11849 }
11850
11851 E = E->IgnoreParenCasts()->IgnoreImplicit();
11852
11853 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
11854 if (BO->getOpcode() == BO_Assign)
11855 TargetCall = getDirectCallExpr(BO->getRHS());
11856 } else {
11857 if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
11858 if (COCE->getOperator() == OO_Equal)
11859 TargetCall = getDirectCallExpr(COCE->getArg(1));
11860 if (!TargetCall)
11861 TargetCall = getDirectCallExpr(E);
11862 }
11863 if (!TargetCall) {
11864 Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
11865 return StmtError();
11866 }
11867 TargetCallLoc = TargetCall->getExprLoc();
11868 }
11869
11870 SemaRef.setFunctionHasBranchProtectedScope();
11871
11872 return OMPDispatchDirective::Create(getASTContext(), StartLoc, EndLoc,
11873 Clauses, AStmt, TargetCallLoc);
11874}
11875
11878 DSAStackTy *Stack) {
11879 bool ErrorFound = false;
11880 for (OMPClause *C : Clauses) {
11881 if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) {
11882 for (Expr *RefExpr : LPC->varlist()) {
11883 SourceLocation ELoc;
11884 SourceRange ERange;
11885 Expr *SimpleRefExpr = RefExpr;
11886 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
11887 if (ValueDecl *D = Res.first) {
11888 auto &&Info = Stack->isLoopControlVariable(D);
11889 if (!Info.first) {
11890 llvm::omp::Version OMPVersion = S.getLangOpts().getOpenMPVersion();
11891 S.Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration)
11892 << getOpenMPDirectiveName(K, OMPVersion);
11893 ErrorFound = true;
11894 }
11895 }
11896 }
11897 }
11898 }
11899 return ErrorFound;
11900}
11901
11903 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11904 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
11905 if (!AStmt)
11906 return StmtError();
11907
11908 // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
11909 // A list item may not appear in a lastprivate clause unless it is the
11910 // loop iteration variable of a loop that is associated with the construct.
11911 if (checkGenericLoopLastprivate(SemaRef, Clauses, OMPD_loop, DSAStack))
11912 return StmtError();
11913
11914 setBranchProtectedScope(SemaRef, OMPD_loop, AStmt);
11915
11916 OMPLoopDirective::HelperExprs B;
11917 // In presence of clause 'collapse', it will define the nested loops number.
11918 unsigned NestedLoopCount = checkOpenMPLoop(
11919 OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
11920 AStmt, SemaRef, *DSAStack, VarsWithImplicitDSA, B);
11921 if (NestedLoopCount == 0)
11922 return StmtError();
11923
11924 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
11925 "omp loop exprs were not built");
11926
11927 return OMPGenericLoopDirective::Create(getASTContext(), StartLoc, EndLoc,
11928 NestedLoopCount, Clauses, AStmt, B);
11929}
11930
11931/// Check the number of expressions specified in a multidimensional clause and
11932/// return whether an error was encountered.
11934 SemaBase &SemaRef, OpenMPClauseKind ClauseKind,
11935 SourceLocation ClauseBeginLoc, ArrayRef<const Expr *> ClauseVarList,
11936 const Expr *DimsModifierExpr, const OMPXBareClause *BareClause = nullptr) {
11937 const uint64_t NumVars = ClauseVarList.size();
11938
11939 // The ompx_bare clause allows up to three expressions.
11940 if (BareClause) {
11941 if (NumVars > 3) {
11942 SemaRef.Diag(ClauseBeginLoc,
11943 diag::err_ompx_more_than_three_expr_not_allowed)
11944 << getOpenMPClauseName(ClauseKind);
11945 return true;
11946 }
11947 return false;
11948 }
11949
11950 // By default, only one expression accepted.
11951 uint64_t MaxExprs = 1;
11952 if (DimsModifierExpr) {
11953 // Cannot verify the expected size yet.
11954 if (DimsModifierExpr->isInstantiationDependent())
11955 return false;
11956
11957 // The dims modifier determines the exact number of expressions.
11958 MaxExprs = DimsModifierExpr->EvaluateKnownConstInt(SemaRef.getASTContext())
11959 .getExtValue();
11960 }
11961
11962 if (NumVars != MaxExprs) {
11963 SemaRef.Diag(ClauseBeginLoc, diag::err_omp_unexpected_num_exprs)
11964 << getOpenMPClauseName(ClauseKind) << MaxExprs << NumVars;
11965 return true;
11966 }
11967 if (NumVars > 3) {
11968 SemaRef.Diag(ClauseBeginLoc, diag::err_omp_max_three_exprs)
11969 << getOpenMPClauseName(ClauseKind);
11970 return true;
11971 }
11972 return false;
11973}
11974
11975/// Check the number of expressions specified in a multidimensional clause and
11976/// return whether an error was encountered.
11977template <typename ClauseT>
11979 const ClauseT *Clause,
11980 const OMPXBareClause *BareClause) {
11981 if (!Clause)
11982 return false;
11984 SemaRef, Clause->getClauseKind(), Clause->getBeginLoc(),
11985 Clause->getVarRefs(), Clause->getDimsModifierExpr(), BareClause);
11986}
11987
11988/// Check the number of expressions specified in clauses that can contain
11989/// multidimensional values, e.g., num_teams and thread_limit. The function
11990/// returns true on error.
11992 ArrayRef<OMPClause *> Clauses,
11993 bool MayHaveBareClause = false) {
11994 auto BareClauseIt =
11995 MayHaveBareClause ? llvm::find_if(Clauses, llvm::IsaPred<OMPXBareClause>)
11996 : Clauses.end();
11997 auto ThreadLimitIt =
11998 llvm::find_if(Clauses, llvm::IsaPred<OMPThreadLimitClause>);
11999 auto NumTeamsIt = llvm::find_if(Clauses, llvm::IsaPred<OMPNumTeamsClause>);
12000
12001 const auto *BareClause = BareClauseIt != Clauses.end()
12002 ? cast<OMPXBareClause>(*BareClauseIt)
12003 : nullptr;
12004 const auto *ThreadLimitClause =
12005 ThreadLimitIt != Clauses.end()
12006 ? cast<OMPThreadLimitClause>(*ThreadLimitIt)
12007 : nullptr;
12008 const auto *NumTeamsClause = NumTeamsIt != Clauses.end()
12009 ? cast<OMPNumTeamsClause>(*NumTeamsIt)
12010 : nullptr;
12011
12012 if (BareClause) {
12013 if (!NumTeamsClause || !ThreadLimitClause) {
12014 SemaRef.Diag(BareClause->getBeginLoc(), diag::err_ompx_bare_no_grid);
12015 return true;
12016 }
12017 if (ThreadLimitClause->getModifier() == OMPC_THREADLIMIT_dims ||
12018 NumTeamsClause->getModifier() == OMPC_NUMTEAMS_dims) {
12019 SemaRef.Diag(BareClause->getBeginLoc(), diag::err_ompx_bare_no_dims);
12020 return true;
12021 }
12022 }
12023 return validateMultidimClauseExprs(SemaRef, ThreadLimitClause, BareClause) ||
12024 validateMultidimClauseExprs(SemaRef, NumTeamsClause, BareClause);
12025}
12026
12028 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12029 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12030 if (!AStmt)
12031 return StmtError();
12032
12033 if (validateMultidimClauses(*this, Clauses))
12034 return StmtError();
12035
12036 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_teams_loop, Clauses))
12037 return StmtError();
12038
12039 // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
12040 // A list item may not appear in a lastprivate clause unless it is the
12041 // loop iteration variable of a loop that is associated with the construct.
12042 if (checkGenericLoopLastprivate(SemaRef, Clauses, OMPD_teams_loop, DSAStack))
12043 return StmtError();
12044
12045 CapturedStmt *CS = setBranchProtectedScope(SemaRef, OMPD_teams_loop, AStmt);
12046
12047 OMPLoopDirective::HelperExprs B;
12048 // In presence of clause 'collapse', it will define the nested loops number.
12049 unsigned NestedLoopCount =
12050 checkOpenMPLoop(OMPD_teams_loop, getCollapseNumberExpr(Clauses),
12051 /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
12052 VarsWithImplicitDSA, B);
12053 if (NestedLoopCount == 0)
12054 return StmtError();
12055
12056 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
12057 "omp loop exprs were not built");
12058
12059 DSAStack->setParentTeamsRegionLoc(StartLoc);
12060
12062 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12063}
12064
12066 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12067 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12068 if (!AStmt)
12069 return StmtError();
12070
12071 if (validateMultidimClauses(*this, Clauses))
12072 return StmtError();
12073
12074 // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
12075 // A list item may not appear in a lastprivate clause unless it is the
12076 // loop iteration variable of a loop that is associated with the construct.
12077 if (checkGenericLoopLastprivate(SemaRef, Clauses, OMPD_target_teams_loop,
12078 DSAStack))
12079 return StmtError();
12080
12081 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_target_teams_loop,
12082 Clauses))
12083 return StmtError();
12084
12086 return StmtError();
12087
12088 CapturedStmt *CS =
12089 setBranchProtectedScope(SemaRef, OMPD_target_teams_loop, AStmt);
12090
12091 OMPLoopDirective::HelperExprs B;
12092 // In presence of clause 'collapse', it will define the nested loops number.
12093 unsigned NestedLoopCount =
12094 checkOpenMPLoop(OMPD_target_teams_loop, getCollapseNumberExpr(Clauses),
12095 /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
12096 VarsWithImplicitDSA, B);
12097 if (NestedLoopCount == 0)
12098 return StmtError();
12099
12100 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
12101 "omp loop exprs were not built");
12102
12104 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12106}
12107
12109 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12110 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12111 if (!AStmt)
12112 return StmtError();
12113
12114 // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
12115 // A list item may not appear in a lastprivate clause unless it is the
12116 // loop iteration variable of a loop that is associated with the construct.
12117 if (checkGenericLoopLastprivate(SemaRef, Clauses, OMPD_parallel_loop,
12118 DSAStack))
12119 return StmtError();
12120
12121 CapturedStmt *CS =
12122 setBranchProtectedScope(SemaRef, OMPD_parallel_loop, AStmt);
12123
12124 OMPLoopDirective::HelperExprs B;
12125 // In presence of clause 'collapse', it will define the nested loops number.
12126 unsigned NestedLoopCount =
12127 checkOpenMPLoop(OMPD_parallel_loop, getCollapseNumberExpr(Clauses),
12128 /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
12129 VarsWithImplicitDSA, B);
12130 if (NestedLoopCount == 0)
12131 return StmtError();
12132
12133 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
12134 "omp loop exprs were not built");
12135
12137 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12138}
12139
12140/// Shared by 'target loop' and 'target parallel loop'.
12141template <typename DirectiveTy>
12143 SemaOpenMP &S, DSAStackTy *Stack, OpenMPDirectiveKind DKind,
12144 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12145 SourceLocation EndLoc,
12146 SemaOpenMP::VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12147 if (!AStmt)
12148 return StmtError();
12149
12150 if (validateMultidimClauses(S, Clauses))
12151 return StmtError();
12152
12153 Sema &SemaRef = S.SemaRef;
12154 if (checkClausesForDecompositionConflicts(SemaRef, DKind, Clauses))
12155 return StmtError();
12156
12157 if (checkOriginalVarMappedButOnlyBindingsUsed(SemaRef, Clauses, AStmt))
12158 return StmtError();
12159
12160 // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
12161 // A list item may not appear in a lastprivate clause unless it is the
12162 // loop iteration variable of a loop that is associated with the construct.
12163 if (checkGenericLoopLastprivate(SemaRef, Clauses, DKind, Stack))
12164 return StmtError();
12165
12166 CapturedStmt *CS = setBranchProtectedScope(SemaRef, DKind, AStmt);
12167
12168 OMPLoopDirective::HelperExprs B;
12169 // In presence of clause 'collapse', it will define the nested loops number.
12170 unsigned NestedLoopCount = checkOpenMPLoop(
12171 DKind, getCollapseNumberExpr(Clauses), /*OrderedLoopCountExpr=*/nullptr,
12172 CS, SemaRef, *Stack, VarsWithImplicitDSA, B);
12173 if (NestedLoopCount == 0)
12174 return StmtError();
12175
12176 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
12177 "omp loop exprs were not built");
12178
12179 return DirectiveTy::Create(S.getASTContext(), StartLoc, EndLoc,
12180 NestedLoopCount, Clauses, AStmt, B);
12181}
12182
12184 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12185 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12187 *this, DSAStack, OMPD_target_parallel_loop, Clauses, AStmt, StartLoc,
12188 EndLoc, VarsWithImplicitDSA);
12189}
12190
12192 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12193 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12194 // OpenMP 5.1 [2.11.7, loop Construct, Restrictions]
12195 // If the bind clause is present on the loop construct and binding is teams
12196 // then the corresponding loop region must be strictly nested inside a teams
12197 // region.
12198 if (const auto *BC =
12199 OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses);
12200 BC && BC->getBindKind() == OMPC_BIND_teams) {
12201 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
12202 Diag(StartLoc, diag::err_omp_prohibited_region)
12203 << /*IsClose=*/true << getOpenMPDirectiveName(OMPD_target, OMPVersion)
12204 << /*ShouldBeInTeamsRegion=*/4
12205 << getOpenMPDirectiveName(OMPD_loop, OMPVersion);
12206 return StmtError();
12207 }
12209 *this, DSAStack, OMPD_target_loop, Clauses, AStmt, StartLoc, EndLoc,
12210 VarsWithImplicitDSA);
12211}
12212
12214 Stmt *AStmt,
12215 SourceLocation StartLoc,
12216 SourceLocation EndLoc) {
12217 if (!AStmt)
12218 return StmtError();
12219
12220 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12221
12222 SemaRef.setFunctionHasBranchProtectedScope();
12223
12224 // OpenMP [2.7.3, single Construct, Restrictions]
12225 // The copyprivate clause must not be used with the nowait clause.
12226 const OMPClause *Nowait = nullptr;
12227 const OMPClause *Copyprivate = nullptr;
12228 for (const OMPClause *Clause : Clauses) {
12229 if (Clause->getClauseKind() == OMPC_nowait)
12230 Nowait = Clause;
12231 else if (Clause->getClauseKind() == OMPC_copyprivate)
12232 Copyprivate = Clause;
12233 if (Copyprivate && Nowait) {
12234 Diag(Copyprivate->getBeginLoc(),
12235 diag::err_omp_single_copyprivate_with_nowait);
12236 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
12237 return StmtError();
12238 }
12239 }
12240
12241 return OMPSingleDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses,
12242 AStmt);
12243}
12244
12246 SourceLocation StartLoc,
12247 SourceLocation EndLoc) {
12248 if (!AStmt)
12249 return StmtError();
12250
12251 SemaRef.setFunctionHasBranchProtectedScope();
12252
12253 return OMPMasterDirective::Create(getASTContext(), StartLoc, EndLoc, AStmt);
12254}
12255
12257 Stmt *AStmt,
12258 SourceLocation StartLoc,
12259 SourceLocation EndLoc) {
12260 if (!AStmt)
12261 return StmtError();
12262
12263 SemaRef.setFunctionHasBranchProtectedScope();
12264
12265 return OMPMaskedDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses,
12266 AStmt);
12267}
12268
12270 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
12271 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
12272 if (!AStmt)
12273 return StmtError();
12274
12275 bool ErrorFound = false;
12276 llvm::APSInt Hint;
12277 SourceLocation HintLoc;
12278 bool DependentHint = false;
12279 for (const OMPClause *C : Clauses) {
12280 if (C->getClauseKind() == OMPC_hint) {
12281 if (!DirName.getName()) {
12282 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
12283 ErrorFound = true;
12284 }
12285 Expr *E = cast<OMPHintClause>(C)->getHint();
12286 if (E->isTypeDependent() || E->isValueDependent() ||
12288 DependentHint = true;
12289 } else {
12291 HintLoc = C->getBeginLoc();
12292 }
12293 }
12294 }
12295 if (ErrorFound)
12296 return StmtError();
12297 const auto Pair = DSAStack->getCriticalWithHint(DirName);
12298 if (Pair.first && DirName.getName() && !DependentHint) {
12299 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
12300 Diag(StartLoc, diag::err_omp_critical_with_hint);
12301 if (HintLoc.isValid())
12302 Diag(HintLoc, diag::note_omp_critical_hint_here)
12303 << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
12304 else
12305 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
12306 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
12307 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
12308 << 1
12309 << toString(C->getHint()->EvaluateKnownConstInt(getASTContext()),
12310 /*Radix=*/10, /*Signed=*/false);
12311 } else {
12312 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
12313 }
12314 }
12315 }
12316
12317 SemaRef.setFunctionHasBranchProtectedScope();
12318
12319 auto *Dir = OMPCriticalDirective::Create(getASTContext(), DirName, StartLoc,
12320 EndLoc, Clauses, AStmt);
12321 if (!Pair.first && DirName.getName() && !DependentHint)
12322 DSAStack->addCriticalWithHint(Dir, Hint);
12323 return Dir;
12324}
12325
12327 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12328 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12329 if (!AStmt)
12330 return StmtError();
12331
12332 setBranchProtectedScope(SemaRef, OMPD_parallel_for, AStmt);
12333
12334 OMPLoopBasedDirective::HelperExprs B;
12335 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12336 // define the nested loops number.
12337 unsigned NestedLoopCount =
12338 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
12339 getOrderedNumberExpr(Clauses), AStmt, SemaRef, *DSAStack,
12340 VarsWithImplicitDSA, B);
12341 if (NestedLoopCount == 0)
12342 return StmtError();
12343
12344 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
12345 return StmtError();
12346
12348 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
12349 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12350}
12351
12353 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12354 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
12355 if (!AStmt)
12356 return StmtError();
12357
12358 CapturedStmt *CS =
12359 setBranchProtectedScope(SemaRef, OMPD_parallel_for_simd, AStmt);
12360
12361 OMPLoopBasedDirective::HelperExprs B;
12362 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
12363 // define the nested loops number.
12364 unsigned NestedLoopCount =
12365 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
12366 getOrderedNumberExpr(Clauses), CS, SemaRef, *DSAStack,
12367 VarsWithImplicitDSA, B);
12368 if (NestedLoopCount == 0)
12369 return StmtError();
12370
12371 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
12372 return StmtError();
12373
12375 return StmtError();
12376
12378 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
12379}
12380
12382 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12383 SourceLocation EndLoc) {
12384 if (!AStmt)
12385 return StmtError();
12386
12387 setBranchProtectedScope(SemaRef, OMPD_parallel_master, AStmt);
12388
12390 getASTContext(), StartLoc, EndLoc, Clauses, AStmt,
12391 DSAStack->getTaskgroupReductionRef());
12392}
12393
12395 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12396 SourceLocation EndLoc) {
12397 if (!AStmt)
12398 return StmtError();
12399
12400 setBranchProtectedScope(SemaRef, OMPD_parallel_masked, AStmt);
12401
12403 getASTContext(), StartLoc, EndLoc, Clauses, AStmt,
12404 DSAStack->getTaskgroupReductionRef());
12405}
12406
12408 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
12409 SourceLocation EndLoc) {
12410 if (checkSectionsDirective(SemaRef, OMPD_parallel_sections, AStmt, DSAStack))
12411 return StmtError();
12412
12413 SemaRef.setFunctionHasBranchProtectedScope();
12414
12416 getASTContext(), StartLoc, EndLoc, Clauses, AStmt,
12417 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
12418}
12419
12420/// Find and diagnose mutually exclusive clause kinds.
12422 Sema &S, ArrayRef<OMPClause *> Clauses,
12423 ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
12424 const OMPClause *PrevClause = nullptr;
12425 bool ErrorFound = false;
12426 for (const OMPClause *C : Clauses) {
12427 if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
12428 if (!PrevClause) {
12429 PrevClause = C;
12430 } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
12431 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
12432 << getOpenMPClauseNameForDiag(C->getClauseKind())
12433 << getOpenMPClauseNameForDiag(PrevClause->getClauseKind());
12434 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
12435 << getOpenMPClauseNameForDiag(PrevClause->getClauseKind());
12436 ErrorFound = true;
12437 }
12438 }
12439 }
12440 return ErrorFound;
12441}
12442
12444 Stmt *AStmt,
12445 SourceLocation StartLoc,
12446 SourceLocation EndLoc) {
12447 if (!AStmt)
12448 return StmtError();
12449
12450 // OpenMP 5.0, 2.10.1 task Construct
12451 // If a detach clause appears on the directive, then a mergeable clause cannot
12452 // appear on the same directive.
12454 {OMPC_detach, OMPC_mergeable}))
12455 return StmtError();
12456
12457 // Check for conflicting capture kinds on structured bindings.
12458 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_task, Clauses, AStmt))
12459 return StmtError();
12460
12461 setBranchProtectedScope(SemaRef, OMPD_task, AStmt);
12462
12463 return OMPTaskDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses,
12464 AStmt, DSAStack->isCancelRegion());
12465}
12466
12471
12476
12478 SourceLocation StartLoc,
12479 SourceLocation EndLoc,
12480 bool InExContext) {
12481 const OMPAtClause *AtC =
12482 OMPExecutableDirective::getSingleClause<OMPAtClause>(Clauses);
12483
12484 if (AtC && !InExContext && AtC->getAtKind() == OMPC_AT_execution) {
12485 Diag(AtC->getAtKindKwLoc(), diag::err_omp_unexpected_execution_modifier);
12486 return StmtError();
12487 }
12488
12489 if (!AtC || AtC->getAtKind() == OMPC_AT_compilation) {
12490 const OMPSeverityClause *SeverityC =
12491 OMPExecutableDirective::getSingleClause<OMPSeverityClause>(Clauses);
12492 const OMPMessageClause *MessageC =
12493 OMPExecutableDirective::getSingleClause<OMPMessageClause>(Clauses);
12494 std::optional<std::string> SL =
12495 MessageC ? MessageC->tryEvaluateString(getASTContext()) : std::nullopt;
12496
12497 if (MessageC && !SL)
12498 Diag(MessageC->getMessageString()->getBeginLoc(),
12499 diag::warn_clause_expected_string)
12500 << getOpenMPClauseNameForDiag(OMPC_message) << 1;
12501 if (SeverityC && SeverityC->getSeverityKind() == OMPC_SEVERITY_warning)
12502 Diag(SeverityC->getSeverityKindKwLoc(), diag::warn_diagnose_if_succeeded)
12503 << SL.value_or("WARNING");
12504 else
12505 Diag(StartLoc, diag::err_diagnose_if_succeeded) << SL.value_or("ERROR");
12506 if (!SeverityC || SeverityC->getSeverityKind() != OMPC_SEVERITY_warning)
12507 return StmtError();
12508 }
12509
12510 return OMPErrorDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses);
12511}
12512
12515 SourceLocation StartLoc,
12516 SourceLocation EndLoc) {
12517 const OMPNowaitClause *NowaitC =
12518 OMPExecutableDirective::getSingleClause<OMPNowaitClause>(Clauses);
12519 bool HasDependC =
12520 !OMPExecutableDirective::getClausesOfKind<OMPDependClause>(Clauses)
12521 .empty();
12522 if (NowaitC && !HasDependC) {
12523 Diag(StartLoc, diag::err_omp_nowait_clause_without_depend);
12524 return StmtError();
12525 }
12526
12527 return OMPTaskwaitDirective::Create(getASTContext(), StartLoc, EndLoc,
12528 Clauses);
12529}
12530
12533 Stmt *AStmt, SourceLocation StartLoc,
12534 SourceLocation EndLoc) {
12535 if (!AStmt)
12536 return StmtError();
12537
12538 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12539
12540 SemaRef.setFunctionHasBranchProtectedScope();
12541
12542 return OMPTaskgroupDirective::Create(getASTContext(), StartLoc, EndLoc,
12543 Clauses, AStmt,
12544 DSAStack->getTaskgroupReductionRef());
12545}
12546
12548 SourceLocation StartLoc,
12549 SourceLocation EndLoc) {
12550 OMPFlushClause *FC = nullptr;
12551 OMPClause *OrderClause = nullptr;
12552 for (OMPClause *C : Clauses) {
12553 if (C->getClauseKind() == OMPC_flush)
12554 FC = cast<OMPFlushClause>(C);
12555 else
12556 OrderClause = C;
12557 }
12558 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
12559 OpenMPClauseKind MemOrderKind = OMPC_unknown;
12560 SourceLocation MemOrderLoc;
12561 for (const OMPClause *C : Clauses) {
12562 if (C->getClauseKind() == OMPC_acq_rel ||
12563 C->getClauseKind() == OMPC_acquire ||
12564 C->getClauseKind() == OMPC_release ||
12565 C->getClauseKind() == OMPC_seq_cst /*OpenMP 5.1*/) {
12566 if (MemOrderKind != OMPC_unknown) {
12567 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
12568 << getOpenMPDirectiveName(OMPD_flush, OMPVersion) << 1
12569 << SourceRange(C->getBeginLoc(), C->getEndLoc());
12570 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
12571 << getOpenMPClauseNameForDiag(MemOrderKind);
12572 } else {
12573 MemOrderKind = C->getClauseKind();
12574 MemOrderLoc = C->getBeginLoc();
12575 }
12576 }
12577 }
12578 if (FC && OrderClause) {
12579 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
12580 << getOpenMPClauseNameForDiag(OrderClause->getClauseKind());
12581 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
12582 << getOpenMPClauseNameForDiag(OrderClause->getClauseKind());
12583 return StmtError();
12584 }
12585 return OMPFlushDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses);
12586}
12587
12589 SourceLocation StartLoc,
12590 SourceLocation EndLoc) {
12591 if (Clauses.empty()) {
12592 Diag(StartLoc, diag::err_omp_depobj_expected);
12593 return StmtError();
12594 } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
12595 Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
12596 return StmtError();
12597 }
12598 // Only depobj expression and another single clause is allowed.
12599 if (Clauses.size() > 2) {
12600 Diag(Clauses[2]->getBeginLoc(),
12601 diag::err_omp_depobj_single_clause_expected);
12602 return StmtError();
12603 } else if (Clauses.size() < 1) {
12604 Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
12605 return StmtError();
12606 }
12607 return OMPDepobjDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses);
12608}
12609
12611 SourceLocation StartLoc,
12612 SourceLocation EndLoc) {
12613 // Check that exactly one clause is specified.
12614 if (Clauses.size() != 1) {
12615 Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
12616 diag::err_omp_scan_single_clause_expected);
12617 return StmtError();
12618 }
12619 // Check that scan directive is used in the scope of the OpenMP loop body.
12620 if (Scope *S = DSAStack->getCurScope()) {
12621 Scope *ParentS = S->getParent();
12622 if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
12623 !ParentS->getBreakParent()->isOpenMPLoopScope()) {
12624 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
12625 return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
12626 << getOpenMPDirectiveName(OMPD_scan, OMPVersion) << 5);
12627 }
12628 }
12629 // Check that only one instance of scan directives is used in the same outer
12630 // region.
12631 if (DSAStack->doesParentHasScanDirective()) {
12632 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
12633 Diag(DSAStack->getParentScanDirectiveLoc(),
12634 diag::note_omp_previous_directive)
12635 << "scan";
12636 return StmtError();
12637 }
12638 DSAStack->setParentHasScanDirective(StartLoc);
12639 return OMPScanDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses);
12640}
12641
12644 Stmt *AStmt, SourceLocation StartLoc,
12645 SourceLocation EndLoc) {
12646 const OMPClause *DependFound = nullptr;
12647 const OMPClause *DependSourceClause = nullptr;
12648 const OMPClause *DependSinkClause = nullptr;
12649 const OMPClause *DoacrossFound = nullptr;
12650 const OMPClause *DoacrossSourceClause = nullptr;
12651 const OMPClause *DoacrossSinkClause = nullptr;
12652 bool ErrorFound = false;
12653 const OMPThreadsClause *TC = nullptr;
12654 const OMPSIMDClause *SC = nullptr;
12655 for (const OMPClause *C : Clauses) {
12656 auto DOC = dyn_cast<OMPDoacrossClause>(C);
12657 auto DC = dyn_cast<OMPDependClause>(C);
12658 if (DC || DOC) {
12659 DependFound = DC ? C : nullptr;
12660 DoacrossFound = DOC ? C : nullptr;
12661 OMPDoacrossKind ODK;
12662 if ((DC && DC->getDependencyKind() == OMPC_DEPEND_source) ||
12663 (DOC && (ODK.isSource(DOC)))) {
12664 if ((DC && DependSourceClause) || (DOC && DoacrossSourceClause)) {
12665 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
12666 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
12667 << getOpenMPDirectiveName(DSAStack->getCurrentDirective(),
12668 OMPVersion)
12669 << getOpenMPClauseNameForDiag(DC ? OMPC_depend : OMPC_doacross)
12670 << 2;
12671 ErrorFound = true;
12672 } else {
12673 if (DC)
12674 DependSourceClause = C;
12675 else
12676 DoacrossSourceClause = C;
12677 }
12678 if ((DC && DependSinkClause) || (DOC && DoacrossSinkClause)) {
12679 Diag(C->getBeginLoc(), diag::err_omp_sink_and_source_not_allowed)
12680 << (DC ? "depend" : "doacross") << 0;
12681 ErrorFound = true;
12682 }
12683 } else if ((DC && DC->getDependencyKind() == OMPC_DEPEND_sink) ||
12684 (DOC && (ODK.isSink(DOC) || ODK.isSinkIter(DOC)))) {
12685 if (DependSourceClause || DoacrossSourceClause) {
12686 Diag(C->getBeginLoc(), diag::err_omp_sink_and_source_not_allowed)
12687 << (DC ? "depend" : "doacross") << 1;
12688 ErrorFound = true;
12689 }
12690 if (DC)
12691 DependSinkClause = C;
12692 else
12693 DoacrossSinkClause = C;
12694 }
12695 } else if (C->getClauseKind() == OMPC_threads) {
12697 } else if (C->getClauseKind() == OMPC_simd) {
12698 SC = cast<OMPSIMDClause>(C);
12699 }
12700 }
12701 if (!ErrorFound && !SC &&
12702 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
12703 // OpenMP [2.8.1,simd Construct, Restrictions]
12704 // An ordered construct with the simd clause is the only OpenMP construct
12705 // that can appear in the simd region.
12706 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
12707 << (getLangOpts().OpenMP >= 50 ? 1 : 0);
12708 ErrorFound = true;
12709 } else if ((DependFound || DoacrossFound) && (TC || SC)) {
12710 SourceLocation Loc =
12711 DependFound ? DependFound->getBeginLoc() : DoacrossFound->getBeginLoc();
12712 Diag(Loc, diag::err_omp_depend_clause_thread_simd)
12713 << getOpenMPClauseNameForDiag(DependFound ? OMPC_depend : OMPC_doacross)
12714 << getOpenMPClauseNameForDiag(TC ? TC->getClauseKind()
12715 : SC->getClauseKind());
12716 ErrorFound = true;
12717 } else if ((DependFound || DoacrossFound) &&
12718 !DSAStack->getParentOrderedRegionParam().first) {
12719 SourceLocation Loc =
12720 DependFound ? DependFound->getBeginLoc() : DoacrossFound->getBeginLoc();
12721 Diag(Loc, diag::err_omp_ordered_directive_without_param)
12722 << getOpenMPClauseNameForDiag(DependFound ? OMPC_depend
12723 : OMPC_doacross);
12724 ErrorFound = true;
12725 } else if (TC || Clauses.empty()) {
12726 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
12727 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
12728 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
12729 << (TC != nullptr);
12730 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
12731 ErrorFound = true;
12732 }
12733 }
12734 if ((!AStmt && !DependFound && !DoacrossFound) || ErrorFound)
12735 return StmtError();
12736
12737 // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
12738 // During execution of an iteration of a worksharing-loop or a loop nest
12739 // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
12740 // must not execute more than one ordered region corresponding to an ordered
12741 // construct without a depend clause.
12742 if (!DependFound && !DoacrossFound) {
12743 if (DSAStack->doesParentHasOrderedDirective()) {
12744 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
12745 Diag(DSAStack->getParentOrderedDirectiveLoc(),
12746 diag::note_omp_previous_directive)
12747 << "ordered";
12748 return StmtError();
12749 }
12750 DSAStack->setParentHasOrderedDirective(StartLoc);
12751 }
12752
12753 if (AStmt) {
12754 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
12755
12756 SemaRef.setFunctionHasBranchProtectedScope();
12757 }
12758
12759 if (!AStmt)
12761 EndLoc, Clauses);
12763 EndLoc, Clauses, AStmt);
12764}
12765
12766namespace {
12767/// Helper class for checking expression in 'omp atomic [update]'
12768/// construct.
12769class OpenMPAtomicUpdateChecker {
12770 /// Error results for atomic update expressions.
12771 enum ExprAnalysisErrorCode {
12772 /// A statement is not an expression statement.
12773 NotAnExpression,
12774 /// Expression is not builtin binary or unary operation.
12775 NotABinaryOrUnaryExpression,
12776 /// Unary operation is not post-/pre- increment/decrement operation.
12777 NotAnUnaryIncDecExpression,
12778 /// An expression is not of scalar type.
12779 NotAScalarType,
12780 /// A binary operation is not an assignment operation.
12781 NotAnAssignmentOp,
12782 /// RHS part of the binary operation is not a binary expression.
12783 NotABinaryExpression,
12784 /// RHS part is not additive/multiplicative/shift/bitwise binary
12785 /// expression.
12786 NotABinaryOperator,
12787 /// RHS binary operation does not have reference to the updated LHS
12788 /// part.
12789 NotAnUpdateExpression,
12790 /// An expression contains semantical error not related to
12791 /// 'omp atomic [update]'
12792 NotAValidExpression,
12793 /// No errors is found.
12794 NoError
12795 };
12796 /// Reference to Sema.
12797 Sema &SemaRef;
12798 /// A location for note diagnostics (when error is found).
12799 SourceLocation NoteLoc;
12800 /// 'x' lvalue part of the source atomic expression.
12801 Expr *X;
12802 /// 'expr' rvalue part of the source atomic expression.
12803 Expr *E;
12804 /// Helper expression of the form
12805 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
12806 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
12807 Expr *UpdateExpr;
12808 /// Is 'x' a LHS in a RHS part of full update expression. It is
12809 /// important for non-associative operations.
12810 bool IsXLHSInRHSPart;
12812 SourceLocation OpLoc;
12813 /// true if the source expression is a postfix unary operation, false
12814 /// if it is a prefix unary operation.
12815 bool IsPostfixUpdate;
12816
12817public:
12818 OpenMPAtomicUpdateChecker(Sema &SemaRef)
12819 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
12820 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
12821 /// Check specified statement that it is suitable for 'atomic update'
12822 /// constructs and extract 'x', 'expr' and Operation from the original
12823 /// expression. If DiagId and NoteId == 0, then only check is performed
12824 /// without error notification.
12825 /// \param DiagId Diagnostic which should be emitted if error is found.
12826 /// \param NoteId Diagnostic note for the main error message.
12827 /// \return true if statement is not an update expression, false otherwise.
12828 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
12829 /// Return the 'x' lvalue part of the source atomic expression.
12830 Expr *getX() const { return X; }
12831 /// Return the 'expr' rvalue part of the source atomic expression.
12832 Expr *getExpr() const { return E; }
12833 /// Return the update expression used in calculation of the updated
12834 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
12835 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
12836 Expr *getUpdateExpr() const { return UpdateExpr; }
12837 /// Return true if 'x' is LHS in RHS part of full update expression,
12838 /// false otherwise.
12839 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
12840
12841 /// true if the source expression is a postfix unary operation, false
12842 /// if it is a prefix unary operation.
12843 bool isPostfixUpdate() const { return IsPostfixUpdate; }
12844
12845private:
12846 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
12847 unsigned NoteId = 0);
12848};
12849
12850bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
12851 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
12852 ExprAnalysisErrorCode ErrorFound = NoError;
12853 SourceLocation ErrorLoc, NoteLoc;
12854 SourceRange ErrorRange, NoteRange;
12855 // Allowed constructs are:
12856 // x = x binop expr;
12857 // x = expr binop x;
12858 if (AtomicBinOp->getOpcode() == BO_Assign) {
12859 X = AtomicBinOp->getLHS();
12860 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
12861 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
12862 if (AtomicInnerBinOp->isMultiplicativeOp() ||
12863 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
12864 AtomicInnerBinOp->isBitwiseOp()) {
12865 Op = AtomicInnerBinOp->getOpcode();
12866 OpLoc = AtomicInnerBinOp->getOperatorLoc();
12867 Expr *LHS = AtomicInnerBinOp->getLHS();
12868 Expr *RHS = AtomicInnerBinOp->getRHS();
12869 llvm::FoldingSetNodeID XId, LHSId, RHSId;
12870 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
12871 /*Canonical=*/true);
12872 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
12873 /*Canonical=*/true);
12874 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
12875 /*Canonical=*/true);
12876 if (XId == LHSId) {
12877 E = RHS;
12878 IsXLHSInRHSPart = true;
12879 } else if (XId == RHSId) {
12880 E = LHS;
12881 IsXLHSInRHSPart = false;
12882 } else {
12883 ErrorLoc = AtomicInnerBinOp->getExprLoc();
12884 ErrorRange = AtomicInnerBinOp->getSourceRange();
12885 NoteLoc = X->getExprLoc();
12886 NoteRange = X->getSourceRange();
12887 ErrorFound = NotAnUpdateExpression;
12888 }
12889 } else {
12890 ErrorLoc = AtomicInnerBinOp->getExprLoc();
12891 ErrorRange = AtomicInnerBinOp->getSourceRange();
12892 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
12893 NoteRange = SourceRange(NoteLoc, NoteLoc);
12894 ErrorFound = NotABinaryOperator;
12895 }
12896 } else {
12897 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
12898 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
12899 ErrorFound = NotABinaryExpression;
12900 }
12901 } else {
12902 ErrorLoc = AtomicBinOp->getExprLoc();
12903 ErrorRange = AtomicBinOp->getSourceRange();
12904 NoteLoc = AtomicBinOp->getOperatorLoc();
12905 NoteRange = SourceRange(NoteLoc, NoteLoc);
12906 ErrorFound = NotAnAssignmentOp;
12907 }
12908 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
12909 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
12910 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
12911 return true;
12912 }
12913 if (SemaRef.CurContext->isDependentContext())
12914 E = X = UpdateExpr = nullptr;
12915 return ErrorFound != NoError;
12916}
12917
12918bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
12919 unsigned NoteId) {
12920 ExprAnalysisErrorCode ErrorFound = NoError;
12921 SourceLocation ErrorLoc, NoteLoc;
12922 SourceRange ErrorRange, NoteRange;
12923 // Allowed constructs are:
12924 // x++;
12925 // x--;
12926 // ++x;
12927 // --x;
12928 // x binop= expr;
12929 // x = x binop expr;
12930 // x = expr binop x;
12931 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
12932 AtomicBody = AtomicBody->IgnoreParenImpCasts();
12933 if (AtomicBody->getType()->isScalarType() ||
12934 AtomicBody->isInstantiationDependent()) {
12935 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
12936 AtomicBody->IgnoreParenImpCasts())) {
12937 // Check for Compound Assignment Operation
12939 AtomicCompAssignOp->getOpcode());
12940 OpLoc = AtomicCompAssignOp->getOperatorLoc();
12941 E = AtomicCompAssignOp->getRHS();
12942 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
12943 IsXLHSInRHSPart = true;
12944 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
12945 AtomicBody->IgnoreParenImpCasts())) {
12946 // Check for Binary Operation
12947 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
12948 return true;
12949 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
12950 AtomicBody->IgnoreParenImpCasts())) {
12951 // Check for Unary Operation
12952 if (AtomicUnaryOp->isIncrementDecrementOp()) {
12953 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
12954 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
12955 OpLoc = AtomicUnaryOp->getOperatorLoc();
12956 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
12957 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
12958 IsXLHSInRHSPart = true;
12959 } else {
12960 ErrorFound = NotAnUnaryIncDecExpression;
12961 ErrorLoc = AtomicUnaryOp->getExprLoc();
12962 ErrorRange = AtomicUnaryOp->getSourceRange();
12963 NoteLoc = AtomicUnaryOp->getOperatorLoc();
12964 NoteRange = SourceRange(NoteLoc, NoteLoc);
12965 }
12966 } else if (!AtomicBody->isInstantiationDependent()) {
12967 ErrorFound = NotABinaryOrUnaryExpression;
12968 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
12969 NoteRange = ErrorRange = AtomicBody->getSourceRange();
12970 } else if (AtomicBody->containsErrors()) {
12971 ErrorFound = NotAValidExpression;
12972 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
12973 NoteRange = ErrorRange = AtomicBody->getSourceRange();
12974 }
12975 } else {
12976 ErrorFound = NotAScalarType;
12977 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
12978 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
12979 }
12980 } else {
12981 ErrorFound = NotAnExpression;
12982 NoteLoc = ErrorLoc = S->getBeginLoc();
12983 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
12984 }
12985 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
12986 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
12987 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
12988 return true;
12989 }
12990 if (SemaRef.CurContext->isDependentContext())
12991 E = X = UpdateExpr = nullptr;
12992 if (ErrorFound == NoError && E && X && !E->containsErrors() &&
12993 !X->containsErrors()) {
12994 // Build an update expression of form 'OpaqueValueExpr(x) binop
12995 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
12996 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
12997 auto *OVEX = new (SemaRef.getASTContext())
12998 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
12999 auto *OVEExpr = new (SemaRef.getASTContext())
13002 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
13003 IsXLHSInRHSPart ? OVEExpr : OVEX);
13004 if (Update.isInvalid())
13005 return true;
13006 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
13008 if (Update.isInvalid())
13009 return true;
13010 UpdateExpr = Update.get();
13011 }
13012 return ErrorFound != NoError;
13013}
13014
13015/// Get the node id of the fixed point of an expression \a S.
13016llvm::FoldingSetNodeID getNodeId(ASTContext &Context, const Expr *S) {
13017 llvm::FoldingSetNodeID Id;
13018 S->IgnoreParenImpCasts()->Profile(Id, Context, true);
13019 return Id;
13020}
13021
13022/// Check if two expressions are same.
13023bool checkIfTwoExprsAreSame(ASTContext &Context, const Expr *LHS,
13024 const Expr *RHS) {
13025 return getNodeId(Context, LHS) == getNodeId(Context, RHS);
13026}
13027
13028class OpenMPAtomicCompareChecker {
13029public:
13030 /// All kinds of errors that can occur in `atomic compare`
13031 enum ErrorTy {
13032 /// Empty compound statement.
13033 NoStmt = 0,
13034 /// More than one statement in a compound statement.
13035 MoreThanOneStmt,
13036 /// Not an assignment binary operator.
13037 NotAnAssignment,
13038 /// Not a conditional operator.
13039 NotCondOp,
13040 /// Wrong false expr. According to the spec, 'x' should be at the false
13041 /// expression of a conditional expression.
13042 WrongFalseExpr,
13043 /// The condition of a conditional expression is not a binary operator.
13044 NotABinaryOp,
13045 /// Invalid binary operator (not <, >, or ==).
13046 InvalidBinaryOp,
13047 /// Invalid comparison (not x == e, e == x, x ordop expr, or expr ordop x).
13048 InvalidComparison,
13049 /// X is not a lvalue.
13050 XNotLValue,
13051 /// Not a scalar.
13052 NotScalar,
13053 /// Not an integer.
13054 NotInteger,
13055 /// 'else' statement is not expected.
13056 UnexpectedElse,
13057 /// Not an equality operator.
13058 NotEQ,
13059 /// Invalid assignment (not v == x).
13060 InvalidAssignment,
13061 /// Not if statement
13062 NotIfStmt,
13063 /// More than two statements in a compound statement.
13064 MoreThanTwoStmts,
13065 /// Not a compound statement.
13066 NotCompoundStmt,
13067 /// No else statement.
13068 NoElse,
13069 /// Not 'if (r)'.
13070 InvalidCondition,
13071 /// No error.
13072 NoError,
13073 };
13074
13075 struct ErrorInfoTy {
13076 ErrorTy Error;
13077 SourceLocation ErrorLoc;
13078 SourceRange ErrorRange;
13079 SourceLocation NoteLoc;
13080 SourceRange NoteRange;
13081 };
13082
13083 OpenMPAtomicCompareChecker(Sema &S) : ContextRef(S.getASTContext()) {}
13084
13085 /// Check if statement \a S is valid for <tt>atomic compare</tt>.
13086 bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
13087
13088 Expr *getX() const { return X; }
13089 Expr *getE() const { return E; }
13090 Expr *getD() const { return D; }
13091 Expr *getCond() const { return C; }
13092 bool isXBinopExpr() const { return IsXBinopExpr; }
13093
13094protected:
13095 /// Reference to ASTContext
13096 ASTContext &ContextRef;
13097 /// 'x' lvalue part of the source atomic expression.
13098 Expr *X = nullptr;
13099 /// 'expr' or 'e' rvalue part of the source atomic expression.
13100 Expr *E = nullptr;
13101 /// 'd' rvalue part of the source atomic expression.
13102 Expr *D = nullptr;
13103 /// 'cond' part of the source atomic expression. It is in one of the following
13104 /// forms:
13105 /// expr ordop x
13106 /// x ordop expr
13107 /// x == e
13108 /// e == x
13109 Expr *C = nullptr;
13110 /// True if the cond expr is in the form of 'x ordop expr'.
13111 bool IsXBinopExpr = true;
13112
13113 /// Check if it is a valid conditional update statement (cond-update-stmt).
13114 bool checkCondUpdateStmt(IfStmt *S, ErrorInfoTy &ErrorInfo);
13115
13116 /// Check if it is a valid conditional expression statement (cond-expr-stmt).
13117 bool checkCondExprStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
13118
13119 /// Check if all captured values have right type.
13120 bool checkType(ErrorInfoTy &ErrorInfo) const;
13121
13122 static bool CheckValue(const Expr *E, ErrorInfoTy &ErrorInfo,
13123 bool ShouldBeLValue, bool ShouldBeInteger = false) {
13124 if (E->isInstantiationDependent())
13125 return true;
13126
13127 if (ShouldBeLValue && !E->isLValue()) {
13128 ErrorInfo.Error = ErrorTy::XNotLValue;
13129 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
13130 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
13131 return false;
13132 }
13133
13134 QualType QTy = E->getType();
13135 if (!QTy->isScalarType()) {
13136 ErrorInfo.Error = ErrorTy::NotScalar;
13137 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
13138 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
13139 return false;
13140 }
13141 if (ShouldBeInteger && !QTy->isIntegerType()) {
13142 ErrorInfo.Error = ErrorTy::NotInteger;
13143 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
13144 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
13145 return false;
13146 }
13147
13148 return true;
13149 }
13150};
13151
13152bool OpenMPAtomicCompareChecker::checkCondUpdateStmt(IfStmt *S,
13153 ErrorInfoTy &ErrorInfo) {
13154 auto *Then = S->getThen();
13155 if (auto *CS = dyn_cast<CompoundStmt>(Then)) {
13156 if (CS->body_empty()) {
13157 ErrorInfo.Error = ErrorTy::NoStmt;
13158 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
13159 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
13160 return false;
13161 }
13162 if (CS->size() > 1) {
13163 ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
13164 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
13165 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
13166 return false;
13167 }
13168 Then = CS->body_front();
13169 }
13170
13171 auto *BO = dyn_cast<BinaryOperator>(Then);
13172 if (!BO) {
13173 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13174 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc();
13175 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange();
13176 return false;
13177 }
13178 if (BO->getOpcode() != BO_Assign) {
13179 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13180 ErrorInfo.ErrorLoc = BO->getExprLoc();
13181 ErrorInfo.NoteLoc = BO->getOperatorLoc();
13182 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
13183 return false;
13184 }
13185
13186 X = BO->getLHS();
13187
13188 auto *Cond = dyn_cast<BinaryOperator>(S->getCond());
13189 auto *Call = dyn_cast<CXXOperatorCallExpr>(S->getCond());
13190 Expr *LHS = nullptr;
13191 Expr *RHS = nullptr;
13192 if (Cond) {
13193 LHS = Cond->getLHS();
13194 RHS = Cond->getRHS();
13195 } else if (Call) {
13196 LHS = Call->getArg(0);
13197 RHS = Call->getArg(1);
13198 } else {
13199 ErrorInfo.Error = ErrorTy::NotABinaryOp;
13200 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
13201 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
13202 return false;
13203 }
13204
13205 if ((Cond && Cond->getOpcode() == BO_EQ) ||
13206 (Call && Call->getOperator() == OverloadedOperatorKind::OO_EqualEqual)) {
13207 C = S->getCond();
13208 D = BO->getRHS();
13209 if (checkIfTwoExprsAreSame(ContextRef, X, LHS)) {
13210 E = RHS;
13211 } else if (checkIfTwoExprsAreSame(ContextRef, X, RHS)) {
13212 E = LHS;
13213 } else {
13214 ErrorInfo.Error = ErrorTy::InvalidComparison;
13215 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
13216 ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
13217 S->getCond()->getSourceRange();
13218 return false;
13219 }
13220 } else if ((Cond &&
13221 (Cond->getOpcode() == BO_LT || Cond->getOpcode() == BO_GT)) ||
13222 (Call &&
13223 (Call->getOperator() == OverloadedOperatorKind::OO_Less ||
13224 Call->getOperator() == OverloadedOperatorKind::OO_Greater))) {
13225 E = BO->getRHS();
13226 if (checkIfTwoExprsAreSame(ContextRef, X, LHS) &&
13227 checkIfTwoExprsAreSame(ContextRef, E, RHS)) {
13228 C = S->getCond();
13229 } else if (checkIfTwoExprsAreSame(ContextRef, E, LHS) &&
13230 checkIfTwoExprsAreSame(ContextRef, X, RHS)) {
13231 C = S->getCond();
13232 IsXBinopExpr = false;
13233 } else {
13234 ErrorInfo.Error = ErrorTy::InvalidComparison;
13235 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
13236 ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
13237 S->getCond()->getSourceRange();
13238 return false;
13239 }
13240 } else {
13241 ErrorInfo.Error = ErrorTy::InvalidBinaryOp;
13242 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
13243 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
13244 return false;
13245 }
13246
13247 if (S->getElse()) {
13248 ErrorInfo.Error = ErrorTy::UnexpectedElse;
13249 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getElse()->getBeginLoc();
13250 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getElse()->getSourceRange();
13251 return false;
13252 }
13253
13254 return true;
13255}
13256
13257bool OpenMPAtomicCompareChecker::checkCondExprStmt(Stmt *S,
13258 ErrorInfoTy &ErrorInfo) {
13259 auto *BO = dyn_cast<BinaryOperator>(S);
13260 if (!BO) {
13261 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13262 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
13263 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
13264 return false;
13265 }
13266 if (BO->getOpcode() != BO_Assign) {
13267 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13268 ErrorInfo.ErrorLoc = BO->getExprLoc();
13269 ErrorInfo.NoteLoc = BO->getOperatorLoc();
13270 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
13271 return false;
13272 }
13273
13274 X = BO->getLHS();
13275
13276 auto *CO = dyn_cast<ConditionalOperator>(BO->getRHS()->IgnoreParenImpCasts());
13277 if (!CO) {
13278 ErrorInfo.Error = ErrorTy::NotCondOp;
13279 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getRHS()->getExprLoc();
13280 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getRHS()->getSourceRange();
13281 return false;
13282 }
13283
13284 if (!checkIfTwoExprsAreSame(ContextRef, X, CO->getFalseExpr())) {
13285 ErrorInfo.Error = ErrorTy::WrongFalseExpr;
13286 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getFalseExpr()->getExprLoc();
13287 ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
13288 CO->getFalseExpr()->getSourceRange();
13289 return false;
13290 }
13291
13292 auto *Cond = dyn_cast<BinaryOperator>(CO->getCond());
13293 auto *Call = dyn_cast<CXXOperatorCallExpr>(CO->getCond());
13294 Expr *LHS = nullptr;
13295 Expr *RHS = nullptr;
13296 if (Cond) {
13297 LHS = Cond->getLHS();
13298 RHS = Cond->getRHS();
13299 } else if (Call) {
13300 LHS = Call->getArg(0);
13301 RHS = Call->getArg(1);
13302 } else {
13303 ErrorInfo.Error = ErrorTy::NotABinaryOp;
13304 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc();
13305 ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
13306 CO->getCond()->getSourceRange();
13307 return false;
13308 }
13309
13310 if ((Cond && Cond->getOpcode() == BO_EQ) ||
13311 (Call && Call->getOperator() == OverloadedOperatorKind::OO_EqualEqual)) {
13312 C = CO->getCond();
13313 D = CO->getTrueExpr();
13314 if (checkIfTwoExprsAreSame(ContextRef, X, LHS)) {
13315 E = RHS;
13316 } else if (checkIfTwoExprsAreSame(ContextRef, X, RHS)) {
13317 E = LHS;
13318 } else {
13319 ErrorInfo.Error = ErrorTy::InvalidComparison;
13320 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc();
13321 ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
13322 CO->getCond()->getSourceRange();
13323 return false;
13324 }
13325 } else if ((Cond &&
13326 (Cond->getOpcode() == BO_LT || Cond->getOpcode() == BO_GT)) ||
13327 (Call &&
13328 (Call->getOperator() == OverloadedOperatorKind::OO_Less ||
13329 Call->getOperator() == OverloadedOperatorKind::OO_Greater))) {
13330
13331 E = CO->getTrueExpr();
13332 if (checkIfTwoExprsAreSame(ContextRef, X, LHS) &&
13333 checkIfTwoExprsAreSame(ContextRef, E, RHS)) {
13334 C = CO->getCond();
13335 } else if (checkIfTwoExprsAreSame(ContextRef, E, LHS) &&
13336 checkIfTwoExprsAreSame(ContextRef, X, RHS)) {
13337 C = CO->getCond();
13338 IsXBinopExpr = false;
13339 } else {
13340 ErrorInfo.Error = ErrorTy::InvalidComparison;
13341 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc();
13342 ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
13343 CO->getCond()->getSourceRange();
13344 return false;
13345 }
13346 } else {
13347 ErrorInfo.Error = ErrorTy::InvalidBinaryOp;
13348 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc();
13349 ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
13350 CO->getCond()->getSourceRange();
13351 return false;
13352 }
13353
13354 return true;
13355}
13356
13357bool OpenMPAtomicCompareChecker::checkType(ErrorInfoTy &ErrorInfo) const {
13358 // 'x' and 'e' cannot be nullptr
13359 assert(X && E && "X and E cannot be nullptr");
13360
13361 if (!CheckValue(X, ErrorInfo, true))
13362 return false;
13363
13364 if (!CheckValue(E, ErrorInfo, false))
13365 return false;
13366
13367 if (D && !CheckValue(D, ErrorInfo, false))
13368 return false;
13369
13370 return true;
13371}
13372
13373bool OpenMPAtomicCompareChecker::checkStmt(
13374 Stmt *S, OpenMPAtomicCompareChecker::ErrorInfoTy &ErrorInfo) {
13375 auto *CS = dyn_cast<CompoundStmt>(S);
13376 if (CS) {
13377 if (CS->body_empty()) {
13378 ErrorInfo.Error = ErrorTy::NoStmt;
13379 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
13380 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
13381 return false;
13382 }
13383
13384 if (CS->size() != 1) {
13385 ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
13386 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
13387 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
13388 return false;
13389 }
13390 S = CS->body_front();
13391 }
13392
13393 auto Res = false;
13394
13395 if (auto *IS = dyn_cast<IfStmt>(S)) {
13396 // Check if the statement is in one of the following forms
13397 // (cond-update-stmt):
13398 // if (expr ordop x) { x = expr; }
13399 // if (x ordop expr) { x = expr; }
13400 // if (x == e) { x = d; }
13401 Res = checkCondUpdateStmt(IS, ErrorInfo);
13402 } else {
13403 // Check if the statement is in one of the following forms (cond-expr-stmt):
13404 // x = expr ordop x ? expr : x;
13405 // x = x ordop expr ? expr : x;
13406 // x = x == e ? d : x;
13407 Res = checkCondExprStmt(S, ErrorInfo);
13408 }
13409
13410 if (!Res)
13411 return false;
13412
13413 return checkType(ErrorInfo);
13414}
13415
13416class OpenMPAtomicCompareCaptureChecker final
13417 : public OpenMPAtomicCompareChecker {
13418public:
13419 OpenMPAtomicCompareCaptureChecker(Sema &S) : OpenMPAtomicCompareChecker(S) {}
13420
13421 Expr *getV() const { return V; }
13422 Expr *getR() const { return R; }
13423 bool isFailOnly() const { return IsFailOnly; }
13424 bool isPostfixUpdate() const { return IsPostfixUpdate; }
13425
13426 /// Check if statement \a S is valid for <tt>atomic compare capture</tt>.
13427 bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
13428
13429private:
13430 bool checkType(ErrorInfoTy &ErrorInfo);
13431
13432 // NOTE: Form 3, 4, 5 in the following comments mean the 3rd, 4th, and 5th
13433 // form of 'conditional-update-capture-atomic' structured block on the v5.2
13434 // spec p.p. 82:
13435 // (1) { v = x; cond-update-stmt }
13436 // (2) { cond-update-stmt v = x; }
13437 // (3) if(x == e) { x = d; } else { v = x; }
13438 // (4) { r = x == e; if(r) { x = d; } }
13439 // (5) { r = x == e; if(r) { x = d; } else { v = x; } }
13440
13441 /// Check if it is valid 'if(x == e) { x = d; } else { v = x; }' (form 3)
13442 bool checkForm3(IfStmt *S, ErrorInfoTy &ErrorInfo);
13443
13444 /// Check if it is valid '{ r = x == e; if(r) { x = d; } }',
13445 /// or '{ r = x == e; if(r) { x = d; } else { v = x; } }' (form 4 and 5)
13446 bool checkForm45(Stmt *S, ErrorInfoTy &ErrorInfo);
13447
13448 /// 'v' lvalue part of the source atomic expression.
13449 Expr *V = nullptr;
13450 /// 'r' lvalue part of the source atomic expression.
13451 Expr *R = nullptr;
13452 /// If 'v' is only updated when the comparison fails.
13453 bool IsFailOnly = false;
13454 /// If original value of 'x' must be stored in 'v', not an updated one.
13455 bool IsPostfixUpdate = false;
13456};
13457
13458bool OpenMPAtomicCompareCaptureChecker::checkType(ErrorInfoTy &ErrorInfo) {
13459 if (!OpenMPAtomicCompareChecker::checkType(ErrorInfo))
13460 return false;
13461
13462 if (V && !CheckValue(V, ErrorInfo, true))
13463 return false;
13464
13465 if (R && !CheckValue(R, ErrorInfo, true, true))
13466 return false;
13467
13468 return true;
13469}
13470
13471bool OpenMPAtomicCompareCaptureChecker::checkForm3(IfStmt *S,
13472 ErrorInfoTy &ErrorInfo) {
13473 IsFailOnly = true;
13474
13475 auto *Then = S->getThen();
13476 if (auto *CS = dyn_cast<CompoundStmt>(Then)) {
13477 if (CS->body_empty()) {
13478 ErrorInfo.Error = ErrorTy::NoStmt;
13479 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
13480 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
13481 return false;
13482 }
13483 if (CS->size() > 1) {
13484 ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
13485 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
13486 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
13487 return false;
13488 }
13489 Then = CS->body_front();
13490 }
13491
13492 auto *BO = dyn_cast<BinaryOperator>(Then);
13493 if (!BO) {
13494 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13495 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc();
13496 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange();
13497 return false;
13498 }
13499 if (BO->getOpcode() != BO_Assign) {
13500 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13501 ErrorInfo.ErrorLoc = BO->getExprLoc();
13502 ErrorInfo.NoteLoc = BO->getOperatorLoc();
13503 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
13504 return false;
13505 }
13506
13507 X = BO->getLHS();
13508 D = BO->getRHS();
13509
13510 auto *Cond = dyn_cast<BinaryOperator>(S->getCond());
13511 auto *Call = dyn_cast<CXXOperatorCallExpr>(S->getCond());
13512 Expr *LHS = nullptr;
13513 Expr *RHS = nullptr;
13514 if (Cond) {
13515 LHS = Cond->getLHS();
13516 RHS = Cond->getRHS();
13517 } else if (Call) {
13518 LHS = Call->getArg(0);
13519 RHS = Call->getArg(1);
13520 } else {
13521 ErrorInfo.Error = ErrorTy::NotABinaryOp;
13522 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
13523 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
13524 return false;
13525 }
13526 if ((Cond && Cond->getOpcode() != BO_EQ) ||
13527 (Call && Call->getOperator() != OverloadedOperatorKind::OO_EqualEqual)) {
13528 ErrorInfo.Error = ErrorTy::NotEQ;
13529 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
13530 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
13531 return false;
13532 }
13533
13534 if (checkIfTwoExprsAreSame(ContextRef, X, LHS)) {
13535 E = RHS;
13536 } else if (checkIfTwoExprsAreSame(ContextRef, X, RHS)) {
13537 E = LHS;
13538 } else {
13539 ErrorInfo.Error = ErrorTy::InvalidComparison;
13540 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
13541 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
13542 return false;
13543 }
13544
13545 C = S->getCond();
13546
13547 if (!S->getElse()) {
13548 ErrorInfo.Error = ErrorTy::NoElse;
13549 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
13550 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
13551 return false;
13552 }
13553
13554 auto *Else = S->getElse();
13555 if (auto *CS = dyn_cast<CompoundStmt>(Else)) {
13556 if (CS->body_empty()) {
13557 ErrorInfo.Error = ErrorTy::NoStmt;
13558 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
13559 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
13560 return false;
13561 }
13562 if (CS->size() > 1) {
13563 ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
13564 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
13565 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
13566 return false;
13567 }
13568 Else = CS->body_front();
13569 }
13570
13571 auto *ElseBO = dyn_cast<BinaryOperator>(Else);
13572 if (!ElseBO) {
13573 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13574 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Else->getBeginLoc();
13575 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Else->getSourceRange();
13576 return false;
13577 }
13578 if (ElseBO->getOpcode() != BO_Assign) {
13579 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13580 ErrorInfo.ErrorLoc = ElseBO->getExprLoc();
13581 ErrorInfo.NoteLoc = ElseBO->getOperatorLoc();
13582 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseBO->getSourceRange();
13583 return false;
13584 }
13585
13586 if (!checkIfTwoExprsAreSame(ContextRef, X, ElseBO->getRHS())) {
13587 ErrorInfo.Error = ErrorTy::InvalidAssignment;
13588 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseBO->getRHS()->getExprLoc();
13589 ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
13590 ElseBO->getRHS()->getSourceRange();
13591 return false;
13592 }
13593
13594 V = ElseBO->getLHS();
13595
13596 return checkType(ErrorInfo);
13597}
13598
13599bool OpenMPAtomicCompareCaptureChecker::checkForm45(Stmt *S,
13600 ErrorInfoTy &ErrorInfo) {
13601 // We don't check here as they should be already done before call this
13602 // function.
13603 auto *CS = cast<CompoundStmt>(S);
13604 assert(CS->size() == 2 && "CompoundStmt size is not expected");
13605 auto *S1 = cast<BinaryOperator>(CS->body_front());
13606 auto *S2 = cast<IfStmt>(CS->body_back());
13607 assert(S1->getOpcode() == BO_Assign && "unexpected binary operator");
13608
13609 if (!checkIfTwoExprsAreSame(ContextRef, S1->getLHS(), S2->getCond())) {
13610 ErrorInfo.Error = ErrorTy::InvalidCondition;
13611 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S2->getCond()->getExprLoc();
13612 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S1->getLHS()->getSourceRange();
13613 return false;
13614 }
13615
13616 R = S1->getLHS();
13617
13618 auto *Then = S2->getThen();
13619 if (auto *ThenCS = dyn_cast<CompoundStmt>(Then)) {
13620 if (ThenCS->body_empty()) {
13621 ErrorInfo.Error = ErrorTy::NoStmt;
13622 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ThenCS->getBeginLoc();
13623 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenCS->getSourceRange();
13624 return false;
13625 }
13626 if (ThenCS->size() > 1) {
13627 ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
13628 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ThenCS->getBeginLoc();
13629 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenCS->getSourceRange();
13630 return false;
13631 }
13632 Then = ThenCS->body_front();
13633 }
13634
13635 auto *ThenBO = dyn_cast<BinaryOperator>(Then);
13636 if (!ThenBO) {
13637 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13638 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S2->getBeginLoc();
13639 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S2->getSourceRange();
13640 return false;
13641 }
13642 if (ThenBO->getOpcode() != BO_Assign) {
13643 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13644 ErrorInfo.ErrorLoc = ThenBO->getExprLoc();
13645 ErrorInfo.NoteLoc = ThenBO->getOperatorLoc();
13646 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenBO->getSourceRange();
13647 return false;
13648 }
13649
13650 X = ThenBO->getLHS();
13651 D = ThenBO->getRHS();
13652
13653 auto *BO = cast<BinaryOperator>(S1->getRHS()->IgnoreImpCasts());
13654 if (BO->getOpcode() != BO_EQ) {
13655 ErrorInfo.Error = ErrorTy::NotEQ;
13656 ErrorInfo.ErrorLoc = BO->getExprLoc();
13657 ErrorInfo.NoteLoc = BO->getOperatorLoc();
13658 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
13659 return false;
13660 }
13661
13662 C = BO;
13663
13664 if (checkIfTwoExprsAreSame(ContextRef, X, BO->getLHS())) {
13665 E = BO->getRHS();
13666 } else if (checkIfTwoExprsAreSame(ContextRef, X, BO->getRHS())) {
13667 E = BO->getLHS();
13668 } else {
13669 ErrorInfo.Error = ErrorTy::InvalidComparison;
13670 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getExprLoc();
13671 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
13672 return false;
13673 }
13674
13675 if (S2->getElse()) {
13676 IsFailOnly = true;
13677
13678 auto *Else = S2->getElse();
13679 if (auto *ElseCS = dyn_cast<CompoundStmt>(Else)) {
13680 if (ElseCS->body_empty()) {
13681 ErrorInfo.Error = ErrorTy::NoStmt;
13682 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseCS->getBeginLoc();
13683 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseCS->getSourceRange();
13684 return false;
13685 }
13686 if (ElseCS->size() > 1) {
13687 ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
13688 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseCS->getBeginLoc();
13689 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseCS->getSourceRange();
13690 return false;
13691 }
13692 Else = ElseCS->body_front();
13693 }
13694
13695 auto *ElseBO = dyn_cast<BinaryOperator>(Else);
13696 if (!ElseBO) {
13697 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13698 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Else->getBeginLoc();
13699 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Else->getSourceRange();
13700 return false;
13701 }
13702 if (ElseBO->getOpcode() != BO_Assign) {
13703 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13704 ErrorInfo.ErrorLoc = ElseBO->getExprLoc();
13705 ErrorInfo.NoteLoc = ElseBO->getOperatorLoc();
13706 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseBO->getSourceRange();
13707 return false;
13708 }
13709 if (!checkIfTwoExprsAreSame(ContextRef, X, ElseBO->getRHS())) {
13710 ErrorInfo.Error = ErrorTy::InvalidAssignment;
13711 ErrorInfo.ErrorLoc = ElseBO->getRHS()->getExprLoc();
13712 ErrorInfo.NoteLoc = X->getExprLoc();
13713 ErrorInfo.ErrorRange = ElseBO->getRHS()->getSourceRange();
13714 ErrorInfo.NoteRange = X->getSourceRange();
13715 return false;
13716 }
13717
13718 V = ElseBO->getLHS();
13719 }
13720
13721 return checkType(ErrorInfo);
13722}
13723
13724bool OpenMPAtomicCompareCaptureChecker::checkStmt(Stmt *S,
13725 ErrorInfoTy &ErrorInfo) {
13726 // if(x == e) { x = d; } else { v = x; }
13727 if (auto *IS = dyn_cast<IfStmt>(S))
13728 return checkForm3(IS, ErrorInfo);
13729
13730 auto *CS = dyn_cast<CompoundStmt>(S);
13731 if (!CS) {
13732 ErrorInfo.Error = ErrorTy::NotCompoundStmt;
13733 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
13734 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
13735 return false;
13736 }
13737 if (CS->body_empty()) {
13738 ErrorInfo.Error = ErrorTy::NoStmt;
13739 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
13740 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
13741 return false;
13742 }
13743
13744 // { if(x == e) { x = d; } else { v = x; } }
13745 if (CS->size() == 1) {
13746 auto *IS = dyn_cast<IfStmt>(CS->body_front());
13747 if (!IS) {
13748 ErrorInfo.Error = ErrorTy::NotIfStmt;
13749 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->body_front()->getBeginLoc();
13750 ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
13751 CS->body_front()->getSourceRange();
13752 return false;
13753 }
13754
13755 return checkForm3(IS, ErrorInfo);
13756 } else if (CS->size() == 2) {
13757 auto *S1 = CS->body_front();
13758 auto *S2 = CS->body_back();
13759
13760 Stmt *UpdateStmt = nullptr;
13761 Stmt *CondUpdateStmt = nullptr;
13762 Stmt *CondExprStmt = nullptr;
13763
13764 if (auto *BO = dyn_cast<BinaryOperator>(S1)) {
13765 // It could be one of the following cases:
13766 // { v = x; cond-update-stmt }
13767 // { v = x; cond-expr-stmt }
13768 // { cond-expr-stmt; v = x; }
13769 // form 45
13770 if (isa<BinaryOperator>(BO->getRHS()->IgnoreImpCasts()) ||
13771 isa<ConditionalOperator>(BO->getRHS()->IgnoreImpCasts())) {
13772 // check if form 45
13773 if (isa<IfStmt>(S2))
13774 return checkForm45(CS, ErrorInfo);
13775 // { cond-expr-stmt; v = x; }
13776 CondExprStmt = S1;
13777 UpdateStmt = S2;
13778 } else {
13779 IsPostfixUpdate = true;
13780 UpdateStmt = S1;
13781 if (isa<IfStmt>(S2)) {
13782 // { v = x; cond-update-stmt }
13783 CondUpdateStmt = S2;
13784 } else {
13785 // { v = x; cond-expr-stmt }
13786 CondExprStmt = S2;
13787 }
13788 }
13789 } else {
13790 // { cond-update-stmt v = x; }
13791 UpdateStmt = S2;
13792 CondUpdateStmt = S1;
13793 }
13794
13795 auto CheckCondUpdateStmt = [this, &ErrorInfo](Stmt *CUS) {
13796 auto *IS = dyn_cast<IfStmt>(CUS);
13797 if (!IS) {
13798 ErrorInfo.Error = ErrorTy::NotIfStmt;
13799 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CUS->getBeginLoc();
13800 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CUS->getSourceRange();
13801 return false;
13802 }
13803
13804 return checkCondUpdateStmt(IS, ErrorInfo);
13805 };
13806
13807 // CheckUpdateStmt has to be called *after* CheckCondUpdateStmt.
13808 auto CheckUpdateStmt = [this, &ErrorInfo](Stmt *US) {
13809 auto *BO = dyn_cast<BinaryOperator>(US);
13810 if (!BO) {
13811 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13812 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = US->getBeginLoc();
13813 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = US->getSourceRange();
13814 return false;
13815 }
13816 if (BO->getOpcode() != BO_Assign) {
13817 ErrorInfo.Error = ErrorTy::NotAnAssignment;
13818 ErrorInfo.ErrorLoc = BO->getExprLoc();
13819 ErrorInfo.NoteLoc = BO->getOperatorLoc();
13820 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
13821 return false;
13822 }
13823 if (!checkIfTwoExprsAreSame(ContextRef, this->X, BO->getRHS())) {
13824 ErrorInfo.Error = ErrorTy::InvalidAssignment;
13825 ErrorInfo.ErrorLoc = BO->getRHS()->getExprLoc();
13826 ErrorInfo.NoteLoc = this->X->getExprLoc();
13827 ErrorInfo.ErrorRange = BO->getRHS()->getSourceRange();
13828 ErrorInfo.NoteRange = this->X->getSourceRange();
13829 return false;
13830 }
13831
13832 this->V = BO->getLHS();
13833
13834 return true;
13835 };
13836
13837 if (CondUpdateStmt && !CheckCondUpdateStmt(CondUpdateStmt))
13838 return false;
13839 if (CondExprStmt && !checkCondExprStmt(CondExprStmt, ErrorInfo))
13840 return false;
13841 if (!CheckUpdateStmt(UpdateStmt))
13842 return false;
13843 } else {
13844 ErrorInfo.Error = ErrorTy::MoreThanTwoStmts;
13845 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
13846 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
13847 return false;
13848 }
13849
13850 return checkType(ErrorInfo);
13851}
13852} // namespace
13853
13855 Stmt *AStmt,
13856 SourceLocation StartLoc,
13857 SourceLocation EndLoc) {
13858 ASTContext &Context = getASTContext();
13859 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
13860 // Register location of the first atomic directive.
13861 DSAStack->addAtomicDirectiveLoc(StartLoc);
13862 if (!AStmt)
13863 return StmtError();
13864
13865 // 1.2.2 OpenMP Language Terminology
13866 // Structured block - An executable statement with a single entry at the
13867 // top and a single exit at the bottom.
13868 // The point of exit cannot be a branch out of the structured block.
13869 // longjmp() and throw() must not violate the entry/exit criteria.
13870 OpenMPClauseKind AtomicKind = OMPC_unknown;
13871 SourceLocation AtomicKindLoc;
13872 OpenMPClauseKind MemOrderKind = OMPC_unknown;
13873 SourceLocation MemOrderLoc;
13874 bool MutexClauseEncountered = false;
13875 llvm::SmallSet<OpenMPClauseKind, 2> EncounteredAtomicKinds;
13876 for (const OMPClause *C : Clauses) {
13877 switch (C->getClauseKind()) {
13878 case OMPC_read:
13879 case OMPC_write:
13880 case OMPC_update:
13881 MutexClauseEncountered = true;
13882 [[fallthrough]];
13883 case OMPC_capture:
13884 case OMPC_compare: {
13885 if (AtomicKind != OMPC_unknown && MutexClauseEncountered) {
13886 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
13887 << SourceRange(C->getBeginLoc(), C->getEndLoc());
13888 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
13889 << getOpenMPClauseNameForDiag(AtomicKind);
13890 } else {
13891 AtomicKind = C->getClauseKind();
13892 AtomicKindLoc = C->getBeginLoc();
13893 if (!EncounteredAtomicKinds.insert(C->getClauseKind()).second) {
13894 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
13895 << SourceRange(C->getBeginLoc(), C->getEndLoc());
13896 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
13897 << getOpenMPClauseNameForDiag(AtomicKind);
13898 }
13899 }
13900 break;
13901 }
13902 case OMPC_weak:
13903 case OMPC_fail: {
13904 if (!EncounteredAtomicKinds.contains(OMPC_compare)) {
13905 Diag(C->getBeginLoc(), diag::err_omp_atomic_no_compare)
13906 << getOpenMPClauseNameForDiag(C->getClauseKind())
13907 << SourceRange(C->getBeginLoc(), C->getEndLoc());
13908 return StmtError();
13909 }
13910 break;
13911 }
13912 case OMPC_seq_cst:
13913 case OMPC_acq_rel:
13914 case OMPC_acquire:
13915 case OMPC_release:
13916 case OMPC_relaxed: {
13917 if (MemOrderKind != OMPC_unknown) {
13918 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
13919 << getOpenMPDirectiveName(OMPD_atomic, OMPVersion) << 0
13920 << SourceRange(C->getBeginLoc(), C->getEndLoc());
13921 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
13922 << getOpenMPClauseNameForDiag(MemOrderKind);
13923 } else {
13924 MemOrderKind = C->getClauseKind();
13925 MemOrderLoc = C->getBeginLoc();
13926 }
13927 break;
13928 }
13929 // The following clauses are allowed, but we don't need to do anything here.
13930 case OMPC_hint:
13931 break;
13932 default:
13933 llvm_unreachable("unknown clause is encountered");
13934 }
13935 }
13936 bool IsCompareCapture = false;
13937 if (EncounteredAtomicKinds.contains(OMPC_compare) &&
13938 EncounteredAtomicKinds.contains(OMPC_capture)) {
13939 IsCompareCapture = true;
13940 AtomicKind = OMPC_compare;
13941 }
13942 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
13943 // If atomic-clause is read then memory-order-clause must not be acq_rel or
13944 // release.
13945 // If atomic-clause is write then memory-order-clause must not be acq_rel or
13946 // acquire.
13947 // If atomic-clause is update or not present then memory-order-clause must not
13948 // be acq_rel or acquire.
13949 if ((AtomicKind == OMPC_read &&
13950 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
13951 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
13952 AtomicKind == OMPC_unknown) &&
13953 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
13954 SourceLocation Loc = AtomicKindLoc;
13955 if (AtomicKind == OMPC_unknown)
13956 Loc = StartLoc;
13957 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
13958 << getOpenMPClauseNameForDiag(AtomicKind)
13959 << (AtomicKind == OMPC_unknown ? 1 : 0)
13960 << getOpenMPClauseNameForDiag(MemOrderKind);
13961 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
13962 << getOpenMPClauseNameForDiag(MemOrderKind);
13963 }
13964
13965 Stmt *Body = AStmt;
13966 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
13967 Body = EWC->getSubExpr();
13968
13969 Expr *X = nullptr;
13970 Expr *V = nullptr;
13971 Expr *E = nullptr;
13972 Expr *UE = nullptr;
13973 Expr *D = nullptr;
13974 Expr *CE = nullptr;
13975 Expr *R = nullptr;
13976 bool IsXLHSInRHSPart = false;
13977 bool IsPostfixUpdate = false;
13978 bool IsFailOnly = false;
13979 // OpenMP [2.12.6, atomic Construct]
13980 // In the next expressions:
13981 // * x and v (as applicable) are both l-value expressions with scalar type.
13982 // * During the execution of an atomic region, multiple syntactic
13983 // occurrences of x must designate the same storage location.
13984 // * Neither of v and expr (as applicable) may access the storage location
13985 // designated by x.
13986 // * Neither of x and expr (as applicable) may access the storage location
13987 // designated by v.
13988 // * expr is an expression with scalar type.
13989 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
13990 // * binop, binop=, ++, and -- are not overloaded operators.
13991 // * The expression x binop expr must be numerically equivalent to x binop
13992 // (expr). This requirement is satisfied if the operators in expr have
13993 // precedence greater than binop, or by using parentheses around expr or
13994 // subexpressions of expr.
13995 // * The expression expr binop x must be numerically equivalent to (expr)
13996 // binop x. This requirement is satisfied if the operators in expr have
13997 // precedence equal to or greater than binop, or by using parentheses around
13998 // expr or subexpressions of expr.
13999 // * For forms that allow multiple occurrences of x, the number of times
14000 // that x is evaluated is unspecified.
14001 if (AtomicKind == OMPC_read) {
14002 enum {
14003 NotAnExpression,
14004 NotAnAssignmentOp,
14005 NotAScalarType,
14006 NotAnLValue,
14007 NoError
14008 } ErrorFound = NoError;
14009 SourceLocation ErrorLoc, NoteLoc;
14010 SourceRange ErrorRange, NoteRange;
14011 // If clause is read:
14012 // v = x;
14013 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
14014 const auto *AtomicBinOp =
14015 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
14016 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
14017 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
14018 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
14019 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
14020 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
14021 if (!X->isLValue() || !V->isLValue()) {
14022 const Expr *NotLValueExpr = X->isLValue() ? V : X;
14023 ErrorFound = NotAnLValue;
14024 ErrorLoc = AtomicBinOp->getExprLoc();
14025 ErrorRange = AtomicBinOp->getSourceRange();
14026 NoteLoc = NotLValueExpr->getExprLoc();
14027 NoteRange = NotLValueExpr->getSourceRange();
14028 }
14029 } else if (!X->isInstantiationDependent() ||
14030 !V->isInstantiationDependent()) {
14031 const Expr *NotScalarExpr =
14032 (X->isInstantiationDependent() || X->getType()->isScalarType())
14033 ? V
14034 : X;
14035 ErrorFound = NotAScalarType;
14036 ErrorLoc = AtomicBinOp->getExprLoc();
14037 ErrorRange = AtomicBinOp->getSourceRange();
14038 NoteLoc = NotScalarExpr->getExprLoc();
14039 NoteRange = NotScalarExpr->getSourceRange();
14040 }
14041 } else if (!AtomicBody->isInstantiationDependent()) {
14042 ErrorFound = NotAnAssignmentOp;
14043 ErrorLoc = AtomicBody->getExprLoc();
14044 ErrorRange = AtomicBody->getSourceRange();
14045 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
14046 : AtomicBody->getExprLoc();
14047 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
14048 : AtomicBody->getSourceRange();
14049 }
14050 } else {
14051 ErrorFound = NotAnExpression;
14052 NoteLoc = ErrorLoc = Body->getBeginLoc();
14053 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
14054 }
14055 if (ErrorFound != NoError) {
14056 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
14057 << ErrorRange;
14058 Diag(NoteLoc, diag::note_omp_atomic_read_write)
14059 << ErrorFound << NoteRange;
14060 return StmtError();
14061 }
14062 if (SemaRef.CurContext->isDependentContext())
14063 V = X = nullptr;
14064 } else if (AtomicKind == OMPC_write) {
14065 enum {
14066 NotAnExpression,
14067 NotAnAssignmentOp,
14068 NotAScalarType,
14069 NotAnLValue,
14070 NoError
14071 } ErrorFound = NoError;
14072 SourceLocation ErrorLoc, NoteLoc;
14073 SourceRange ErrorRange, NoteRange;
14074 // If clause is write:
14075 // x = expr;
14076 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
14077 const auto *AtomicBinOp =
14078 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
14079 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
14080 X = AtomicBinOp->getLHS();
14081 E = AtomicBinOp->getRHS();
14082 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
14083 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
14084 if (!X->isLValue()) {
14085 ErrorFound = NotAnLValue;
14086 ErrorLoc = AtomicBinOp->getExprLoc();
14087 ErrorRange = AtomicBinOp->getSourceRange();
14088 NoteLoc = X->getExprLoc();
14089 NoteRange = X->getSourceRange();
14090 }
14091 } else if (!X->isInstantiationDependent() ||
14093 const Expr *NotScalarExpr =
14094 (X->isInstantiationDependent() || X->getType()->isScalarType())
14095 ? E
14096 : X;
14097 ErrorFound = NotAScalarType;
14098 ErrorLoc = AtomicBinOp->getExprLoc();
14099 ErrorRange = AtomicBinOp->getSourceRange();
14100 NoteLoc = NotScalarExpr->getExprLoc();
14101 NoteRange = NotScalarExpr->getSourceRange();
14102 }
14103 } else if (!AtomicBody->isInstantiationDependent()) {
14104 ErrorFound = NotAnAssignmentOp;
14105 ErrorLoc = AtomicBody->getExprLoc();
14106 ErrorRange = AtomicBody->getSourceRange();
14107 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
14108 : AtomicBody->getExprLoc();
14109 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
14110 : AtomicBody->getSourceRange();
14111 }
14112 } else {
14113 ErrorFound = NotAnExpression;
14114 NoteLoc = ErrorLoc = Body->getBeginLoc();
14115 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
14116 }
14117 if (ErrorFound != NoError) {
14118 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
14119 << ErrorRange;
14120 Diag(NoteLoc, diag::note_omp_atomic_read_write)
14121 << ErrorFound << NoteRange;
14122 return StmtError();
14123 }
14124 if (SemaRef.CurContext->isDependentContext())
14125 E = X = nullptr;
14126 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
14127 // If clause is update:
14128 // x++;
14129 // x--;
14130 // ++x;
14131 // --x;
14132 // x binop= expr;
14133 // x = x binop expr;
14134 // x = expr binop x;
14135 OpenMPAtomicUpdateChecker Checker(SemaRef);
14136 if (Checker.checkStatement(
14137 Body,
14138 (AtomicKind == OMPC_update)
14139 ? diag::err_omp_atomic_update_not_expression_statement
14140 : diag::err_omp_atomic_not_expression_statement,
14141 diag::note_omp_atomic_update))
14142 return StmtError();
14143 if (!SemaRef.CurContext->isDependentContext()) {
14144 E = Checker.getExpr();
14145 X = Checker.getX();
14146 UE = Checker.getUpdateExpr();
14147 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
14148 }
14149 } else if (AtomicKind == OMPC_capture) {
14150 enum {
14151 NotAnAssignmentOp,
14152 NotACompoundStatement,
14153 NotTwoSubstatements,
14154 NotASpecificExpression,
14155 NoError
14156 } ErrorFound = NoError;
14157 SourceLocation ErrorLoc, NoteLoc;
14158 SourceRange ErrorRange, NoteRange;
14159 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
14160 // If clause is a capture:
14161 // v = x++;
14162 // v = x--;
14163 // v = ++x;
14164 // v = --x;
14165 // v = x binop= expr;
14166 // v = x = x binop expr;
14167 // v = x = expr binop x;
14168 const auto *AtomicBinOp =
14169 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
14170 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
14171 V = AtomicBinOp->getLHS();
14172 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
14173 OpenMPAtomicUpdateChecker Checker(SemaRef);
14174 if (Checker.checkStatement(
14175 Body, diag::err_omp_atomic_capture_not_expression_statement,
14176 diag::note_omp_atomic_update))
14177 return StmtError();
14178 E = Checker.getExpr();
14179 X = Checker.getX();
14180 UE = Checker.getUpdateExpr();
14181 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
14182 IsPostfixUpdate = Checker.isPostfixUpdate();
14183 } else if (!AtomicBody->isInstantiationDependent()) {
14184 ErrorLoc = AtomicBody->getExprLoc();
14185 ErrorRange = AtomicBody->getSourceRange();
14186 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
14187 : AtomicBody->getExprLoc();
14188 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
14189 : AtomicBody->getSourceRange();
14190 ErrorFound = NotAnAssignmentOp;
14191 }
14192 if (ErrorFound != NoError) {
14193 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
14194 << ErrorRange;
14195 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
14196 return StmtError();
14197 }
14198 if (SemaRef.CurContext->isDependentContext())
14199 UE = V = E = X = nullptr;
14200 } else {
14201 // If clause is a capture:
14202 // { v = x; x = expr; }
14203 // { v = x; x++; }
14204 // { v = x; x--; }
14205 // { v = x; ++x; }
14206 // { v = x; --x; }
14207 // { v = x; x binop= expr; }
14208 // { v = x; x = x binop expr; }
14209 // { v = x; x = expr binop x; }
14210 // { x++; v = x; }
14211 // { x--; v = x; }
14212 // { ++x; v = x; }
14213 // { --x; v = x; }
14214 // { x binop= expr; v = x; }
14215 // { x = x binop expr; v = x; }
14216 // { x = expr binop x; v = x; }
14217 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
14218 // Check that this is { expr1; expr2; }
14219 if (CS->size() == 2) {
14220 Stmt *First = CS->body_front();
14221 Stmt *Second = CS->body_back();
14222 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
14223 First = EWC->getSubExpr()->IgnoreParenImpCasts();
14224 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
14225 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
14226 // Need to find what subexpression is 'v' and what is 'x'.
14227 OpenMPAtomicUpdateChecker Checker(SemaRef);
14228 bool IsUpdateExprFound = !Checker.checkStatement(Second);
14229 BinaryOperator *BinOp = nullptr;
14230 if (IsUpdateExprFound) {
14231 BinOp = dyn_cast<BinaryOperator>(First);
14232 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
14233 }
14234 if (IsUpdateExprFound && !SemaRef.CurContext->isDependentContext()) {
14235 // { v = x; x++; }
14236 // { v = x; x--; }
14237 // { v = x; ++x; }
14238 // { v = x; --x; }
14239 // { v = x; x binop= expr; }
14240 // { v = x; x = x binop expr; }
14241 // { v = x; x = expr binop x; }
14242 // Check that the first expression has form v = x.
14243 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
14244 llvm::FoldingSetNodeID XId, PossibleXId;
14245 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
14246 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
14247 IsUpdateExprFound = XId == PossibleXId;
14248 if (IsUpdateExprFound) {
14249 V = BinOp->getLHS();
14250 X = Checker.getX();
14251 E = Checker.getExpr();
14252 UE = Checker.getUpdateExpr();
14253 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
14254 IsPostfixUpdate = true;
14255 }
14256 }
14257 if (!IsUpdateExprFound) {
14258 IsUpdateExprFound = !Checker.checkStatement(First);
14259 BinOp = nullptr;
14260 if (IsUpdateExprFound) {
14261 BinOp = dyn_cast<BinaryOperator>(Second);
14262 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
14263 }
14264 if (IsUpdateExprFound &&
14265 !SemaRef.CurContext->isDependentContext()) {
14266 // { x++; v = x; }
14267 // { x--; v = x; }
14268 // { ++x; v = x; }
14269 // { --x; v = x; }
14270 // { x binop= expr; v = x; }
14271 // { x = x binop expr; v = x; }
14272 // { x = expr binop x; v = x; }
14273 // Check that the second expression has form v = x.
14274 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
14275 llvm::FoldingSetNodeID XId, PossibleXId;
14276 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
14277 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
14278 IsUpdateExprFound = XId == PossibleXId;
14279 if (IsUpdateExprFound) {
14280 V = BinOp->getLHS();
14281 X = Checker.getX();
14282 E = Checker.getExpr();
14283 UE = Checker.getUpdateExpr();
14284 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
14285 IsPostfixUpdate = false;
14286 }
14287 }
14288 }
14289 if (!IsUpdateExprFound) {
14290 // { v = x; x = expr; }
14291 auto *FirstExpr = dyn_cast<Expr>(First);
14292 auto *SecondExpr = dyn_cast<Expr>(Second);
14293 if (!FirstExpr || !SecondExpr ||
14294 !(FirstExpr->isInstantiationDependent() ||
14295 SecondExpr->isInstantiationDependent())) {
14296 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
14297 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
14298 ErrorFound = NotAnAssignmentOp;
14299 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
14300 : First->getBeginLoc();
14301 NoteRange = ErrorRange = FirstBinOp
14302 ? FirstBinOp->getSourceRange()
14303 : SourceRange(ErrorLoc, ErrorLoc);
14304 } else {
14305 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
14306 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
14307 ErrorFound = NotAnAssignmentOp;
14308 NoteLoc = ErrorLoc = SecondBinOp
14309 ? SecondBinOp->getOperatorLoc()
14310 : Second->getBeginLoc();
14311 NoteRange = ErrorRange =
14312 SecondBinOp ? SecondBinOp->getSourceRange()
14313 : SourceRange(ErrorLoc, ErrorLoc);
14314 } else {
14315 Expr *PossibleXRHSInFirst =
14316 FirstBinOp->getRHS()->IgnoreParenImpCasts();
14317 Expr *PossibleXLHSInSecond =
14318 SecondBinOp->getLHS()->IgnoreParenImpCasts();
14319 llvm::FoldingSetNodeID X1Id, X2Id;
14320 PossibleXRHSInFirst->Profile(X1Id, Context,
14321 /*Canonical=*/true);
14322 PossibleXLHSInSecond->Profile(X2Id, Context,
14323 /*Canonical=*/true);
14324 IsUpdateExprFound = X1Id == X2Id;
14325 if (IsUpdateExprFound) {
14326 V = FirstBinOp->getLHS();
14327 X = SecondBinOp->getLHS();
14328 E = SecondBinOp->getRHS();
14329 UE = nullptr;
14330 IsXLHSInRHSPart = false;
14331 IsPostfixUpdate = true;
14332 } else {
14333 ErrorFound = NotASpecificExpression;
14334 ErrorLoc = FirstBinOp->getExprLoc();
14335 ErrorRange = FirstBinOp->getSourceRange();
14336 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
14337 NoteRange = SecondBinOp->getRHS()->getSourceRange();
14338 }
14339 }
14340 }
14341 }
14342 }
14343 } else {
14344 NoteLoc = ErrorLoc = Body->getBeginLoc();
14345 NoteRange = ErrorRange =
14346 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
14347 ErrorFound = NotTwoSubstatements;
14348 }
14349 } else {
14350 NoteLoc = ErrorLoc = Body->getBeginLoc();
14351 NoteRange = ErrorRange =
14352 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
14353 ErrorFound = NotACompoundStatement;
14354 }
14355 }
14356 if (ErrorFound != NoError) {
14357 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
14358 << ErrorRange;
14359 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
14360 return StmtError();
14361 }
14362 if (SemaRef.CurContext->isDependentContext())
14363 UE = V = E = X = nullptr;
14364 } else if (AtomicKind == OMPC_compare) {
14365 if (IsCompareCapture) {
14366 OpenMPAtomicCompareCaptureChecker::ErrorInfoTy ErrorInfo;
14367 OpenMPAtomicCompareCaptureChecker Checker(SemaRef);
14368 if (!Checker.checkStmt(Body, ErrorInfo)) {
14369 Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare_capture)
14370 << ErrorInfo.ErrorRange;
14371 Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare)
14372 << ErrorInfo.Error << ErrorInfo.NoteRange;
14373 return StmtError();
14374 }
14375 X = Checker.getX();
14376 E = Checker.getE();
14377 D = Checker.getD();
14378 CE = Checker.getCond();
14379 V = Checker.getV();
14380 R = Checker.getR();
14381 // We reuse IsXLHSInRHSPart to tell if it is in the form 'x ordop expr'.
14382 IsXLHSInRHSPart = Checker.isXBinopExpr();
14383 IsFailOnly = Checker.isFailOnly();
14384 IsPostfixUpdate = Checker.isPostfixUpdate();
14385 } else {
14386 OpenMPAtomicCompareChecker::ErrorInfoTy ErrorInfo;
14387 OpenMPAtomicCompareChecker Checker(SemaRef);
14388 if (!Checker.checkStmt(Body, ErrorInfo)) {
14389 Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare)
14390 << ErrorInfo.ErrorRange;
14391 Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare)
14392 << ErrorInfo.Error << ErrorInfo.NoteRange;
14393 return StmtError();
14394 }
14395 X = Checker.getX();
14396 E = Checker.getE();
14397 D = Checker.getD();
14398 CE = Checker.getCond();
14399 // The weak clause may only appear if the resulting atomic operation is
14400 // an atomic conditional update for which the comparison tests for
14401 // equality. It was not possible to do this check in
14402 // OpenMPAtomicCompareChecker::checkStmt() as the check for OMPC_weak
14403 // could not be performed (Clauses are not available).
14404 auto *It = find_if(Clauses, [](OMPClause *C) {
14405 return C->getClauseKind() == llvm::omp::Clause::OMPC_weak;
14406 });
14407 if (It != Clauses.end()) {
14408 auto *Cond = dyn_cast<BinaryOperator>(CE);
14409 if (Cond->getOpcode() != BO_EQ) {
14410 ErrorInfo.Error = Checker.ErrorTy::NotAnAssignment;
14411 ErrorInfo.ErrorLoc = Cond->getExprLoc();
14412 ErrorInfo.NoteLoc = Cond->getOperatorLoc();
14413 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
14414
14415 Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_weak_no_equality)
14416 << ErrorInfo.ErrorRange;
14417 return StmtError();
14418 }
14419 }
14420 // We reuse IsXLHSInRHSPart to tell if it is in the form 'x ordop expr'.
14421 IsXLHSInRHSPart = Checker.isXBinopExpr();
14422 }
14423 }
14424
14425 SemaRef.setFunctionHasBranchProtectedScope();
14426
14428 Context, StartLoc, EndLoc, Clauses, AStmt,
14429 {X, V, R, E, UE, D, CE, IsXLHSInRHSPart, IsPostfixUpdate, IsFailOnly});
14430}
14431
14433 Stmt *AStmt,
14434 SourceLocation StartLoc,
14435 SourceLocation EndLoc) {
14436 if (!AStmt)
14437 return StmtError();
14438
14439 if (validateMultidimClauses(*this, Clauses))
14440 return StmtError();
14441
14442 // Check for conflicting capture kinds on structured bindings.
14443 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_target, Clauses))
14444 return StmtError();
14445
14447 return StmtError();
14448
14449 CapturedStmt *CS = setBranchProtectedScope(SemaRef, OMPD_target, AStmt);
14450
14451 // OpenMP [2.16, Nesting of Regions]
14452 // If specified, a teams construct must be contained within a target
14453 // construct. That target construct must contain no statements or directives
14454 // outside of the teams construct.
14455 if (DSAStack->hasInnerTeamsRegion()) {
14456 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
14457 bool OMPTeamsFound = true;
14458 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
14459 auto I = CS->body_begin();
14460 while (I != CS->body_end()) {
14461 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
14462 bool IsTeams = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
14463 if (!IsTeams || I != CS->body_begin()) {
14464 OMPTeamsFound = false;
14465 if (IsTeams && I != CS->body_begin()) {
14466 // This is the two teams case. Since the InnerTeamsRegionLoc will
14467 // point to this second one reset the iterator to the other teams.
14468 --I;
14469 }
14470 break;
14471 }
14472 ++I;
14473 }
14474 assert(I != CS->body_end() && "Not found statement");
14475 S = *I;
14476 } else {
14477 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
14478 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
14479 }
14480 if (!OMPTeamsFound) {
14481 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
14482 Diag(DSAStack->getInnerTeamsRegionLoc(),
14483 diag::note_omp_nested_teams_construct_here);
14484 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
14486 return StmtError();
14487 }
14488 }
14489
14490 return OMPTargetDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses,
14491 AStmt);
14492}
14493
14495 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
14496 SourceLocation EndLoc) {
14497 if (!AStmt)
14498 return StmtError();
14499
14500 if (validateMultidimClauses(*this, Clauses))
14501 return StmtError();
14502
14503 // Check for conflicting capture kinds on structured bindings.
14504 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_target_parallel,
14505 Clauses))
14506 return StmtError();
14507
14509 return StmtError();
14510
14511 setBranchProtectedScope(SemaRef, OMPD_target_parallel, AStmt);
14512
14514 getASTContext(), StartLoc, EndLoc, Clauses, AStmt,
14515 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
14516}
14517
14519 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
14520 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
14521 if (!AStmt)
14522 return StmtError();
14523
14524 if (validateMultidimClauses(*this, Clauses))
14525 return StmtError();
14526
14527 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_target_parallel_for,
14528 Clauses))
14529 return StmtError();
14530
14532 return StmtError();
14533
14534 CapturedStmt *CS =
14535 setBranchProtectedScope(SemaRef, OMPD_target_parallel_for, AStmt);
14536
14537 OMPLoopBasedDirective::HelperExprs B;
14538 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
14539 // define the nested loops number.
14540 unsigned NestedLoopCount =
14541 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
14542 getOrderedNumberExpr(Clauses), CS, SemaRef, *DSAStack,
14543 VarsWithImplicitDSA, B);
14544 if (NestedLoopCount == 0)
14545 return StmtError();
14546
14547 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
14548 return StmtError();
14549
14551 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
14552 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
14553}
14554
14555/// Check for existence of a map clause in the list of clauses.
14557 const OpenMPClauseKind K) {
14558 return llvm::any_of(
14559 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
14560}
14561
14562template <typename... Params>
14564 const Params... ClauseTypes) {
14565 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
14566}
14567
14568/// Check if the variables in the mapping clause are externally visible.
14570 for (const OMPClause *C : Clauses) {
14571 if (auto *TC = dyn_cast<OMPToClause>(C))
14572 return llvm::all_of(TC->all_decls(), [](ValueDecl *VD) {
14573 return !VD || !VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14574 (VD->isExternallyVisible() &&
14575 VD->getVisibility() != HiddenVisibility);
14576 });
14577 else if (auto *FC = dyn_cast<OMPFromClause>(C))
14578 return llvm::all_of(FC->all_decls(), [](ValueDecl *VD) {
14579 return !VD || !VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14580 (VD->isExternallyVisible() &&
14581 VD->getVisibility() != HiddenVisibility);
14582 });
14583 }
14584
14585 return true;
14586}
14587
14590 Stmt *AStmt, SourceLocation StartLoc,
14591 SourceLocation EndLoc) {
14592 if (!AStmt)
14593 return StmtError();
14594
14595 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
14596
14597 // OpenMP [2.12.2, target data Construct, Restrictions]
14598 // At least one map, use_device_addr or use_device_ptr clause must appear on
14599 // the directive.
14600 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
14601 (getLangOpts().OpenMP < 50 ||
14602 !hasClauses(Clauses, OMPC_use_device_addr))) {
14603 StringRef Expected;
14604 if (getLangOpts().OpenMP < 50)
14605 Expected = "'map' or 'use_device_ptr'";
14606 else
14607 Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
14608 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
14609 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
14610 << Expected << getOpenMPDirectiveName(OMPD_target_data, OMPVersion);
14611 return StmtError();
14612 }
14613
14614 SemaRef.setFunctionHasBranchProtectedScope();
14615
14616 return OMPTargetDataDirective::Create(getASTContext(), StartLoc, EndLoc,
14617 Clauses, AStmt);
14618}
14619
14621 ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc,
14622 SourceLocation EndLoc, Stmt *AStmt) {
14623 if (!AStmt)
14624 return StmtError();
14625
14626 setBranchProtectedScope(SemaRef, OMPD_target_enter_data, AStmt);
14627
14628 // OpenMP [2.10.2, Restrictions, p. 99]
14629 // At least one map clause must appear on the directive.
14630 if (!hasClauses(Clauses, OMPC_map)) {
14631 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
14632 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
14633 << "'map'"
14634 << getOpenMPDirectiveName(OMPD_target_enter_data, OMPVersion);
14635 return StmtError();
14636 }
14637
14638 return OMPTargetEnterDataDirective::Create(getASTContext(), StartLoc, EndLoc,
14639 Clauses, AStmt);
14640}
14641
14643 ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc,
14644 SourceLocation EndLoc, Stmt *AStmt) {
14645 if (!AStmt)
14646 return StmtError();
14647
14648 setBranchProtectedScope(SemaRef, OMPD_target_exit_data, AStmt);
14649
14650 // OpenMP [2.10.3, Restrictions, p. 102]
14651 // At least one map clause must appear on the directive.
14652 if (!hasClauses(Clauses, OMPC_map)) {
14653 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
14654 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
14655 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data, OMPVersion);
14656 return StmtError();
14657 }
14658
14659 return OMPTargetExitDataDirective::Create(getASTContext(), StartLoc, EndLoc,
14660 Clauses, AStmt);
14661}
14662
14664 ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc,
14665 SourceLocation EndLoc, Stmt *AStmt) {
14666 if (!AStmt)
14667 return StmtError();
14668
14669 setBranchProtectedScope(SemaRef, OMPD_target_update, AStmt);
14670
14671 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
14672 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
14673 return StmtError();
14674 }
14675
14676 if (!isClauseMappable(Clauses)) {
14677 Diag(StartLoc, diag::err_omp_cannot_update_with_internal_linkage);
14678 return StmtError();
14679 }
14680
14681 return OMPTargetUpdateDirective::Create(getASTContext(), StartLoc, EndLoc,
14682 Clauses, AStmt);
14683}
14684
14686 Stmt *AStmt,
14687 SourceLocation StartLoc,
14688 SourceLocation EndLoc) {
14689 if (!AStmt)
14690 return StmtError();
14691
14692 if (validateMultidimClauses(*this, Clauses))
14693 return StmtError();
14694
14695 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_teams, Clauses))
14696 return StmtError();
14697
14698 // Report affected OpenMP target offloading behavior when in HIP lang-mode.
14699 if (getLangOpts().HIP && (DSAStack->getParentDirective() == OMPD_target))
14700 Diag(StartLoc, diag::warn_hip_omp_target_directives);
14701
14702 setBranchProtectedScope(SemaRef, OMPD_teams, AStmt);
14703
14704 DSAStack->setParentTeamsRegionLoc(StartLoc);
14705
14706 return OMPTeamsDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses,
14707 AStmt);
14708}
14709
14711 SourceLocation StartLoc, SourceLocation EndLoc,
14712 OpenMPDirectiveKind CancelRegion) {
14713 if (DSAStack->isParentNowaitRegion()) {
14714 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
14715 return StmtError();
14716 }
14717 if (DSAStack->isParentOrderedRegion()) {
14718 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
14719 return StmtError();
14720 }
14722 EndLoc, CancelRegion);
14723}
14724
14726 ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc,
14727 SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion) {
14728 if (DSAStack->isParentNowaitRegion()) {
14729 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
14730 return StmtError();
14731 }
14732 if (DSAStack->isParentOrderedRegion()) {
14733 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
14734 return StmtError();
14735 }
14736 DSAStack->setParentCancelRegion(/*Cancel=*/true);
14737 return OMPCancelDirective::Create(getASTContext(), StartLoc, EndLoc, Clauses,
14738 CancelRegion);
14739}
14740
14742 ArrayRef<OMPClause *> Clauses) {
14743 const OMPClause *ReductionClause = nullptr;
14744 const OMPClause *NogroupClause = nullptr;
14745 for (const OMPClause *C : Clauses) {
14746 if (C->getClauseKind() == OMPC_reduction) {
14747 ReductionClause = C;
14748 if (NogroupClause)
14749 break;
14750 continue;
14751 }
14752 if (C->getClauseKind() == OMPC_nogroup) {
14753 NogroupClause = C;
14754 if (ReductionClause)
14755 break;
14756 continue;
14757 }
14758 }
14759 if (ReductionClause && NogroupClause) {
14760 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
14761 << SourceRange(NogroupClause->getBeginLoc(),
14762 NogroupClause->getEndLoc());
14763 return true;
14764 }
14765 return false;
14766}
14767
14769 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
14770 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
14771 if (!AStmt)
14772 return StmtError();
14773
14774 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
14775 OMPLoopBasedDirective::HelperExprs B;
14776 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
14777 // define the nested loops number.
14778 unsigned NestedLoopCount =
14779 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
14780 /*OrderedLoopCountExpr=*/nullptr, AStmt, SemaRef,
14781 *DSAStack, VarsWithImplicitDSA, B);
14782 if (NestedLoopCount == 0)
14783 return StmtError();
14784
14785 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
14786 "omp for loop exprs were not built");
14787
14788 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14789 // The grainsize clause and num_tasks clause are mutually exclusive and may
14790 // not appear on the same taskloop directive.
14792 {OMPC_grainsize, OMPC_num_tasks}))
14793 return StmtError();
14794 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14795 // If a reduction clause is present on the taskloop directive, the nogroup
14796 // clause must not be specified.
14798 return StmtError();
14799
14800 SemaRef.setFunctionHasBranchProtectedScope();
14801 return OMPTaskLoopDirective::Create(getASTContext(), StartLoc, EndLoc,
14802 NestedLoopCount, Clauses, AStmt, B,
14803 DSAStack->isCancelRegion());
14804}
14805
14807 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
14808 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
14809 if (!AStmt)
14810 return StmtError();
14811
14812 CapturedStmt *CS =
14813 setBranchProtectedScope(SemaRef, OMPD_taskloop_simd, AStmt);
14814
14815 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
14816 OMPLoopBasedDirective::HelperExprs B;
14817 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
14818 // define the nested loops number.
14819 unsigned NestedLoopCount =
14820 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
14821 /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
14822 VarsWithImplicitDSA, B);
14823 if (NestedLoopCount == 0)
14824 return StmtError();
14825
14826 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
14827 return StmtError();
14828
14829 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14830 // The grainsize clause and num_tasks clause are mutually exclusive and may
14831 // not appear on the same taskloop directive.
14833 {OMPC_grainsize, OMPC_num_tasks}))
14834 return StmtError();
14835 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14836 // If a reduction clause is present on the taskloop directive, the nogroup
14837 // clause must not be specified.
14839 return StmtError();
14841 return StmtError();
14842
14843 return OMPTaskLoopSimdDirective::Create(getASTContext(), StartLoc, EndLoc,
14844 NestedLoopCount, Clauses, AStmt, B);
14845}
14846
14848 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
14849 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
14850 if (!AStmt)
14851 return StmtError();
14852
14853 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
14854 OMPLoopBasedDirective::HelperExprs B;
14855 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
14856 // define the nested loops number.
14857 unsigned NestedLoopCount =
14858 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
14859 /*OrderedLoopCountExpr=*/nullptr, AStmt, SemaRef,
14860 *DSAStack, VarsWithImplicitDSA, B);
14861 if (NestedLoopCount == 0)
14862 return StmtError();
14863
14864 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
14865 "omp for loop exprs were not built");
14866
14867 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14868 // The grainsize clause and num_tasks clause are mutually exclusive and may
14869 // not appear on the same taskloop directive.
14871 {OMPC_grainsize, OMPC_num_tasks}))
14872 return StmtError();
14873 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14874 // If a reduction clause is present on the taskloop directive, the nogroup
14875 // clause must not be specified.
14877 return StmtError();
14878
14879 SemaRef.setFunctionHasBranchProtectedScope();
14880 return OMPMasterTaskLoopDirective::Create(getASTContext(), StartLoc, EndLoc,
14881 NestedLoopCount, Clauses, AStmt, B,
14882 DSAStack->isCancelRegion());
14883}
14884
14886 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
14887 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
14888 if (!AStmt)
14889 return StmtError();
14890
14891 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
14892 OMPLoopBasedDirective::HelperExprs B;
14893 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
14894 // define the nested loops number.
14895 unsigned NestedLoopCount =
14896 checkOpenMPLoop(OMPD_masked_taskloop, getCollapseNumberExpr(Clauses),
14897 /*OrderedLoopCountExpr=*/nullptr, AStmt, SemaRef,
14898 *DSAStack, VarsWithImplicitDSA, B);
14899 if (NestedLoopCount == 0)
14900 return StmtError();
14901
14902 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
14903 "omp for loop exprs were not built");
14904
14905 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14906 // The grainsize clause and num_tasks clause are mutually exclusive and may
14907 // not appear on the same taskloop directive.
14909 {OMPC_grainsize, OMPC_num_tasks}))
14910 return StmtError();
14911 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14912 // If a reduction clause is present on the taskloop directive, the nogroup
14913 // clause must not be specified.
14915 return StmtError();
14916
14917 SemaRef.setFunctionHasBranchProtectedScope();
14918 return OMPMaskedTaskLoopDirective::Create(getASTContext(), StartLoc, EndLoc,
14919 NestedLoopCount, Clauses, AStmt, B,
14920 DSAStack->isCancelRegion());
14921}
14922
14924 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
14925 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
14926 if (!AStmt)
14927 return StmtError();
14928
14929 CapturedStmt *CS =
14930 setBranchProtectedScope(SemaRef, OMPD_master_taskloop_simd, AStmt);
14931
14932 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
14933 OMPLoopBasedDirective::HelperExprs B;
14934 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
14935 // define the nested loops number.
14936 unsigned NestedLoopCount =
14937 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
14938 /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
14939 VarsWithImplicitDSA, B);
14940 if (NestedLoopCount == 0)
14941 return StmtError();
14942
14943 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
14944 return StmtError();
14945
14946 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14947 // The grainsize clause and num_tasks clause are mutually exclusive and may
14948 // not appear on the same taskloop directive.
14950 {OMPC_grainsize, OMPC_num_tasks}))
14951 return StmtError();
14952 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14953 // If a reduction clause is present on the taskloop directive, the nogroup
14954 // clause must not be specified.
14956 return StmtError();
14958 return StmtError();
14959
14961 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
14962}
14963
14965 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
14966 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
14967 if (!AStmt)
14968 return StmtError();
14969
14970 CapturedStmt *CS =
14971 setBranchProtectedScope(SemaRef, OMPD_masked_taskloop_simd, AStmt);
14972
14973 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
14974 OMPLoopBasedDirective::HelperExprs B;
14975 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
14976 // define the nested loops number.
14977 unsigned NestedLoopCount =
14978 checkOpenMPLoop(OMPD_masked_taskloop_simd, getCollapseNumberExpr(Clauses),
14979 /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
14980 VarsWithImplicitDSA, B);
14981 if (NestedLoopCount == 0)
14982 return StmtError();
14983
14984 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
14985 return StmtError();
14986
14987 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14988 // The grainsize clause and num_tasks clause are mutually exclusive and may
14989 // not appear on the same taskloop directive.
14991 {OMPC_grainsize, OMPC_num_tasks}))
14992 return StmtError();
14993 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
14994 // If a reduction clause is present on the taskloop directive, the nogroup
14995 // clause must not be specified.
14997 return StmtError();
14999 return StmtError();
15000
15002 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15003}
15004
15006 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15007 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15008 if (!AStmt)
15009 return StmtError();
15010
15011 CapturedStmt *CS =
15012 setBranchProtectedScope(SemaRef, OMPD_parallel_master_taskloop, AStmt);
15013
15014 OMPLoopBasedDirective::HelperExprs B;
15015 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
15016 // define the nested loops number.
15017 unsigned NestedLoopCount = checkOpenMPLoop(
15018 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
15019 /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
15020 VarsWithImplicitDSA, B);
15021 if (NestedLoopCount == 0)
15022 return StmtError();
15023
15024 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
15025 "omp for loop exprs were not built");
15026
15027 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
15028 // The grainsize clause and num_tasks clause are mutually exclusive and may
15029 // not appear on the same taskloop directive.
15031 {OMPC_grainsize, OMPC_num_tasks}))
15032 return StmtError();
15033 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
15034 // If a reduction clause is present on the taskloop directive, the nogroup
15035 // clause must not be specified.
15037 return StmtError();
15038
15040 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
15041 DSAStack->isCancelRegion());
15042}
15043
15045 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15046 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15047 if (!AStmt)
15048 return StmtError();
15049
15050 CapturedStmt *CS =
15051 setBranchProtectedScope(SemaRef, OMPD_parallel_masked_taskloop, AStmt);
15052
15053 OMPLoopBasedDirective::HelperExprs B;
15054 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
15055 // define the nested loops number.
15056 unsigned NestedLoopCount = checkOpenMPLoop(
15057 OMPD_parallel_masked_taskloop, getCollapseNumberExpr(Clauses),
15058 /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
15059 VarsWithImplicitDSA, B);
15060 if (NestedLoopCount == 0)
15061 return StmtError();
15062
15063 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
15064 "omp for loop exprs were not built");
15065
15066 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
15067 // The grainsize clause and num_tasks clause are mutually exclusive and may
15068 // not appear on the same taskloop directive.
15070 {OMPC_grainsize, OMPC_num_tasks}))
15071 return StmtError();
15072 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
15073 // If a reduction clause is present on the taskloop directive, the nogroup
15074 // clause must not be specified.
15076 return StmtError();
15077
15079 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
15080 DSAStack->isCancelRegion());
15081}
15082
15084 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15085 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15086 if (!AStmt)
15087 return StmtError();
15088
15090 SemaRef, OMPD_parallel_master_taskloop_simd, AStmt);
15091
15092 OMPLoopBasedDirective::HelperExprs B;
15093 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
15094 // define the nested loops number.
15095 unsigned NestedLoopCount = checkOpenMPLoop(
15096 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
15097 /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
15098 VarsWithImplicitDSA, B);
15099 if (NestedLoopCount == 0)
15100 return StmtError();
15101
15102 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15103 return StmtError();
15104
15105 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
15106 // The grainsize clause and num_tasks clause are mutually exclusive and may
15107 // not appear on the same taskloop directive.
15109 {OMPC_grainsize, OMPC_num_tasks}))
15110 return StmtError();
15111 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
15112 // If a reduction clause is present on the taskloop directive, the nogroup
15113 // clause must not be specified.
15115 return StmtError();
15117 return StmtError();
15118
15120 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15121}
15122
15124 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15125 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15126 if (!AStmt)
15127 return StmtError();
15128
15130 SemaRef, OMPD_parallel_masked_taskloop_simd, AStmt);
15131
15132 OMPLoopBasedDirective::HelperExprs B;
15133 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
15134 // define the nested loops number.
15135 unsigned NestedLoopCount = checkOpenMPLoop(
15136 OMPD_parallel_masked_taskloop_simd, getCollapseNumberExpr(Clauses),
15137 /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
15138 VarsWithImplicitDSA, B);
15139 if (NestedLoopCount == 0)
15140 return StmtError();
15141
15142 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15143 return StmtError();
15144
15145 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
15146 // The grainsize clause and num_tasks clause are mutually exclusive and may
15147 // not appear on the same taskloop directive.
15149 {OMPC_grainsize, OMPC_num_tasks}))
15150 return StmtError();
15151 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
15152 // If a reduction clause is present on the taskloop directive, the nogroup
15153 // clause must not be specified.
15155 return StmtError();
15157 return StmtError();
15158
15160 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15161}
15162
15164 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15165 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15166 if (!AStmt)
15167 return StmtError();
15168
15169 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
15170 OMPLoopBasedDirective::HelperExprs B;
15171 // In presence of clause 'collapse' with number of loops, it will
15172 // define the nested loops number.
15173 unsigned NestedLoopCount =
15174 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
15175 nullptr /*ordered not a clause on distribute*/, AStmt,
15176 SemaRef, *DSAStack, VarsWithImplicitDSA, B);
15177 if (NestedLoopCount == 0)
15178 return StmtError();
15179
15180 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
15181 "omp for loop exprs were not built");
15182
15183 SemaRef.setFunctionHasBranchProtectedScope();
15184 auto *DistributeDirective = OMPDistributeDirective::Create(
15185 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15186 return DistributeDirective;
15187}
15188
15190 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15191 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15192 if (!AStmt)
15193 return StmtError();
15194
15195 CapturedStmt *CS =
15196 setBranchProtectedScope(SemaRef, OMPD_distribute_parallel_for, AStmt);
15197
15198 OMPLoopBasedDirective::HelperExprs B;
15199 // In presence of clause 'collapse' with number of loops, it will
15200 // define the nested loops number.
15201 unsigned NestedLoopCount = checkOpenMPLoop(
15202 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
15203 nullptr /*ordered not a clause on distribute*/, CS, SemaRef, *DSAStack,
15204 VarsWithImplicitDSA, B);
15205 if (NestedLoopCount == 0)
15206 return StmtError();
15207
15208 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
15209 "omp for loop exprs were not built");
15210
15212 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
15213 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
15214}
15215
15217 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15218 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15219 if (!AStmt)
15220 return StmtError();
15221
15223 SemaRef, OMPD_distribute_parallel_for_simd, AStmt);
15224
15225 OMPLoopBasedDirective::HelperExprs B;
15226 // In presence of clause 'collapse' with number of loops, it will
15227 // define the nested loops number.
15228 unsigned NestedLoopCount = checkOpenMPLoop(
15229 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
15230 nullptr /*ordered not a clause on distribute*/, CS, SemaRef, *DSAStack,
15231 VarsWithImplicitDSA, B);
15232 if (NestedLoopCount == 0)
15233 return StmtError();
15234
15235 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15236 return StmtError();
15237
15239 return StmtError();
15240
15242 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15243}
15244
15246 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15247 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15248 if (!AStmt)
15249 return StmtError();
15250
15251 CapturedStmt *CS =
15252 setBranchProtectedScope(SemaRef, OMPD_distribute_simd, AStmt);
15253
15254 OMPLoopBasedDirective::HelperExprs B;
15255 // In presence of clause 'collapse' with number of loops, it will
15256 // define the nested loops number.
15257 unsigned NestedLoopCount =
15258 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
15259 nullptr /*ordered not a clause on distribute*/, CS,
15260 SemaRef, *DSAStack, VarsWithImplicitDSA, B);
15261 if (NestedLoopCount == 0)
15262 return StmtError();
15263
15264 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15265 return StmtError();
15266
15268 return StmtError();
15269
15270 return OMPDistributeSimdDirective::Create(getASTContext(), StartLoc, EndLoc,
15271 NestedLoopCount, Clauses, AStmt, B);
15272}
15273
15275 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15276 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15277 if (!AStmt)
15278 return StmtError();
15279
15280 if (validateMultidimClauses(*this, Clauses))
15281 return StmtError();
15282
15284 SemaRef, OMPD_target_parallel_for_simd, Clauses))
15285 return StmtError();
15286
15288 return StmtError();
15289
15290 CapturedStmt *CS =
15291 setBranchProtectedScope(SemaRef, OMPD_target_parallel_for_simd, AStmt);
15292
15293 OMPLoopBasedDirective::HelperExprs B;
15294 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
15295 // define the nested loops number.
15296 unsigned NestedLoopCount = checkOpenMPLoop(
15297 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
15298 getOrderedNumberExpr(Clauses), CS, SemaRef, *DSAStack,
15299 VarsWithImplicitDSA, B);
15300 if (NestedLoopCount == 0)
15301 return StmtError();
15302
15303 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15304 return StmtError();
15305
15307 return StmtError();
15308
15310 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15311}
15312
15314 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15315 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15316 if (!AStmt)
15317 return StmtError();
15318
15319 if (validateMultidimClauses(*this, Clauses))
15320 return StmtError();
15321
15322 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_target_simd, Clauses))
15323 return StmtError();
15324
15326 return StmtError();
15327
15328 CapturedStmt *CS = setBranchProtectedScope(SemaRef, OMPD_target_simd, AStmt);
15329
15330 OMPLoopBasedDirective::HelperExprs B;
15331 // In presence of clause 'collapse' with number of loops, it will define the
15332 // nested loops number.
15333 unsigned NestedLoopCount =
15334 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
15335 getOrderedNumberExpr(Clauses), CS, SemaRef, *DSAStack,
15336 VarsWithImplicitDSA, B);
15337 if (NestedLoopCount == 0)
15338 return StmtError();
15339
15340 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15341 return StmtError();
15342
15344 return StmtError();
15345
15346 return OMPTargetSimdDirective::Create(getASTContext(), StartLoc, EndLoc,
15347 NestedLoopCount, Clauses, AStmt, B);
15348}
15349
15351 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15352 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15353 if (!AStmt)
15354 return StmtError();
15355
15356 if (validateMultidimClauses(*this, Clauses))
15357 return StmtError();
15358
15359 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_teams_distribute,
15360 Clauses))
15361 return StmtError();
15362
15363 CapturedStmt *CS =
15364 setBranchProtectedScope(SemaRef, OMPD_teams_distribute, AStmt);
15365
15366 OMPLoopBasedDirective::HelperExprs B;
15367 // In presence of clause 'collapse' with number of loops, it will
15368 // define the nested loops number.
15369 unsigned NestedLoopCount =
15370 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
15371 nullptr /*ordered not a clause on distribute*/, CS,
15372 SemaRef, *DSAStack, VarsWithImplicitDSA, B);
15373 if (NestedLoopCount == 0)
15374 return StmtError();
15375
15376 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
15377 "omp teams distribute loop exprs were not built");
15378
15379 DSAStack->setParentTeamsRegionLoc(StartLoc);
15380
15382 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15383}
15384
15386 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15387 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15388 if (!AStmt)
15389 return StmtError();
15390
15391 if (validateMultidimClauses(*this, Clauses))
15392 return StmtError();
15393 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_teams_distribute_simd,
15394 Clauses))
15395 return StmtError();
15396
15397 CapturedStmt *CS =
15398 setBranchProtectedScope(SemaRef, OMPD_teams_distribute_simd, AStmt);
15399
15400 OMPLoopBasedDirective::HelperExprs B;
15401 // In presence of clause 'collapse' with number of loops, it will
15402 // define the nested loops number.
15403 unsigned NestedLoopCount = checkOpenMPLoop(
15404 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
15405 nullptr /*ordered not a clause on distribute*/, CS, SemaRef, *DSAStack,
15406 VarsWithImplicitDSA, B);
15407 if (NestedLoopCount == 0)
15408 return StmtError();
15409
15410 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15411 return StmtError();
15412
15414 return StmtError();
15415
15416 DSAStack->setParentTeamsRegionLoc(StartLoc);
15417
15419 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15420}
15421
15423 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15424 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15425 if (!AStmt)
15426 return StmtError();
15427
15428 if (validateMultidimClauses(*this, Clauses))
15429 return StmtError();
15430
15432 SemaRef, OMPD_teams_distribute_parallel_for_simd, Clauses))
15433 return StmtError();
15434
15436 SemaRef, OMPD_teams_distribute_parallel_for_simd, AStmt);
15437
15438 OMPLoopBasedDirective::HelperExprs B;
15439 // In presence of clause 'collapse' with number of loops, it will
15440 // define the nested loops number.
15441 unsigned NestedLoopCount = checkOpenMPLoop(
15442 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
15443 nullptr /*ordered not a clause on distribute*/, CS, SemaRef, *DSAStack,
15444 VarsWithImplicitDSA, B);
15445 if (NestedLoopCount == 0)
15446 return StmtError();
15447
15448 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15449 return StmtError();
15450
15452 return StmtError();
15453
15454 DSAStack->setParentTeamsRegionLoc(StartLoc);
15455
15457 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15458}
15459
15461 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15462 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15463 if (!AStmt)
15464 return StmtError();
15465
15466 if (validateMultidimClauses(*this, Clauses))
15467 return StmtError();
15468
15470 SemaRef, OMPD_teams_distribute_parallel_for, Clauses))
15471 return StmtError();
15472
15474 SemaRef, OMPD_teams_distribute_parallel_for, AStmt);
15475
15476 OMPLoopBasedDirective::HelperExprs B;
15477 // In presence of clause 'collapse' with number of loops, it will
15478 // define the nested loops number.
15479 unsigned NestedLoopCount = checkOpenMPLoop(
15480 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
15481 nullptr /*ordered not a clause on distribute*/, CS, SemaRef, *DSAStack,
15482 VarsWithImplicitDSA, B);
15483
15484 if (NestedLoopCount == 0)
15485 return StmtError();
15486
15487 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
15488 "omp for loop exprs were not built");
15489
15490 DSAStack->setParentTeamsRegionLoc(StartLoc);
15491
15493 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
15494 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
15495}
15496
15498 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15499 SourceLocation EndLoc) {
15500 if (!AStmt)
15501 return StmtError();
15502
15503 if (checkClausesForDecompositionConflicts(SemaRef, OMPD_target_teams,
15504 Clauses))
15505 return StmtError();
15506
15508 return StmtError();
15509
15510 setBranchProtectedScope(SemaRef, OMPD_target_teams, AStmt);
15511
15512 if (validateMultidimClauses(*this, Clauses, /*MayHaveBareClause=*/true))
15513 return StmtError();
15514
15515 return OMPTargetTeamsDirective::Create(getASTContext(), StartLoc, EndLoc,
15516 Clauses, AStmt);
15517}
15518
15520 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15521 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15522 if (!AStmt)
15523 return StmtError();
15524
15525 if (validateMultidimClauses(*this, Clauses))
15526 return StmtError();
15527
15529 SemaRef, OMPD_target_teams_distribute, Clauses))
15530 return StmtError();
15531
15533 return StmtError();
15534
15535 CapturedStmt *CS =
15536 setBranchProtectedScope(SemaRef, OMPD_target_teams_distribute, AStmt);
15537
15538 OMPLoopBasedDirective::HelperExprs B;
15539 // In presence of clause 'collapse' with number of loops, it will
15540 // define the nested loops number.
15541 unsigned NestedLoopCount = checkOpenMPLoop(
15542 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
15543 nullptr /*ordered not a clause on distribute*/, CS, SemaRef, *DSAStack,
15544 VarsWithImplicitDSA, B);
15545 if (NestedLoopCount == 0)
15546 return StmtError();
15547
15548 assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
15549 "omp target teams distribute loop exprs were not built");
15550
15552 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15553}
15554
15556 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15557 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15558 if (!AStmt)
15559 return StmtError();
15560
15561 if (validateMultidimClauses(*this, Clauses))
15562 return StmtError();
15563
15565 SemaRef, OMPD_target_teams_distribute_parallel_for, Clauses))
15566 return StmtError();
15567
15569 return StmtError();
15570
15572 SemaRef, OMPD_target_teams_distribute_parallel_for, AStmt);
15573
15574 OMPLoopBasedDirective::HelperExprs B;
15575 // In presence of clause 'collapse' with number of loops, it will
15576 // define the nested loops number.
15577 unsigned NestedLoopCount = checkOpenMPLoop(
15578 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
15579 nullptr /*ordered not a clause on distribute*/, CS, SemaRef, *DSAStack,
15580 VarsWithImplicitDSA, B);
15581 if (NestedLoopCount == 0)
15582 return StmtError();
15583
15584 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15585 return StmtError();
15586
15588 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
15589 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
15590}
15591
15593 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15594 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15595 if (!AStmt)
15596 return StmtError();
15597
15598 if (validateMultidimClauses(*this, Clauses))
15599 return StmtError();
15600
15602 SemaRef, OMPD_target_teams_distribute_parallel_for_simd, Clauses))
15603 return StmtError();
15604
15606 return StmtError();
15607
15609 SemaRef, OMPD_target_teams_distribute_parallel_for_simd, AStmt);
15610
15611 OMPLoopBasedDirective::HelperExprs B;
15612 // In presence of clause 'collapse' with number of loops, it will
15613 // define the nested loops number.
15614 unsigned NestedLoopCount =
15615 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
15616 getCollapseNumberExpr(Clauses),
15617 nullptr /*ordered not a clause on distribute*/, CS,
15618 SemaRef, *DSAStack, VarsWithImplicitDSA, B);
15619 if (NestedLoopCount == 0)
15620 return StmtError();
15621
15622 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15623 return StmtError();
15624
15626 return StmtError();
15627
15629 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15630}
15631
15633 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
15634 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
15635 if (!AStmt)
15636 return StmtError();
15637
15638 if (validateMultidimClauses(*this, Clauses))
15639 return StmtError();
15640
15642 SemaRef, OMPD_target_teams_distribute_simd, Clauses))
15643 return StmtError();
15644
15646 return StmtError();
15647
15649 SemaRef, OMPD_target_teams_distribute_simd, AStmt);
15650
15651 OMPLoopBasedDirective::HelperExprs B;
15652 // In presence of clause 'collapse' with number of loops, it will
15653 // define the nested loops number.
15654 unsigned NestedLoopCount = checkOpenMPLoop(
15655 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
15656 nullptr /*ordered not a clause on distribute*/, CS, SemaRef, *DSAStack,
15657 VarsWithImplicitDSA, B);
15658 if (NestedLoopCount == 0)
15659 return StmtError();
15660
15661 if (finishLinearClauses(SemaRef, Clauses, B, DSAStack))
15662 return StmtError();
15663
15665 return StmtError();
15666
15668 getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
15669}
15670
15671/// Updates OriginalInits by checking Transform against loop transformation
15672/// directives and appending their pre-inits if a match is found.
15674 SmallVectorImpl<Stmt *> &PreInits) {
15675 Stmt *Dir = Transform->getDirective();
15676 switch (Dir->getStmtClass()) {
15677#define STMT(CLASS, PARENT)
15678#define ABSTRACT_STMT(CLASS)
15679#define COMMON_OMP_LOOP_TRANSFORMATION(CLASS, PARENT) \
15680 case Stmt::CLASS##Class: \
15681 appendFlattenedStmtList(PreInits, \
15682 static_cast<const CLASS *>(Dir)->getPreInits()); \
15683 break;
15684#define OMPCANONICALLOOPNESTTRANSFORMATIONDIRECTIVE(CLASS, PARENT) \
15685 COMMON_OMP_LOOP_TRANSFORMATION(CLASS, PARENT)
15686#define OMPCANONICALLOOPSEQUENCETRANSFORMATIONDIRECTIVE(CLASS, PARENT) \
15687 COMMON_OMP_LOOP_TRANSFORMATION(CLASS, PARENT)
15688#include "clang/AST/StmtNodes.inc"
15689#undef COMMON_OMP_LOOP_TRANSFORMATION
15690 default:
15691 llvm_unreachable("Not a loop transformation");
15692 }
15693}
15694
15695bool SemaOpenMP::checkTransformableLoopNest(
15696 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
15698 Stmt *&Body, SmallVectorImpl<SmallVector<Stmt *>> &OriginalInits,
15699 SmallVectorImpl<Stmt *> *NestedFinals) {
15700 if (NestedFinals)
15701 NestedFinals->assign(NumLoops, nullptr);
15702 OriginalInits.emplace_back();
15703 // Only tile and stripe re-emit the statements before the nested loop in a
15704 // nested transformation's generated loop (see appendStmtsBeforeNestedLoop);
15705 // other constructs would silently drop them.
15707 Kind == OMPD_tile || Kind == OMPD_stripe;
15708 bool Result = OMPLoopBasedDirective::doForAllLoops(
15709 AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
15710 [this, &LoopHelpers, &Body, &OriginalInits,
15711 Kind](unsigned Cnt, Stmt *CurStmt, Stmt *HintWrapper) {
15712 // The start of this loop is a floor set in the enclosing tile's body.
15713 // Loop analysis reads a start only once, so the nest would repeat the
15714 // first tile. Reject instead of emitting wrong loops.
15715 if (HintWrapper) {
15716 SemaRef.Diag(CurStmt->getBeginLoc(),
15717 diag::err_omp_collapse_stacked_tile)
15718 << /*LoopTransform=*/1;
15719 return true;
15720 }
15722 unsigned SingleNumLoops =
15723 checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, SemaRef, *DSAStack,
15724 TmpDSA, LoopHelpers[Cnt]);
15725 if (SingleNumLoops == 0)
15726 return true;
15727 assert(SingleNumLoops == 1 && "Expect single loop iteration space");
15728 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
15729 OriginalInits.back().push_back(For->getInit());
15730 Body = For->getBody();
15731 } else {
15732 assert(isa<CXXForRangeStmt>(CurStmt) &&
15733 "Expected canonical for or range-based for loops.");
15734 auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
15735 OriginalInits.back().push_back(CXXFor->getBeginStmt());
15736 Body = CXXFor->getBody();
15737 }
15738 OriginalInits.emplace_back();
15739 return false;
15740 },
15741 [&OriginalInits,
15742 NestedFinals](OMPLoopTransformationDirective *Transform) {
15743 updatePreInits(Transform, OriginalInits.back());
15744 if (NestedFinals)
15745 if (Stmt *Finals = Transform->getFinals()) {
15746 assert(!(*NestedFinals)[OriginalInits.size() - 1] &&
15747 "Expected one nested transformation per loop");
15748 (*NestedFinals)[OriginalInits.size() - 1] = Finals;
15749 }
15750 },
15752 assert(OriginalInits.back().empty() && "No preinit after innermost loop");
15753 OriginalInits.pop_back();
15754 return Result;
15755}
15756
15757/// Counts the total number of OpenMP canonical nested loops, including the
15758/// outermost loop (the original loop). PRECONDITION of this visitor is that it
15759/// must be invoked from the original loop to be analyzed. The traversal stops
15760/// for Decl's and Expr's given that they may contain inner loops that must not
15761/// be counted.
15762///
15763/// Example AST structure for the code:
15764///
15765/// int main() {
15766/// #pragma omp fuse
15767/// {
15768/// for (int i = 0; i < 100; i++) { <-- Outer loop
15769/// []() {
15770/// for(int j = 0; j < 100; j++) {} <-- NOT A LOOP (1)
15771/// };
15772/// for(int j = 0; j < 5; ++j) {} <-- Inner loop
15773/// }
15774/// for (int r = 0; i < 100; i++) { <-- Outer loop
15775/// struct LocalClass {
15776/// void bar() {
15777/// for(int j = 0; j < 100; j++) {} <-- NOT A LOOP (2)
15778/// }
15779/// };
15780/// for(int k = 0; k < 10; ++k) {} <-- Inner loop
15781/// {x = 5; for(k = 0; k < 10; ++k) x += k; x}; <-- NOT A LOOP (3)
15782/// }
15783/// }
15784/// }
15785/// (1) because in a different function (here: a lambda)
15786/// (2) because in a different function (here: class method)
15787/// (3) because considered to be intervening-code of non-perfectly nested loop
15788/// Result: Loop 'i' contains 2 loops, Loop 'r' also contains 2 loops.
15790private:
15791 unsigned NestedLoopCount = 0;
15792
15793public:
15794 explicit NestedLoopCounterVisitor() = default;
15795
15796 unsigned getNestedLoopCount() const { return NestedLoopCount; }
15797
15798 bool VisitForStmt(ForStmt *FS) override {
15799 ++NestedLoopCount;
15800 return true;
15801 }
15802
15804 ++NestedLoopCount;
15805 return true;
15806 }
15807
15808 bool TraverseStmt(Stmt *S) override {
15809 if (!S)
15810 return true;
15811
15812 // Skip traversal of all expressions, including special cases like
15813 // LambdaExpr, StmtExpr, BlockExpr, and RequiresExpr. These expressions
15814 // may contain inner statements (and even loops), but they are not part
15815 // of the syntactic body of the surrounding loop structure.
15816 // Therefore must not be counted.
15817 if (isa<Expr>(S))
15818 return true;
15819
15820 // Only recurse into CompoundStmt (block {}) and loop bodies.
15823 }
15824
15825 // Stop traversal of the rest of statements, that break perfect
15826 // loop nesting, such as control flow (IfStmt, SwitchStmt...).
15827 return true;
15828 }
15829
15830 bool TraverseDecl(Decl *D) override {
15831 // Stop in the case of finding a declaration, it is not important
15832 // in order to find nested loops (Possible CXXRecordDecl, RecordDecl,
15833 // FunctionDecl...).
15834 return true;
15835 }
15836};
15837
15838bool SemaOpenMP::analyzeLoopSequence(Stmt *LoopSeqStmt,
15839 LoopSequenceAnalysis &SeqAnalysis,
15840 ASTContext &Context,
15842 bool IsGeneratedSequence) {
15844 // Helper Lambda to handle storing initialization and body statements for
15845 // both ForStmt and CXXForRangeStmt.
15846 auto StoreLoopStatements = [](LoopAnalysis &Analysis, Stmt *LoopStmt) {
15847 if (auto *For = dyn_cast<ForStmt>(LoopStmt)) {
15848 Analysis.OriginalInits.push_back(For->getInit());
15849 Analysis.TheForStmt = For;
15850 } else {
15851 auto *CXXFor = cast<CXXForRangeStmt>(LoopStmt);
15852 Analysis.OriginalInits.push_back(CXXFor->getBeginStmt());
15853 Analysis.TheForStmt = CXXFor;
15854 }
15855 };
15856
15857 // Helper lambda functions to encapsulate the processing of different
15858 // derivations of the canonical loop sequence grammar
15859 // Modularized code for handling loop generation and transformations.
15860 auto AnalyzeLoopGeneration = [&](Stmt *Child) {
15861 auto *LoopTransform = cast<OMPLoopTransformationDirective>(Child);
15862 Stmt *TransformedStmt = LoopTransform->getTransformedStmt();
15863 unsigned NumGeneratedTopLevelLoops =
15864 LoopTransform->getNumGeneratedTopLevelLoops();
15865 // Handle the case where transformed statement is not available due to
15866 // dependent contexts
15867 if (!TransformedStmt) {
15868 if (NumGeneratedTopLevelLoops > 0) {
15869 SeqAnalysis.LoopSeqSize += NumGeneratedTopLevelLoops;
15870 return true;
15871 }
15872 // Unroll full (0 loops produced)
15873 Diag(Child->getBeginLoc(), diag::err_omp_not_for)
15874 << 0 << getOpenMPDirectiveName(Kind);
15875 return false;
15876 }
15877 // Handle loop transformations with multiple loop nests
15878 // Unroll full
15879 if (!NumGeneratedTopLevelLoops) {
15880 Diag(Child->getBeginLoc(), diag::err_omp_not_for)
15881 << 0 << getOpenMPDirectiveName(Kind);
15882 return false;
15883 }
15884 // Loop transformatons such as split or loopranged fuse
15885 if (NumGeneratedTopLevelLoops > 1) {
15886 // Get the preinits related to this loop sequence generating
15887 // loop transformation (i.e loopranged fuse, split...)
15888 // These preinits differ slightly from regular inits/pre-inits related
15889 // to single loop generating loop transformations (interchange, unroll)
15890 // given that they are not bounded to a particular loop nest
15891 // so they need to be treated independently
15892 updatePreInits(LoopTransform, SeqAnalysis.LoopSequencePreInits);
15893 if (!analyzeLoopSequence(TransformedStmt, SeqAnalysis, Context, Kind,
15894 /*IsGeneratedSequence=*/true))
15895 return false;
15896 // Finals follow the last generated loop; looprange fuse inlines its own.
15897 if (Stmt *Finals = LoopTransform->getFinals()) {
15898 assert(!SeqAnalysis.Loops.back().TransformFinals &&
15899 "Generated loop already has Finals");
15900 SeqAnalysis.Loops.back().TransformFinals = Finals;
15901 }
15902 return true;
15903 }
15904 // Vast majority: (Tile, Unroll, Stripe, Reverse, Interchange, Fuse all)
15905 // Process the transformed loop statement
15906 LoopAnalysis &NewTransformedSingleLoop =
15907 SeqAnalysis.Loops.emplace_back(Child);
15908 unsigned IsCanonical = checkOpenMPLoop(
15909 Kind, nullptr, nullptr, TransformedStmt, SemaRef, *DSAStack, TmpDSA,
15910 NewTransformedSingleLoop.HelperExprs);
15911
15912 if (!IsCanonical)
15913 return false;
15914
15915 StoreLoopStatements(NewTransformedSingleLoop, TransformedStmt);
15916 updatePreInits(LoopTransform, NewTransformedSingleLoop.TransformsPreInits);
15917 NewTransformedSingleLoop.TransformFinals = LoopTransform->getFinals();
15918
15919 SeqAnalysis.LoopSeqSize++;
15920 return true;
15921 };
15922
15923 // Modularized code for handling regular canonical loops.
15924 auto AnalyzeRegularLoop = [&](Stmt *Child) {
15925 LoopAnalysis &NewRegularLoop = SeqAnalysis.Loops.emplace_back(Child);
15926 unsigned IsCanonical =
15927 checkOpenMPLoop(Kind, nullptr, nullptr, Child, SemaRef, *DSAStack,
15928 TmpDSA, NewRegularLoop.HelperExprs);
15929
15930 if (!IsCanonical)
15931 return false;
15932
15933 StoreLoopStatements(NewRegularLoop, Child);
15934 NestedLoopCounterVisitor NLCV;
15935 NLCV.TraverseStmt(Child);
15936 return true;
15937 };
15938
15939 // High level grammar validation.
15940 for (Stmt *Child : LoopSeqStmt->children()) {
15941 if (!Child)
15942 continue;
15943 // A sequence-generating transformation (e.g. looprange fuse) emits each
15944 // out-of-range loop transformation as `{ Loop; Finals }` so its loop
15945 // variables are finalized right after the loop. Analyze the loop and carry
15946 // its Finals along so the enclosing directive can place them.
15947 if (IsGeneratedSequence) {
15948 auto *CS = dyn_cast<CompoundStmt>(Child);
15949 if (CS && CS->size() == 2 &&
15950 LoopAnalysis::isRegularLoop(CS->body_front()) &&
15951 !LoopAnalysis::isRegularLoop(CS->body_back())) {
15952 if (!AnalyzeRegularLoop(CS->body_front()))
15953 return false;
15954 SeqAnalysis.Loops.back().TransformFinals = CS->body_back();
15955 SeqAnalysis.LoopSeqSize++;
15956 continue;
15957 }
15958 }
15959 // Skip over non-loop-sequence statements.
15960 if (!LoopSequenceAnalysis::isLoopSequenceDerivation(Child)) {
15961 Child = Child->IgnoreContainers();
15962 // Ignore empty compound statement.
15963 if (!Child)
15964 continue;
15965 // In the case of a nested loop sequence ignoring containers would not
15966 // be enough, a recurisve transversal of the loop sequence is required.
15967 if (isa<CompoundStmt>(Child)) {
15968 if (!analyzeLoopSequence(Child, SeqAnalysis, Context, Kind,
15969 IsGeneratedSequence))
15970 return false;
15971 // Already been treated, skip this children
15972 continue;
15973 }
15974 }
15975 // Regular loop sequence handling.
15976 if (LoopSequenceAnalysis::isLoopSequenceDerivation(Child)) {
15977 if (LoopAnalysis::isLoopTransformation(Child)) {
15978 if (!AnalyzeLoopGeneration(Child))
15979 return false;
15980 // AnalyzeLoopGeneration updates SeqAnalysis.LoopSeqSize accordingly.
15981 } else {
15982 if (!AnalyzeRegularLoop(Child))
15983 return false;
15984 SeqAnalysis.LoopSeqSize++;
15985 }
15986 } else {
15987 // Report error for invalid statement inside canonical loop sequence.
15988 Diag(Child->getBeginLoc(), diag::err_omp_not_for)
15989 << 0 << getOpenMPDirectiveName(Kind);
15990 return false;
15991 }
15992 }
15993 return true;
15994}
15995
15996bool SemaOpenMP::checkTransformableLoopSequence(
15997 OpenMPDirectiveKind Kind, Stmt *AStmt, LoopSequenceAnalysis &SeqAnalysis,
15998 ASTContext &Context) {
15999 // Following OpenMP 6.0 API Specification, a Canonical Loop Sequence follows
16000 // the grammar:
16001 //
16002 // canonical-loop-sequence:
16003 // {
16004 // loop-sequence+
16005 // }
16006 // where loop-sequence can be any of the following:
16007 // 1. canonical-loop-sequence
16008 // 2. loop-nest
16009 // 3. loop-sequence-generating-construct (i.e OMPLoopTransformationDirective)
16010 //
16011 // To recognise and traverse this structure the helper function
16012 // analyzeLoopSequence serves as the recurisve entry point
16013 // and tries to match the input AST to the canonical loop sequence grammar
16014 // structure. This function will perform both a semantic and syntactical
16015 // analysis of the given statement according to OpenMP 6.0 definition of
16016 // the aforementioned canonical loop sequence.
16017
16018 // We expect an outer compound statement.
16019 if (!isa<CompoundStmt>(AStmt)) {
16020 Diag(AStmt->getBeginLoc(), diag::err_omp_not_a_loop_sequence)
16021 << getOpenMPDirectiveName(Kind);
16022 return false;
16023 }
16024
16025 // Recursive entry point to process the main loop sequence
16026 if (!analyzeLoopSequence(AStmt, SeqAnalysis, Context, Kind))
16027 return false;
16028
16029 // Diagnose an empty loop sequence.
16030 if (!SeqAnalysis.LoopSeqSize) {
16031 Diag(AStmt->getBeginLoc(), diag::err_omp_empty_loop_sequence)
16032 << getOpenMPDirectiveName(Kind);
16033 return false;
16034 }
16035 return true;
16036}
16037
16038/// Add preinit statements that need to be propagated from the selected loop.
16039static void addLoopPreInits(ASTContext &Context,
16040 OMPLoopBasedDirective::HelperExprs &LoopHelper,
16041 Stmt *LoopStmt, ArrayRef<Stmt *> OriginalInit,
16042 SmallVectorImpl<Stmt *> &PreInits) {
16043
16044 // For range-based for-statements, ensure that their syntactic sugar is
16045 // executed by adding them as pre-init statements.
16046 if (auto *CXXRangeFor = dyn_cast<CXXForRangeStmt>(LoopStmt)) {
16047 Stmt *RangeInit = CXXRangeFor->getInit();
16048 if (RangeInit)
16049 PreInits.push_back(RangeInit);
16050
16051 DeclStmt *RangeStmt = CXXRangeFor->getRangeStmt();
16052 PreInits.push_back(new (Context) DeclStmt(RangeStmt->getDeclGroup(),
16053 RangeStmt->getBeginLoc(),
16054 RangeStmt->getEndLoc()));
16055
16056 DeclStmt *RangeEnd = CXXRangeFor->getEndStmt();
16057 PreInits.push_back(new (Context) DeclStmt(RangeEnd->getDeclGroup(),
16058 RangeEnd->getBeginLoc(),
16059 RangeEnd->getEndLoc()));
16060 }
16061
16062 llvm::append_range(PreInits, OriginalInit);
16063
16064 // List of OMPCapturedExprDecl, for __begin, __end, and NumIterations
16065 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) {
16066 PreInits.push_back(new (Context) DeclStmt(
16067 PI->getDeclGroup(), PI->getBeginLoc(), PI->getEndLoc()));
16068 }
16069
16070 // Gather declarations for the data members used as counters.
16071 for (Expr *CounterRef : LoopHelper.Counters) {
16072 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
16073 if (isa<OMPCapturedExprDecl>(CounterDecl))
16074 PreInits.push_back(new (Context) DeclStmt(
16075 DeclGroupRef(CounterDecl), SourceLocation(), SourceLocation()));
16076 }
16077}
16078
16079/// Collect the loop statements (ForStmt or CXXRangeForStmt) of the affected
16080/// loop of a construct.
16081static void collectLoopStmts(Stmt *AStmt, MutableArrayRef<Stmt *> LoopStmts,
16082 bool RelaxNestForPeeledTransformation = false) {
16083 size_t NumLoops = LoopStmts.size();
16084 OMPLoopBasedDirective::doForAllLoops(
16085 AStmt, /*TryImperfectlyNestedLoops=*/false, NumLoops,
16086 [LoopStmts](unsigned Cnt, Stmt *CurStmt) {
16087 assert(!LoopStmts[Cnt] && "Loop statement must not yet be assigned");
16088 LoopStmts[Cnt] = CurStmt;
16089 return false;
16090 },
16092 assert(!is_contained(LoopStmts, nullptr) &&
16093 "Expecting a loop statement for each affected loop");
16094}
16095
16096/// A non-innermost affected loop generated by a nested loop transformation
16097/// (e.g. `omp reverse`) computes the user counter in statements ahead of the
16098/// next loop. A construct that rebuilds the nest only keeps the innermost
16099/// body, so it must re-emit these statements in the matching loop.
16100static void appendStmtsBeforeNestedLoop(Stmt *LoopStmt,
16101 SmallVectorImpl<Stmt *> &BodyParts) {
16102 Stmt *Body = isa<ForStmt>(LoopStmt)
16103 ? cast<ForStmt>(LoopStmt)->getBody()
16104 : cast<CXXForRangeStmt>(LoopStmt)->getBody();
16105 llvm::append_range(BodyParts,
16106 OMPLoopBasedDirective::getStmtsBeforeNestedLoop(Body));
16107}
16108
16109/// Build and return a DeclRefExpr for the floor induction variable using the
16110/// SemaRef and the provided parameters.
16111static Expr *makeFloorIVRef(Sema &SemaRef, ArrayRef<VarDecl *> FloorIndVars,
16112 int I, QualType IVTy, DeclRefExpr *OrigCntVar) {
16113 return buildDeclRefExpr(SemaRef, FloorIndVars[I], IVTy,
16114 OrigCntVar->getExprLoc());
16115}
16116
16117/// Whether \p Counter is dead after \p LoopStmt: compiler generated (e.g. a
16118/// fuse index) or declared by the loop's own init statement.
16119static bool isDeadAfterLoop(const Expr *Counter, const Stmt *LoopStmt) {
16120 const auto *DRE = dyn_cast<DeclRefExpr>(Counter);
16121 const auto *VD = DRE ? dyn_cast<VarDecl>(DRE->getDecl()) : nullptr;
16122 if (!VD)
16123 return false;
16124 if (VD->isImplicit())
16125 return !isa<OMPCapturedExprDecl>(VD);
16126 const auto *For = dyn_cast<ForStmt>(LoopStmt);
16127 const auto *Init = For ? dyn_cast_or_null<DeclStmt>(For->getInit()) : nullptr;
16128 return Init && llvm::is_contained(Init->decls(), VD);
16129}
16130
16131/// Wrap \p S so it runs only if every loop in \p Loops has iterations.
16132static Stmt *
16135 Stmt *S) {
16136 for (const auto &Loop : llvm::reverse(Loops))
16138 nullptr, nullptr, Loop.PreCond, SourceLocation(),
16139 SourceLocation(), S, SourceLocation(), nullptr);
16140 return S;
16141}
16142
16143/// Run loop \p I's inits only if all enclosing loops have iterations.
16144/// Declarations are left as is.
16145static void
16148 unsigned I, SmallVectorImpl<Stmt *> &OriginalInit) {
16149 if (I == 0)
16150 return;
16151 for (Stmt *&Init : OriginalInit)
16152 if (Init && !isa<DeclStmt>(Init))
16153 Init = guardByLoopPreConds(Context, LoopHelpers.take_front(I), Init);
16154}
16155
16156/// Build loop variable finalization statement from HelperExprs.Finals.
16157/// Each Final runs only if its loop and all enclosing loops have iterations;
16158/// \p NestedFinals[I] is emitted with loop I's.
16159/// Returns nullptr if there is nothing to finalize.
16160/// Counters that are dead after their loop and class-type iterators are
16161/// skipped.
16162static Stmt *
16165 ArrayRef<Stmt *> LoopStmts,
16166 ArrayRef<Stmt *> NestedFinals = {}) {
16167 assert(LoopStmts.size() == LoopHelpers.size() &&
16168 "Expected one loop statement per loop");
16169 auto GetFinals = [](const OMPLoopBasedDirective::HelperExprs &Helper,
16170 const Stmt *LoopStmt) {
16172 for (auto [Counter, Final] :
16173 llvm::zip_equal(Helper.Counters, Helper.Finals)) {
16174 if (isDeadAfterLoop(Counter, LoopStmt))
16175 continue;
16176 // FIXME: finalize class-type iterators too (random-access arithmetic
16177 // is available per the canonical loop form).
16178 QualType CounterTy = Counter->getType();
16179 if (Final &&
16180 (CounterTy->isArithmeticType() || CounterTy->isPointerType()))
16181 Finals.push_back(Final);
16182 }
16183 return Finals;
16184 };
16185 auto MakeCompound = [&Context](ArrayRef<Stmt *> Stmts) -> Stmt * {
16186 return CompoundStmt::Create(Context, Stmts, FPOptionsOverride(),
16188 };
16189
16190 auto GetNestedFinals = [&](size_t I) -> Stmt * {
16191 return I < NestedFinals.size() ? NestedFinals[I] : nullptr;
16192 };
16193
16194 // if (P0) { F0; if (P1) { F1; ... } }, built from the innermost loop out.
16195 Stmt *Nested = nullptr;
16196 for (size_t I = LoopHelpers.size(); I-- > 0;) {
16197 SmallVector<Stmt *, 2> Body = GetFinals(LoopHelpers[I], LoopStmts[I]);
16198 if (Stmt *F = GetNestedFinals(I))
16199 Body.push_back(F);
16200 if (Nested)
16201 Body.push_back(Nested);
16202 if (Body.empty())
16203 continue;
16204 Nested = guardByLoopPreConds(Context, LoopHelpers[I],
16205 Body.size() == 1 ? Body.front()
16206 : MakeCompound(Body));
16207 }
16208 return Nested;
16209}
16210
16212 Stmt *AStmt,
16213 SourceLocation StartLoc,
16214 SourceLocation EndLoc) {
16215 ASTContext &Context = getASTContext();
16216 Scope *CurScope = SemaRef.getCurScope();
16217
16218 const auto *SizesClause =
16219 OMPExecutableDirective::getSingleClause<OMPSizesClause>(Clauses);
16220 if (!SizesClause ||
16221 llvm::any_of(SizesClause->getSizesRefs(), [](Expr *E) { return !E; }))
16222 return StmtError();
16223 unsigned NumLoops = SizesClause->getNumSizes();
16224
16225 // Empty statement should only be possible if there already was an error.
16226 if (!AStmt)
16227 return StmtError();
16228
16229 // Verify and diagnose loop nest.
16231 Stmt *Body = nullptr;
16232 SmallVector<SmallVector<Stmt *>, 4> OriginalInits;
16233 SmallVector<Stmt *, 4> NestedFinals;
16234 if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
16235 OriginalInits, &NestedFinals))
16236 return StmtError();
16237
16238 // Delay tiling to when template is completely instantiated.
16239 if (SemaRef.CurContext->isDependentContext())
16240 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
16241 NumLoops, AStmt, nullptr, nullptr, nullptr);
16242
16243 assert(LoopHelpers.size() == NumLoops &&
16244 "Expecting loop iteration space dimensionality to match number of "
16245 "affected loops");
16246 assert(OriginalInits.size() == NumLoops &&
16247 "Expecting loop iteration space dimensionality to match number of "
16248 "affected loops");
16249
16250 // Collect all affected loop statements.
16251 SmallVector<Stmt *> LoopStmts(NumLoops, nullptr);
16252 collectLoopStmts(AStmt, LoopStmts, /*RelaxNestForPeeledTransformation=*/true);
16253
16254 SmallVector<Stmt *, 4> PreInits;
16255 CaptureVars CopyTransformer(SemaRef);
16256
16257 // Create iteration variables for the generated loops.
16258 SmallVector<VarDecl *, 4> FloorIndVars;
16259 SmallVector<VarDecl *, 4> TileIndVars;
16260 FloorIndVars.resize(NumLoops);
16261 TileIndVars.resize(NumLoops);
16262 for (unsigned I = 0; I < NumLoops; ++I) {
16263 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
16264
16265 assert(LoopHelper.Counters.size() == 1 &&
16266 "Expect single-dimensional loop iteration space");
16267 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
16268 std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
16269 DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
16270 QualType CntTy = IterVarRef->getType();
16271
16272 // Iteration variable for the floor (i.e. outer) loop.
16273 {
16274 std::string FloorCntName =
16275 (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
16276 VarDecl *FloorCntDecl =
16277 buildVarDecl(SemaRef, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
16278 FloorIndVars[I] = FloorCntDecl;
16279 }
16280
16281 // Iteration variable for the tile (i.e. inner) loop.
16282 {
16283 std::string TileCntName =
16284 (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
16285
16286 // Reuse the iteration variable created by checkOpenMPLoop. It is also
16287 // used by the expressions to derive the original iteration variable's
16288 // value from the logical iteration number.
16289 auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
16290 TileCntDecl->setDeclName(
16291 &SemaRef.PP.getIdentifierTable().get(TileCntName));
16292 TileIndVars[I] = TileCntDecl;
16293 }
16294
16295 guardNestedLoopInit(Context, LoopHelpers, I, OriginalInits[I]);
16296 addLoopPreInits(Context, LoopHelper, LoopStmts[I], OriginalInits[I],
16297 PreInits);
16298 }
16299
16300 // Once the original iteration values are set, append the innermost body.
16301 Stmt *Inner = Body;
16302
16303 auto MakeDimTileSize = [&SemaRef = this->SemaRef, &CopyTransformer, &Context,
16304 SizesClause, CurScope](int I) -> Expr * {
16305 Expr *DimTileSizeExpr = SizesClause->getSizesRefs()[I];
16306
16307 if (DimTileSizeExpr->containsErrors())
16308 return nullptr;
16309
16310 if (isa<ConstantExpr>(DimTileSizeExpr))
16311 return AssertSuccess(CopyTransformer.TransformExpr(DimTileSizeExpr));
16312
16313 // When the tile size is not a constant but a variable, it is possible to
16314 // pass non-positive numbers. For instance:
16315 // \code{c}
16316 // int a = 0;
16317 // #pragma omp tile sizes(a)
16318 // for (int i = 0; i < 42; ++i)
16319 // body(i);
16320 // \endcode
16321 // Although there is no meaningful interpretation of the tile size, the body
16322 // should still be executed 42 times to avoid surprises. To preserve the
16323 // invariant that every loop iteration is executed exactly once and not
16324 // cause an infinite loop, apply a minimum tile size of one.
16325 // Build expr:
16326 // \code{c}
16327 // (TS <= 0) ? 1 : TS
16328 // \endcode
16329 QualType DimTy = DimTileSizeExpr->getType();
16330 unsigned DimWidth = Context.getIntWidth(DimTy);
16332 Context, llvm::APInt::getZero(DimWidth), DimTy, {});
16333 IntegerLiteral *One =
16334 IntegerLiteral::Create(Context, llvm::APInt(DimWidth, 1), DimTy, {});
16335 Expr *Cond = AssertSuccess(SemaRef.BuildBinOp(
16336 CurScope, {}, BO_LE,
16337 AssertSuccess(CopyTransformer.TransformExpr(DimTileSizeExpr)), Zero));
16338 Expr *MinOne = new (Context) ConditionalOperator(
16339 Cond, {}, One, {},
16340 AssertSuccess(CopyTransformer.TransformExpr(DimTileSizeExpr)), DimTy,
16342 return MinOne;
16343 };
16344
16345 // Create tile loops from the inside to the outside.
16346 //
16347 // Each intra-tile loop is emitted in its natural min-bounded form, which has
16348 // no per-iteration body predicate and vectorizes well when run directly:
16349 // for (.tile.iv = .floor.iv; .tile.iv < min(.floor.iv + T, N); ++.tile.iv)
16350 //
16351 // A loop-associated directive that *consumes* this loop (e.g. `collapse`)
16352 // instead needs a constant, floor-independent trip count to linearize the
16353 // nest, which the min() bound cannot give it. Rather than change the
16354 // emitted loop, we attach a droppable OMPInvariantPredicateBoundAttr hint
16355 // below carrying an equivalent rectangular reinterpretation:
16356 // RectCond : .tile.iv < .floor.iv + T -- rectangular bound, analyzed by
16357 // checkOpenMPIterationSpace in place of the stored condition
16358 // TileSize : T -- constant per-tile trip count
16359 // Predicate : .tile.iv < N -- remainder-tile overshoot,
16360 // applied as a body guard instead of shortening the trip count;
16361 // omitted when N is known to be a multiple of T, as there is
16362 // then no partial tile to guard against
16363 // Because the reinterpreted lower bound is still `.floor.iv`,
16364 // checkOpenMPIterationSpace sets IsNonRectangularLB on the matching floor
16365 // counter, so a collapsed `.tile.iv` re-reads the floor's current value
16366 // instead of a stale preheader snapshot. Collapsing through stacked tiles
16367 // (tile-of-tile) is not supported: the inner floor is not itself a collapsed
16368 // counter.
16369 for (int I = NumLoops - 1; I >= 0; --I) {
16370 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
16371 Expr *NumIterations = LoopHelper.NumIterations;
16372 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
16373 QualType IVTy = NumIterations->getType();
16374 Stmt *LoopStmt = LoopStmts[I];
16375
16376 // Commonly used variables. One of the constraints of an AST is that every
16377 // node object must appear at most once, hence we define a lambda that
16378 // creates a new AST node at every use.
16379 auto MakeTileIVRef = [&SemaRef = this->SemaRef, &TileIndVars, I, IVTy,
16380 OrigCntVar]() {
16381 return buildDeclRefExpr(SemaRef, TileIndVars[I], IVTy,
16382 OrigCntVar->getExprLoc());
16383 };
16384
16385 // For init-statement: auto .tile.iv = .floor.iv
16386 SemaRef.AddInitializerToDecl(
16387 TileIndVars[I],
16388 SemaRef
16389 .DefaultLvalueConversion(
16390 makeFloorIVRef(SemaRef, FloorIndVars, I, IVTy, OrigCntVar))
16391 .get(),
16392 /*DirectInit=*/false);
16393 Decl *CounterDecl = TileIndVars[I];
16394 StmtResult InitStmt = new (Context)
16395 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
16396 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
16397 if (!InitStmt.isUsable())
16398 return StmtError();
16399
16400 // For cond-expression:
16401 // .tile.iv < min(.floor.iv + DimTileSize, NumIterations)
16402 Expr *DimTileSize = MakeDimTileSize(I);
16403 if (!DimTileSize)
16404 return StmtError();
16405 ExprResult EndOfTile = SemaRef.BuildBinOp(
16406 CurScope, LoopHelper.Cond->getExprLoc(), BO_Add,
16407 makeFloorIVRef(SemaRef, FloorIndVars, I, IVTy, OrigCntVar),
16408 DimTileSize);
16409 if (!EndOfTile.isUsable())
16410 return StmtError();
16411 ExprResult IsPartialTile =
16412 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
16413 NumIterations, EndOfTile.get());
16414 if (!IsPartialTile.isUsable())
16415 return StmtError();
16416 ExprResult MinTileAndIterSpace = SemaRef.ActOnConditionalOp(
16417 LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
16418 IsPartialTile.get(), NumIterations, EndOfTile.get());
16419 if (!MinTileAndIterSpace.isUsable())
16420 return StmtError();
16421 ExprResult CondExpr =
16422 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
16423 MakeTileIVRef(), MinTileAndIterSpace.get());
16424 if (!CondExpr.isUsable())
16425 return StmtError();
16426
16427 // For incr-statement: ++.tile.iv
16428 ExprResult IncrStmt = SemaRef.BuildUnaryOp(
16429 CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, MakeTileIVRef());
16430 if (!IncrStmt.isUsable())
16431 return StmtError();
16432
16433 // Build OMPInvariantPredicateBoundAttr hint (RectCond, TileSize,
16434 // Predicate).
16435 Expr *RectDimTileSize = MakeDimTileSize(I);
16436 if (!RectDimTileSize)
16437 return StmtError();
16438 ExprResult RectEndOfTile = SemaRef.BuildBinOp(
16439 CurScope, LoopHelper.Cond->getExprLoc(), BO_Add,
16440 makeFloorIVRef(SemaRef, FloorIndVars, I, IVTy, OrigCntVar),
16441 RectDimTileSize);
16442 if (!RectEndOfTile.isUsable())
16443 return StmtError();
16444 ExprResult RectCond =
16445 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
16446 MakeTileIVRef(), RectEndOfTile.get());
16447 Expr *TileSizeExpr = MakeDimTileSize(I);
16448 if (!TileSizeExpr)
16449 return StmtError();
16450 ExprResult TileSize = SemaRef.PerformImplicitConversion(
16451 TileSizeExpr, IVTy, AssignmentAction::Converting,
16452 /*AllowExplicit=*/true);
16453 if (!RectCond.isUsable() || !TileSize.isUsable())
16454 return StmtError();
16455
16456 // The overshoot guard is only needed if the last tile can be partial. When
16457 // both the trip count and the tile size are known at compile time and the
16458 // former is a multiple of the latter, every tile is full, so leave the
16459 // predicate out. A dependent or run-time value makes
16460 // the evaluation fail, which keeps the guard.
16461 bool NoPartialTile = false;
16462 Expr::EvalResult TileSizeVal, NumIterationsVal;
16463 if (TileSizeExpr->EvaluateAsInt(TileSizeVal, Context) &&
16464 NumIterations->EvaluateAsInt(NumIterationsVal, Context)) {
16465 llvm::APSInt TS = TileSizeVal.Val.getInt();
16466 llvm::APSInt N = NumIterationsVal.Val.getInt();
16467 unsigned Width = std::max(TS.getBitWidth(), N.getBitWidth());
16468 TS = TS.extend(Width);
16469 N = N.extend(Width);
16470 NoPartialTile =
16471 TS.isStrictlyPositive() && N.isStrictlyPositive() && N.urem(TS) == 0;
16472 }
16473
16474 ExprResult Predicate;
16475 if (!NoPartialTile) {
16476 Predicate = SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
16477 BO_LT, MakeTileIVRef(), NumIterations);
16478 if (!Predicate.isUsable())
16479 return StmtError();
16480 }
16481
16482 // Statements to set the original iteration variable's value from the
16483 // logical iteration number.
16484 // Generated for loop is:
16485 // \code
16486 // Original_for_init;
16487 // for (auto .tile.iv = .floor.iv;
16488 // .tile.iv < min(.floor.iv + DimTileSize, NumIterations);
16489 // ++.tile.iv) {
16490 // Original_Body;
16491 // Original_counter_update;
16492 // }
16493 // \endcode
16494 // FIXME: If the innermost body is an loop itself, inserting these
16495 // statements stops it being recognized as a perfectly nested loop (e.g.
16496 // for applying tiling again). If this is the case, sink the expressions
16497 // further into the inner loop.
16498 SmallVector<Stmt *, 4> BodyParts;
16499 BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
16500 if (auto *SourceCXXFor = dyn_cast<CXXForRangeStmt>(LoopStmt))
16501 BodyParts.push_back(SourceCXXFor->getLoopVarStmt());
16502 if (static_cast<unsigned>(I) + 1 < NumLoops)
16503 appendStmtsBeforeNestedLoop(LoopStmt, BodyParts);
16504 BodyParts.push_back(Inner);
16505 Inner = CompoundStmt::Create(Context, BodyParts, FPOptionsOverride(),
16506 Inner->getBeginLoc(), Inner->getEndLoc());
16507 Inner = new (Context)
16508 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
16509 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
16510 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
16511
16512 // Attach the droppable reinterpretation attribute to the intra-tile loop.
16513 auto *Hint = OMPInvariantPredicateBoundAttr::CreateImplicit(
16514 Context, RectCond.get(), TileSize.get(),
16515 Predicate.isUsable() ? Predicate.get() : nullptr,
16516 Inner->getSourceRange());
16517 Inner =
16518 AttributedStmt::Create(Context, Inner->getBeginLoc(), {Hint}, Inner);
16519 }
16520
16521 // Create floor loops from the inside to the outside.
16522 for (int I = NumLoops - 1; I >= 0; --I) {
16523 auto &LoopHelper = LoopHelpers[I];
16524 Expr *NumIterations = LoopHelper.NumIterations;
16525 DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
16526 QualType IVTy = NumIterations->getType();
16527
16528 // For init-statement: auto .floor.iv = 0
16529 SemaRef.AddInitializerToDecl(
16530 FloorIndVars[I],
16531 SemaRef.ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
16532 /*DirectInit=*/false);
16533 Decl *CounterDecl = FloorIndVars[I];
16534 StmtResult InitStmt = new (Context)
16535 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
16536 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
16537 if (!InitStmt.isUsable())
16538 return StmtError();
16539
16540 // For cond-expression: .floor.iv < NumIterations
16541 ExprResult CondExpr = SemaRef.BuildBinOp(
16542 CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
16543 makeFloorIVRef(SemaRef, FloorIndVars, I, IVTy, OrigCntVar),
16544 NumIterations);
16545 if (!CondExpr.isUsable())
16546 return StmtError();
16547
16548 // For incr-statement: .floor.iv += DimTileSize
16549 Expr *DimTileSize = MakeDimTileSize(I);
16550 if (!DimTileSize)
16551 return StmtError();
16552 ExprResult IncrStmt = SemaRef.BuildBinOp(
16553 CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
16554 makeFloorIVRef(SemaRef, FloorIndVars, I, IVTy, OrigCntVar),
16555 DimTileSize);
16556 if (!IncrStmt.isUsable())
16557 return StmtError();
16558
16559 Inner = new (Context)
16560 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
16561 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
16562 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
16563 }
16564
16566 Context, StartLoc, EndLoc, Clauses, NumLoops, AStmt, Inner,
16567 buildPreInits(Context, PreInits),
16568 buildLoopFinalization(Context, LoopHelpers, LoopStmts, NestedFinals));
16569}
16570
16572 Stmt *AStmt,
16573 SourceLocation StartLoc,
16574 SourceLocation EndLoc) {
16575 ASTContext &Context = getASTContext();
16576 Scope *CurScope = SemaRef.getCurScope();
16577
16578 const auto *SizesClause =
16579 OMPExecutableDirective::getSingleClause<OMPSizesClause>(Clauses);
16580 if (!SizesClause ||
16581 llvm::any_of(SizesClause->getSizesRefs(), [](const Expr *SizeExpr) {
16582 return !SizeExpr || SizeExpr->containsErrors();
16583 }))
16584 return StmtError();
16585 unsigned NumLoops = SizesClause->getNumSizes();
16586
16587 // Empty statement should only be possible if there already was an error.
16588 if (!AStmt)
16589 return StmtError();
16590
16591 // Verify and diagnose loop nest.
16593 Stmt *Body = nullptr;
16594 SmallVector<SmallVector<Stmt *>, 4> OriginalInits;
16595 SmallVector<Stmt *, 4> NestedFinals;
16596 if (!checkTransformableLoopNest(OMPD_stripe, AStmt, NumLoops, LoopHelpers,
16597 Body, OriginalInits, &NestedFinals))
16598 return StmtError();
16599
16600 // Delay striping to when template is completely instantiated.
16601 if (SemaRef.CurContext->isDependentContext())
16602 return OMPStripeDirective::Create(Context, StartLoc, EndLoc, Clauses,
16603 NumLoops, AStmt, nullptr, nullptr,
16604 nullptr);
16605
16606 assert(LoopHelpers.size() == NumLoops &&
16607 "Expecting loop iteration space dimensionality to match number of "
16608 "affected loops");
16609 assert(OriginalInits.size() == NumLoops &&
16610 "Expecting loop iteration space dimensionality to match number of "
16611 "affected loops");
16612
16613 // Collect all affected loop statements.
16614 SmallVector<Stmt *> LoopStmts(NumLoops, nullptr);
16615 collectLoopStmts(AStmt, LoopStmts, /*RelaxNestForPeeledTransformation=*/true);
16616
16617 SmallVector<Stmt *, 4> PreInits;
16618 CaptureVars CopyTransformer(SemaRef);
16619
16620 // Create iteration variables for the generated loops.
16621 SmallVector<VarDecl *, 4> FloorIndVars;
16622 SmallVector<VarDecl *, 4> StripeIndVars;
16623 FloorIndVars.resize(NumLoops);
16624 StripeIndVars.resize(NumLoops);
16625 for (unsigned I : llvm::seq<unsigned>(NumLoops)) {
16626 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
16627
16628 assert(LoopHelper.Counters.size() == 1 &&
16629 "Expect single-dimensional loop iteration space");
16630 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
16631 std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
16632 DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
16633 QualType CntTy = IterVarRef->getType();
16634
16635 // Iteration variable for the stripe (i.e. outer) loop.
16636 {
16637 std::string FloorCntName =
16638 (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
16639 VarDecl *FloorCntDecl =
16640 buildVarDecl(SemaRef, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
16641 FloorIndVars[I] = FloorCntDecl;
16642 }
16643
16644 // Iteration variable for the stripe (i.e. inner) loop.
16645 {
16646 std::string StripeCntName =
16647 (Twine(".stripe_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
16648
16649 // Reuse the iteration variable created by checkOpenMPLoop. It is also
16650 // used by the expressions to derive the original iteration variable's
16651 // value from the logical iteration number.
16652 auto *StripeCntDecl = cast<VarDecl>(IterVarRef->getDecl());
16653 StripeCntDecl->setDeclName(
16654 &SemaRef.PP.getIdentifierTable().get(StripeCntName));
16655 StripeIndVars[I] = StripeCntDecl;
16656 }
16657
16658 guardNestedLoopInit(Context, LoopHelpers, I, OriginalInits[I]);
16659 addLoopPreInits(Context, LoopHelper, LoopStmts[I], OriginalInits[I],
16660 PreInits);
16661 }
16662
16663 // Once the original iteration values are set, append the innermost body.
16664 Stmt *Inner = Body;
16665
16666 auto MakeDimStripeSize = [&](int I) -> Expr * {
16667 Expr *DimStripeSizeExpr = SizesClause->getSizesRefs()[I];
16668 if (isa<ConstantExpr>(DimStripeSizeExpr))
16669 return AssertSuccess(CopyTransformer.TransformExpr(DimStripeSizeExpr));
16670
16671 // When the stripe size is not a constant but a variable, it is possible to
16672 // pass non-positive numbers. For instance:
16673 // \code{c}
16674 // int a = 0;
16675 // #pragma omp stripe sizes(a)
16676 // for (int i = 0; i < 42; ++i)
16677 // body(i);
16678 // \endcode
16679 // Although there is no meaningful interpretation of the stripe size, the
16680 // body should still be executed 42 times to avoid surprises. To preserve
16681 // the invariant that every loop iteration is executed exactly once and not
16682 // cause an infinite loop, apply a minimum stripe size of one.
16683 // Build expr:
16684 // \code{c}
16685 // (TS <= 0) ? 1 : TS
16686 // \endcode
16687 QualType DimTy = DimStripeSizeExpr->getType();
16688 unsigned DimWidth = Context.getIntWidth(DimTy);
16690 Context, llvm::APInt::getZero(DimWidth), DimTy, {});
16691 IntegerLiteral *One =
16692 IntegerLiteral::Create(Context, llvm::APInt(DimWidth, 1), DimTy, {});
16693 Expr *Cond = AssertSuccess(SemaRef.BuildBinOp(
16694 CurScope, {}, BO_LE,
16695 AssertSuccess(CopyTransformer.TransformExpr(DimStripeSizeExpr)), Zero));
16696 Expr *MinOne = new (Context) ConditionalOperator(
16697 Cond, {}, One, {},
16698 AssertSuccess(CopyTransformer.TransformExpr(DimStripeSizeExpr)), DimTy,
16700 return MinOne;
16701 };
16702
16703 // Create stripe loops from the inside to the outside.
16704 for (int I = NumLoops - 1; I >= 0; --I) {
16705 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
16706 Expr *NumIterations = LoopHelper.NumIterations;
16707 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
16708 QualType IVTy = NumIterations->getType();
16709 Stmt *LoopStmt = LoopStmts[I];
16710
16711 // For init-statement: auto .stripe.iv = .floor.iv
16712 SemaRef.AddInitializerToDecl(
16713 StripeIndVars[I],
16714 SemaRef
16715 .DefaultLvalueConversion(
16716 makeFloorIVRef(SemaRef, FloorIndVars, I, IVTy, OrigCntVar))
16717 .get(),
16718 /*DirectInit=*/false);
16719 Decl *CounterDecl = StripeIndVars[I];
16720 StmtResult InitStmt = new (Context)
16721 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
16722 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
16723 if (!InitStmt.isUsable())
16724 return StmtError();
16725
16726 // For cond-expression:
16727 // .stripe.iv < min(.floor.iv + DimStripeSize, NumIterations)
16728 ExprResult EndOfStripe = SemaRef.BuildBinOp(
16729 CurScope, LoopHelper.Cond->getExprLoc(), BO_Add,
16730 makeFloorIVRef(SemaRef, FloorIndVars, I, IVTy, OrigCntVar),
16731 MakeDimStripeSize(I));
16732 if (!EndOfStripe.isUsable())
16733 return StmtError();
16734 ExprResult IsPartialStripe =
16735 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
16736 NumIterations, EndOfStripe.get());
16737 if (!IsPartialStripe.isUsable())
16738 return StmtError();
16739 ExprResult MinStripeAndIterSpace = SemaRef.ActOnConditionalOp(
16740 LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
16741 IsPartialStripe.get(), NumIterations, EndOfStripe.get());
16742 if (!MinStripeAndIterSpace.isUsable())
16743 return StmtError();
16744 ExprResult CondExpr = SemaRef.BuildBinOp(
16745 CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
16746 makeFloorIVRef(SemaRef, StripeIndVars, I, IVTy, OrigCntVar),
16747 MinStripeAndIterSpace.get());
16748 if (!CondExpr.isUsable())
16749 return StmtError();
16750
16751 // For incr-statement: ++.stripe.iv
16752 ExprResult IncrStmt = SemaRef.BuildUnaryOp(
16753 CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc,
16754 makeFloorIVRef(SemaRef, StripeIndVars, I, IVTy, OrigCntVar));
16755 if (!IncrStmt.isUsable())
16756 return StmtError();
16757
16758 // Statements to set the original iteration variable's value from the
16759 // logical iteration number.
16760 // Generated for loop is:
16761 // \code
16762 // Original_for_init;
16763 // for (auto .stripe.iv = .floor.iv;
16764 // .stripe.iv < min(.floor.iv + DimStripeSize, NumIterations);
16765 // ++.stripe.iv) {
16766 // Original_Body;
16767 // Original_counter_update;
16768 // }
16769 // \endcode
16770 // FIXME: If the innermost body is a loop itself, inserting these
16771 // statements stops it being recognized as a perfectly nested loop (e.g.
16772 // for applying another loop transformation). If this is the case, sink the
16773 // expressions further into the inner loop.
16774 SmallVector<Stmt *, 4> BodyParts;
16775 BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
16776 if (auto *SourceCXXFor = dyn_cast<CXXForRangeStmt>(LoopStmt))
16777 BodyParts.push_back(SourceCXXFor->getLoopVarStmt());
16778 if (static_cast<unsigned>(I) + 1 < NumLoops)
16779 appendStmtsBeforeNestedLoop(LoopStmt, BodyParts);
16780 BodyParts.push_back(Inner);
16781 Inner = CompoundStmt::Create(Context, BodyParts, FPOptionsOverride(),
16782 Inner->getBeginLoc(), Inner->getEndLoc());
16783 Inner = new (Context)
16784 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
16785 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
16786 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
16787 }
16788
16789 // Create grid loops from the inside to the outside.
16790 for (int I = NumLoops - 1; I >= 0; --I) {
16791 auto &LoopHelper = LoopHelpers[I];
16792 Expr *NumIterations = LoopHelper.NumIterations;
16793 DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
16794 QualType IVTy = NumIterations->getType();
16795
16796 // For init-statement: auto .grid.iv = 0
16797 SemaRef.AddInitializerToDecl(
16798 FloorIndVars[I],
16799 SemaRef.ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
16800 /*DirectInit=*/false);
16801 Decl *CounterDecl = FloorIndVars[I];
16802 StmtResult InitStmt = new (Context)
16803 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
16804 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
16805 if (!InitStmt.isUsable())
16806 return StmtError();
16807
16808 // For cond-expression: .floor.iv < NumIterations
16809 ExprResult CondExpr = SemaRef.BuildBinOp(
16810 CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
16811 makeFloorIVRef(SemaRef, FloorIndVars, I, IVTy, OrigCntVar),
16812 NumIterations);
16813 if (!CondExpr.isUsable())
16814 return StmtError();
16815
16816 // For incr-statement: .floor.iv += DimStripeSize
16817 ExprResult IncrStmt = SemaRef.BuildBinOp(
16818 CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
16819 makeFloorIVRef(SemaRef, FloorIndVars, I, IVTy, OrigCntVar),
16820 MakeDimStripeSize(I));
16821 if (!IncrStmt.isUsable())
16822 return StmtError();
16823
16824 Inner = new (Context)
16825 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
16826 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
16827 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
16828 }
16829
16831 Context, StartLoc, EndLoc, Clauses, NumLoops, AStmt, Inner,
16832 buildPreInits(Context, PreInits),
16833 buildLoopFinalization(Context, LoopHelpers, LoopStmts, NestedFinals));
16834}
16835
16837 Stmt *AStmt,
16838 SourceLocation StartLoc,
16839 SourceLocation EndLoc) {
16840 ASTContext &Context = getASTContext();
16841 Scope *CurScope = SemaRef.getCurScope();
16842 // Empty statement should only be possible if there already was an error.
16843 if (!AStmt)
16844 return StmtError();
16845
16847 {OMPC_partial, OMPC_full}))
16848 return StmtError();
16849
16850 const OMPFullClause *FullClause =
16851 OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
16852 const OMPPartialClause *PartialClause =
16853 OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
16854 assert(!(FullClause && PartialClause) &&
16855 "mutual exclusivity must have been checked before");
16856
16857 constexpr unsigned NumLoops = 1;
16858 Stmt *Body = nullptr;
16860 NumLoops);
16861 SmallVector<SmallVector<Stmt *>, NumLoops + 1> OriginalInits;
16862 SmallVector<Stmt *, 4> NestedFinals;
16863 if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
16864 Body, OriginalInits, &NestedFinals))
16865 return StmtError();
16866
16867 unsigned NumGeneratedTopLevelLoops = PartialClause ? 1 : 0;
16868
16869 // Delay unrolling to when template is completely instantiated.
16870 if (SemaRef.CurContext->isDependentContext())
16871 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
16872 NumGeneratedTopLevelLoops, nullptr,
16873 nullptr, nullptr);
16874
16875 assert(LoopHelpers.size() == NumLoops &&
16876 "Expecting a single-dimensional loop iteration space");
16877 assert(OriginalInits.size() == NumLoops &&
16878 "Expecting a single-dimensional loop iteration space");
16879 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
16880
16881 if (FullClause) {
16883 LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
16884 /*SuppressExprDiags=*/true)
16885 .isUsable()) {
16886 Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
16887 Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
16888 << "#pragma omp unroll full";
16889 return StmtError();
16890 }
16891 }
16892
16893 // The generated loop may only be passed to other loop-associated directive
16894 // when a partial clause is specified. Without the requirement it is
16895 // sufficient to generate loop unroll metadata at code-generation.
16896 if (NumGeneratedTopLevelLoops == 0)
16897 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
16898 NumGeneratedTopLevelLoops, nullptr,
16899 nullptr, nullptr);
16900
16901 // Otherwise, we need to provide a de-sugared/transformed AST that can be
16902 // associated with another loop directive.
16903 //
16904 // The canonical loop analysis return by checkTransformableLoopNest assumes
16905 // the following structure to be the same loop without transformations or
16906 // directives applied: \code OriginalInits; LoopHelper.PreInits;
16907 // LoopHelper.Counters;
16908 // for (; IV < LoopHelper.NumIterations; ++IV) {
16909 // LoopHelper.Updates;
16910 // Body;
16911 // }
16912 // \endcode
16913 // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
16914 // and referenced by LoopHelper.IterationVarRef.
16915 //
16916 // The unrolling directive transforms this into the following loop:
16917 // \code
16918 // OriginalInits; \
16919 // LoopHelper.PreInits; > NewPreInits
16920 // LoopHelper.Counters; /
16921 // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
16922 // #pragma clang loop unroll_count(Factor)
16923 // for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
16924 // {
16925 // LoopHelper.Updates;
16926 // Body;
16927 // }
16928 // }
16929 // \endcode
16930 // where UIV is a new logical iteration counter. IV must be the same VarDecl
16931 // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
16932 // references it. If the partially unrolled loop is associated with another
16933 // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
16934 // analyze this loop, i.e. the outer loop must fulfill the constraints of an
16935 // OpenMP canonical loop. The inner loop is not an associable canonical loop
16936 // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
16937 // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
16938 // property of the OMPLoopBasedDirective instead of statements in
16939 // CompoundStatement. This is to allow the loop to become a non-outermost loop
16940 // of a canonical loop nest where these PreInits are emitted before the
16941 // outermost directive.
16942
16943 // Find the loop statement.
16944 Stmt *LoopStmt = nullptr;
16945 collectLoopStmts(AStmt, {LoopStmt});
16946
16947 // Determine the PreInit declarations.
16948 SmallVector<Stmt *, 4> PreInits;
16949 addLoopPreInits(Context, LoopHelper, LoopStmt, OriginalInits[0], PreInits);
16950
16951 auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
16952 QualType IVTy = IterationVarRef->getType();
16953 assert(LoopHelper.Counters.size() == 1 &&
16954 "Expecting a single-dimensional loop iteration space");
16955 auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
16956
16957 // Determine the unroll factor.
16958 uint64_t Factor;
16959 SourceLocation FactorLoc;
16960 if (Expr *FactorVal = PartialClause->getFactor();
16961 FactorVal && !FactorVal->containsErrors()) {
16962 Factor = FactorVal->getIntegerConstantExpr(Context)->getLimitedValue();
16963 FactorLoc = FactorVal->getExprLoc();
16964 } else {
16965 // TODO: Use a better profitability model.
16966 Factor = llvm::omp::DefaultPartialUnrollFactor;
16967 }
16968 assert(Factor > 0 && "Expected positive unroll factor");
16969 auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
16971 getASTContext(), llvm::APInt(getASTContext().getIntWidth(IVTy), Factor),
16972 IVTy, FactorLoc);
16973 };
16974
16975 // Iteration variable SourceLocations.
16976 SourceLocation OrigVarLoc = OrigVar->getExprLoc();
16977 SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
16978 SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
16979
16980 // Internal variable names.
16981 std::string OrigVarName = OrigVar->getNameInfo().getAsString();
16982 std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
16983 std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
16984
16985 // Create the iteration variable for the unrolled loop.
16986 VarDecl *OuterIVDecl =
16987 buildVarDecl(SemaRef, {}, IVTy, OuterIVName, nullptr, OrigVar);
16988 auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
16989 return buildDeclRefExpr(SemaRef, OuterIVDecl, IVTy, OrigVarLoc);
16990 };
16991
16992 // Iteration variable for the inner loop: Reuse the iteration variable created
16993 // by checkOpenMPLoop.
16994 auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
16995 InnerIVDecl->setDeclName(&SemaRef.PP.getIdentifierTable().get(InnerIVName));
16996 auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
16997 return buildDeclRefExpr(SemaRef, InnerIVDecl, IVTy, OrigVarLoc);
16998 };
16999
17000 // Make a copy of the NumIterations expression for each use: By the AST
17001 // constraints, every expression object in a DeclContext must be unique.
17002 CaptureVars CopyTransformer(SemaRef);
17003 auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
17004 return AssertSuccess(
17005 CopyTransformer.TransformExpr(LoopHelper.NumIterations));
17006 };
17007
17008 // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
17009 ExprResult LValueConv = SemaRef.DefaultLvalueConversion(MakeOuterRef());
17010 SemaRef.AddInitializerToDecl(InnerIVDecl, LValueConv.get(),
17011 /*DirectInit=*/false);
17012 StmtResult InnerInit = new (Context)
17013 DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
17014 if (!InnerInit.isUsable())
17015 return StmtError();
17016
17017 // Inner For cond-expression:
17018 // \code
17019 // .unroll_inner.iv < .unrolled.iv + Factor &&
17020 // .unroll_inner.iv < NumIterations
17021 // \endcode
17022 // This conjunction of two conditions allows ScalarEvolution to derive the
17023 // maximum trip count of the inner loop.
17024 ExprResult EndOfTile =
17025 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_Add,
17026 MakeOuterRef(), MakeFactorExpr());
17027 if (!EndOfTile.isUsable())
17028 return StmtError();
17029 ExprResult InnerCond1 =
17030 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
17031 MakeInnerRef(), EndOfTile.get());
17032 if (!InnerCond1.isUsable())
17033 return StmtError();
17034 ExprResult InnerCond2 =
17035 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
17036 MakeInnerRef(), MakeNumIterations());
17037 if (!InnerCond2.isUsable())
17038 return StmtError();
17039 ExprResult InnerCond =
17040 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
17041 InnerCond1.get(), InnerCond2.get());
17042 if (!InnerCond.isUsable())
17043 return StmtError();
17044
17045 // Inner For incr-statement: ++.unroll_inner.iv
17046 ExprResult InnerIncr = SemaRef.BuildUnaryOp(
17047 CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, MakeInnerRef());
17048 if (!InnerIncr.isUsable())
17049 return StmtError();
17050
17051 // Inner For statement.
17052 SmallVector<Stmt *> InnerBodyStmts;
17053 InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
17054 if (auto *CXXRangeFor = dyn_cast<CXXForRangeStmt>(LoopStmt))
17055 InnerBodyStmts.push_back(CXXRangeFor->getLoopVarStmt());
17056 InnerBodyStmts.push_back(Body);
17057 CompoundStmt *InnerBody =
17059 Body->getBeginLoc(), Body->getEndLoc());
17060 ForStmt *InnerFor = new (Context)
17061 ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
17062 InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
17063 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
17064
17065 // Unroll metadata for the inner loop.
17066 // This needs to take into account the remainder portion of the unrolled loop,
17067 // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
17068 // supports multiple loop exits. Instead, unroll using a factor equivalent to
17069 // the maximum trip count, which will also generate a remainder loop. Just
17070 // `unroll(enable)` (which could have been useful if the user has not
17071 // specified a concrete factor; even though the outer loop cannot be
17072 // influenced anymore, would avoid more code bloat than necessary) will refuse
17073 // the loop because "Won't unroll; remainder loop could not be generated when
17074 // assuming runtime trip count". Even if it did work, it must not choose a
17075 // larger unroll factor than the maximum loop length, or it would always just
17076 // execute the remainder loop.
17077 LoopHintAttr *UnrollHintAttr =
17078 LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
17079 LoopHintAttr::Numeric, MakeFactorExpr());
17080 AttributedStmt *InnerUnrolled = AttributedStmt::Create(
17081 getASTContext(), StartLoc, {UnrollHintAttr}, InnerFor);
17082
17083 // Outer For init-statement: auto .unrolled.iv = 0
17084 SemaRef.AddInitializerToDecl(
17085 OuterIVDecl,
17086 SemaRef.ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
17087 /*DirectInit=*/false);
17088 StmtResult OuterInit = new (Context)
17089 DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
17090 if (!OuterInit.isUsable())
17091 return StmtError();
17092
17093 // Outer For cond-expression: .unrolled.iv < NumIterations
17094 ExprResult OuterConde =
17095 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
17096 MakeOuterRef(), MakeNumIterations());
17097 if (!OuterConde.isUsable())
17098 return StmtError();
17099
17100 // Outer For incr-statement: .unrolled.iv += Factor
17101 ExprResult OuterIncr =
17102 SemaRef.BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
17103 MakeOuterRef(), MakeFactorExpr());
17104 if (!OuterIncr.isUsable())
17105 return StmtError();
17106
17107 // Outer For statement.
17108 ForStmt *OuterFor = new (Context)
17109 ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
17110 OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
17111 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
17112
17114 Context, StartLoc, EndLoc, Clauses, AStmt, NumGeneratedTopLevelLoops,
17115 OuterFor, buildPreInits(Context, PreInits),
17116 buildLoopFinalization(Context, LoopHelpers, LoopStmt, NestedFinals));
17117}
17118
17120 SourceLocation StartLoc,
17121 SourceLocation EndLoc) {
17122 ASTContext &Context = getASTContext();
17123 Scope *CurScope = SemaRef.getCurScope();
17124
17125 // Empty statement should only be possible if there already was an error.
17126 if (!AStmt)
17127 return StmtError();
17128
17129 constexpr unsigned NumLoops = 1;
17130 Stmt *Body = nullptr;
17132 NumLoops);
17133 SmallVector<SmallVector<Stmt *>, NumLoops + 1> OriginalInits;
17134 SmallVector<Stmt *, 4> NestedFinals;
17135 if (!checkTransformableLoopNest(OMPD_reverse, AStmt, NumLoops, LoopHelpers,
17136 Body, OriginalInits, &NestedFinals))
17137 return StmtError();
17138
17139 // Delay applying the transformation to when template is completely
17140 // instantiated.
17141 if (SemaRef.CurContext->isDependentContext())
17142 return OMPReverseDirective::Create(Context, StartLoc, EndLoc, AStmt,
17143 NumLoops, nullptr, nullptr, nullptr);
17144
17145 assert(LoopHelpers.size() == NumLoops &&
17146 "Expecting a single-dimensional loop iteration space");
17147 assert(OriginalInits.size() == NumLoops &&
17148 "Expecting a single-dimensional loop iteration space");
17149 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
17150
17151 // Find the loop statement.
17152 Stmt *LoopStmt = nullptr;
17153 collectLoopStmts(AStmt, {LoopStmt});
17154
17155 // Determine the PreInit declarations.
17156 SmallVector<Stmt *> PreInits;
17157 addLoopPreInits(Context, LoopHelper, LoopStmt, OriginalInits[0], PreInits);
17158
17159 auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
17160 QualType IVTy = IterationVarRef->getType();
17161 uint64_t IVWidth = Context.getTypeSize(IVTy);
17162 auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
17163
17164 // Iteration variable SourceLocations.
17165 SourceLocation OrigVarLoc = OrigVar->getExprLoc();
17166 SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
17167 SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
17168
17169 // Locations pointing to the transformation.
17170 SourceLocation TransformLoc = StartLoc;
17171 SourceLocation TransformLocBegin = StartLoc;
17172 SourceLocation TransformLocEnd = EndLoc;
17173
17174 // Internal variable names.
17175 std::string OrigVarName = OrigVar->getNameInfo().getAsString();
17176 SmallString<64> ForwardIVName(".forward.iv.");
17177 ForwardIVName += OrigVarName;
17178 SmallString<64> ReversedIVName(".reversed.iv.");
17179 ReversedIVName += OrigVarName;
17180
17181 // LoopHelper.Updates will read the logical iteration number from
17182 // LoopHelper.IterationVarRef, compute the value of the user loop counter of
17183 // that logical iteration from it, then assign it to the user loop counter
17184 // variable. We cannot directly use LoopHelper.IterationVarRef as the
17185 // induction variable of the generated loop because it may cause an underflow:
17186 // \code{.c}
17187 // for (unsigned i = 0; i < n; ++i)
17188 // body(i);
17189 // \endcode
17190 //
17191 // Naive reversal:
17192 // \code{.c}
17193 // for (unsigned i = n-1; i >= 0; --i)
17194 // body(i);
17195 // \endcode
17196 //
17197 // Instead, we introduce a new iteration variable representing the logical
17198 // iteration counter of the original loop, convert it to the logical iteration
17199 // number of the reversed loop, then let LoopHelper.Updates compute the user's
17200 // loop iteration variable from it.
17201 // \code{.cpp}
17202 // for (auto .forward.iv = 0; .forward.iv < n; ++.forward.iv) {
17203 // auto .reversed.iv = n - .forward.iv - 1;
17204 // i = (.reversed.iv + 0) * 1; // LoopHelper.Updates
17205 // body(i); // Body
17206 // }
17207 // \endcode
17208
17209 // Subexpressions with more than one use. One of the constraints of an AST is
17210 // that every node object must appear at most once, hence we define a lambda
17211 // that creates a new AST node at every use.
17212 CaptureVars CopyTransformer(SemaRef);
17213 auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
17214 return AssertSuccess(
17215 CopyTransformer.TransformExpr(LoopHelper.NumIterations));
17216 };
17217
17218 // Create the iteration variable for the forward loop (from 0 to n-1).
17219 VarDecl *ForwardIVDecl =
17220 buildVarDecl(SemaRef, {}, IVTy, ForwardIVName, nullptr, OrigVar);
17221 auto MakeForwardRef = [&SemaRef = this->SemaRef, ForwardIVDecl, IVTy,
17222 OrigVarLoc]() {
17223 return buildDeclRefExpr(SemaRef, ForwardIVDecl, IVTy, OrigVarLoc);
17224 };
17225
17226 // Iteration variable for the reversed induction variable (from n-1 downto 0):
17227 // Reuse the iteration variable created by checkOpenMPLoop.
17228 auto *ReversedIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
17229 ReversedIVDecl->setDeclName(
17230 &SemaRef.PP.getIdentifierTable().get(ReversedIVName));
17231
17232 // For init-statement:
17233 // \code{.cpp}
17234 // auto .forward.iv = 0;
17235 // \endcode
17236 auto *Zero = IntegerLiteral::Create(Context, llvm::APInt::getZero(IVWidth),
17237 ForwardIVDecl->getType(), OrigVarLoc);
17238 SemaRef.AddInitializerToDecl(ForwardIVDecl, Zero, /*DirectInit=*/false);
17239 StmtResult Init = new (Context)
17240 DeclStmt(DeclGroupRef(ForwardIVDecl), OrigVarLocBegin, OrigVarLocEnd);
17241 if (!Init.isUsable())
17242 return StmtError();
17243
17244 // Forward iv cond-expression:
17245 // \code{.cpp}
17246 // .forward.iv < MakeNumIterations()
17247 // \endcode
17248 ExprResult Cond =
17249 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
17250 MakeForwardRef(), MakeNumIterations());
17251 if (!Cond.isUsable())
17252 return StmtError();
17253
17254 // Forward incr-statement:
17255 // \code{.c}
17256 // ++.forward.iv
17257 // \endcode
17258 ExprResult Incr = SemaRef.BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
17259 UO_PreInc, MakeForwardRef());
17260 if (!Incr.isUsable())
17261 return StmtError();
17262
17263 // Reverse the forward-iv:
17264 // \code{.cpp}
17265 // auto .reversed.iv = MakeNumIterations() - 1 - .forward.iv
17266 // \endcode
17267 auto *One = IntegerLiteral::Create(Context, llvm::APInt(IVWidth, 1), IVTy,
17268 TransformLoc);
17269 ExprResult Minus = SemaRef.BuildBinOp(CurScope, TransformLoc, BO_Sub,
17270 MakeNumIterations(), One);
17271 if (!Minus.isUsable())
17272 return StmtError();
17273 Minus = SemaRef.BuildBinOp(CurScope, TransformLoc, BO_Sub, Minus.get(),
17274 MakeForwardRef());
17275 if (!Minus.isUsable())
17276 return StmtError();
17277 StmtResult InitReversed = new (Context) DeclStmt(
17278 DeclGroupRef(ReversedIVDecl), TransformLocBegin, TransformLocEnd);
17279 if (!InitReversed.isUsable())
17280 return StmtError();
17281 SemaRef.AddInitializerToDecl(ReversedIVDecl, Minus.get(),
17282 /*DirectInit=*/false);
17283
17284 // The new loop body.
17285 SmallVector<Stmt *, 4> BodyStmts;
17286 BodyStmts.reserve(LoopHelper.Updates.size() + 2 +
17287 (isa<CXXForRangeStmt>(LoopStmt) ? 1 : 0));
17288 BodyStmts.push_back(InitReversed.get());
17289 llvm::append_range(BodyStmts, LoopHelper.Updates);
17290 if (auto *CXXRangeFor = dyn_cast<CXXForRangeStmt>(LoopStmt))
17291 BodyStmts.push_back(CXXRangeFor->getLoopVarStmt());
17292 BodyStmts.push_back(Body);
17293 auto *ReversedBody =
17294 CompoundStmt::Create(Context, BodyStmts, FPOptionsOverride(),
17295 Body->getBeginLoc(), Body->getEndLoc());
17296
17297 // Finally create the reversed For-statement.
17298 auto *ReversedFor = new (Context)
17299 ForStmt(Context, Init.get(), Cond.get(), nullptr, Incr.get(),
17300 ReversedBody, LoopHelper.Init->getBeginLoc(),
17301 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
17303 Context, StartLoc, EndLoc, AStmt, NumLoops, ReversedFor,
17304 buildPreInits(Context, PreInits),
17305 buildLoopFinalization(Context, LoopHelpers, LoopStmt, NestedFinals));
17306}
17307
17308/// Build the AST for \#pragma omp split counts(c1, c2, ...).
17309///
17310/// Splits the single associated loop into N consecutive loops, where N is the
17311/// number of count expressions.
17313 Stmt *AStmt,
17314 SourceLocation StartLoc,
17315 SourceLocation EndLoc) {
17316 ASTContext &Context = getASTContext();
17317 Scope *CurScope = SemaRef.getCurScope();
17318
17319 // Empty statement should only be possible if there already was an error.
17320 if (!AStmt)
17321 return StmtError();
17322
17323 const auto *CountsClause =
17324 OMPExecutableDirective::getSingleClause<OMPCountsClause>(Clauses);
17325 if (!CountsClause)
17326 return StmtError();
17327
17328 // Split applies to a single loop; check it is transformable and get helpers.
17329 constexpr unsigned NumLoops = 1;
17330 Stmt *Body = nullptr;
17332 NumLoops);
17333 SmallVector<SmallVector<Stmt *>, NumLoops + 1> OriginalInits;
17334 SmallVector<Stmt *, 4> NestedFinals;
17335 if (!checkTransformableLoopNest(OMPD_split, AStmt, NumLoops, LoopHelpers,
17336 Body, OriginalInits, &NestedFinals))
17337 return StmtError();
17338
17339 // Delay applying the transformation to when template is completely
17340 // instantiated.
17341 if (SemaRef.CurContext->isDependentContext())
17342 return OMPSplitDirective::Create(Context, StartLoc, EndLoc, Clauses,
17343 NumLoops, AStmt, nullptr, nullptr,
17344 nullptr);
17345
17346 assert(LoopHelpers.size() == NumLoops &&
17347 "Expecting a single-dimensional loop iteration space");
17348 assert(OriginalInits.size() == NumLoops &&
17349 "Expecting a single-dimensional loop iteration space");
17350 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
17351
17352 // Find the loop statement.
17353 Stmt *LoopStmt = nullptr;
17354 collectLoopStmts(AStmt, {LoopStmt});
17355
17356 // Determine the PreInit declarations.
17357 SmallVector<Stmt *> PreInits;
17358 addLoopPreInits(Context, LoopHelper, LoopStmt, OriginalInits[0], PreInits);
17359
17360 // Type and name of the original loop variable; we create one IV per segment
17361 // and assign it to the original var so the body sees the same name.
17362 auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
17363 QualType IVTy = IterationVarRef->getType();
17364 uint64_t IVWidth = Context.getTypeSize(IVTy);
17365 auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
17366
17367 // Iteration variable SourceLocations.
17368 SourceLocation OrigVarLoc = OrigVar->getExprLoc();
17369 SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
17370 SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
17371 // Internal variable names.
17372 std::string OrigVarName = OrigVar->getNameInfo().getAsString();
17373
17374 if (!CountsClause->hasOmpFill())
17375 return StmtError();
17376 unsigned FillIdx = *CountsClause->getOmpFillIndex();
17377
17378 unsigned NumItems = CountsClause->getNumCounts();
17379 SmallVector<uint64_t, 4> CountValues(NumItems, 0);
17380 ArrayRef<Expr *> Refs = CountsClause->getCountsRefs();
17381 for (unsigned I = 0; I < NumItems; ++I) {
17382 if (I == FillIdx)
17383 continue;
17384 Expr *CountExpr = Refs[I];
17385 if (!CountExpr)
17386 return OMPSplitDirective::Create(Context, StartLoc, EndLoc, Clauses,
17387 NumLoops, AStmt, nullptr, nullptr,
17388 nullptr);
17389 std::optional<llvm::APSInt> OptVal =
17390 CountExpr->getIntegerConstantExpr(Context);
17391 if (!OptVal || OptVal->isNegative())
17392 return OMPSplitDirective::Create(Context, StartLoc, EndLoc, Clauses,
17393 NumLoops, AStmt, nullptr, nullptr,
17394 nullptr);
17395 CountValues[I] = OptVal->getLimitedValue();
17396 }
17397
17398 Expr *NumIterExpr = LoopHelper.NumIterations;
17399
17400 uint64_t RightSum = 0;
17401 for (unsigned I = FillIdx + 1; I < NumItems; ++I)
17402 RightSum += CountValues[I];
17403
17404 auto MakeIntLit = [&](uint64_t Val) {
17405 return IntegerLiteral::Create(Context, llvm::APInt(IVWidth, Val), IVTy,
17406 OrigVarLoc);
17407 };
17408
17409 size_t NumSegments = NumItems;
17410 SmallVector<Stmt *, 4> SplitLoops;
17411
17412 auto *IterVarDecl = cast<VarDecl>(IterationVarRef->getDecl());
17413 SplitLoops.push_back(new (Context) DeclStmt(DeclGroupRef(IterVarDecl),
17414 IterationVarRef->getBeginLoc(),
17415 IterationVarRef->getEndLoc()));
17416
17417 uint64_t LeftAccum = 0;
17418 uint64_t RightRemaining = RightSum;
17419
17420 for (size_t Seg = 0; Seg < NumSegments; ++Seg) {
17421 Expr *StartExpr = nullptr;
17422 Expr *EndExpr = nullptr;
17423
17424 if (Seg < FillIdx) {
17425 StartExpr = MakeIntLit(LeftAccum);
17426 LeftAccum += CountValues[Seg];
17427 EndExpr = MakeIntLit(LeftAccum);
17428 } else if (Seg == FillIdx) {
17429 StartExpr = MakeIntLit(LeftAccum);
17430 if (RightRemaining == 0) {
17431 EndExpr = NumIterExpr;
17432 } else {
17433 ExprResult Sub =
17434 SemaRef.BuildBinOp(CurScope, OrigVarLoc, BO_Sub, NumIterExpr,
17435 MakeIntLit(RightRemaining));
17436 if (!Sub.isUsable())
17437 return StmtError();
17438 EndExpr = Sub.get();
17439 }
17440 } else {
17441 if (RightRemaining == RightSum) {
17442 if (RightSum == 0)
17443 StartExpr = NumIterExpr;
17444 else {
17445 ExprResult Sub =
17446 SemaRef.BuildBinOp(CurScope, OrigVarLoc, BO_Sub, NumIterExpr,
17447 MakeIntLit(RightRemaining));
17448 if (!Sub.isUsable())
17449 return StmtError();
17450 StartExpr = Sub.get();
17451 }
17452 } else {
17453 ExprResult Sub =
17454 SemaRef.BuildBinOp(CurScope, OrigVarLoc, BO_Sub, NumIterExpr,
17455 MakeIntLit(RightRemaining));
17456 if (!Sub.isUsable())
17457 return StmtError();
17458 StartExpr = Sub.get();
17459 }
17460 RightRemaining -= CountValues[Seg];
17461 if (RightRemaining == 0)
17462 EndExpr = NumIterExpr;
17463 else {
17464 ExprResult Sub =
17465 SemaRef.BuildBinOp(CurScope, OrigVarLoc, BO_Sub, NumIterExpr,
17466 MakeIntLit(RightRemaining));
17467 if (!Sub.isUsable())
17468 return StmtError();
17469 EndExpr = Sub.get();
17470 }
17471 }
17472
17473 SmallString<64> IVName(".split.iv.");
17474 IVName += (Twine(Seg) + "." + OrigVarName).str();
17475 VarDecl *IVDecl = buildVarDecl(SemaRef, {}, IVTy, IVName, nullptr, OrigVar);
17476 auto MakeIVRef = [&SemaRef = this->SemaRef, IVDecl, IVTy, OrigVarLoc]() {
17477 return buildDeclRefExpr(SemaRef, IVDecl, IVTy, OrigVarLoc);
17478 };
17479
17480 SemaRef.AddInitializerToDecl(IVDecl, StartExpr, /*DirectInit=*/false);
17481 StmtResult InitStmt = new (Context)
17482 DeclStmt(DeclGroupRef(IVDecl), OrigVarLocBegin, OrigVarLocEnd);
17483 if (!InitStmt.isUsable())
17484 return StmtError();
17485
17486 ExprResult CondExpr = SemaRef.BuildBinOp(
17487 CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeIVRef(), EndExpr);
17488 if (!CondExpr.isUsable())
17489 return StmtError();
17490
17491 ExprResult IncrExpr = SemaRef.BuildUnaryOp(
17492 CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, MakeIVRef());
17493 if (!IncrExpr.isUsable())
17494 return StmtError();
17495
17496 ExprResult IVAssign = SemaRef.BuildBinOp(CurScope, OrigVarLoc, BO_Assign,
17497 IterationVarRef, MakeIVRef());
17498 if (!IVAssign.isUsable())
17499 return StmtError();
17500
17501 SmallVector<Stmt *, 4> BodyStmts;
17502 BodyStmts.push_back(IVAssign.get());
17503 BodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
17504 if (auto *CXXRangeFor = dyn_cast<CXXForRangeStmt>(LoopStmt)) {
17505 if (Seg == 0) {
17506 BodyStmts.push_back(CXXRangeFor->getLoopVarStmt());
17507 } else {
17508 VarDecl *LoopVar = CXXRangeFor->getLoopVariable();
17510 SemaRef, LoopVar, LoopVar->getType().getNonReferenceType(),
17511 OrigVarLoc);
17512 ExprResult LVAssign = SemaRef.BuildBinOp(
17513 CurScope, OrigVarLoc, BO_Assign, LVRef, LoopVar->getInit());
17514 if (!LVAssign.isUsable())
17515 return StmtError();
17516 BodyStmts.push_back(LVAssign.get());
17517 }
17518 }
17519 BodyStmts.push_back(Body);
17520
17521 auto *LoopBody =
17522 CompoundStmt::Create(Context, BodyStmts, FPOptionsOverride(),
17523 Body->getBeginLoc(), Body->getEndLoc());
17524
17525 auto *For = new (Context)
17526 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
17527 IncrExpr.get(), LoopBody, LoopHelper.Init->getBeginLoc(),
17528 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
17529 SplitLoops.push_back(For);
17530 }
17531
17532 auto *SplitStmt = CompoundStmt::Create(
17533 Context, SplitLoops, FPOptionsOverride(),
17534 SplitLoops.front()->getBeginLoc(), SplitLoops.back()->getEndLoc());
17535
17537 Context, StartLoc, EndLoc, Clauses, NumLoops, AStmt, SplitStmt,
17538 buildPreInits(Context, PreInits),
17539 buildLoopFinalization(Context, LoopHelpers, LoopStmt, NestedFinals));
17540}
17541
17543 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
17544 SourceLocation EndLoc) {
17545 ASTContext &Context = getASTContext();
17546 DeclContext *CurContext = SemaRef.CurContext;
17547 Scope *CurScope = SemaRef.getCurScope();
17548
17549 // Empty statement should only be possible if there already was an error.
17550 if (!AStmt)
17551 return StmtError();
17552
17553 // interchange without permutation clause swaps two loops.
17554 const OMPPermutationClause *PermutationClause =
17555 OMPExecutableDirective::getSingleClause<OMPPermutationClause>(Clauses);
17556 size_t NumLoops = PermutationClause ? PermutationClause->getNumLoops() : 2;
17557
17558 // Verify and diagnose loop nest.
17560 Stmt *Body = nullptr;
17561 SmallVector<SmallVector<Stmt *>, 2> OriginalInits;
17562 SmallVector<Stmt *, 4> NestedFinals;
17563 if (!checkTransformableLoopNest(OMPD_interchange, AStmt, NumLoops,
17564 LoopHelpers, Body, OriginalInits,
17565 &NestedFinals))
17566 return StmtError();
17567
17568 // Delay interchange to when template is completely instantiated.
17569 if (CurContext->isDependentContext())
17570 return OMPInterchangeDirective::Create(Context, StartLoc, EndLoc, Clauses,
17571 NumLoops, AStmt, nullptr, nullptr,
17572 nullptr);
17573
17574 // An invalid expression in the permutation clause is set to nullptr in
17575 // ActOnOpenMPPermutationClause.
17576 if (PermutationClause &&
17577 llvm::is_contained(PermutationClause->getArgsRefs(), nullptr))
17578 return StmtError();
17579
17580 assert(LoopHelpers.size() == NumLoops &&
17581 "Expecting loop iteration space dimensionaly to match number of "
17582 "affected loops");
17583 assert(OriginalInits.size() == NumLoops &&
17584 "Expecting loop iteration space dimensionaly to match number of "
17585 "affected loops");
17586
17587 // Decode the permutation clause.
17588 SmallVector<uint64_t, 2> Permutation;
17589 if (!PermutationClause) {
17590 Permutation = {1, 0};
17591 } else {
17592 ArrayRef<Expr *> PermArgs = PermutationClause->getArgsRefs();
17593 llvm::BitVector Flags(PermArgs.size());
17594 for (Expr *PermArg : PermArgs) {
17595 std::optional<llvm::APSInt> PermCstExpr =
17596 PermArg->getIntegerConstantExpr(Context);
17597 if (!PermCstExpr)
17598 continue;
17599 uint64_t PermInt = PermCstExpr->getLimitedValue();
17600 assert(1 <= PermInt && PermInt <= NumLoops &&
17601 "Must be a permutation; diagnostic emitted in "
17602 "ActOnOpenMPPermutationClause");
17603 if (Flags[PermInt - 1]) {
17604 SourceRange ExprRange(PermArg->getBeginLoc(), PermArg->getEndLoc());
17605 Diag(PermArg->getExprLoc(),
17606 diag::err_omp_interchange_permutation_value_repeated)
17607 << PermInt << ExprRange;
17608 continue;
17609 }
17610 Flags[PermInt - 1] = true;
17611
17612 Permutation.push_back(PermInt - 1);
17613 }
17614
17615 if (Permutation.size() != NumLoops)
17616 return StmtError();
17617 }
17618
17619 // Nothing to transform with trivial permutation.
17620 if (NumLoops <= 1 || llvm::all_of(llvm::enumerate(Permutation), [](auto P) {
17621 auto [Idx, Arg] = P;
17622 return Idx == Arg;
17623 }))
17624 return OMPInterchangeDirective::Create(Context, StartLoc, EndLoc, Clauses,
17625 NumLoops, AStmt, AStmt, nullptr,
17626 nullptr);
17627
17628 // Find the affected loops.
17629 SmallVector<Stmt *> LoopStmts(NumLoops, nullptr);
17630 collectLoopStmts(AStmt, LoopStmts);
17631
17632 // Collect pre-init statements on the order before the permuation.
17633 SmallVector<Stmt *> PreInits;
17634 for (auto I : llvm::seq<int>(NumLoops)) {
17635 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
17636
17637 assert(LoopHelper.Counters.size() == 1 &&
17638 "Single-dimensional loop iteration space expected");
17639
17640 guardNestedLoopInit(Context, LoopHelpers, I, OriginalInits[I]);
17641 addLoopPreInits(Context, LoopHelper, LoopStmts[I], OriginalInits[I],
17642 PreInits);
17643 }
17644
17645 SmallVector<VarDecl *> PermutedIndVars(NumLoops);
17646 CaptureVars CopyTransformer(SemaRef);
17647
17648 // True if no loop of the nest has a zero trip count.
17649 auto MakeNotEmpty = [&]() -> Expr * {
17650 Expr *NotEmpty = nullptr;
17651 for (const OMPLoopBasedDirective::HelperExprs &Helper : LoopHelpers) {
17652 Expr *NumIters =
17653 AssertSuccess(CopyTransformer.TransformExpr(Helper.NumIterations));
17654 Expr *HasIters = AssertSuccess(SemaRef.BuildBinOp(
17655 CurScope, NumIters->getExprLoc(), BO_NE, NumIters,
17656 SemaRef.ActOnIntegerConstant(NumIters->getExprLoc(), 0).get()));
17657 NotEmpty = NotEmpty ? AssertSuccess(SemaRef.BuildBinOp(
17658 CurScope, HasIters->getExprLoc(), BO_LAnd,
17659 NotEmpty, HasIters))
17660 : HasIters;
17661 }
17662 return NotEmpty;
17663 };
17664
17665 // Create the permuted loops from the inside to the outside of the
17666 // interchanged loop nest. Body of the innermost new loop is the original
17667 // innermost body.
17668 Stmt *Inner = Body;
17669 for (auto TargetIdx : llvm::reverse(llvm::seq<int>(NumLoops))) {
17670 // Get the original loop that belongs to this new position.
17671 uint64_t SourceIdx = Permutation[TargetIdx];
17672 OMPLoopBasedDirective::HelperExprs &SourceHelper = LoopHelpers[SourceIdx];
17673 Stmt *SourceLoopStmt = LoopStmts[SourceIdx];
17674 assert(SourceHelper.Counters.size() == 1 &&
17675 "Single-dimensional loop iteration space expected");
17676 auto *OrigCntVar = cast<DeclRefExpr>(SourceHelper.Counters.front());
17677
17678 // Normalized loop counter variable: From 0 to n-1, always an integer type.
17679 DeclRefExpr *IterVarRef = cast<DeclRefExpr>(SourceHelper.IterationVarRef);
17680 QualType IVTy = IterVarRef->getType();
17681 assert(IVTy->isIntegerType() &&
17682 "Expected the logical iteration counter to be an integer");
17683
17684 std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
17685 SourceLocation OrigVarLoc = IterVarRef->getExprLoc();
17686
17687 // Make a copy of the NumIterations expression for each use: By the AST
17688 // constraints, every expression object in a DeclContext must be unique.
17689 auto MakeNumIterations = [&CopyTransformer, &SourceHelper]() -> Expr * {
17690 return AssertSuccess(
17691 CopyTransformer.TransformExpr(SourceHelper.NumIterations));
17692 };
17693
17694 // Iteration variable for the permuted loop. Reuse the one from
17695 // checkOpenMPLoop which will also be used to update the original loop
17696 // variable.
17697 SmallString<64> PermutedCntName(".permuted_");
17698 PermutedCntName.append({llvm::utostr(TargetIdx), ".iv.", OrigVarName});
17699 auto *PermutedCntDecl = cast<VarDecl>(IterVarRef->getDecl());
17700 PermutedCntDecl->setDeclName(
17701 &SemaRef.PP.getIdentifierTable().get(PermutedCntName));
17702 PermutedIndVars[TargetIdx] = PermutedCntDecl;
17703 auto MakePermutedRef = [this, PermutedCntDecl, IVTy, OrigVarLoc]() {
17704 return buildDeclRefExpr(SemaRef, PermutedCntDecl, IVTy, OrigVarLoc);
17705 };
17706
17707 // For init-statement:
17708 // \code
17709 // auto .permuted_{target}.iv = 0
17710 // \endcode
17711 ExprResult Zero = SemaRef.ActOnIntegerConstant(OrigVarLoc, 0);
17712 if (!Zero.isUsable())
17713 return StmtError();
17714 SemaRef.AddInitializerToDecl(PermutedCntDecl, Zero.get(),
17715 /*DirectInit=*/false);
17716 StmtResult InitStmt = new (Context)
17717 DeclStmt(DeclGroupRef(PermutedCntDecl), OrigCntVar->getBeginLoc(),
17718 OrigCntVar->getEndLoc());
17719 if (!InitStmt.isUsable())
17720 return StmtError();
17721
17722 // For cond-expression:
17723 // \code
17724 // .permuted_{target}.iv < MakeNumIterations()
17725 // \endcode
17726 Expr *UpperBound = MakeNumIterations();
17727 // The outermost loop runs only if the iteration space is not empty, so
17728 // that no loop variable is assigned when an original loop has none.
17729 if (TargetIdx == 0) {
17730 ExprResult NoIterations = SemaRef.ActOnIntegerConstant(OrigVarLoc, 0);
17731 ExprResult Guarded =
17732 SemaRef.ActOnConditionalOp(OrigVarLoc, OrigVarLoc, MakeNotEmpty(),
17733 UpperBound, NoIterations.get());
17734 if (!Guarded.isUsable())
17735 return StmtError();
17736 UpperBound = Guarded.get();
17737 }
17738 ExprResult CondExpr =
17739 SemaRef.BuildBinOp(CurScope, SourceHelper.Cond->getExprLoc(), BO_LT,
17740 MakePermutedRef(), UpperBound);
17741 if (!CondExpr.isUsable())
17742 return StmtError();
17743
17744 // For incr-statement:
17745 // \code
17746 // ++.tile.iv
17747 // \endcode
17748 ExprResult IncrStmt = SemaRef.BuildUnaryOp(
17749 CurScope, SourceHelper.Inc->getExprLoc(), UO_PreInc, MakePermutedRef());
17750 if (!IncrStmt.isUsable())
17751 return StmtError();
17752
17753 SmallVector<Stmt *, 4> BodyParts(SourceHelper.Updates.begin(),
17754 SourceHelper.Updates.end());
17755 if (auto *SourceCXXFor = dyn_cast<CXXForRangeStmt>(SourceLoopStmt))
17756 BodyParts.push_back(SourceCXXFor->getLoopVarStmt());
17757 BodyParts.push_back(Inner);
17758 Inner = CompoundStmt::Create(Context, BodyParts, FPOptionsOverride(),
17759 Inner->getBeginLoc(), Inner->getEndLoc());
17760 Inner = new (Context) ForStmt(
17761 Context, InitStmt.get(), CondExpr.get(), nullptr, IncrStmt.get(), Inner,
17762 SourceHelper.Init->getBeginLoc(), SourceHelper.Init->getBeginLoc(),
17763 SourceHelper.Inc->getEndLoc());
17764 }
17765
17767 Context, StartLoc, EndLoc, Clauses, NumLoops, AStmt, Inner,
17768 buildPreInits(Context, PreInits),
17769 buildLoopFinalization(Context, LoopHelpers, LoopStmts, NestedFinals));
17770}
17771
17774 Stmt *AStmt, SourceLocation StartLoc,
17775 SourceLocation EndLoc) {
17776 ASTContext &Context = getASTContext();
17777 DeclContext *CurContext = SemaRef.CurContext;
17778 Scope *CurScope = SemaRef.getCurScope();
17779
17780 // Empty statement should only be possible if there already was an error.
17781 if (!AStmt)
17782 return StmtError();
17783
17784 // flatten without 'depth' clause combines two loops; 'depth(k)' selects k.
17785 unsigned NumLoops = 2;
17786 bool DepthIsDependent = false;
17787 const auto *DepthClause =
17788 OMPExecutableDirective::getSingleClause<OMPDepthClause>(Clauses);
17789 if (DepthClause) {
17790 Expr *DepthExpr = DepthClause->getDepth();
17791 if (DepthExpr && DepthExpr->isInstantiationDependent()) {
17792 DepthIsDependent = true;
17793 } else if (DepthExpr) {
17794 Expr::EvalResult EvalResult;
17795 if (DepthExpr->EvaluateAsInt(EvalResult, Context))
17796 NumLoops = EvalResult.Val.getInt().getLimitedValue(
17797 std::numeric_limits<unsigned>::max());
17798 }
17799 }
17800
17801 // Count perfectly nested loops with doForAllLoops. When 'depth' is present,
17802 // walk NumLoops iterations to diagnose an insufficient nest. When it is
17803 // omitted, walk one extra loop (3 total) so we can warn that default
17804 // flatten only combines 2 of a deeper nest.
17805 if (!DepthIsDependent) {
17806 unsigned WalkLimit = DepthClause ? NumLoops : 3;
17807 unsigned Found = 0;
17808 bool Enough = OMPLoopBasedDirective::doForAllLoops(
17809 AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false,
17810 WalkLimit, [&](unsigned Cnt, Stmt *S) {
17811 if (!isa<ForStmt>(S) && !isa<CXXForRangeStmt>(S))
17812 return true;
17813 Found = Cnt + 1;
17814 return false;
17815 });
17816 if (DepthClause && !Enough) {
17817 Diag(AStmt->getBeginLoc(), diag::err_omp_not_for)
17818 << /*expected N for loops form=*/1
17819 << getOpenMPDirectiveName(OMPD_flatten) << NumLoops << (Found > 0)
17820 << Found;
17821 return StmtError();
17822 }
17823 if (!DepthClause && Found >= 3) {
17824 Diag(StartLoc, diag::warn_omp_flatten_omitted_depth);
17825 if (SemaRef.getLangOpts().OpenMP >= 61)
17826 Diag(StartLoc, diag::note_omp_flatten_insert_depth)
17827 << FixItHint::CreateInsertion(EndLoc, " depth(2)");
17828 }
17829 }
17830
17831 // Defer when 'depth' is instantiation-dependent (concrete k unknown until
17832 // instantiation).
17833 if (DepthIsDependent)
17834 return OMPFlattenDirective::Create(Context, StartLoc, EndLoc, Clauses,
17835 NumLoops, AStmt, nullptr, nullptr,
17836 nullptr);
17837
17838 // Verify and diagnose loop nest.
17840 Stmt *Body = nullptr;
17841 SmallVector<SmallVector<Stmt *>, 4> OriginalInits;
17842 SmallVector<Stmt *, 4> NestedFinals;
17843 if (!checkTransformableLoopNest(OMPD_flatten, AStmt, NumLoops, LoopHelpers,
17844 Body, OriginalInits, &NestedFinals))
17845 return StmtError();
17846
17847 // Delay flattening to when template is completely instantiated.
17848 if (CurContext->isDependentContext())
17849 return OMPFlattenDirective::Create(Context, StartLoc, EndLoc, Clauses,
17850 NumLoops, AStmt, nullptr, nullptr,
17851 nullptr);
17852
17853 assert(LoopHelpers.size() == NumLoops &&
17854 "Expecting loop iteration space dimensionality to match number of "
17855 "affected loops");
17856 assert(OriginalInits.size() == NumLoops &&
17857 "Expecting loop iteration space dimensionality to match number of "
17858 "affected loops");
17859
17860 // Find the affected loops.
17861 SmallVector<Stmt *> LoopStmts(NumLoops, nullptr);
17862 collectLoopStmts(AStmt, LoopStmts);
17863
17864 // Collect pre-init statements in outer-to-inner order.
17865 SmallVector<Stmt *> PreInits;
17866 for (auto I : llvm::seq<unsigned>(NumLoops)) {
17867 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
17868 assert(LoopHelper.Counters.size() == 1 &&
17869 "Single-dimensional loop iteration space expected");
17870 guardNestedLoopInit(Context, LoopHelpers, I, OriginalInits[I]);
17871 addLoopPreInits(Context, LoopHelper, LoopStmts[I], OriginalInits[I],
17872 PreInits);
17873 }
17874
17875 CaptureVars CopyTransformer(SemaRef);
17876 // Convert a non-integer trip count. Width matches buildNumIterations.
17877 // Signedness follows an integer loop variable so a float count stays signed.
17878 auto MakeNumIterations = [&CopyTransformer, &LoopHelpers, &Context,
17879 &SemaRef =
17880 this->SemaRef](unsigned I) -> ExprResult {
17881 ExprResult N = CopyTransformer.TransformExpr(LoopHelpers[I].NumIterations);
17882 if (!N.isUsable())
17883 return ExprError();
17884 QualType Type = N.get()->getType();
17885 if (Type->isIntegerType())
17886 return N;
17887 const auto *Counter = cast<DeclRefExpr>(LoopHelpers[I].Counters.front());
17888 QualType VarType = Counter->getType().getNonReferenceType();
17889 bool VarIsInt = VarType->hasIntegerRepresentation();
17890 bool UseVarWidth =
17891 VarIsInt && Context.getTypeSize(Type) > Context.getTypeSize(VarType);
17892 unsigned NewSize =
17893 UseVarWidth ? Context.getTypeSize(VarType) : Context.getTypeSize(Type);
17894 bool IsSigned = VarIsInt ? VarType->hasSignedIntegerRepresentation()
17896 QualType IntTy = getIntTypeForBitwidthOrBitInt(Context, NewSize, IsSigned);
17897 N = SemaRef.PerformImplicitConversion(
17898 N.get(), IntTy, AssignmentAction::Converting, /*AllowExplicit=*/true);
17899 if (!N.isUsable())
17900 return ExprError();
17901 return N;
17902 };
17903
17904 OMPLoopBasedDirective::HelperExprs &OutermostHelper = LoopHelpers[0];
17905 auto *OutermostCntVar = cast<DeclRefExpr>(OutermostHelper.Counters.front());
17906 SourceLocation OrigVarLoc = OutermostCntVar->getExprLoc();
17907 SourceLocation OrigVarLocBegin = OutermostCntVar->getBeginLoc();
17908 SourceLocation OrigVarLocEnd = OutermostCntVar->getEndLoc();
17909 SourceLocation CondLoc = OutermostHelper.Cond->getExprLoc();
17910
17911 // Product of trip counts; mirror 'collapse' IV-width selection to avoid
17912 // overflow when several counts are multiplied.
17913 auto BuildTripCount = [&](unsigned Bits) -> ExprResult {
17914 ExprResult Product;
17915 for (unsigned I = 0; I < NumLoops; ++I) {
17916 ExprResult N = MakeNumIterations(I);
17917 if (!N.isUsable())
17918 return ExprError();
17919 N = widenIterationCount(Bits, N.get(), SemaRef);
17920 if (!N.isUsable())
17921 return ExprError();
17922 if (I == 0)
17923 Product = N;
17924 else
17925 Product = SemaRef.BuildBinOp(CurScope, CondLoc, BO_Mul, Product.get(),
17926 N.get());
17927 if (!Product.isUsable())
17928 return ExprError();
17929 }
17930 return Product;
17931 };
17932
17933 bool AllCountsLessThan32Bits =
17934 llvm::all_of(llvm::seq<unsigned>(NumLoops), [&](unsigned I) {
17935 return Context.getTypeSize(LoopHelpers[I].NumIterations->getType()) <
17936 32;
17937 });
17938
17939 ExprResult TripCount;
17940 if (AllCountsLessThan32Bits || NumLoops == 1) {
17941 TripCount = BuildTripCount(/*Bits=*/32);
17942 } else {
17943 ExprResult TripCount64 = BuildTripCount(/*Bits=*/64);
17944 if (!TripCount64.isUsable())
17945 return StmtError();
17946 TripCount = TripCount64;
17947 if (TripCount64.get()->isIntegerConstantExpr(Context)) {
17948 ExprResult TripCount32 = BuildTripCount(/*Bits=*/32);
17949 if (TripCount32.isUsable() &&
17950 Context.getTypeSize(TripCount32.get()->getType()) == 32 &&
17951 fitsInto(
17952 /*Bits=*/32,
17953 TripCount32.get()->getType()->hasSignedIntegerRepresentation(),
17954 TripCount64.get(), SemaRef))
17955 TripCount = TripCount32;
17956 }
17957 }
17958 if (!TripCount.isUsable())
17959 return StmtError();
17960
17961 QualType IVTy = TripCount.get()->getType();
17962 uint64_t IVWidth = Context.getTypeSize(IVTy);
17963
17964 // Build a condition that is true if the outermost \p Count loops all have at
17965 // least one iteration.
17966 auto BuildHasIterations = [&](unsigned Count) -> ExprResult {
17968 for (unsigned I = 0; I < Count; ++I) {
17969 ExprResult LoopPreCond =
17970 CopyTransformer.TransformExpr(LoopHelpers[I].PreCond);
17971 if (!LoopPreCond.isUsable())
17972 return ExprError();
17973 if (I == 0)
17974 Result = LoopPreCond;
17975 else
17976 Result = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LAnd, Result.get(),
17977 LoopPreCond.get());
17978 if (!Result.isUsable())
17979 return ExprError();
17980 }
17981 return Result;
17982 };
17983
17984 // NumIterations may wrap or overflow when an empty loop has extreme runtime
17985 // bounds. Test whether every original loop has at least one iteration before
17986 // evaluating their product.
17987 ExprResult HasIterations = BuildHasIterations(NumLoops);
17988 if (!HasIterations.isUsable())
17989 return StmtError();
17990 Expr *ZeroTripCount = IntegerLiteral::Create(
17991 Context, llvm::APInt::getZero(IVWidth), IVTy, CondLoc);
17992 TripCount = SemaRef.ActOnConditionalOp(CondLoc, CondLoc, HasIterations.get(),
17993 TripCount.get(), ZeroTripCount);
17994 if (!TripCount.isUsable())
17995 return StmtError();
17996
17997 auto MakeNumIterationsInIVTy = [&](unsigned I) -> ExprResult {
17998 ExprResult N = MakeNumIterations(I);
17999 if (!N.isUsable())
18000 return ExprError();
18001 return SemaRef.PerformImplicitConversion(
18002 N.get(), IVTy, AssignmentAction::Converting, /*AllowExplicit=*/true);
18003 };
18004
18005 // Divisors in index recovery use (N == 0 ? 1 : N) so a zero trip count does
18006 // not warn.
18007 auto MakeDivisorInIVTy = [&](unsigned I) -> ExprResult {
18008 ExprResult N = MakeNumIterationsInIVTy(I);
18009 ExprResult NCmp = MakeNumIterationsInIVTy(I);
18010 if (!N.isUsable() || !NCmp.isUsable())
18011 return ExprError();
18012 auto MakeCst = [&](uint64_t V) -> Expr * {
18013 return IntegerLiteral::Create(Context, llvm::APInt(IVWidth, V), IVTy,
18014 CondLoc);
18015 };
18016 ExprResult IsZero =
18017 SemaRef.BuildBinOp(CurScope, CondLoc, BO_EQ, NCmp.get(), MakeCst(0));
18018 if (!IsZero.isUsable())
18019 return N;
18020 return SemaRef.ActOnConditionalOp(CondLoc, CondLoc, IsZero.get(),
18021 MakeCst(1), N.get());
18022 };
18023
18024 // \code{.cpp}
18025 // for (auto .flatten.iv = 0; .flatten.iv < n0 * n1 * ...; ++.flatten.iv) {
18026 // .flatten.iv.0 = .flatten.iv / (n1 * ...);
18027 // i0 = ...; // Updates[0]
18028 // .flatten.iv.1 = (.flatten.iv / ...) % n1;
18029 // i1 = ...; // Updates[1]
18030 // ...
18031 // body(i0, i1, ...);
18032 // }
18033 // \endcode
18034 SmallString<64> FlattenedIVName(".flatten.iv");
18035 VarDecl *FlattenedIVDecl = buildVarDecl(SemaRef, {}, IVTy, FlattenedIVName,
18036 nullptr, OutermostCntVar);
18037 auto MakeFlattenedRef = [&SemaRef = this->SemaRef, FlattenedIVDecl, IVTy,
18038 OrigVarLoc]() {
18039 return buildDeclRefExpr(SemaRef, FlattenedIVDecl, IVTy, OrigVarLoc);
18040 };
18041
18042 // For init-statement:
18043 // \code{.cpp}
18044 // auto .flatten.iv = 0;
18045 // \endcode
18046 auto *Zero = IntegerLiteral::Create(Context, llvm::APInt::getZero(IVWidth),
18047 IVTy, OrigVarLoc);
18048 SemaRef.AddInitializerToDecl(FlattenedIVDecl, Zero, /*DirectInit=*/false);
18049 StmtResult Init = new (Context)
18050 DeclStmt(DeclGroupRef(FlattenedIVDecl), OrigVarLocBegin, OrigVarLocEnd);
18051 if (!Init.isUsable())
18052 return StmtError();
18053
18054 // For cond-expression:
18055 // \code{.cpp}
18056 // .flatten.iv < n0 * n1 * ... * n(k-1)
18057 // \endcode
18058 ExprResult Cond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT,
18059 MakeFlattenedRef(), TripCount.get());
18060 if (!Cond.isUsable())
18061 return StmtError();
18062
18063 // For incr-statement:
18064 // \code{.cpp}
18065 // ++.flatten.iv
18066 // \endcode
18067 ExprResult Incr =
18068 SemaRef.BuildUnaryOp(CurScope, OutermostHelper.Inc->getExprLoc(),
18069 UO_PreInc, MakeFlattenedRef());
18070 if (!Incr.isUsable())
18071 return StmtError();
18072
18073 // Recover each logical iteration counter via mixed-radix div/mod; reuse the
18074 // iteration variables from checkOpenMPLoop so Updates compute user counters.
18075 SmallVector<Stmt *, 8> BodyStmts;
18076 for (unsigned I = 0; I < NumLoops; ++I) {
18077 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
18078 auto *IVRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
18079 auto *IVDecl = cast<VarDecl>(IVRef->getDecl());
18080 std::string IVName = (".flatten.iv." + llvm::Twine(I)).str();
18081 IVDecl->setDeclName(&SemaRef.PP.getIdentifierTable().get(IVName));
18082
18083 ExprResult Value = MakeFlattenedRef();
18084 if (I + 1 < NumLoops) {
18085 ExprResult Divisor = MakeDivisorInIVTy(I + 1);
18086 if (!Divisor.isUsable())
18087 return StmtError();
18088 for (unsigned J = I + 2; J < NumLoops; ++J) {
18089 ExprResult Next = MakeDivisorInIVTy(J);
18090 if (!Next.isUsable())
18091 return StmtError();
18092 Divisor = SemaRef.BuildBinOp(CurScope, OrigVarLoc, BO_Mul,
18093 Divisor.get(), Next.get());
18094 if (!Divisor.isUsable())
18095 return StmtError();
18096 }
18097 Value = SemaRef.BuildBinOp(CurScope, OrigVarLoc, BO_Div, Value.get(),
18098 Divisor.get());
18099 if (!Value.isUsable())
18100 return StmtError();
18101 }
18102 if (I > 0) {
18103 ExprResult RemDivisor = MakeDivisorInIVTy(I);
18104 if (!RemDivisor.isUsable())
18105 return StmtError();
18106 Value = SemaRef.BuildBinOp(CurScope, OrigVarLoc, BO_Rem, Value.get(),
18107 RemDivisor.get());
18108 if (!Value.isUsable())
18109 return StmtError();
18110 }
18111
18112 SemaRef.AddInitializerToDecl(IVDecl, Value.get(), /*DirectInit=*/false);
18113 StmtResult IVStmt = new (Context)
18114 DeclStmt(DeclGroupRef(IVDecl), OrigVarLocBegin, OrigVarLocEnd);
18115 if (!IVStmt.isUsable())
18116 return StmtError();
18117
18118 BodyStmts.push_back(IVStmt.get());
18119 llvm::append_range(BodyStmts, LoopHelper.Updates);
18120 if (auto *CXXFor = dyn_cast<CXXForRangeStmt>(LoopStmts[I]))
18121 BodyStmts.push_back(CXXFor->getLoopVarStmt());
18122 }
18123 BodyStmts.push_back(Body);
18124 auto *FlattenedBody =
18125 CompoundStmt::Create(Context, BodyStmts, FPOptionsOverride(),
18126 Body->getBeginLoc(), Body->getEndLoc());
18127
18128 auto *FlattenedFor = new (Context) ForStmt(
18129 Context, Init.get(), Cond.get(), nullptr, Incr.get(), FlattenedBody,
18130 OutermostHelper.Init->getBeginLoc(), OutermostHelper.Init->getBeginLoc(),
18131 OutermostHelper.Inc->getEndLoc());
18132
18133 // A counter only reaches its final value if its own loop and all enclosing
18134 // loops execute at least one iteration; otherwise it keeps the value assigned
18135 // by the pre-inits. Guarding also avoids evaluating 'start + n * step' for an
18136 // empty loop, whose trip count may have wrapped.
18138 for (unsigned I = 0; I < NumLoops; ++I) {
18139 assert(LoopHelpers[I].Finals.size() == 1 &&
18140 "Single-dimensional loop iteration space expected");
18141 ExprResult Final =
18142 CopyTransformer.TransformExpr(LoopHelpers[I].Finals.front());
18143 if (!Final.isUsable())
18144 return StmtError();
18145 ExprResult FinalCond = BuildHasIterations(/*Count=*/I + 1);
18146 if (!FinalCond.isUsable())
18147 return StmtError();
18148 // If the loop has its own directive (e.g. reverse), restore its variable.
18149 Stmt *Then = Final.get();
18150 if (Stmt *Nested = NestedFinals[I])
18151 Then = CompoundStmt::Create(Context, {Then, Nested}, FPOptionsOverride(),
18152 CondLoc, CondLoc);
18153 Finals.push_back(IfStmt::Create(Context, CondLoc, IfStatementKind::Ordinary,
18154 nullptr, nullptr, FinalCond.get(), CondLoc,
18155 CondLoc, Then, SourceLocation(), nullptr));
18156 }
18157 Stmt *FinalsStmt = CompoundStmt::Create(Context, Finals, FPOptionsOverride(),
18158 FlattenedFor->getBeginLoc(),
18159 FlattenedFor->getEndLoc());
18160
18162 Context, StartLoc, EndLoc, Clauses, NumLoops, AStmt, FlattenedFor,
18163 buildPreInits(Context, PreInits), FinalsStmt);
18164}
18165
18167 Stmt *AStmt,
18168 SourceLocation StartLoc,
18169 SourceLocation EndLoc) {
18170
18171 ASTContext &Context = getASTContext();
18172 DeclContext *CurrContext = SemaRef.CurContext;
18173 Scope *CurScope = SemaRef.getCurScope();
18174 CaptureVars CopyTransformer(SemaRef);
18175
18176 // Ensure the structured block is not empty
18177 if (!AStmt)
18178 return StmtError();
18179
18180 if (const auto *DepthC =
18181 OMPExecutableDirective::getSingleClause<OMPDepthClause>(Clauses)) {
18182 Diag(DepthC->getBeginLoc(), diag::err_omp_clause_not_supported_yet)
18183 << "depth" << getOpenMPDirectiveName(OMPD_fuse);
18184 return StmtError();
18185 }
18186
18187 // Defer transformation in dependent contexts
18188 // The NumLoopNests argument is set to a placeholder 1 (even though
18189 // using looprange fuse could yield up to 3 top level loop nests)
18190 // because a dependent context could prevent determining its true value
18191 if (CurrContext->isDependentContext())
18192 return OMPFuseDirective::Create(Context, StartLoc, EndLoc, Clauses,
18193 /* NumLoops */ 1, AStmt, nullptr, nullptr,
18194 nullptr);
18195
18196 // Validate that the potential loop sequence is transformable for fusion
18197 // Also collect the HelperExprs, Loop Stmts, Inits, and Number of loops
18198 LoopSequenceAnalysis SeqAnalysis;
18199 if (!checkTransformableLoopSequence(OMPD_fuse, AStmt, SeqAnalysis, Context))
18200 return StmtError();
18201
18202 // SeqAnalysis.LoopSeqSize exists mostly to handle dependent contexts,
18203 // otherwise it must be the same as SeqAnalysis.Loops.size().
18204 assert(SeqAnalysis.LoopSeqSize == SeqAnalysis.Loops.size() &&
18205 "Inconsistent size of the loop sequence and the number of loops "
18206 "found in the sequence");
18207
18208 // Handle clauses, which can be any of the following: [looprange, apply]
18209 const auto *LRC =
18210 OMPExecutableDirective::getSingleClause<OMPLoopRangeClause>(Clauses);
18211
18212 // The clause arguments are invalidated if any error arises
18213 // such as non-constant or non-positive arguments
18214 if (LRC && (!LRC->getFirst() || !LRC->getCount()))
18215 return StmtError();
18216
18217 // Delayed semantic check of LoopRange constraint
18218 // Evaluates the loop range arguments and returns the first and count values
18219 auto EvaluateLoopRangeArguments = [&Context](Expr *First, Expr *Count,
18220 uint64_t &FirstVal,
18221 uint64_t &CountVal) {
18222 llvm::APSInt FirstInt = First->EvaluateKnownConstInt(Context);
18223 llvm::APSInt CountInt = Count->EvaluateKnownConstInt(Context);
18224 FirstVal = FirstInt.getLimitedValue();
18225 CountVal = CountInt.getLimitedValue();
18226 };
18227
18228 // OpenMP [6.0, Restrictions]
18229 // first + count - 1 must not evaluate to a value greater than the
18230 // loop sequence length of the associated canonical loop sequence.
18231 auto ValidLoopRange = [](uint64_t FirstVal, uint64_t CountVal,
18232 unsigned NumLoops) -> bool {
18233 return FirstVal + CountVal - 1 <= NumLoops;
18234 };
18235 uint64_t FirstVal = 1, CountVal = 0, LastVal = SeqAnalysis.LoopSeqSize;
18236
18237 // Validates the loop range after evaluating the semantic information
18238 // and ensures that the range is valid for the given loop sequence size.
18239 // Expressions are evaluated at compile time to obtain constant values.
18240 if (LRC) {
18241 EvaluateLoopRangeArguments(LRC->getFirst(), LRC->getCount(), FirstVal,
18242 CountVal);
18243 if (CountVal == 1)
18244 SemaRef.Diag(LRC->getCountLoc(), diag::warn_omp_redundant_fusion)
18245 << getOpenMPDirectiveName(OMPD_fuse);
18246
18247 if (!ValidLoopRange(FirstVal, CountVal, SeqAnalysis.LoopSeqSize)) {
18248 SemaRef.Diag(LRC->getFirstLoc(), diag::err_omp_invalid_looprange)
18249 << getOpenMPDirectiveName(OMPD_fuse) << FirstVal
18250 << (FirstVal + CountVal - 1) << SeqAnalysis.LoopSeqSize;
18251 return StmtError();
18252 }
18253
18254 LastVal = FirstVal + CountVal - 1;
18255 }
18256
18257 // Complete fusion generates a single canonical loop nest
18258 // However looprange clause may generate several loop nests
18259 unsigned NumGeneratedTopLevelLoops =
18260 LRC ? SeqAnalysis.LoopSeqSize - CountVal + 1 : 1;
18261
18262 // Emit a warning for redundant loop fusion when the sequence contains only
18263 // one loop.
18264 if (SeqAnalysis.LoopSeqSize == 1)
18265 SemaRef.Diag(AStmt->getBeginLoc(), diag::warn_omp_redundant_fusion)
18266 << getOpenMPDirectiveName(OMPD_fuse);
18267
18268 // Select the type with the largest bit width among all induction variables
18269 QualType IVType =
18270 SeqAnalysis.Loops[FirstVal - 1].HelperExprs.IterationVarRef->getType();
18271 for (unsigned I : llvm::seq<unsigned>(FirstVal, LastVal)) {
18272 QualType CurrentIVType =
18273 SeqAnalysis.Loops[I].HelperExprs.IterationVarRef->getType();
18274 if (Context.getTypeSize(CurrentIVType) > Context.getTypeSize(IVType)) {
18275 IVType = CurrentIVType;
18276 }
18277 }
18278 uint64_t IVBitWidth = Context.getIntWidth(IVType);
18279
18280 // Create pre-init declarations for all loops lower bounds, upper bounds,
18281 // strides and num-iterations for every top level loop in the fusion
18282 SmallVector<VarDecl *, 4> LBVarDecls;
18283 SmallVector<VarDecl *, 4> STVarDecls;
18284 SmallVector<VarDecl *, 4> NIVarDecls;
18285 SmallVector<VarDecl *, 4> IVVarDecls;
18286
18287 // Helper lambda to create variables for bounds, strides, and other
18288 // expressions. Generates both the variable declaration and the corresponding
18289 // initialization statement.
18290 auto CreateHelperVarAndStmt =
18291 [&, &SemaRef = SemaRef](Expr *ExprToCopy, const std::string &BaseName,
18292 unsigned I, bool NeedsNewVD = false) {
18293 Expr *TransformedExpr =
18294 AssertSuccess(CopyTransformer.TransformExpr(ExprToCopy));
18295 if (!TransformedExpr)
18296 return std::pair<VarDecl *, StmtResult>(nullptr, StmtError());
18297
18298 auto Name = (Twine(".omp.") + BaseName + std::to_string(I)).str();
18299
18300 VarDecl *VD;
18301 if (NeedsNewVD) {
18302 VD = buildVarDecl(SemaRef, SourceLocation(), IVType, Name);
18303 SemaRef.AddInitializerToDecl(VD, TransformedExpr, false);
18304 } else {
18305 // Create a unique variable name
18306 DeclRefExpr *DRE = cast<DeclRefExpr>(TransformedExpr);
18307 VD = cast<VarDecl>(DRE->getDecl());
18308 VD->setDeclName(&SemaRef.PP.getIdentifierTable().get(Name));
18309 }
18310 // Create the corresponding declaration statement
18311 StmtResult DeclStmt = new (Context) class DeclStmt(
18313 return std::make_pair(VD, DeclStmt);
18314 };
18315
18316 // PreInits hold a sequence of variable declarations that must be executed
18317 // before the fused loop begins. These include bounds, strides, and other
18318 // helper variables required for the transformation. Other loop transforms
18319 // also contain their own preinits
18320 SmallVector<Stmt *> PreInits;
18321
18322 // Update the general preinits using the preinits generated by loop sequence
18323 // generating loop transformations. These preinits differ slightly from
18324 // single-loop transformation preinits, as they can be detached from a
18325 // specific loop inside multiple generated loop nests. This happens
18326 // because certain helper variables, like '.omp.fuse.max', are introduced to
18327 // handle fused iteration spaces and may not be directly tied to a single
18328 // original loop. The preinit structure must ensure that hidden variables
18329 // like '.omp.fuse.max' are still properly handled.
18330 // Transformations that apply this concept: Loopranged Fuse, Split
18331 llvm::append_range(PreInits, SeqAnalysis.LoopSequencePreInits);
18332
18333 // Process each single loop to generate and collect declarations
18334 // and statements for all helper expressions related to
18335 // particular single loop nests
18336
18337 // Also In the case of the fused loops, we keep track of their original
18338 // inits by appending them to their preinits statement, and in the case of
18339 // transformations, also append their preinits (which contain the original
18340 // loop initialization statement or other statements)
18341
18342 for (unsigned int I = FirstVal - 1, J = 0; I < LastVal; ++I, ++J) {
18343 if (SeqAnalysis.Loops[I].isRegularLoop()) {
18344 addLoopPreInits(Context, SeqAnalysis.Loops[I].HelperExprs,
18345 SeqAnalysis.Loops[I].TheForStmt,
18346 SeqAnalysis.Loops[I].OriginalInits, PreInits);
18347 } else if (SeqAnalysis.Loops[I].isLoopTransformation()) {
18348 // For transformed loops, insert both pre-inits and original inits.
18349 // Order matters: pre-inits may define variables used in the original
18350 // inits such as upper bounds...
18351 llvm::append_range(PreInits, SeqAnalysis.Loops[I].TransformsPreInits);
18352
18353 addLoopPreInits(Context, SeqAnalysis.Loops[I].HelperExprs,
18354 SeqAnalysis.Loops[I].TheForStmt,
18355 SeqAnalysis.Loops[I].OriginalInits, PreInits);
18356 }
18357 auto [LBVD, LBDStmt] =
18358 CreateHelperVarAndStmt(SeqAnalysis.Loops[I].HelperExprs.LB, "lb", J);
18359 auto [STVD, STDStmt] =
18360 CreateHelperVarAndStmt(SeqAnalysis.Loops[I].HelperExprs.ST, "st", J);
18361 auto [NIVD, NIDStmt] = CreateHelperVarAndStmt(
18362 SeqAnalysis.Loops[I].HelperExprs.NumIterations, "ni", J, true);
18363 auto [IVVD, IVDStmt] = CreateHelperVarAndStmt(
18364 SeqAnalysis.Loops[I].HelperExprs.IterationVarRef, "iv", J);
18365
18366 assert(LBVD && STVD && NIVD && IVVD &&
18367 "OpenMP Fuse Helper variables creation failed");
18368
18369 LBVarDecls.push_back(LBVD);
18370 STVarDecls.push_back(STVD);
18371 NIVarDecls.push_back(NIVD);
18372 IVVarDecls.push_back(IVVD);
18373
18374 PreInits.push_back(LBDStmt.get());
18375 PreInits.push_back(STDStmt.get());
18376 PreInits.push_back(NIDStmt.get());
18377 PreInits.push_back(IVDStmt.get());
18378 }
18379
18380 auto MakeVarDeclRef = [&SemaRef = this->SemaRef](VarDecl *VD) {
18381 return buildDeclRefExpr(SemaRef, VD, VD->getType(), VD->getLocation(),
18382 false);
18383 };
18384
18385 // Following up the creation of the final fused loop will be performed
18386 // which has the following shape (considering the selected loops):
18387 //
18388 // for (fuse.index = 0; fuse.index < max(ni0, ni1..., nik); ++fuse.index) {
18389 // if (fuse.index < ni0){
18390 // iv0 = lb0 + st0 * fuse.index;
18391 // original.index0 = iv0
18392 // body(0);
18393 // }
18394 // if (fuse.index < ni1){
18395 // iv1 = lb1 + st1 * fuse.index;
18396 // original.index1 = iv1
18397 // body(1);
18398 // }
18399 //
18400 // ...
18401 //
18402 // if (fuse.index < nik){
18403 // ivk = lbk + stk * fuse.index;
18404 // original.indexk = ivk
18405 // body(k); Expr *InitVal = IntegerLiteral::Create(Context,
18406 // llvm::APInt(IVWidth, 0),
18407 // }
18408
18409 // 1. Create the initialized fuse index
18410 StringRef IndexName = ".omp.fuse.index";
18411 Expr *InitVal = IntegerLiteral::Create(Context, llvm::APInt(IVBitWidth, 0),
18412 IVType, SourceLocation());
18413 VarDecl *IndexDecl =
18414 buildVarDecl(SemaRef, {}, IVType, IndexName, nullptr, nullptr);
18415 SemaRef.AddInitializerToDecl(IndexDecl, InitVal, false);
18416 StmtResult InitStmt = new (Context)
18418
18419 if (!InitStmt.isUsable())
18420 return StmtError();
18421
18422 auto MakeIVRef = [&SemaRef = this->SemaRef, IndexDecl, IVType,
18423 Loc = InitVal->getExprLoc()]() {
18424 return buildDeclRefExpr(SemaRef, IndexDecl, IVType, Loc, false);
18425 };
18426
18427 // 2. Iteratively compute the max number of logical iterations Max(NI_1, NI_2,
18428 // ..., NI_k)
18429 //
18430 // This loop accumulates the maximum value across multiple expressions,
18431 // ensuring each step constructs a unique AST node for correctness. By using
18432 // intermediate temporary variables and conditional operators, we maintain
18433 // distinct nodes and avoid duplicating subtrees, For instance, max(a,b,c):
18434 // omp.temp0 = max(a, b)
18435 // omp.temp1 = max(omp.temp0, c)
18436 // omp.fuse.max = max(omp.temp1, omp.temp0)
18437
18438 ExprResult MaxExpr;
18439 // I is the range of loops in the sequence that we fuse.
18440 for (unsigned I = FirstVal - 1, J = 0; I < LastVal; ++I, ++J) {
18441 DeclRefExpr *NIRef = MakeVarDeclRef(NIVarDecls[J]);
18442 QualType NITy = NIRef->getType();
18443
18444 if (MaxExpr.isUnset()) {
18445 // Initialize MaxExpr with the first NI expression
18446 MaxExpr = NIRef;
18447 } else {
18448 // Create a new acummulator variable t_i = MaxExpr
18449 std::string TempName = (Twine(".omp.temp.") + Twine(J)).str();
18450 VarDecl *TempDecl =
18451 buildVarDecl(SemaRef, {}, NITy, TempName, nullptr, nullptr);
18452 TempDecl->setInit(MaxExpr.get());
18453 DeclRefExpr *TempRef =
18454 buildDeclRefExpr(SemaRef, TempDecl, NITy, SourceLocation(), false);
18455 DeclRefExpr *TempRef2 =
18456 buildDeclRefExpr(SemaRef, TempDecl, NITy, SourceLocation(), false);
18457 // Add a DeclStmt to PreInits to ensure the variable is declared.
18458 StmtResult TempStmt = new (Context)
18460
18461 if (!TempStmt.isUsable())
18462 return StmtError();
18463 PreInits.push_back(TempStmt.get());
18464
18465 // Build MaxExpr <-(MaxExpr > NIRef ? MaxExpr : NIRef)
18467 SemaRef.BuildBinOp(nullptr, SourceLocation(), BO_GT, TempRef, NIRef);
18468 // Handle any errors in Comparison creation
18469 if (!Comparison.isUsable())
18470 return StmtError();
18471
18472 DeclRefExpr *NIRef2 = MakeVarDeclRef(NIVarDecls[J]);
18473 // Update MaxExpr using a conditional expression to hold the max value
18474 MaxExpr = new (Context) ConditionalOperator(
18475 Comparison.get(), SourceLocation(), TempRef2, SourceLocation(),
18476 NIRef2->getExprStmt(), NITy, VK_LValue, OK_Ordinary);
18477
18478 if (!MaxExpr.isUsable())
18479 return StmtError();
18480 }
18481 }
18482 if (!MaxExpr.isUsable())
18483 return StmtError();
18484
18485 // 3. Declare the max variable
18486 const std::string MaxName = Twine(".omp.fuse.max").str();
18487 VarDecl *MaxDecl =
18488 buildVarDecl(SemaRef, {}, IVType, MaxName, nullptr, nullptr);
18489 MaxDecl->setInit(MaxExpr.get());
18490 DeclRefExpr *MaxRef = buildDeclRefExpr(SemaRef, MaxDecl, IVType, {}, false);
18491 StmtResult MaxStmt = new (Context)
18493
18494 if (MaxStmt.isInvalid())
18495 return StmtError();
18496 PreInits.push_back(MaxStmt.get());
18497
18498 // 4. Create condition Expr: index < n_max
18499 ExprResult CondExpr = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LT,
18500 MakeIVRef(), MaxRef);
18501 if (!CondExpr.isUsable())
18502 return StmtError();
18503
18504 // 5. Increment Expr: ++index
18505 ExprResult IncrExpr =
18506 SemaRef.BuildUnaryOp(CurScope, SourceLocation(), UO_PreInc, MakeIVRef());
18507 if (!IncrExpr.isUsable())
18508 return StmtError();
18509
18510 // 6. Build the Fused Loop Body
18511 // The final fused loop iterates over the maximum logical range. Inside the
18512 // loop, each original loop's index is calculated dynamically, and its body
18513 // is executed conditionally.
18514 //
18515 // Each sub-loop's body is guarded by a conditional statement to ensure
18516 // it executes only within its logical iteration range:
18517 //
18518 // if (fuse.index < ni_k){
18519 // iv_k = lb_k + st_k * fuse.index;
18520 // original.index = iv_k
18521 // body(k);
18522 // }
18523
18524 CompoundStmt *FusedBody = nullptr;
18525 SmallVector<Stmt *, 4> FusedBodyStmts;
18526 for (unsigned I = FirstVal - 1, J = 0; I < LastVal; ++I, ++J) {
18527 // Assingment of the original sub-loop index to compute the logical index
18528 // IV_k = LB_k + omp.fuse.index * ST_k
18529 ExprResult IdxExpr =
18530 SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Mul,
18531 MakeVarDeclRef(STVarDecls[J]), MakeIVRef());
18532 if (!IdxExpr.isUsable())
18533 return StmtError();
18534 IdxExpr = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Add,
18535 MakeVarDeclRef(LBVarDecls[J]), IdxExpr.get());
18536
18537 if (!IdxExpr.isUsable())
18538 return StmtError();
18539 IdxExpr = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_Assign,
18540 MakeVarDeclRef(IVVarDecls[J]), IdxExpr.get());
18541 if (!IdxExpr.isUsable())
18542 return StmtError();
18543
18544 // Update the original i_k = IV_k
18545 SmallVector<Stmt *, 4> BodyStmts;
18546 BodyStmts.push_back(IdxExpr.get());
18547 llvm::append_range(BodyStmts, SeqAnalysis.Loops[I].HelperExprs.Updates);
18548
18549 // If the loop is a CXXForRangeStmt then the iterator variable is needed
18550 if (auto *SourceCXXFor =
18551 dyn_cast<CXXForRangeStmt>(SeqAnalysis.Loops[I].TheForStmt))
18552 BodyStmts.push_back(SourceCXXFor->getLoopVarStmt());
18553
18554 Stmt *Body =
18555 (isa<ForStmt>(SeqAnalysis.Loops[I].TheForStmt))
18556 ? cast<ForStmt>(SeqAnalysis.Loops[I].TheForStmt)->getBody()
18557 : cast<CXXForRangeStmt>(SeqAnalysis.Loops[I].TheForStmt)->getBody();
18558 BodyStmts.push_back(Body);
18559
18560 CompoundStmt *CombinedBody =
18561 CompoundStmt::Create(Context, BodyStmts, FPOptionsOverride(),
18564 SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LT, MakeIVRef(),
18565 MakeVarDeclRef(NIVarDecls[J]));
18566
18567 if (!Condition.isUsable())
18568 return StmtError();
18569
18570 IfStmt *IfStatement = IfStmt::Create(
18571 Context, SourceLocation(), IfStatementKind::Ordinary, nullptr, nullptr,
18572 Condition.get(), SourceLocation(), SourceLocation(), CombinedBody,
18573 SourceLocation(), nullptr);
18574
18575 FusedBodyStmts.push_back(IfStatement);
18576 }
18577 FusedBody = CompoundStmt::Create(Context, FusedBodyStmts, FPOptionsOverride(),
18579
18580 // 7. Construct the final fused loop
18581 ForStmt *FusedForStmt = new (Context)
18582 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, IncrExpr.get(),
18583 FusedBody, InitStmt.get()->getBeginLoc(), SourceLocation(),
18584 IncrExpr.get()->getEndLoc());
18585
18586 // 8. Finals of the fused loops, in sequence order. Out-of-range loops keep
18587 // theirs inline.
18588 SmallVector<Stmt *, 4> AllFinalsStmts;
18589 for (unsigned I : llvm::seq<unsigned>(FirstVal - 1, LastVal)) {
18590 const LoopAnalysis &Loop = SeqAnalysis.Loops[I];
18591 if (Loop.isRegularLoop())
18592 if (Stmt *Own =
18593 buildLoopFinalization(Context, Loop.HelperExprs, Loop.TheForStmt))
18594 AllFinalsStmts.push_back(Own);
18595 if (Loop.TransformFinals)
18596 AllFinalsStmts.push_back(Loop.TransformFinals);
18597 }
18598 Stmt *CombinedFinals = nullptr;
18599 if (AllFinalsStmts.size() == 1)
18600 CombinedFinals = AllFinalsStmts.front();
18601 else if (!AllFinalsStmts.empty())
18602 CombinedFinals =
18603 CompoundStmt::Create(Context, AllFinalsStmts, FPOptionsOverride(),
18605
18606 // In the case of looprange, the result of fuse won't simply
18607 // be a single loop (ForStmt), but rather a loop sequence
18608 // (CompoundStmt) of 3 parts: the pre-fusion loops, the fused loop
18609 // and the post-fusion loops, preserving its original order.
18610 //
18611 // Note: If looprange clause produces a single fused loop nest then
18612 // this compound statement wrapper is unnecessary (Therefore this
18613 // treatment is skipped)
18614
18615 auto WithFinals = [&](Stmt *Loop, Stmt *Finals) -> Stmt * {
18616 return Finals ? CompoundStmt::Create(Context, {Loop, Finals},
18619 : Loop;
18620 };
18621 Stmt *FusionStmt = FusedForStmt;
18622 if (LRC && CountVal != SeqAnalysis.LoopSeqSize) {
18623 SmallVector<Stmt *, 4> FinalLoops;
18624
18625 // Collect all non-fused loops before and after the fused region.
18626 // Pre-fusion and post-fusion loops are inserted in order exploiting their
18627 // symmetry, along with their corresponding transformation pre-inits if
18628 // needed. The fused loop is added between the two regions.
18629 for (unsigned I : llvm::seq<unsigned>(SeqAnalysis.LoopSeqSize)) {
18630 if (I >= FirstVal - 1 && I < FirstVal + CountVal - 1)
18631 continue;
18632
18633 // Out-of-range transformations still need their pre-inits.
18634 if (SeqAnalysis.Loops[I].isLoopTransformation())
18635 llvm::append_range(PreInits, SeqAnalysis.Loops[I].TransformsPreInits);
18636
18637 // For out-of-range loop-transformations, emit their finalization inline
18638 // right after the transformed loop so that IVs are restored as if the
18639 // transformation had not been present (OpenMP 6.0 finalization rule).
18640 FinalLoops.push_back(WithFinals(SeqAnalysis.Loops[I].TheForStmt,
18641 SeqAnalysis.Loops[I].TransformFinals));
18642 }
18643
18644 // Insert the fused loop with its Finals between the pre- and post-fusion
18645 // loops.
18646 FinalLoops.insert(FinalLoops.begin() + (FirstVal - 1),
18647 WithFinals(FusedForStmt, CombinedFinals));
18648 CombinedFinals = nullptr; // emitted inline
18649 FusionStmt = CompoundStmt::Create(Context, FinalLoops, FPOptionsOverride(),
18651 }
18653 Context, StartLoc, EndLoc, Clauses, NumGeneratedTopLevelLoops, AStmt,
18654 FusionStmt, buildPreInits(Context, PreInits), CombinedFinals);
18655}
18656
18658 Expr *Expr,
18659 SourceLocation StartLoc,
18660 SourceLocation LParenLoc,
18661 SourceLocation EndLoc) {
18662 OMPClause *Res = nullptr;
18663 switch (Kind) {
18664 case OMPC_final:
18665 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
18666 break;
18667 case OMPC_safelen:
18668 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
18669 break;
18670 case OMPC_simdlen:
18671 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
18672 break;
18673 case OMPC_allocator:
18674 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
18675 break;
18676 case OMPC_collapse:
18677 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
18678 break;
18679 case OMPC_ordered:
18680 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
18681 break;
18682 case OMPC_nowait:
18683 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc, LParenLoc, Expr);
18684 break;
18685 case OMPC_priority:
18686 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
18687 break;
18688 case OMPC_hint:
18689 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
18690 break;
18691 case OMPC_depobj:
18692 Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
18693 break;
18694 case OMPC_detach:
18695 Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
18696 break;
18697 case OMPC_novariants:
18698 Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
18699 break;
18700 case OMPC_nocontext:
18701 Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
18702 break;
18703 case OMPC_filter:
18704 Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
18705 break;
18706 case OMPC_partial:
18707 Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
18708 break;
18709 case OMPC_depth:
18710 Res = ActOnOpenMPDepthClause(Expr, StartLoc, LParenLoc, EndLoc);
18711 break;
18712 case OMPC_message:
18713 Res = ActOnOpenMPMessageClause(Expr, StartLoc, LParenLoc, EndLoc);
18714 break;
18715 case OMPC_align:
18716 Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc);
18717 break;
18718 case OMPC_ompx_dyn_cgroup_mem:
18719 Res = ActOnOpenMPXDynCGroupMemClause(Expr, StartLoc, LParenLoc, EndLoc);
18720 break;
18721 case OMPC_holds:
18722 Res = ActOnOpenMPHoldsClause(Expr, StartLoc, LParenLoc, EndLoc);
18723 break;
18724 case OMPC_transparent:
18725 Res = ActOnOpenMPTransparentClause(Expr, StartLoc, LParenLoc, EndLoc);
18726 break;
18727 case OMPC_dyn_groupprivate:
18728 case OMPC_grainsize:
18729 case OMPC_num_tasks:
18730 case OMPC_num_threads:
18731 case OMPC_device:
18732 case OMPC_if:
18733 case OMPC_default:
18734 case OMPC_proc_bind:
18735 case OMPC_schedule:
18736 case OMPC_private:
18737 case OMPC_firstprivate:
18738 case OMPC_lastprivate:
18739 case OMPC_shared:
18740 case OMPC_reduction:
18741 case OMPC_task_reduction:
18742 case OMPC_in_reduction:
18743 case OMPC_linear:
18744 case OMPC_aligned:
18745 case OMPC_copyin:
18746 case OMPC_copyprivate:
18747 case OMPC_untied:
18748 case OMPC_mergeable:
18749 case OMPC_threadprivate:
18750 case OMPC_groupprivate:
18751 case OMPC_sizes:
18752 case OMPC_allocate:
18753 case OMPC_flush:
18754 case OMPC_read:
18755 case OMPC_write:
18756 case OMPC_update:
18757 case OMPC_capture:
18758 case OMPC_compare:
18759 case OMPC_seq_cst:
18760 case OMPC_acq_rel:
18761 case OMPC_acquire:
18762 case OMPC_release:
18763 case OMPC_relaxed:
18764 case OMPC_depend:
18765 case OMPC_threads:
18766 case OMPC_simd:
18767 case OMPC_map:
18768 case OMPC_nogroup:
18769 case OMPC_dist_schedule:
18770 case OMPC_defaultmap:
18771 case OMPC_unknown:
18772 case OMPC_uniform:
18773 case OMPC_to:
18774 case OMPC_from:
18775 case OMPC_use_device_ptr:
18776 case OMPC_use_device_addr:
18777 case OMPC_is_device_ptr:
18778 case OMPC_unified_address:
18779 case OMPC_unified_shared_memory:
18780 case OMPC_reverse_offload:
18781 case OMPC_dynamic_allocators:
18782 case OMPC_atomic_default_mem_order:
18783 case OMPC_self_maps:
18784 case OMPC_device_type:
18785 case OMPC_match:
18786 case OMPC_nontemporal:
18787 case OMPC_order:
18788 case OMPC_at:
18789 case OMPC_severity:
18790 case OMPC_destroy:
18791 case OMPC_inclusive:
18792 case OMPC_exclusive:
18793 case OMPC_uses_allocators:
18794 case OMPC_affinity:
18795 case OMPC_when:
18796 case OMPC_bind:
18797 case OMPC_num_teams:
18798 case OMPC_thread_limit:
18799 default:
18800 llvm_unreachable("Clause is not allowed.");
18801 }
18802 return Res;
18803}
18804
18805// An OpenMP directive such as 'target parallel' has two captured regions:
18806// for the 'target' and 'parallel' respectively. This function returns
18807// the region in which to capture expressions associated with a clause.
18808// A return value of OMPD_unknown signifies that the expression should not
18809// be captured.
18812 llvm::omp::Version OMPVersion,
18813 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
18814 assert(isAllowedClauseForDirective(DKind, CKind, OMPVersion) &&
18815 "Invalid directive with CKind-clause");
18816
18817 // Invalid modifier will be diagnosed separately, just return OMPD_unknown.
18818 if (NameModifier != OMPD_unknown &&
18819 !isAllowedClauseForDirective(NameModifier, CKind, OMPVersion))
18820 return OMPD_unknown;
18821
18822 ArrayRef<OpenMPDirectiveKind> Leafs = getLeafConstructsOrSelf(DKind);
18823
18824 // [5.2:341:24-30]
18825 // If the clauses have expressions on them, such as for various clauses where
18826 // the argument of the clause is an expression, or lower-bound, length, or
18827 // stride expressions inside array sections (or subscript and stride
18828 // expressions in subscript-triplet for Fortran), or linear-step or alignment
18829 // expressions, the expressions are evaluated immediately before the construct
18830 // to which the clause has been split or duplicated per the above rules
18831 // (therefore inside of the outer leaf constructs). However, the expressions
18832 // inside the num_teams and thread_limit clauses are always evaluated before
18833 // the outermost leaf construct.
18834
18835 // Process special cases first.
18836 switch (CKind) {
18837 case OMPC_if:
18838 switch (DKind) {
18839 case OMPD_teams_loop:
18840 case OMPD_target_teams_loop:
18841 // For [target] teams loop, assume capture region is 'teams' so it's
18842 // available for codegen later to use if/when necessary.
18843 return OMPD_teams;
18844 case OMPD_target_update:
18845 case OMPD_target_enter_data:
18846 case OMPD_target_exit_data:
18847 return OMPD_task;
18848 default:
18849 break;
18850 }
18851 break;
18852 case OMPC_num_teams:
18853 case OMPC_thread_limit:
18854 case OMPC_ompx_dyn_cgroup_mem:
18855 case OMPC_dyn_groupprivate:
18856 // TODO: This may need to consider teams too.
18857 if (Leafs[0] == OMPD_target)
18858 return OMPD_target;
18859 break;
18860 case OMPC_device:
18861 if (Leafs[0] == OMPD_target ||
18862 llvm::is_contained({OMPD_dispatch, OMPD_target_update,
18863 OMPD_target_enter_data, OMPD_target_exit_data},
18864 DKind))
18865 return OMPD_task;
18866 break;
18867 case OMPC_novariants:
18868 case OMPC_nocontext:
18869 if (DKind == OMPD_dispatch)
18870 return OMPD_task;
18871 break;
18872 case OMPC_when:
18873 if (DKind == OMPD_metadirective)
18874 return OMPD_metadirective;
18875 break;
18876 case OMPC_filter:
18877 return OMPD_unknown;
18878 default:
18879 break;
18880 }
18881
18882 // If none of the special cases above applied, and DKind is a capturing
18883 // directive, find the innermost enclosing leaf construct that allows the
18884 // clause, and returns the corresponding capture region.
18885
18886 auto GetEnclosingRegion = [&](int EndIdx, OpenMPClauseKind Clause) {
18887 // Find the index in "Leafs" of the last leaf that allows the given
18888 // clause. The search will only include indexes [0, EndIdx).
18889 // EndIdx may be set to the index of the NameModifier, if present.
18890 int InnermostIdx = [&]() {
18891 for (int I = EndIdx - 1; I >= 0; --I) {
18892 if (isAllowedClauseForDirective(Leafs[I], Clause, OMPVersion))
18893 return I;
18894 }
18895 return -1;
18896 }();
18897
18898 // Find the nearest enclosing capture region.
18900 for (int I = InnermostIdx - 1; I >= 0; --I) {
18901 if (!isOpenMPCapturingDirective(Leafs[I]))
18902 continue;
18903 Regions.clear();
18904 getOpenMPCaptureRegions(Regions, Leafs[I]);
18905 if (Regions[0] != OMPD_unknown)
18906 return Regions.back();
18907 }
18908 return OMPD_unknown;
18909 };
18910
18911 if (isOpenMPCapturingDirective(DKind)) {
18912 auto GetLeafIndex = [&](OpenMPDirectiveKind Dir) {
18913 for (int I = 0, E = Leafs.size(); I != E; ++I) {
18914 if (Leafs[I] == Dir)
18915 return I + 1;
18916 }
18917 return 0;
18918 };
18919
18920 int End = NameModifier == OMPD_unknown ? Leafs.size()
18921 : GetLeafIndex(NameModifier);
18922 return GetEnclosingRegion(End, CKind);
18923 }
18924
18925 return OMPD_unknown;
18926}
18927
18929 OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc,
18930 SourceLocation LParenLoc, SourceLocation NameModifierLoc,
18931 SourceLocation ColonLoc, SourceLocation EndLoc) {
18932 Expr *ValExpr = Condition;
18933 Stmt *HelperValStmt = nullptr;
18934 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18935 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
18936 !Condition->isInstantiationDependent() &&
18937 !Condition->containsUnexpandedParameterPack()) {
18938 ExprResult Val = SemaRef.CheckBooleanCondition(StartLoc, Condition);
18939 if (Val.isInvalid())
18940 return nullptr;
18941
18942 ValExpr = Val.get();
18943
18944 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18945 CaptureRegion = getOpenMPCaptureRegionForClause(
18946 DKind, OMPC_if, getLangOpts().getOpenMPVersion(), NameModifier);
18947 if (CaptureRegion != OMPD_unknown &&
18948 !SemaRef.CurContext->isDependentContext()) {
18949 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
18950 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18951 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
18952 HelperValStmt = buildPreInits(getASTContext(), Captures);
18953 }
18954 }
18955
18956 return new (getASTContext())
18957 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
18958 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
18959}
18960
18962 SourceLocation StartLoc,
18963 SourceLocation LParenLoc,
18964 SourceLocation EndLoc) {
18965 Expr *ValExpr = Condition;
18966 Stmt *HelperValStmt = nullptr;
18967 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
18968 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
18969 !Condition->isInstantiationDependent() &&
18970 !Condition->containsUnexpandedParameterPack()) {
18971 ExprResult Val = SemaRef.CheckBooleanCondition(StartLoc, Condition);
18972 if (Val.isInvalid())
18973 return nullptr;
18974
18975 ValExpr = SemaRef.MakeFullExpr(Val.get()).get();
18976
18977 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
18978 CaptureRegion = getOpenMPCaptureRegionForClause(
18979 DKind, OMPC_final, getLangOpts().getOpenMPVersion());
18980 if (CaptureRegion != OMPD_unknown &&
18981 !SemaRef.CurContext->isDependentContext()) {
18982 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
18983 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
18984 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
18985 HelperValStmt = buildPreInits(getASTContext(), Captures);
18986 }
18987 }
18988
18989 return new (getASTContext()) OMPFinalClause(
18990 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
18991}
18992
18995 Expr *Op) {
18996 if (!Op)
18997 return ExprError();
18998
18999 class IntConvertDiagnoser : public Sema::ICEConvertDiagnoser {
19000 public:
19001 IntConvertDiagnoser()
19002 : ICEConvertDiagnoser(/*AllowScopedEnumerations=*/false, false, true) {}
19003 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
19004 QualType T) override {
19005 return S.Diag(Loc, diag::err_omp_not_integral) << T;
19006 }
19007 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
19008 QualType T) override {
19009 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
19010 }
19011 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
19012 QualType T,
19013 QualType ConvTy) override {
19014 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
19015 }
19016 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
19017 QualType ConvTy) override {
19018 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
19019 << ConvTy->isEnumeralType() << ConvTy;
19020 }
19021 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
19022 QualType T) override {
19023 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
19024 }
19025 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
19026 QualType ConvTy) override {
19027 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
19028 << ConvTy->isEnumeralType() << ConvTy;
19029 }
19030 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
19031 QualType) override {
19032 llvm_unreachable("conversion functions are permitted");
19033 }
19034 } ConvertDiagnoser;
19035 return SemaRef.PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
19036}
19037
19038static bool
19040 bool StrictlyPositive, bool BuildCapture = false,
19041 OpenMPDirectiveKind DKind = OMPD_unknown,
19042 OpenMPDirectiveKind *CaptureRegion = nullptr,
19043 Stmt **HelperValStmt = nullptr) {
19044 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
19045 !ValExpr->isInstantiationDependent()) {
19046 SourceLocation Loc = ValExpr->getExprLoc();
19048 SemaRef.OpenMP().PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
19049 if (Value.isInvalid())
19050 return false;
19051
19052 ValExpr = Value.get();
19053 // The expression must evaluate to a non-negative integer value.
19054 if (std::optional<llvm::APSInt> Result =
19055 ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
19056 if (Result->isSigned() &&
19057 !((!StrictlyPositive && Result->isNonNegative()) ||
19058 (StrictlyPositive && Result->isStrictlyPositive()))) {
19059 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
19060 << getOpenMPClauseNameForDiag(CKind) << (StrictlyPositive ? 1 : 0)
19061 << ValExpr->getSourceRange();
19062 return false;
19063 }
19064 }
19065 if (!BuildCapture)
19066 return true;
19067 *CaptureRegion = getOpenMPCaptureRegionForClause(
19068 DKind, CKind, SemaRef.getLangOpts().getOpenMPVersion());
19069 if (*CaptureRegion != OMPD_unknown &&
19070 !SemaRef.CurContext->isDependentContext()) {
19071 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
19072 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19073 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
19074 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
19075 }
19076 }
19077 return true;
19078}
19079
19080static std::string getListOfPossibleValues(OpenMPClauseKind K, unsigned First,
19081 unsigned Last,
19082 ArrayRef<unsigned> Exclude = {}) {
19083 SmallString<256> Buffer;
19084 llvm::raw_svector_ostream Out(Buffer);
19085 unsigned Skipped = Exclude.size();
19086 for (unsigned I = First; I < Last; ++I) {
19087 if (llvm::is_contained(Exclude, I)) {
19088 --Skipped;
19089 continue;
19090 }
19091 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
19092 if (I + Skipped + 2 == Last)
19093 Out << " or ";
19094 else if (I + Skipped + 1 != Last)
19095 Out << ", ";
19096 }
19097 return std::string(Out.str());
19098}
19099
19101 ArrayRef<Expr *> VarList, OpenMPNumThreadsClauseModifier SimpleModifier,
19102 SourceLocation SimpleModifierLoc,
19103 OpenMPNumThreadsClauseModifier ComplexModifier, Expr *ComplexModifierExpr,
19104 SourceLocation ComplexModifierLoc, SourceLocation StartLoc,
19105 SourceLocation LParenLoc, SourceLocation EndLoc) {
19106 // Check that modifiers were correctly specified.
19107 if (ComplexModifierLoc.isValid() &&
19108 (ComplexModifier != OMPC_NUMTHREADS_dims || !ComplexModifierExpr)) {
19109 Diag(ComplexModifierLoc, diag::err_omp_malformed_complex_modifier)
19110 << getOpenMPSimpleClauseTypeName(OMPC_num_threads, OMPC_NUMTHREADS_dims)
19111 << getOpenMPClauseName(OMPC_num_threads);
19112 return nullptr;
19113 }
19114 if (SimpleModifierLoc.isValid() && SimpleModifier == OMPC_NUMTHREADS_dims) {
19115 Diag(SimpleModifierLoc, diag::err_omp_malformed_complex_modifier)
19116 << getOpenMPSimpleClauseTypeName(OMPC_num_threads, OMPC_NUMTHREADS_dims)
19117 << getOpenMPClauseName(OMPC_num_threads);
19118 return nullptr;
19119 }
19120 if (SimpleModifierLoc.isValid() && SimpleModifier != OMPC_NUMTHREADS_strict) {
19121 Diag(SimpleModifierLoc, diag::err_omp_unexpected_clause_value)
19122 << getOpenMPSimpleClauseTypeName(OMPC_num_threads,
19123 OMPC_NUMTHREADS_strict)
19124 << getOpenMPClauseName(OMPC_num_threads);
19125 return nullptr;
19126 }
19127
19128 if (VarList.empty())
19129 return nullptr;
19130
19131 SmallVector<Expr *, 3> Vars(VarList.begin(), VarList.end());
19132 for (Expr *&ValExpr : Vars) {
19133 // OpenMP [2.5, Restrictions]
19134 // The num_threads expression must evaluate to a positive integer value.
19135 if (!isNonNegativeIntegerValue(ValExpr, SemaRef, OMPC_num_threads,
19136 /*StrictlyPositive=*/true))
19137 return nullptr;
19138 }
19139
19140 if (ComplexModifier == OMPC_NUMTHREADS_dims) {
19141 ExprResult Res = ActOnOpenMPDimsModifier(OMPC_num_threads, ComplexModifier,
19142 ComplexModifierExpr,
19143 ComplexModifierLoc, Vars, EndLoc);
19144 if (Res.isInvalid())
19145 return nullptr;
19146 ComplexModifierExpr = Res.get();
19147
19148 if (validateMultidimClauseExprs(*this, OMPC_num_threads, StartLoc, Vars,
19149 ComplexModifierExpr))
19150 return nullptr;
19151 }
19152 if (SimpleModifier == OMPC_NUMTHREADS_strict && getLangOpts().OpenMP < 60) {
19153 Diag(SimpleModifierLoc, diag::err_omp_modifier_requires_version)
19154 << getOpenMPSimpleClauseTypeName(OMPC_num_threads, SimpleModifier)
19155 << getOpenMPClauseName(OMPC_num_threads) << "6.0";
19156 return nullptr;
19157 }
19158
19159 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19161 DKind, OMPC_num_threads, getLangOpts().getOpenMPVersion());
19162 if (CaptureRegion == OMPD_unknown || SemaRef.CurContext->isDependentContext())
19164 getASTContext(), CaptureRegion, StartLoc, LParenLoc, EndLoc, Vars,
19165 SimpleModifier, ComplexModifier, SimpleModifierLoc, ComplexModifierLoc,
19166 ComplexModifierExpr, /*PreInit=*/nullptr);
19167
19168 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19169 for (Expr *&ValExpr : Vars) {
19170 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
19171 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
19172 }
19173 if (ComplexModifierExpr) {
19174 ComplexModifierExpr = SemaRef.MakeFullExpr(ComplexModifierExpr).get();
19175 ComplexModifierExpr =
19176 tryBuildCapture(SemaRef, ComplexModifierExpr, Captures).get();
19177 }
19178 Stmt *PreInit = buildPreInits(getASTContext(), Captures);
19179
19181 getASTContext(), CaptureRegion, StartLoc, LParenLoc, EndLoc, Vars,
19182 SimpleModifier, ComplexModifier, SimpleModifierLoc, ComplexModifierLoc,
19183 ComplexModifierExpr, PreInit);
19184}
19185
19187 Expr *E, OpenMPClauseKind CKind, bool StrictlyPositive,
19188 bool SuppressExprDiags) {
19189 if (!E)
19190 return ExprError();
19191 if (E->isValueDependent() || E->isTypeDependent() ||
19193 return E;
19194
19195 llvm::APSInt Result;
19196 ExprResult ICE;
19197 if (SuppressExprDiags) {
19198 // Use a custom diagnoser that suppresses 'note' diagnostics about the
19199 // expression.
19200 struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
19201 SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
19203 diagnoseNotICE(Sema &S, SourceLocation Loc) override {
19204 llvm_unreachable("Diagnostic suppressed");
19205 }
19206 } Diagnoser;
19207 ICE = SemaRef.VerifyIntegerConstantExpression(E, &Result, Diagnoser,
19209 } else {
19210 ICE =
19211 SemaRef.VerifyIntegerConstantExpression(E, &Result,
19212 /*FIXME*/ AllowFoldKind::Allow);
19213 }
19214 if (ICE.isInvalid())
19215 return ExprError();
19216
19217 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
19218 (!StrictlyPositive && !Result.isNonNegative())) {
19219 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
19220 << getOpenMPClauseNameForDiag(CKind) << (StrictlyPositive ? 1 : 0)
19221 << E->getSourceRange();
19222 return ExprError();
19223 }
19224 if ((CKind == OMPC_aligned || CKind == OMPC_align ||
19225 CKind == OMPC_allocate) &&
19226 !Result.isPowerOf2()) {
19227 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
19228 << E->getSourceRange();
19229 return ExprError();
19230 }
19231
19232 if (!Result.isRepresentableByInt64()) {
19233 Diag(E->getExprLoc(), diag::err_omp_large_expression_in_clause)
19235 return ExprError();
19236 }
19237
19238 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
19239 DSAStack->setAssociatedLoops(Result.getExtValue());
19240 else if (CKind == OMPC_ordered)
19241 DSAStack->setAssociatedLoops(Result.getExtValue());
19242 return ICE;
19243}
19244
19245void SemaOpenMP::setOpenMPDeviceNum(int Num) { DeviceNum = Num; }
19246
19247void SemaOpenMP::setOpenMPDeviceNumID(StringRef ID) { DeviceNumID = ID; }
19248
19249int SemaOpenMP::getOpenMPDeviceNum() const { return DeviceNum; }
19250
19252 llvm::APSInt Result;
19253 Expr::EvalResult EvalResult;
19254 // Evaluate the expression to an integer value
19255 if (!DeviceNumExpr->isValueDependent() &&
19256 DeviceNumExpr->EvaluateAsInt(EvalResult, SemaRef.Context)) {
19257 // The device expression must evaluate to a non-negative integer value.
19258 Result = EvalResult.Val.getInt();
19259 if (Result.isNonNegative()) {
19260 setOpenMPDeviceNum(Result.getZExtValue());
19261 } else {
19262 Diag(DeviceNumExpr->getExprLoc(),
19263 diag::err_omp_negative_expression_in_clause)
19264 << "device_num" << 0 << DeviceNumExpr->getSourceRange();
19265 }
19266 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(DeviceNumExpr)) {
19267 // Check if the expression is an identifier
19268 IdentifierInfo *IdInfo = DeclRef->getDecl()->getIdentifier();
19269 if (IdInfo) {
19270 setOpenMPDeviceNumID(IdInfo->getName());
19271 }
19272 } else {
19273 Diag(DeviceNumExpr->getExprLoc(), diag::err_expected_expression);
19274 }
19275}
19276
19278 SourceLocation StartLoc,
19279 SourceLocation LParenLoc,
19280 SourceLocation EndLoc) {
19281 // OpenMP [2.8.1, simd construct, Description]
19282 // The parameter of the safelen clause must be a constant
19283 // positive integer expression.
19284 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
19285 if (Safelen.isInvalid())
19286 return nullptr;
19287 return new (getASTContext())
19288 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
19289}
19290
19292 SourceLocation StartLoc,
19293 SourceLocation LParenLoc,
19294 SourceLocation EndLoc) {
19295 // OpenMP [2.8.1, simd construct, Description]
19296 // The parameter of the simdlen clause must be a constant
19297 // positive integer expression.
19298 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
19299 if (Simdlen.isInvalid())
19300 return nullptr;
19301 return new (getASTContext())
19302 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
19303}
19304
19305/// Tries to find omp_allocator_handle_t type.
19307 DSAStackTy *Stack) {
19308 if (!Stack->getOMPAllocatorHandleT().isNull())
19309 return true;
19310
19311 // Set the allocator handle type.
19312 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_allocator_handle_t");
19313 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
19314 if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
19315 S.Diag(Loc, diag::err_omp_implied_type_not_found)
19316 << "omp_allocator_handle_t";
19317 return false;
19318 }
19319 QualType AllocatorHandleEnumTy = PT.get();
19320 AllocatorHandleEnumTy.addConst();
19321
19322 // Fill the predefined allocator map.
19323 bool ErrorFound = false;
19324 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
19325 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
19326 StringRef Allocator =
19327 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
19328 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
19329 auto *VD = dyn_cast_or_null<ValueDecl>(
19330 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
19331 if (!VD) {
19332 ErrorFound = true;
19333 break;
19334 }
19335 QualType AllocatorType =
19337 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
19338 if (!Res.isUsable()) {
19339 ErrorFound = true;
19340 break;
19341 }
19342 Res = S.PerformImplicitConversion(Res.get(), AllocatorHandleEnumTy,
19344 /*AllowExplicit=*/true);
19345 if (!Res.isUsable()) {
19346 ErrorFound = true;
19347 break;
19348 }
19349 Stack->setAllocator(AllocatorKind, Res.get());
19350 }
19351 if (ErrorFound) {
19352 S.Diag(Loc, diag::err_omp_implied_type_not_found)
19353 << "omp_allocator_handle_t";
19354 return false;
19355 }
19356
19357 // Record the type only now. It is what tells a later call that the map above
19358 // is ready to be read, so setting it before the map is filled would let that
19359 // call proceed on a map this one gave up on halfway through.
19360 Stack->setOMPAllocatorHandleT(AllocatorHandleEnumTy);
19361
19362 return true;
19363}
19364
19366 SourceLocation StartLoc,
19367 SourceLocation LParenLoc,
19368 SourceLocation EndLoc) {
19369 // OpenMP [2.11.3, allocate Directive, Description]
19370 // allocator is an expression of omp_allocator_handle_t type.
19372 return nullptr;
19373
19374 ExprResult Allocator = SemaRef.DefaultLvalueConversion(A);
19375 if (Allocator.isInvalid())
19376 return nullptr;
19377 Allocator = SemaRef.PerformImplicitConversion(
19378 Allocator.get(), DSAStack->getOMPAllocatorHandleT(),
19380 /*AllowExplicit=*/true);
19381 if (Allocator.isInvalid())
19382 return nullptr;
19383 return new (getASTContext())
19384 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
19385}
19386
19388 SourceLocation StartLoc,
19389 SourceLocation LParenLoc,
19390 SourceLocation EndLoc) {
19391 // OpenMP [2.7.1, loop construct, Description]
19392 // OpenMP [2.8.1, simd construct, Description]
19393 // OpenMP [2.9.6, distribute construct, Description]
19394 // The parameter of the collapse clause must be a constant
19395 // positive integer expression.
19396 ExprResult NumForLoopsResult =
19397 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
19398 if (NumForLoopsResult.isInvalid())
19399 return nullptr;
19400 return new (getASTContext())
19401 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
19402}
19403
19405 SourceLocation EndLoc,
19406 SourceLocation LParenLoc,
19407 Expr *NumForLoops) {
19408 // OpenMP [2.7.1, loop construct, Description]
19409 // OpenMP [2.8.1, simd construct, Description]
19410 // OpenMP [2.9.6, distribute construct, Description]
19411 // The parameter of the ordered clause must be a constant
19412 // positive integer expression if any.
19413 if (NumForLoops && LParenLoc.isValid()) {
19414 ExprResult NumForLoopsResult =
19415 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
19416 if (NumForLoopsResult.isInvalid())
19417 return nullptr;
19418 NumForLoops = NumForLoopsResult.get();
19419 } else {
19420 NumForLoops = nullptr;
19421 }
19422 auto *Clause =
19423 OMPOrderedClause::Create(getASTContext(), NumForLoops,
19424 NumForLoops ? DSAStack->getAssociatedLoops() : 0,
19425 StartLoc, LParenLoc, EndLoc);
19426 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
19427 return Clause;
19428}
19429
19431 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
19432 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
19433 OMPClause *Res = nullptr;
19434 switch (Kind) {
19435 case OMPC_proc_bind:
19436 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
19437 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
19438 break;
19439 case OMPC_atomic_default_mem_order:
19441 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
19442 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
19443 break;
19444 case OMPC_fail:
19445 Res = ActOnOpenMPFailClause(static_cast<OpenMPClauseKind>(Argument),
19446 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
19447 break;
19448 case OMPC_update_depend_objects:
19450 static_cast<OpenMPDependClauseKind>(Argument), ArgumentLoc, StartLoc,
19451 LParenLoc, EndLoc);
19452 break;
19453 case OMPC_bind:
19454 Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument),
19455 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
19456 break;
19457 case OMPC_at:
19458 Res = ActOnOpenMPAtClause(static_cast<OpenMPAtClauseKind>(Argument),
19459 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
19460 break;
19461 case OMPC_severity:
19463 static_cast<OpenMPSeverityClauseKind>(Argument), ArgumentLoc, StartLoc,
19464 LParenLoc, EndLoc);
19465 break;
19466 case OMPC_threadset:
19467 Res = ActOnOpenMPThreadsetClause(static_cast<OpenMPThreadsetKind>(Argument),
19468 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
19469 break;
19470 case OMPC_if:
19471 case OMPC_final:
19472 case OMPC_num_threads:
19473 case OMPC_safelen:
19474 case OMPC_simdlen:
19475 case OMPC_sizes:
19476 case OMPC_depth:
19477 case OMPC_allocator:
19478 case OMPC_collapse:
19479 case OMPC_schedule:
19480 case OMPC_private:
19481 case OMPC_firstprivate:
19482 case OMPC_lastprivate:
19483 case OMPC_shared:
19484 case OMPC_reduction:
19485 case OMPC_task_reduction:
19486 case OMPC_in_reduction:
19487 case OMPC_linear:
19488 case OMPC_aligned:
19489 case OMPC_copyin:
19490 case OMPC_copyprivate:
19491 case OMPC_ordered:
19492 case OMPC_nowait:
19493 case OMPC_untied:
19494 case OMPC_mergeable:
19495 case OMPC_threadprivate:
19496 case OMPC_groupprivate:
19497 case OMPC_allocate:
19498 case OMPC_flush:
19499 case OMPC_depobj:
19500 case OMPC_read:
19501 case OMPC_write:
19502 case OMPC_capture:
19503 case OMPC_compare:
19504 case OMPC_update:
19505 case OMPC_seq_cst:
19506 case OMPC_acq_rel:
19507 case OMPC_acquire:
19508 case OMPC_release:
19509 case OMPC_relaxed:
19510 case OMPC_depend:
19511 case OMPC_device:
19512 case OMPC_threads:
19513 case OMPC_simd:
19514 case OMPC_map:
19515 case OMPC_num_teams:
19516 case OMPC_thread_limit:
19517 case OMPC_priority:
19518 case OMPC_grainsize:
19519 case OMPC_nogroup:
19520 case OMPC_num_tasks:
19521 case OMPC_hint:
19522 case OMPC_dist_schedule:
19523 case OMPC_default:
19524 case OMPC_defaultmap:
19525 case OMPC_unknown:
19526 case OMPC_uniform:
19527 case OMPC_to:
19528 case OMPC_from:
19529 case OMPC_use_device_ptr:
19530 case OMPC_use_device_addr:
19531 case OMPC_is_device_ptr:
19532 case OMPC_has_device_addr:
19533 case OMPC_unified_address:
19534 case OMPC_unified_shared_memory:
19535 case OMPC_reverse_offload:
19536 case OMPC_dynamic_allocators:
19537 case OMPC_self_maps:
19538 case OMPC_device_type:
19539 case OMPC_match:
19540 case OMPC_nontemporal:
19541 case OMPC_destroy:
19542 case OMPC_novariants:
19543 case OMPC_nocontext:
19544 case OMPC_detach:
19545 case OMPC_inclusive:
19546 case OMPC_exclusive:
19547 case OMPC_uses_allocators:
19548 case OMPC_affinity:
19549 case OMPC_when:
19550 case OMPC_message:
19551 default:
19552 llvm_unreachable("Clause is not allowed.");
19553 }
19554 return Res;
19555}
19556
19558 llvm::omp::DefaultKind M, SourceLocation MLoc,
19560 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
19561 if (M == OMP_DEFAULT_unknown) {
19562 Diag(MLoc, diag::err_omp_unexpected_clause_value)
19563 << getListOfPossibleValues(OMPC_default, /*First=*/0,
19564 /*Last=*/unsigned(OMP_DEFAULT_unknown))
19565 << getOpenMPClauseNameForDiag(OMPC_default);
19566 return nullptr;
19567 }
19568 if (VCKind == OMPC_DEFAULT_VC_unknown) {
19569 Diag(VCKindLoc, diag::err_omp_default_vc)
19570 << getOpenMPSimpleClauseTypeName(OMPC_default, unsigned(M));
19571 return nullptr;
19572 }
19573
19574 bool IsTargetDefault =
19575 getLangOpts().OpenMP >= 60 &&
19576 isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective());
19577
19578 // OpenMP 6.0, page 224, lines 3-4 default Clause, Semantics
19579 // If data-sharing-attribute is shared then the clause has no effect
19580 // on a target construct;
19581 if (IsTargetDefault && M == OMP_DEFAULT_shared)
19582 return nullptr;
19583
19584 auto SetDefaultClauseAttrs = [&](llvm::omp::DefaultKind M,
19587 OpenMPDefaultmapClauseKind DefMapKind;
19588 // default data-sharing-attribute
19589 switch (M) {
19590 case OMP_DEFAULT_none:
19591 if (IsTargetDefault)
19592 DefMapMod = OMPC_DEFAULTMAP_MODIFIER_none;
19593 else
19594 DSAStack->setDefaultDSANone(MLoc);
19595 break;
19596 case OMP_DEFAULT_firstprivate:
19597 if (IsTargetDefault)
19598 DefMapMod = OMPC_DEFAULTMAP_MODIFIER_firstprivate;
19599 else
19600 DSAStack->setDefaultDSAFirstPrivate(MLoc);
19601 break;
19602 case OMP_DEFAULT_private:
19603 if (IsTargetDefault)
19604 DefMapMod = OMPC_DEFAULTMAP_MODIFIER_private;
19605 else
19606 DSAStack->setDefaultDSAPrivate(MLoc);
19607 break;
19608 case OMP_DEFAULT_shared:
19609 assert(!IsTargetDefault && "DSA shared invalid with target directive");
19610 DSAStack->setDefaultDSAShared(MLoc);
19611 break;
19612 default:
19613 llvm_unreachable("unexpected DSA in OpenMP default clause");
19614 }
19615 // default variable-category
19616 switch (VCKind) {
19617 case OMPC_DEFAULT_VC_aggregate:
19618 if (IsTargetDefault)
19619 DefMapKind = OMPC_DEFAULTMAP_aggregate;
19620 else
19621 DSAStack->setDefaultDSAVCAggregate(VCKindLoc);
19622 break;
19623 case OMPC_DEFAULT_VC_pointer:
19624 if (IsTargetDefault)
19625 DefMapKind = OMPC_DEFAULTMAP_pointer;
19626 else
19627 DSAStack->setDefaultDSAVCPointer(VCKindLoc);
19628 break;
19629 case OMPC_DEFAULT_VC_scalar:
19630 if (IsTargetDefault)
19631 DefMapKind = OMPC_DEFAULTMAP_scalar;
19632 else
19633 DSAStack->setDefaultDSAVCScalar(VCKindLoc);
19634 break;
19635 case OMPC_DEFAULT_VC_all:
19636 if (IsTargetDefault)
19637 DefMapKind = OMPC_DEFAULTMAP_all;
19638 else
19639 DSAStack->setDefaultDSAVCAll(VCKindLoc);
19640 break;
19641 default:
19642 llvm_unreachable("unexpected variable category in OpenMP default clause");
19643 }
19644 // OpenMP 6.0, page 224, lines 4-5 default Clause, Semantics
19645 // otherwise, its effect on a target construct is equivalent to
19646 // specifying the defaultmap clause with the same data-sharing-attribute
19647 // and variable-category.
19648 //
19649 // If earlier than OpenMP 6.0, or not a target directive, the default DSA
19650 // is/was set as before.
19651 if (IsTargetDefault) {
19652 if (DefMapKind == OMPC_DEFAULTMAP_all) {
19653 DSAStack->setDefaultDMAAttr(DefMapMod, OMPC_DEFAULTMAP_aggregate, MLoc);
19654 DSAStack->setDefaultDMAAttr(DefMapMod, OMPC_DEFAULTMAP_scalar, MLoc);
19655 DSAStack->setDefaultDMAAttr(DefMapMod, OMPC_DEFAULTMAP_pointer, MLoc);
19656 } else {
19657 DSAStack->setDefaultDMAAttr(DefMapMod, DefMapKind, MLoc);
19658 }
19659 }
19660 };
19661
19662 SetDefaultClauseAttrs(M, VCKind);
19663 return new (getASTContext())
19664 OMPDefaultClause(M, MLoc, VCKind, VCKindLoc, StartLoc, LParenLoc, EndLoc);
19665}
19666
19668 SourceLocation KindLoc,
19669 SourceLocation StartLoc,
19670 SourceLocation LParenLoc,
19671 SourceLocation EndLoc) {
19672 if (Kind == OMPC_THREADSET_unknown) {
19673 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19674 << getListOfPossibleValues(OMPC_threadset, /*First=*/0,
19675 /*Last=*/unsigned(OMPC_THREADSET_unknown))
19676 << getOpenMPClauseName(OMPC_threadset);
19677 return nullptr;
19678 }
19679
19680 return new (getASTContext())
19681 OMPThreadsetClause(Kind, KindLoc, StartLoc, LParenLoc, EndLoc);
19682}
19683
19684static OMPClause *
19685createTransparentClause(Sema &SemaRef, ASTContext &Ctx, Expr *ImpexTypeArg,
19686 Stmt *HelperValStmt, OpenMPDirectiveKind CaptureRegion,
19687 SourceLocation StartLoc, SourceLocation LParenLoc,
19688 SourceLocation EndLoc) {
19689 ExprResult ER = SemaRef.DefaultLvalueConversion(ImpexTypeArg);
19690 if (ER.isInvalid())
19691 return nullptr;
19692
19693 return new (Ctx) OMPTransparentClause(ER.get(), HelperValStmt, CaptureRegion,
19694 StartLoc, LParenLoc, EndLoc);
19695}
19696
19698 SourceLocation StartLoc,
19699 SourceLocation LParenLoc,
19700 SourceLocation EndLoc) {
19701 Stmt *HelperValStmt = nullptr;
19702 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19704 DKind, OMPC_transparent, getLangOpts().getOpenMPVersion());
19705 if (CaptureRegion != OMPD_unknown &&
19706 !SemaRef.CurContext->isDependentContext()) {
19707 Expr *ValExpr = SemaRef.MakeFullExpr(ImpexTypeArg).get();
19708 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19709 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
19710 HelperValStmt = buildPreInits(getASTContext(), Captures);
19711 }
19712 if (!ImpexTypeArg) {
19713 return new (getASTContext())
19714 OMPTransparentClause(ImpexTypeArg, HelperValStmt, CaptureRegion,
19715 StartLoc, LParenLoc, EndLoc);
19716 }
19717 QualType Ty = ImpexTypeArg->getType();
19718
19719 if (const auto *TT = Ty->getAs<TypedefType>()) {
19720 const TypedefNameDecl *TypedefDecl = TT->getDecl();
19721 llvm::StringRef TypedefName = TypedefDecl->getName();
19722 IdentifierInfo &II = SemaRef.PP.getIdentifierTable().get(TypedefName);
19723 ParsedType ImpexTy =
19724 SemaRef.getTypeName(II, StartLoc, SemaRef.getCurScope());
19725 if (!ImpexTy.getAsOpaquePtr() || ImpexTy.get().isNull()) {
19726 SemaRef.Diag(StartLoc, diag::err_omp_implied_type_not_found)
19727 << TypedefName;
19728 return nullptr;
19729 }
19730 return new (getASTContext())
19731 OMPTransparentClause(ImpexTypeArg, HelperValStmt, CaptureRegion,
19732 StartLoc, LParenLoc, EndLoc);
19733 }
19734
19735 if (Ty->isEnumeralType())
19736 return createTransparentClause(SemaRef, getASTContext(), ImpexTypeArg,
19737 HelperValStmt, CaptureRegion, StartLoc,
19738 LParenLoc, EndLoc);
19739 if (Ty->isIntegerType()) {
19740 if (isNonNegativeIntegerValue(ImpexTypeArg, SemaRef, OMPC_transparent,
19741 /*StrictlyPositive=*/false)) {
19743 SemaRef.OpenMP().PerformOpenMPImplicitIntegerConversion(StartLoc,
19744 ImpexTypeArg);
19745 if (std::optional<llvm::APSInt> Result =
19746 Value.get()->getIntegerConstantExpr(SemaRef.Context)) {
19747 if (Result->isNegative() ||
19748 Result >
19749 static_cast<int64_t>(SemaOpenMP::OpenMPImpexType::OMP_Export))
19750 SemaRef.Diag(StartLoc, diag::err_omp_transparent_invalid_value);
19751 }
19752 return new (getASTContext())
19753 OMPTransparentClause(ImpexTypeArg, HelperValStmt, CaptureRegion,
19754 StartLoc, LParenLoc, EndLoc);
19755 }
19756 }
19757 if (!isNonNegativeIntegerValue(ImpexTypeArg, SemaRef, OMPC_transparent,
19758 /*StrictlyPositive=*/true))
19759 return nullptr;
19760 return new (getASTContext()) OMPTransparentClause(
19761 ImpexTypeArg, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
19762}
19763
19765 SourceLocation KindKwLoc,
19766 SourceLocation StartLoc,
19767 SourceLocation LParenLoc,
19768 SourceLocation EndLoc) {
19769 if (Kind == OMP_PROC_BIND_unknown) {
19770 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
19771 << getListOfPossibleValues(OMPC_proc_bind,
19772 /*First=*/unsigned(OMP_PROC_BIND_master),
19773 /*Last=*/
19774 unsigned(getLangOpts().OpenMP > 50
19775 ? OMP_PROC_BIND_primary
19776 : OMP_PROC_BIND_spread) +
19777 1)
19778 << getOpenMPClauseNameForDiag(OMPC_proc_bind);
19779 return nullptr;
19780 }
19781 if (Kind == OMP_PROC_BIND_primary && getLangOpts().OpenMP < 51)
19782 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
19783 << getListOfPossibleValues(OMPC_proc_bind,
19784 /*First=*/unsigned(OMP_PROC_BIND_master),
19785 /*Last=*/
19786 unsigned(OMP_PROC_BIND_spread) + 1)
19787 << getOpenMPClauseNameForDiag(OMPC_proc_bind);
19788 return new (getASTContext())
19789 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
19790}
19791
19794 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
19796 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
19798 OMPC_atomic_default_mem_order, /*First=*/0,
19800 << getOpenMPClauseNameForDiag(OMPC_atomic_default_mem_order);
19801 return nullptr;
19802 }
19803 return new (getASTContext()) OMPAtomicDefaultMemOrderClause(
19804 Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
19805}
19806
19808 SourceLocation KindKwLoc,
19809 SourceLocation StartLoc,
19810 SourceLocation LParenLoc,
19811 SourceLocation EndLoc) {
19812 if (Kind == OMPC_AT_unknown) {
19813 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
19814 << getListOfPossibleValues(OMPC_at, /*First=*/0,
19815 /*Last=*/OMPC_AT_unknown)
19816 << getOpenMPClauseNameForDiag(OMPC_at);
19817 return nullptr;
19818 }
19819 return new (getASTContext())
19820 OMPAtClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
19821}
19822
19824 SourceLocation KindKwLoc,
19825 SourceLocation StartLoc,
19826 SourceLocation LParenLoc,
19827 SourceLocation EndLoc) {
19828 if (Kind == OMPC_SEVERITY_unknown) {
19829 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
19830 << getListOfPossibleValues(OMPC_severity, /*First=*/0,
19831 /*Last=*/OMPC_SEVERITY_unknown)
19832 << getOpenMPClauseNameForDiag(OMPC_severity);
19833 return nullptr;
19834 }
19835 return new (getASTContext())
19836 OMPSeverityClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
19837}
19838
19840 SourceLocation StartLoc,
19841 SourceLocation LParenLoc,
19842 SourceLocation EndLoc) {
19843 assert(ME && "NULL expr in Message clause");
19844 QualType Type = ME->getType();
19845 if ((!Type->isPointerType() && !Type->isArrayType()) ||
19847 Diag(ME->getBeginLoc(), diag::warn_clause_expected_string)
19848 << getOpenMPClauseNameForDiag(OMPC_message) << 0;
19849 return nullptr;
19850 }
19851
19852 Stmt *HelperValStmt = nullptr;
19853
19854 // Depending on whether this clause appears in an executable context or not,
19855 // we may or may not build a capture.
19856 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
19857 OpenMPDirectiveKind CaptureRegion =
19858 DKind == OMPD_unknown
19859 ? OMPD_unknown
19860 : getOpenMPCaptureRegionForClause(DKind, OMPC_message,
19861 getLangOpts().getOpenMPVersion());
19862 if (CaptureRegion != OMPD_unknown &&
19863 !SemaRef.CurContext->isDependentContext()) {
19864 ME = SemaRef.MakeFullExpr(ME).get();
19865 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
19866 ME = tryBuildCapture(SemaRef, ME, Captures).get();
19867 HelperValStmt = buildPreInits(getASTContext(), Captures);
19868 }
19869
19870 // Convert array type to pointer type if needed.
19871 ME = SemaRef.DefaultFunctionArrayLvalueConversion(ME).get();
19872
19873 return new (getASTContext()) OMPMessageClause(
19874 ME, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
19875}
19876
19879 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
19880 SourceLocation KindLoc, SourceLocation EndLoc) {
19881 if (Kind != OMPC_ORDER_concurrent ||
19882 (getLangOpts().OpenMP < 51 && MLoc.isValid())) {
19883 // Kind should be concurrent,
19884 // Modifiers introduced in OpenMP 5.1
19885 static_assert(OMPC_ORDER_unknown > 0,
19886 "OMPC_ORDER_unknown not greater than 0");
19887
19888 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
19889 << getListOfPossibleValues(OMPC_order,
19890 /*First=*/0,
19891 /*Last=*/OMPC_ORDER_unknown)
19892 << getOpenMPClauseNameForDiag(OMPC_order);
19893 return nullptr;
19894 }
19895 if (getLangOpts().OpenMP >= 51 && Modifier == OMPC_ORDER_MODIFIER_unknown &&
19896 MLoc.isValid()) {
19897 Diag(MLoc, diag::err_omp_unexpected_clause_value)
19898 << getListOfPossibleValues(OMPC_order,
19899 /*First=*/OMPC_ORDER_MODIFIER_unknown + 1,
19900 /*Last=*/OMPC_ORDER_MODIFIER_last)
19901 << getOpenMPClauseNameForDiag(OMPC_order);
19902 } else if (getLangOpts().OpenMP >= 50) {
19903 DSAStack->setRegionHasOrderConcurrent(/*HasOrderConcurrent=*/true);
19904 if (DSAStack->getCurScope()) {
19905 // mark the current scope with 'order' flag
19906 unsigned existingFlags = DSAStack->getCurScope()->getFlags();
19907 DSAStack->getCurScope()->setFlags(existingFlags |
19909 }
19910 }
19911 return new (getASTContext()) OMPOrderClause(
19912 Kind, KindLoc, StartLoc, LParenLoc, EndLoc, Modifier, MLoc);
19913}
19914
19916 OpenMPDependClauseKind Kind, SourceLocation KindKwLoc,
19917 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
19918 if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
19919 Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
19920 SmallVector<unsigned> Except = {
19921 OMPC_DEPEND_source, OMPC_DEPEND_sink, OMPC_DEPEND_depobj,
19922 OMPC_DEPEND_outallmemory, OMPC_DEPEND_inoutallmemory};
19923 if (getLangOpts().OpenMP < 51)
19924 Except.push_back(OMPC_DEPEND_inoutset);
19925 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
19926 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
19927 /*Last=*/OMPC_DEPEND_unknown, Except)
19928 << getOpenMPClauseNameForDiag(OMPC_update_depend_objects);
19929 return nullptr;
19930 }
19931 return OMPUpdateDependObjectsClause::Create(
19932 getASTContext(), StartLoc, LParenLoc, KindKwLoc, Kind, EndLoc);
19933}
19934
19936 SourceLocation StartLoc,
19937 SourceLocation LParenLoc,
19938 SourceLocation EndLoc) {
19939 SmallVector<Expr *> SanitizedSizeExprs(SizeExprs);
19940
19941 for (Expr *&SizeExpr : SanitizedSizeExprs) {
19942 // Skip if already sanitized, e.g. during a partial template instantiation.
19943 if (!SizeExpr)
19944 continue;
19945
19946 bool IsValid = isNonNegativeIntegerValue(SizeExpr, SemaRef, OMPC_sizes,
19947 /*StrictlyPositive=*/true);
19948
19949 // isNonNegativeIntegerValue returns true for non-integral types (but still
19950 // emits error diagnostic), so check for the expected type explicitly.
19951 QualType SizeTy = SizeExpr->getType();
19952 if (!SizeTy->isIntegerType())
19953 IsValid = false;
19954
19955 // Handling in templates is tricky. There are four possibilities to
19956 // consider:
19957 //
19958 // 1a. The expression is valid and we are in a instantiated template or not
19959 // in a template:
19960 // Pass valid expression to be further analysed later in Sema.
19961 // 1b. The expression is valid and we are in a template (including partial
19962 // instantiation):
19963 // isNonNegativeIntegerValue skipped any checks so there is no
19964 // guarantee it will be correct after instantiation.
19965 // ActOnOpenMPSizesClause will be called again at instantiation when
19966 // it is not in a dependent context anymore. This may cause warnings
19967 // to be emitted multiple times.
19968 // 2a. The expression is invalid and we are in an instantiated template or
19969 // not in a template:
19970 // Invalidate the expression with a clearly wrong value (nullptr) so
19971 // later in Sema we do not have to do the same validity analysis again
19972 // or crash from unexpected data. Error diagnostics have already been
19973 // emitted.
19974 // 2b. The expression is invalid and we are in a template (including partial
19975 // instantiation):
19976 // Pass the invalid expression as-is, template instantiation may
19977 // replace unexpected types/values with valid ones. The directives
19978 // with this clause must not try to use these expressions in dependent
19979 // contexts, but delay analysis until full instantiation.
19980 if (!SizeExpr->isInstantiationDependent() && !IsValid)
19981 SizeExpr = nullptr;
19982 }
19983
19984 return OMPSizesClause::Create(getASTContext(), StartLoc, LParenLoc, EndLoc,
19985 SanitizedSizeExprs);
19986}
19987
19989 SourceLocation StartLoc,
19990 SourceLocation LParenLoc,
19991 SourceLocation EndLoc,
19992 std::optional<unsigned> FillIdx,
19993 SourceLocation FillLoc,
19994 unsigned FillCount) {
19995 SmallVector<Expr *> SanitizedCountExprs(CountExprs);
19996
19997 // OpenMP 6.0: each list item in counts(...) is either the omp_fill keyword
19998 // or an integral constant expression (non-negative). Runtime variables are
19999 // not permitted; this matches split codegen, which needs segment sizes at
20000 // compile time.
20001 for (unsigned I = 0; I < SanitizedCountExprs.size(); ++I) {
20002 Expr *&CountExpr = SanitizedCountExprs[I];
20003 if (FillIdx && I == *FillIdx)
20004 continue;
20005 if (!CountExpr)
20006 continue;
20007
20009 CountExpr, OMPC_counts, /*StrictlyPositive=*/false);
20010 if (Verified.isInvalid())
20011 CountExpr = nullptr;
20012 else
20013 CountExpr = Verified.get();
20014 }
20015
20016 if (FillCount != 1) {
20017 Diag(FillCount == 0 ? StartLoc : FillLoc,
20018 diag::err_omp_split_counts_not_one_omp_fill);
20019 }
20020
20021 return OMPCountsClause::Create(getASTContext(), StartLoc, LParenLoc, EndLoc,
20022 SanitizedCountExprs, FillIdx, FillLoc);
20023}
20024
20026 SourceLocation StartLoc,
20027 SourceLocation LParenLoc,
20028 SourceLocation EndLoc) {
20029 size_t NumLoops = PermExprs.size();
20030 SmallVector<Expr *> SanitizedPermExprs;
20031 llvm::append_range(SanitizedPermExprs, PermExprs);
20032
20033 for (Expr *&PermExpr : SanitizedPermExprs) {
20034 // Skip if template-dependent or already sanitized, e.g. during a partial
20035 // template instantiation.
20036 if (!PermExpr || PermExpr->isInstantiationDependent())
20037 continue;
20038
20039 llvm::APSInt PermVal;
20040 ExprResult PermEvalExpr = SemaRef.VerifyIntegerConstantExpression(
20041 PermExpr, &PermVal, AllowFoldKind::Allow);
20042 bool IsValid = PermEvalExpr.isUsable();
20043 if (IsValid)
20044 PermExpr = PermEvalExpr.get();
20045
20046 if (IsValid && (PermVal < 1 || NumLoops < PermVal)) {
20047 SourceRange ExprRange(PermEvalExpr.get()->getBeginLoc(),
20048 PermEvalExpr.get()->getEndLoc());
20049 Diag(PermEvalExpr.get()->getExprLoc(),
20050 diag::err_omp_interchange_permutation_value_range)
20051 << NumLoops << ExprRange;
20052 IsValid = false;
20053 }
20054
20055 if (!PermExpr->isInstantiationDependent() && !IsValid)
20056 PermExpr = nullptr;
20057 }
20058
20059 return OMPPermutationClause::Create(getASTContext(), StartLoc, LParenLoc,
20060 EndLoc, SanitizedPermExprs);
20061}
20062
20064 SourceLocation EndLoc) {
20065 return new (getASTContext()) OMPFullClause(StartLoc, EndLoc);
20066}
20067
20069 SourceLocation StartLoc,
20070 SourceLocation LParenLoc,
20071 SourceLocation EndLoc) {
20072 if (FactorExpr) {
20073 // If an argument is specified, it must be a constant (or an unevaluated
20074 // template expression).
20076 FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
20077 if (FactorResult.isInvalid())
20078 return nullptr;
20079 FactorExpr = FactorResult.get();
20080 }
20081
20082 return new (getASTContext())
20083 OMPPartialClause(StartLoc, LParenLoc, EndLoc, FactorExpr);
20084}
20085
20087 SourceLocation StartLoc,
20088 SourceLocation LParenLoc,
20089 SourceLocation EndLoc) {
20090 // The depth-expr must be a positive integer constant expression and
20091 // not greater than the number of loops in the associated loop nest.
20093 DepthExpr, OMPC_depth, /*StrictlyPositive=*/true);
20094 if (DepthResult.isInvalid())
20095 return nullptr;
20096 DepthExpr = DepthResult.get();
20097
20098 return new (getASTContext())
20099 OMPDepthClause(StartLoc, LParenLoc, EndLoc, DepthExpr);
20100}
20101
20103 Expr *First, Expr *Count, SourceLocation StartLoc, SourceLocation LParenLoc,
20104 SourceLocation FirstLoc, SourceLocation CountLoc, SourceLocation EndLoc) {
20105
20106 // OpenMP [6.0, Restrictions]
20107 // First and Count must be integer expressions with positive value
20108 ExprResult FirstVal =
20110 if (FirstVal.isInvalid())
20111 First = nullptr;
20112
20113 ExprResult CountVal =
20114 VerifyPositiveIntegerConstantInClause(Count, OMPC_looprange);
20115 if (CountVal.isInvalid())
20116 Count = nullptr;
20117
20118 // OpenMP [6.0, Restrictions]
20119 // first + count - 1 must not evaluate to a value greater than the
20120 // loop sequence length of the associated canonical loop sequence.
20121 // This check must be performed afterwards due to the delayed
20122 // parsing and computation of the associated loop sequence
20123 return new (getASTContext()) OMPLoopRangeClause(
20124 StartLoc, LParenLoc, FirstLoc, CountLoc, EndLoc, First, Count);
20125}
20126
20128 SourceLocation LParenLoc,
20129 SourceLocation EndLoc) {
20130 ExprResult AlignVal;
20131 AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align);
20132 if (AlignVal.isInvalid())
20133 return nullptr;
20134 return new (getASTContext())
20135 OMPAlignClause(AlignVal.get(), StartLoc, LParenLoc, EndLoc);
20136}
20137
20140 SourceLocation StartLoc, SourceLocation LParenLoc,
20141 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
20142 SourceLocation EndLoc) {
20143 OMPClause *Res = nullptr;
20144 switch (Kind) {
20145 case OMPC_schedule: {
20146 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
20147 assert(Argument.size() == NumberOfElements &&
20148 ArgumentLoc.size() == NumberOfElements);
20150 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
20151 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
20152 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
20153 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
20154 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
20155 break;
20156 }
20157 case OMPC_if:
20158 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
20159 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
20160 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
20161 DelimLoc, EndLoc);
20162 break;
20163 case OMPC_dist_schedule:
20165 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
20166 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
20167 break;
20168 case OMPC_default:
20169 enum { DefaultModifier, DefaultVarCategory };
20171 static_cast<llvm::omp::DefaultKind>(Argument[DefaultModifier]),
20172 ArgumentLoc[DefaultModifier],
20174 Argument[DefaultVarCategory]),
20175 ArgumentLoc[DefaultVarCategory], StartLoc, LParenLoc, EndLoc);
20176 break;
20177 case OMPC_defaultmap:
20178 enum { Modifier, DefaultmapKind };
20180 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
20181 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
20182 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
20183 EndLoc);
20184 break;
20185 case OMPC_order:
20186 enum { OrderModifier, OrderKind };
20188 static_cast<OpenMPOrderClauseModifier>(Argument[OrderModifier]),
20189 static_cast<OpenMPOrderClauseKind>(Argument[OrderKind]), StartLoc,
20190 LParenLoc, ArgumentLoc[OrderModifier], ArgumentLoc[OrderKind], EndLoc);
20191 break;
20192 case OMPC_device:
20193 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
20195 static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
20196 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
20197 break;
20198 case OMPC_grainsize:
20199 assert(Argument.size() == 1 && ArgumentLoc.size() == 1 &&
20200 "Modifier for grainsize clause and its location are expected.");
20202 static_cast<OpenMPGrainsizeClauseModifier>(Argument.back()), Expr,
20203 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
20204 break;
20205 case OMPC_num_tasks:
20206 assert(Argument.size() == 1 && ArgumentLoc.size() == 1 &&
20207 "Modifier for num_tasks clause and its location are expected.");
20209 static_cast<OpenMPNumTasksClauseModifier>(Argument.back()), Expr,
20210 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
20211 break;
20212 case OMPC_dyn_groupprivate: {
20213 enum { Modifier1, Modifier2, NumberOfElements };
20214 assert(Argument.size() == NumberOfElements &&
20215 ArgumentLoc.size() == NumberOfElements &&
20216 "Modifiers for dyn_groupprivate clause and their locations are "
20217 "expected.");
20219 static_cast<OpenMPDynGroupprivateClauseModifier>(Argument[Modifier1]),
20221 Argument[Modifier2]),
20222 Expr, StartLoc, LParenLoc, ArgumentLoc[Modifier1],
20223 ArgumentLoc[Modifier2], EndLoc);
20224 break;
20225 }
20226 case OMPC_final:
20227 case OMPC_safelen:
20228 case OMPC_simdlen:
20229 case OMPC_sizes:
20230 case OMPC_depth:
20231 case OMPC_allocator:
20232 case OMPC_collapse:
20233 case OMPC_proc_bind:
20234 case OMPC_private:
20235 case OMPC_firstprivate:
20236 case OMPC_lastprivate:
20237 case OMPC_shared:
20238 case OMPC_reduction:
20239 case OMPC_task_reduction:
20240 case OMPC_in_reduction:
20241 case OMPC_linear:
20242 case OMPC_aligned:
20243 case OMPC_copyin:
20244 case OMPC_copyprivate:
20245 case OMPC_ordered:
20246 case OMPC_nowait:
20247 case OMPC_untied:
20248 case OMPC_mergeable:
20249 case OMPC_threadprivate:
20250 case OMPC_groupprivate:
20251 case OMPC_allocate:
20252 case OMPC_flush:
20253 case OMPC_depobj:
20254 case OMPC_read:
20255 case OMPC_write:
20256 case OMPC_update:
20257 case OMPC_capture:
20258 case OMPC_compare:
20259 case OMPC_seq_cst:
20260 case OMPC_acq_rel:
20261 case OMPC_acquire:
20262 case OMPC_release:
20263 case OMPC_relaxed:
20264 case OMPC_depend:
20265 case OMPC_threads:
20266 case OMPC_simd:
20267 case OMPC_map:
20268 case OMPC_num_teams:
20269 case OMPC_thread_limit:
20270 case OMPC_priority:
20271 case OMPC_nogroup:
20272 case OMPC_hint:
20273 case OMPC_unknown:
20274 case OMPC_uniform:
20275 case OMPC_to:
20276 case OMPC_from:
20277 case OMPC_use_device_ptr:
20278 case OMPC_use_device_addr:
20279 case OMPC_is_device_ptr:
20280 case OMPC_has_device_addr:
20281 case OMPC_unified_address:
20282 case OMPC_unified_shared_memory:
20283 case OMPC_reverse_offload:
20284 case OMPC_dynamic_allocators:
20285 case OMPC_atomic_default_mem_order:
20286 case OMPC_self_maps:
20287 case OMPC_device_type:
20288 case OMPC_match:
20289 case OMPC_nontemporal:
20290 case OMPC_at:
20291 case OMPC_severity:
20292 case OMPC_message:
20293 case OMPC_destroy:
20294 case OMPC_novariants:
20295 case OMPC_nocontext:
20296 case OMPC_detach:
20297 case OMPC_inclusive:
20298 case OMPC_exclusive:
20299 case OMPC_uses_allocators:
20300 case OMPC_affinity:
20301 case OMPC_when:
20302 case OMPC_bind:
20303 default:
20304 llvm_unreachable("Clause is not allowed.");
20305 }
20306 return Res;
20307}
20308
20311 SourceLocation M1Loc, SourceLocation M2Loc) {
20312 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
20313 SmallVector<unsigned, 2> Excluded;
20315 Excluded.push_back(M2);
20316 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
20317 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
20318 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
20319 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
20320 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
20321 << getListOfPossibleValues(OMPC_schedule,
20322 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
20324 Excluded)
20325 << getOpenMPClauseNameForDiag(OMPC_schedule);
20326 return true;
20327 }
20328 return false;
20329}
20330
20333 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
20334 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
20335 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
20336 if (checkScheduleModifiers(SemaRef, M1, M2, M1Loc, M2Loc) ||
20337 checkScheduleModifiers(SemaRef, M2, M1, M2Loc, M1Loc))
20338 return nullptr;
20339 // OpenMP, 2.7.1, Loop Construct, Restrictions
20340 // Either the monotonic modifier or the nonmonotonic modifier can be specified
20341 // but not both.
20342 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
20343 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
20344 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
20345 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
20346 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
20347 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
20348 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
20349 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
20350 return nullptr;
20351 }
20352 if (Kind == OMPC_SCHEDULE_unknown) {
20353 std::string Values;
20354 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
20355 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
20356 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
20358 Exclude);
20359 } else {
20360 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
20361 /*Last=*/OMPC_SCHEDULE_unknown);
20362 }
20363 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
20364 << Values << getOpenMPClauseNameForDiag(OMPC_schedule);
20365 return nullptr;
20366 }
20367 // OpenMP, 2.7.1, Loop Construct, Restrictions
20368 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
20369 // schedule(guided).
20370 // OpenMP 5.0 does not have this restriction.
20371 if (getLangOpts().OpenMP < 50 &&
20372 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
20373 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
20374 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
20375 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
20376 diag::err_omp_schedule_nonmonotonic_static);
20377 return nullptr;
20378 }
20379 Expr *ValExpr = ChunkSize;
20380 Stmt *HelperValStmt = nullptr;
20381 if (ChunkSize) {
20382 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
20383 !ChunkSize->isInstantiationDependent() &&
20384 !ChunkSize->containsUnexpandedParameterPack()) {
20385 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
20386 ExprResult Val =
20387 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
20388 if (Val.isInvalid())
20389 return nullptr;
20390
20391 ValExpr = Val.get();
20392
20393 // OpenMP [2.7.1, Restrictions]
20394 // chunk_size must be a loop invariant integer expression with a positive
20395 // value.
20396 if (std::optional<llvm::APSInt> Result =
20398 if (Result->isSigned() && !Result->isStrictlyPositive()) {
20399 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
20400 << "schedule" << 1 << ChunkSize->getSourceRange();
20401 return nullptr;
20402 }
20404 DSAStack->getCurrentDirective(), OMPC_schedule,
20405 getLangOpts().getOpenMPVersion()) != OMPD_unknown &&
20406 !SemaRef.CurContext->isDependentContext()) {
20407 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
20408 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20409 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
20410 HelperValStmt = buildPreInits(getASTContext(), Captures);
20411 }
20412 }
20413 }
20414
20415 return new (getASTContext())
20416 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
20417 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
20418}
20419
20421 SourceLocation StartLoc,
20422 SourceLocation EndLoc) {
20423 OMPClause *Res = nullptr;
20424 switch (Kind) {
20425 case OMPC_ordered:
20426 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
20427 break;
20428 case OMPC_nowait:
20429 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc,
20430 /*LParenLoc=*/SourceLocation(),
20431 /*Condition=*/nullptr);
20432 break;
20433 case OMPC_untied:
20434 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
20435 break;
20436 case OMPC_mergeable:
20437 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
20438 break;
20439 case OMPC_read:
20440 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
20441 break;
20442 case OMPC_write:
20443 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
20444 break;
20445 case OMPC_update:
20446 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
20447 break;
20448 case OMPC_capture:
20449 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
20450 break;
20451 case OMPC_compare:
20452 Res = ActOnOpenMPCompareClause(StartLoc, EndLoc);
20453 break;
20454 case OMPC_fail:
20455 Res = ActOnOpenMPFailClause(StartLoc, EndLoc);
20456 break;
20457 case OMPC_seq_cst:
20458 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
20459 break;
20460 case OMPC_acq_rel:
20461 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
20462 break;
20463 case OMPC_acquire:
20464 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
20465 break;
20466 case OMPC_release:
20467 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
20468 break;
20469 case OMPC_relaxed:
20470 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
20471 break;
20472 case OMPC_weak:
20473 Res = ActOnOpenMPWeakClause(StartLoc, EndLoc);
20474 break;
20475 case OMPC_threads:
20476 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
20477 break;
20478 case OMPC_simd:
20479 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
20480 break;
20481 case OMPC_nogroup:
20482 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
20483 break;
20484 case OMPC_unified_address:
20485 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
20486 break;
20487 case OMPC_unified_shared_memory:
20488 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
20489 break;
20490 case OMPC_reverse_offload:
20491 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
20492 break;
20493 case OMPC_dynamic_allocators:
20494 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
20495 break;
20496 case OMPC_self_maps:
20497 Res = ActOnOpenMPSelfMapsClause(StartLoc, EndLoc);
20498 break;
20499 case OMPC_destroy:
20500 Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
20501 /*LParenLoc=*/SourceLocation(),
20502 /*VarLoc=*/SourceLocation(), EndLoc);
20503 break;
20504 case OMPC_full:
20505 Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
20506 break;
20507 case OMPC_partial:
20508 Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
20509 break;
20510 case OMPC_ompx_bare:
20511 Res = ActOnOpenMPXBareClause(StartLoc, EndLoc);
20512 break;
20513 case OMPC_if:
20514 case OMPC_final:
20515 case OMPC_num_threads:
20516 case OMPC_safelen:
20517 case OMPC_simdlen:
20518 case OMPC_sizes:
20519 case OMPC_depth:
20520 case OMPC_allocator:
20521 case OMPC_collapse:
20522 case OMPC_schedule:
20523 case OMPC_private:
20524 case OMPC_firstprivate:
20525 case OMPC_lastprivate:
20526 case OMPC_shared:
20527 case OMPC_reduction:
20528 case OMPC_task_reduction:
20529 case OMPC_in_reduction:
20530 case OMPC_linear:
20531 case OMPC_aligned:
20532 case OMPC_copyin:
20533 case OMPC_copyprivate:
20534 case OMPC_default:
20535 case OMPC_proc_bind:
20536 case OMPC_threadprivate:
20537 case OMPC_groupprivate:
20538 case OMPC_allocate:
20539 case OMPC_flush:
20540 case OMPC_depobj:
20541 case OMPC_depend:
20542 case OMPC_device:
20543 case OMPC_map:
20544 case OMPC_num_teams:
20545 case OMPC_thread_limit:
20546 case OMPC_priority:
20547 case OMPC_grainsize:
20548 case OMPC_num_tasks:
20549 case OMPC_hint:
20550 case OMPC_dist_schedule:
20551 case OMPC_defaultmap:
20552 case OMPC_unknown:
20553 case OMPC_uniform:
20554 case OMPC_to:
20555 case OMPC_from:
20556 case OMPC_use_device_ptr:
20557 case OMPC_use_device_addr:
20558 case OMPC_is_device_ptr:
20559 case OMPC_has_device_addr:
20560 case OMPC_atomic_default_mem_order:
20561 case OMPC_device_type:
20562 case OMPC_match:
20563 case OMPC_nontemporal:
20564 case OMPC_order:
20565 case OMPC_at:
20566 case OMPC_severity:
20567 case OMPC_message:
20568 case OMPC_novariants:
20569 case OMPC_nocontext:
20570 case OMPC_detach:
20571 case OMPC_inclusive:
20572 case OMPC_exclusive:
20573 case OMPC_uses_allocators:
20574 case OMPC_affinity:
20575 case OMPC_when:
20576 case OMPC_ompx_dyn_cgroup_mem:
20577 case OMPC_dyn_groupprivate:
20578 default:
20579 llvm_unreachable("Clause is not allowed.");
20580 }
20581 return Res;
20582}
20583
20585 SourceLocation EndLoc,
20586 SourceLocation LParenLoc,
20587 Expr *Condition) {
20588 Expr *ValExpr = Condition;
20589 if (Condition && LParenLoc.isValid()) {
20590 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
20591 !Condition->isInstantiationDependent() &&
20592 !Condition->containsUnexpandedParameterPack()) {
20593 ExprResult Val = SemaRef.CheckBooleanCondition(StartLoc, Condition);
20594 if (Val.isInvalid())
20595 return nullptr;
20596
20597 ValExpr = Val.get();
20598 }
20599 }
20600 DSAStack->setNowaitRegion();
20601 return new (getASTContext())
20602 OMPNowaitClause(ValExpr, StartLoc, LParenLoc, EndLoc);
20603}
20604
20606 SourceLocation EndLoc) {
20607 DSAStack->setUntiedRegion();
20608 return new (getASTContext()) OMPUntiedClause(StartLoc, EndLoc);
20609}
20610
20612 SourceLocation EndLoc) {
20613 return new (getASTContext()) OMPMergeableClause(StartLoc, EndLoc);
20614}
20615
20617 SourceLocation EndLoc) {
20618 return new (getASTContext()) OMPReadClause(StartLoc, EndLoc);
20619}
20620
20622 SourceLocation EndLoc) {
20623 return new (getASTContext()) OMPWriteClause(StartLoc, EndLoc);
20624}
20625
20627 SourceLocation EndLoc) {
20628 return new (getASTContext()) OMPUpdateClause(StartLoc, EndLoc);
20629}
20630
20632 SourceLocation EndLoc) {
20633 return new (getASTContext()) OMPCaptureClause(StartLoc, EndLoc);
20634}
20635
20637 SourceLocation EndLoc) {
20638 return new (getASTContext()) OMPCompareClause(StartLoc, EndLoc);
20639}
20640
20642 SourceLocation EndLoc) {
20643 return new (getASTContext()) OMPFailClause(StartLoc, EndLoc);
20644}
20645
20647 SourceLocation KindLoc,
20648 SourceLocation StartLoc,
20649 SourceLocation LParenLoc,
20650 SourceLocation EndLoc) {
20651
20653 Diag(KindLoc, diag::err_omp_atomic_fail_wrong_or_no_clauses);
20654 return nullptr;
20655 }
20656 return new (getASTContext())
20657 OMPFailClause(Parameter, KindLoc, StartLoc, LParenLoc, EndLoc);
20658}
20659
20661 SourceLocation EndLoc) {
20662 return new (getASTContext()) OMPSeqCstClause(StartLoc, EndLoc);
20663}
20664
20666 SourceLocation EndLoc) {
20667 return new (getASTContext()) OMPAcqRelClause(StartLoc, EndLoc);
20668}
20669
20671 SourceLocation EndLoc) {
20672 return new (getASTContext()) OMPAcquireClause(StartLoc, EndLoc);
20673}
20674
20676 SourceLocation EndLoc) {
20677 return new (getASTContext()) OMPReleaseClause(StartLoc, EndLoc);
20678}
20679
20681 SourceLocation EndLoc) {
20682 return new (getASTContext()) OMPRelaxedClause(StartLoc, EndLoc);
20683}
20684
20686 SourceLocation EndLoc) {
20687 return new (getASTContext()) OMPWeakClause(StartLoc, EndLoc);
20688}
20689
20691 SourceLocation EndLoc) {
20692 return new (getASTContext()) OMPThreadsClause(StartLoc, EndLoc);
20693}
20694
20696 SourceLocation EndLoc) {
20697 return new (getASTContext()) OMPSIMDClause(StartLoc, EndLoc);
20698}
20699
20701 SourceLocation EndLoc) {
20702 return new (getASTContext()) OMPNogroupClause(StartLoc, EndLoc);
20703}
20704
20706 SourceLocation EndLoc) {
20707 return new (getASTContext()) OMPUnifiedAddressClause(StartLoc, EndLoc);
20708}
20709
20710OMPClause *
20712 SourceLocation EndLoc) {
20713 return new (getASTContext()) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
20714}
20715
20717 SourceLocation EndLoc) {
20718 return new (getASTContext()) OMPReverseOffloadClause(StartLoc, EndLoc);
20719}
20720
20721OMPClause *
20723 SourceLocation EndLoc) {
20724 return new (getASTContext()) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
20725}
20726
20728 SourceLocation EndLoc) {
20729 return new (getASTContext()) OMPSelfMapsClause(StartLoc, EndLoc);
20730}
20731
20734 SourceLocation StartLoc,
20735 SourceLocation EndLoc) {
20736
20737 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
20738 // At least one action-clause must appear on a directive.
20739 if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
20740 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
20741 StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
20742 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
20743 << Expected << getOpenMPDirectiveName(OMPD_interop, OMPVersion);
20744 return StmtError();
20745 }
20746
20747 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
20748 // A depend clause can only appear on the directive if a targetsync
20749 // interop-type is present or the interop-var was initialized with
20750 // the targetsync interop-type.
20751
20752 // If there is any 'init' clause diagnose if there is no 'init' clause with
20753 // interop-type of 'targetsync'. Cases involving other directives cannot be
20754 // diagnosed.
20755 const OMPDependClause *DependClause = nullptr;
20756 bool HasInitClause = false;
20757 bool IsTargetSync = false;
20758 for (const OMPClause *C : Clauses) {
20759 if (IsTargetSync)
20760 break;
20761 if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
20762 HasInitClause = true;
20763 if (InitClause->getIsTargetSync())
20764 IsTargetSync = true;
20765 } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
20766 DependClause = DC;
20767 }
20768 }
20769 if (DependClause && HasInitClause && !IsTargetSync) {
20770 Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
20771 return StmtError();
20772 }
20773
20774 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
20775 // Each interop-var may be specified for at most one action-clause of each
20776 // interop construct.
20778 for (OMPClause *C : Clauses) {
20779 OpenMPClauseKind ClauseKind = C->getClauseKind();
20780 std::pair<ValueDecl *, bool> DeclResult;
20781 SourceLocation ELoc;
20782 SourceRange ERange;
20783
20784 if (ClauseKind == OMPC_init) {
20785 auto *E = cast<OMPInitClause>(C)->getInteropVar();
20786 DeclResult = getPrivateItem(SemaRef, E, ELoc, ERange);
20787 } else if (ClauseKind == OMPC_use) {
20788 auto *E = cast<OMPUseClause>(C)->getInteropVar();
20789 DeclResult = getPrivateItem(SemaRef, E, ELoc, ERange);
20790 } else if (ClauseKind == OMPC_destroy) {
20791 auto *E = cast<OMPDestroyClause>(C)->getInteropVar();
20792 DeclResult = getPrivateItem(SemaRef, E, ELoc, ERange);
20793 }
20794
20795 if (DeclResult.first) {
20796 if (!InteropVars.insert(DeclResult.first).second) {
20797 Diag(ELoc, diag::err_omp_interop_var_multiple_actions)
20798 << DeclResult.first;
20799 return StmtError();
20800 }
20801 }
20802 }
20803
20804 return OMPInteropDirective::Create(getASTContext(), StartLoc, EndLoc,
20805 Clauses);
20806}
20807
20808static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
20809 SourceLocation VarLoc,
20810 OpenMPClauseKind Kind) {
20811 SourceLocation ELoc;
20812 SourceRange ERange;
20813 Expr *RefExpr = InteropVarExpr;
20814 auto Res = getPrivateItem(SemaRef, RefExpr, ELoc, ERange,
20815 /*AllowArraySection=*/false,
20816 /*AllowAssumedSizeArray=*/false,
20817 /*DiagType=*/"omp_interop_t");
20818
20819 if (Res.second) {
20820 // It will be analyzed later.
20821 return true;
20822 }
20823
20824 if (!Res.first)
20825 return false;
20826
20827 // Interop variable should be of type omp_interop_t.
20828 bool HasError = false;
20829 QualType InteropType;
20830 LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
20831 VarLoc, Sema::LookupOrdinaryName);
20832 if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
20833 NamedDecl *ND = Result.getFoundDecl();
20834 if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
20835 InteropType = QualType(TD->getTypeForDecl(), 0);
20836 } else {
20837 HasError = true;
20838 }
20839 } else {
20840 HasError = true;
20841 }
20842
20843 if (HasError) {
20844 SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
20845 << "omp_interop_t";
20846 return false;
20847 }
20848
20849 QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
20850 if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
20851 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
20852 return false;
20853 }
20854
20855 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
20856 // The interop-var passed to init or destroy must be non-const.
20857 if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
20858 isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
20859 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
20860 << /*non-const*/ 1;
20861 return false;
20862 }
20863 return true;
20864}
20865
20867 Expr *InteropVar, OMPInteropInfo &InteropInfo, SourceLocation StartLoc,
20868 SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc) {
20869
20870 if (!isValidInteropVariable(SemaRef, InteropVar, VarLoc, OMPC_init))
20871 return nullptr;
20872
20873 if (!checkPreferTypeArgs(*this, InteropInfo))
20874 return nullptr;
20875
20876 return OMPInitClause::Create(getASTContext(), InteropVar, InteropInfo,
20877 StartLoc, LParenLoc, VarLoc, EndLoc);
20878}
20879
20881 SourceLocation StartLoc,
20882 SourceLocation LParenLoc,
20883 SourceLocation VarLoc,
20884 SourceLocation EndLoc) {
20885
20886 if (!isValidInteropVariable(SemaRef, InteropVar, VarLoc, OMPC_use))
20887 return nullptr;
20888
20889 return new (getASTContext())
20890 OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
20891}
20892
20894 SourceLocation StartLoc,
20895 SourceLocation LParenLoc,
20896 SourceLocation VarLoc,
20897 SourceLocation EndLoc) {
20898 if (!InteropVar && getLangOpts().OpenMP >= 52 &&
20899 DSAStack->getCurrentDirective() == OMPD_depobj) {
20900 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
20901 Diag(StartLoc, diag::err_omp_expected_clause_argument)
20902 << getOpenMPClauseNameForDiag(OMPC_destroy)
20903 << getOpenMPDirectiveName(OMPD_depobj, OMPVersion);
20904 return nullptr;
20905 }
20906 if (InteropVar &&
20907 !isValidInteropVariable(SemaRef, InteropVar, VarLoc, OMPC_destroy))
20908 return nullptr;
20909
20910 return new (getASTContext())
20911 OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
20912}
20913
20915 SourceLocation StartLoc,
20916 SourceLocation LParenLoc,
20917 SourceLocation EndLoc) {
20918 Expr *ValExpr = Condition;
20919 Stmt *HelperValStmt = nullptr;
20920 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20921 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
20922 !Condition->isInstantiationDependent() &&
20923 !Condition->containsUnexpandedParameterPack()) {
20924 ExprResult Val = SemaRef.CheckBooleanCondition(StartLoc, Condition);
20925 if (Val.isInvalid())
20926 return nullptr;
20927
20928 ValExpr = SemaRef.MakeFullExpr(Val.get()).get();
20929
20930 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20931 CaptureRegion = getOpenMPCaptureRegionForClause(
20932 DKind, OMPC_novariants, getLangOpts().getOpenMPVersion());
20933 if (CaptureRegion != OMPD_unknown &&
20934 !SemaRef.CurContext->isDependentContext()) {
20935 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
20936 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20937 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
20938 HelperValStmt = buildPreInits(getASTContext(), Captures);
20939 }
20940 }
20941
20942 return new (getASTContext()) OMPNovariantsClause(
20943 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
20944}
20945
20947 SourceLocation StartLoc,
20948 SourceLocation LParenLoc,
20949 SourceLocation EndLoc) {
20950 Expr *ValExpr = Condition;
20951 Stmt *HelperValStmt = nullptr;
20952 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
20953 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
20954 !Condition->isInstantiationDependent() &&
20955 !Condition->containsUnexpandedParameterPack()) {
20956 ExprResult Val = SemaRef.CheckBooleanCondition(StartLoc, Condition);
20957 if (Val.isInvalid())
20958 return nullptr;
20959
20960 ValExpr = SemaRef.MakeFullExpr(Val.get()).get();
20961
20962 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20963 CaptureRegion = getOpenMPCaptureRegionForClause(
20964 DKind, OMPC_nocontext, getLangOpts().getOpenMPVersion());
20965 if (CaptureRegion != OMPD_unknown &&
20966 !SemaRef.CurContext->isDependentContext()) {
20967 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
20968 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20969 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
20970 HelperValStmt = buildPreInits(getASTContext(), Captures);
20971 }
20972 }
20973
20974 return new (getASTContext()) OMPNocontextClause(
20975 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
20976}
20977
20979 SourceLocation StartLoc,
20980 SourceLocation LParenLoc,
20981 SourceLocation EndLoc) {
20982 Expr *ValExpr = ThreadID;
20983 Stmt *HelperValStmt = nullptr;
20984
20985 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
20987 DKind, OMPC_filter, getLangOpts().getOpenMPVersion());
20988 if (CaptureRegion != OMPD_unknown &&
20989 !SemaRef.CurContext->isDependentContext()) {
20990 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
20991 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
20992 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
20993 HelperValStmt = buildPreInits(getASTContext(), Captures);
20994 }
20995
20996 return new (getASTContext()) OMPFilterClause(
20997 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
20998}
20999
21001 ArrayRef<Expr *> VarList,
21002 const OMPVarListLocTy &Locs,
21004 SourceLocation StartLoc = Locs.StartLoc;
21005 SourceLocation LParenLoc = Locs.LParenLoc;
21006 SourceLocation EndLoc = Locs.EndLoc;
21007 OMPClause *Res = nullptr;
21008 int ExtraModifier = Data.ExtraModifier;
21009 int OriginalSharingModifier = Data.OriginalSharingModifier;
21010 Expr *ExtraModifierExpr = Data.ExtraModifierExpr;
21011 SourceLocation ExtraModifierLoc = Data.ExtraModifierLoc;
21012 SourceLocation ColonLoc = Data.ColonLoc;
21013 switch (Kind) {
21014 case OMPC_private:
21015 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
21016 break;
21017 case OMPC_firstprivate:
21018 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
21019 break;
21020 case OMPC_lastprivate:
21021 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
21022 "Unexpected lastprivate modifier.");
21024 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
21025 ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
21026 break;
21027 case OMPC_shared:
21028 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
21029 break;
21030 case OMPC_reduction:
21031 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
21032 "Unexpected lastprivate modifier.");
21034 VarList,
21036 ExtraModifier, OriginalSharingModifier),
21037 StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
21038 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId);
21039 break;
21040 case OMPC_task_reduction:
21042 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc,
21043 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId);
21044 break;
21045 case OMPC_in_reduction:
21047 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc,
21048 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId);
21049 break;
21050 case OMPC_linear:
21051 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
21052 "Unexpected linear modifier.");
21054 VarList, Data.DepModOrTailExpr, StartLoc, LParenLoc,
21055 static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
21056 ColonLoc, Data.StepModifierLoc, EndLoc);
21057 break;
21058 case OMPC_aligned:
21059 Res = ActOnOpenMPAlignedClause(VarList, Data.DepModOrTailExpr, StartLoc,
21060 LParenLoc, ColonLoc, EndLoc);
21061 break;
21062 case OMPC_copyin:
21063 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
21064 break;
21065 case OMPC_copyprivate:
21066 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
21067 break;
21068 case OMPC_flush:
21069 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
21070 break;
21071 case OMPC_depend:
21072 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
21073 "Unexpected depend modifier.");
21075 {static_cast<OpenMPDependClauseKind>(ExtraModifier), ExtraModifierLoc,
21076 ColonLoc, Data.OmpAllMemoryLoc},
21077 Data.DepModOrTailExpr, VarList, StartLoc, LParenLoc, EndLoc);
21078 break;
21079 case OMPC_map:
21080 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
21081 "Unexpected map modifier.");
21083 Data.IteratorExpr, Data.MapTypeModifiers, Data.MapTypeModifiersLoc,
21084 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId,
21085 static_cast<OpenMPMapClauseKind>(ExtraModifier), Data.IsMapTypeImplicit,
21086 ExtraModifierLoc, ColonLoc, VarList, Locs);
21087 break;
21088 case OMPC_to:
21089 Res = ActOnOpenMPToClause(
21090 Data.MotionModifiers, Data.MotionModifiersLoc, Data.IteratorExpr,
21091 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId, ColonLoc,
21092 VarList, Locs);
21093 break;
21094 case OMPC_from:
21096 Data.MotionModifiers, Data.MotionModifiersLoc, Data.IteratorExpr,
21097 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId, ColonLoc,
21098 VarList, Locs);
21099 break;
21100 case OMPC_use_device_ptr:
21101 assert(0 <= Data.ExtraModifier &&
21102 Data.ExtraModifier <= OMPC_USE_DEVICE_PTR_FALLBACK_unknown &&
21103 "Unexpected use_device_ptr fallback modifier.");
21105 VarList, Locs,
21106 static_cast<OpenMPUseDevicePtrFallbackModifier>(Data.ExtraModifier),
21107 Data.ExtraModifierLoc);
21108 break;
21109 case OMPC_use_device_addr:
21110 Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
21111 break;
21112 case OMPC_is_device_ptr:
21113 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
21114 break;
21115 case OMPC_has_device_addr:
21116 Res = ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
21117 break;
21118 case OMPC_allocate: {
21121 SourceLocation Modifier1Loc, Modifier2Loc;
21122 if (!Data.AllocClauseModifiers.empty()) {
21123 assert(Data.AllocClauseModifiers.size() <= 2 &&
21124 "More allocate modifiers than expected");
21125 Modifier1 = Data.AllocClauseModifiers[0];
21126 Modifier1Loc = Data.AllocClauseModifiersLoc[0];
21127 if (Data.AllocClauseModifiers.size() == 2) {
21128 Modifier2 = Data.AllocClauseModifiers[1];
21129 Modifier2Loc = Data.AllocClauseModifiersLoc[1];
21130 }
21131 }
21133 Data.DepModOrTailExpr, Data.AllocateAlignment, Modifier1, Modifier1Loc,
21134 Modifier2, Modifier2Loc, VarList, StartLoc, LParenLoc, ColonLoc,
21135 EndLoc);
21136 break;
21137 }
21138 case OMPC_nontemporal:
21139 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
21140 break;
21141 case OMPC_inclusive:
21142 Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
21143 break;
21144 case OMPC_exclusive:
21145 Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
21146 break;
21147 case OMPC_affinity:
21148 Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
21149 Data.DepModOrTailExpr, VarList);
21150 break;
21151 case OMPC_doacross:
21153 static_cast<OpenMPDoacrossClauseModifier>(ExtraModifier),
21154 ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
21155 break;
21156 case OMPC_num_teams:
21157 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_NUMTEAMS_unknown &&
21158 "Unexpected num_teams modifier.");
21160 VarList,
21161 static_cast<OpenMPNumTeamsClauseModifier>(Data.ExtraModifierArray[0]),
21162 Data.ExtraModifierExprArray[0], Data.ExtraModifierLocArray[0],
21163 static_cast<OpenMPNumTeamsClauseModifier>(Data.ExtraModifierArray[1]),
21164 Data.ExtraModifierExprArray[1], Data.ExtraModifierLocArray[1], StartLoc,
21165 LParenLoc, EndLoc);
21166 break;
21167 case OMPC_thread_limit:
21168 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_THREADLIMIT_unknown &&
21169 "Unexpected thread_limit modifier.");
21171 VarList, static_cast<OpenMPThreadLimitClauseModifier>(ExtraModifier),
21172 ExtraModifierExpr, ExtraModifierLoc, StartLoc, LParenLoc, EndLoc);
21173 break;
21174 case OMPC_num_threads:
21175 assert(0 <= Data.ExtraModifierArray[0] &&
21176 Data.ExtraModifierArray[0] <= OMPC_NUMTHREADS_unknown &&
21177 0 <= Data.ExtraModifierArray[1] &&
21178 Data.ExtraModifierArray[1] <= OMPC_NUMTHREADS_unknown &&
21179 "Unexpected num_threads modifier.");
21181 VarList,
21182 static_cast<OpenMPNumThreadsClauseModifier>(Data.ExtraModifierArray[0]),
21183 Data.ExtraModifierLocArray[0],
21184 static_cast<OpenMPNumThreadsClauseModifier>(Data.ExtraModifierArray[1]),
21185 Data.ExtraModifierExprArray[1], Data.ExtraModifierLocArray[1], StartLoc,
21186 LParenLoc, EndLoc);
21187 break;
21188 case OMPC_if:
21189 case OMPC_depobj:
21190 case OMPC_final:
21191 case OMPC_safelen:
21192 case OMPC_simdlen:
21193 case OMPC_sizes:
21194 case OMPC_depth:
21195 case OMPC_allocator:
21196 case OMPC_collapse:
21197 case OMPC_default:
21198 case OMPC_proc_bind:
21199 case OMPC_schedule:
21200 case OMPC_ordered:
21201 case OMPC_nowait:
21202 case OMPC_untied:
21203 case OMPC_mergeable:
21204 case OMPC_threadprivate:
21205 case OMPC_groupprivate:
21206 case OMPC_read:
21207 case OMPC_write:
21208 case OMPC_update:
21209 case OMPC_capture:
21210 case OMPC_compare:
21211 case OMPC_seq_cst:
21212 case OMPC_acq_rel:
21213 case OMPC_acquire:
21214 case OMPC_release:
21215 case OMPC_relaxed:
21216 case OMPC_device:
21217 case OMPC_threads:
21218 case OMPC_simd:
21219 case OMPC_priority:
21220 case OMPC_grainsize:
21221 case OMPC_nogroup:
21222 case OMPC_num_tasks:
21223 case OMPC_hint:
21224 case OMPC_dist_schedule:
21225 case OMPC_defaultmap:
21226 case OMPC_unknown:
21227 case OMPC_uniform:
21228 case OMPC_unified_address:
21229 case OMPC_unified_shared_memory:
21230 case OMPC_reverse_offload:
21231 case OMPC_dynamic_allocators:
21232 case OMPC_atomic_default_mem_order:
21233 case OMPC_self_maps:
21234 case OMPC_device_type:
21235 case OMPC_match:
21236 case OMPC_order:
21237 case OMPC_at:
21238 case OMPC_severity:
21239 case OMPC_message:
21240 case OMPC_destroy:
21241 case OMPC_novariants:
21242 case OMPC_nocontext:
21243 case OMPC_detach:
21244 case OMPC_uses_allocators:
21245 case OMPC_when:
21246 case OMPC_bind:
21247 default:
21248 llvm_unreachable("Clause is not allowed.");
21249 }
21250 return Res;
21251}
21252
21254 ExprObjectKind OK,
21255 SourceLocation Loc) {
21256 ExprResult Res = SemaRef.BuildDeclRefExpr(
21257 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
21258 if (!Res.isUsable())
21259 return ExprError();
21260 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
21261 Res = SemaRef.CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
21262 if (!Res.isUsable())
21263 return ExprError();
21264 }
21265 if (VK != VK_LValue && Res.get()->isGLValue()) {
21266 Res = SemaRef.DefaultLvalueConversion(Res.get());
21267 if (!Res.isUsable())
21268 return ExprError();
21269 }
21270 return Res;
21271}
21272
21274 SourceLocation StartLoc,
21275 SourceLocation LParenLoc,
21276 SourceLocation EndLoc) {
21278 SmallVector<Expr *, 8> PrivateCopies;
21279 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
21280 bool IsImplicitClause =
21281 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
21282 for (Expr *RefExpr : VarList) {
21283 assert(RefExpr && "NULL expr in OpenMP private clause.");
21284 SourceLocation ELoc;
21285 SourceRange ERange;
21286 Expr *SimpleRefExpr = RefExpr;
21287 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
21288 if (Res.second) {
21289 // It will be analyzed later.
21290 Vars.push_back(RefExpr);
21291 PrivateCopies.push_back(nullptr);
21292 }
21293 ValueDecl *D = Res.first;
21294 if (!D)
21295 continue;
21296
21297 QualType Type = D->getType();
21298 auto *VD = dyn_cast<VarDecl>(D);
21299
21300 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
21301 // A variable that appears in a private clause must not have an incomplete
21302 // type or a reference type.
21303 if (SemaRef.RequireCompleteType(ELoc, Type,
21304 diag::err_omp_private_incomplete_type))
21305 continue;
21306 Type = Type.getNonReferenceType();
21307
21308 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
21309 // A variable that is privatized must not have a const-qualified type
21310 // unless it is of class type with a mutable member. This restriction does
21311 // not apply to the firstprivate clause.
21312 //
21313 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
21314 // A variable that appears in a private clause must not have a
21315 // const-qualified type unless it is of class type with a mutable member.
21316 if (rejectConstNotMutableType(SemaRef, D, Type, OMPC_private, ELoc))
21317 continue;
21318
21319 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
21320 // in a Construct]
21321 // Variables with the predetermined data-sharing attributes may not be
21322 // listed in data-sharing attributes clauses, except for the cases
21323 // listed below. For these exceptions only, listing a predetermined
21324 // variable in a data-sharing attribute clause is allowed and overrides
21325 // the variable's predetermined data-sharing attributes.
21326 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
21327 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
21328 Diag(ELoc, diag::err_omp_wrong_dsa)
21329 << getOpenMPClauseNameForDiag(DVar.CKind)
21330 << getOpenMPClauseNameForDiag(OMPC_private);
21332 continue;
21333 }
21334
21335 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
21336 // Variably modified types are not supported for tasks.
21338 isOpenMPTaskingDirective(CurrDir)) {
21339 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
21340 << getOpenMPClauseNameForDiag(OMPC_private) << Type
21341 << getOpenMPDirectiveName(CurrDir, OMPVersion);
21342 bool IsDecl = !VD || VD->isThisDeclarationADefinition(getASTContext()) ==
21344 Diag(D->getLocation(),
21345 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
21346 << D;
21347 continue;
21348 }
21349
21350 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
21351 // A list item cannot appear in both a map clause and a data-sharing
21352 // attribute clause on the same construct
21353 //
21354 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
21355 // A list item cannot appear in both a map clause and a data-sharing
21356 // attribute clause on the same construct unless the construct is a
21357 // combined construct.
21358 if ((getLangOpts().OpenMP <= 45 &&
21360 CurrDir == OMPD_target) {
21361 OpenMPClauseKind ConflictKind;
21362 if (DSAStack->checkMappableExprComponentListsForDecl(
21363 VD, /*CurrentRegionOnly=*/true,
21365 OpenMPClauseKind WhereFoundClauseKind) -> bool {
21366 ConflictKind = WhereFoundClauseKind;
21367 return true;
21368 })) {
21369 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
21370 << getOpenMPClauseNameForDiag(OMPC_private)
21371 << getOpenMPClauseNameForDiag(ConflictKind)
21372 << getOpenMPDirectiveName(CurrDir, OMPVersion);
21374 continue;
21375 }
21376 }
21377
21378 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
21379 // A variable of class type (or array thereof) that appears in a private
21380 // clause requires an accessible, unambiguous default constructor for the
21381 // class type.
21382 // Generate helper private variable and initialize it with the default
21383 // value. The address of the original variable is replaced by the address of
21384 // the new private variable in CodeGen. This new variable is not added to
21385 // IdResolver, so the code in the OpenMP region uses original variable for
21386 // proper diagnostics.
21387 Type = Type.getUnqualifiedType();
21388 VarDecl *VDPrivate =
21389 buildVarDecl(SemaRef, ELoc, Type, D->getName(),
21390 D->hasAttrs() ? &D->getAttrs() : nullptr,
21391 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
21392 SemaRef.ActOnUninitializedDecl(VDPrivate);
21393 if (VDPrivate->isInvalidDecl())
21394 continue;
21395 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
21396 SemaRef, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
21397
21398 DeclRefExpr *Ref = nullptr;
21399 bool IsBindingDecl = isa<BindingDecl>(D);
21400 if (!VD && !IsBindingDecl && !SemaRef.CurContext->isDependentContext()) {
21401 auto *FD = dyn_cast<FieldDecl>(D);
21402 VarDecl *VD = FD ? DSAStack->getImplicitFDCapExprDecl(FD) : nullptr;
21403 if (VD)
21405 RefExpr->getExprLoc());
21406 else
21407 Ref = buildCapture(SemaRef, D, SimpleRefExpr, /*WithInit=*/false);
21408 }
21409 if (!IsImplicitClause) {
21410 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
21411 }
21412 Vars.push_back(
21413 (VD || IsBindingDecl || SemaRef.CurContext->isDependentContext())
21414 ? RefExpr->IgnoreParens()
21415 : Ref);
21416 PrivateCopies.push_back(VDPrivateRefExpr);
21417 }
21418
21419 if (Vars.empty())
21420 return nullptr;
21421
21422 return OMPPrivateClause::Create(getASTContext(), StartLoc, LParenLoc, EndLoc,
21423 Vars, PrivateCopies);
21424}
21425
21427 SourceLocation StartLoc,
21428 SourceLocation LParenLoc,
21429 SourceLocation EndLoc) {
21431 SmallVector<Expr *, 8> PrivateCopies;
21433 SmallVector<Decl *, 4> ExprCaptures;
21434 bool IsImplicitClause =
21435 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
21436 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
21437 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
21438
21439 for (Expr *RefExpr : VarList) {
21440 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
21441 SourceLocation ELoc;
21442 SourceRange ERange;
21443 Expr *SimpleRefExpr = RefExpr;
21444 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
21445 if (Res.second) {
21446 // It will be analyzed later.
21447 Vars.push_back(RefExpr);
21448 PrivateCopies.push_back(nullptr);
21449 Inits.push_back(nullptr);
21450 }
21451 ValueDecl *D = Res.first;
21452 if (!D)
21453 continue;
21454
21455 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
21456 QualType Type = D->getType();
21457 auto *VD = dyn_cast<VarDecl>(D);
21458
21459 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
21460 // A variable that appears in a private clause must not have an incomplete
21461 // type or a reference type.
21462 if (SemaRef.RequireCompleteType(ELoc, Type,
21463 diag::err_omp_firstprivate_incomplete_type))
21464 continue;
21465 Type = Type.getNonReferenceType();
21466
21467 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
21468 // A variable of class type (or array thereof) that appears in a private
21469 // clause requires an accessible, unambiguous copy constructor for the
21470 // class type.
21471 QualType ElemType =
21473
21474 // If an implicit firstprivate variable found it was checked already.
21475 DSAStackTy::DSAVarData TopDVar;
21476 if (!IsImplicitClause) {
21477 DSAStackTy::DSAVarData DVar =
21478 DSAStack->getTopDSA(D, /*FromParent=*/false);
21479 TopDVar = DVar;
21480 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
21481 bool IsConstant = ElemType.isConstant(getASTContext());
21482 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
21483 // A list item that specifies a given variable may not appear in more
21484 // than one clause on the same directive, except that a variable may be
21485 // specified in both firstprivate and lastprivate clauses.
21486 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
21487 // A list item may appear in a firstprivate or lastprivate clause but not
21488 // both.
21489 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
21490 (isOpenMPDistributeDirective(CurrDir) ||
21491 DVar.CKind != OMPC_lastprivate) &&
21492 DVar.RefExpr) {
21493 Diag(ELoc, diag::err_omp_wrong_dsa)
21494 << getOpenMPClauseNameForDiag(DVar.CKind)
21495 << getOpenMPClauseNameForDiag(OMPC_firstprivate);
21497 continue;
21498 }
21499
21500 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
21501 // in a Construct]
21502 // Variables with the predetermined data-sharing attributes may not be
21503 // listed in data-sharing attributes clauses, except for the cases
21504 // listed below. For these exceptions only, listing a predetermined
21505 // variable in a data-sharing attribute clause is allowed and overrides
21506 // the variable's predetermined data-sharing attributes.
21507 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
21508 // in a Construct, C/C++, p.2]
21509 // Variables with const-qualified type having no mutable member may be
21510 // listed in a firstprivate clause, even if they are static data members.
21511 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
21512 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
21513 Diag(ELoc, diag::err_omp_wrong_dsa)
21514 << getOpenMPClauseNameForDiag(DVar.CKind)
21515 << getOpenMPClauseNameForDiag(OMPC_firstprivate);
21517 continue;
21518 }
21519
21520 // OpenMP [2.9.3.4, Restrictions, p.2]
21521 // A list item that is private within a parallel region must not appear
21522 // in a firstprivate clause on a worksharing construct if any of the
21523 // worksharing regions arising from the worksharing construct ever bind
21524 // to any of the parallel regions arising from the parallel construct.
21525 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
21526 // A list item that is private within a teams region must not appear in a
21527 // firstprivate clause on a distribute construct if any of the distribute
21528 // regions arising from the distribute construct ever bind to any of the
21529 // teams regions arising from the teams construct.
21530 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
21531 // A list item that appears in a reduction clause of a teams construct
21532 // must not appear in a firstprivate clause on a distribute construct if
21533 // any of the distribute regions arising from the distribute construct
21534 // ever bind to any of the teams regions arising from the teams construct.
21535 if ((isOpenMPWorksharingDirective(CurrDir) ||
21536 isOpenMPDistributeDirective(CurrDir)) &&
21537 !isOpenMPParallelDirective(CurrDir) &&
21538 !isOpenMPTeamsDirective(CurrDir)) {
21539 DVar = DSAStack->getImplicitDSA(D, true);
21540 if (DVar.CKind != OMPC_shared &&
21541 (isOpenMPParallelDirective(DVar.DKind) ||
21542 isOpenMPTeamsDirective(DVar.DKind) ||
21543 DVar.DKind == OMPD_unknown)) {
21544 Diag(ELoc, diag::err_omp_required_access)
21545 << getOpenMPClauseNameForDiag(OMPC_firstprivate)
21546 << getOpenMPClauseNameForDiag(OMPC_shared);
21548 continue;
21549 }
21550 }
21551 // OpenMP [2.9.3.4, Restrictions, p.3]
21552 // A list item that appears in a reduction clause of a parallel construct
21553 // must not appear in a firstprivate clause on a worksharing or task
21554 // construct if any of the worksharing or task regions arising from the
21555 // worksharing or task construct ever bind to any of the parallel regions
21556 // arising from the parallel construct.
21557 // OpenMP [2.9.3.4, Restrictions, p.4]
21558 // A list item that appears in a reduction clause in worksharing
21559 // construct must not appear in a firstprivate clause in a task construct
21560 // encountered during execution of any of the worksharing regions arising
21561 // from the worksharing construct.
21562 if (isOpenMPTaskingDirective(CurrDir)) {
21563 DVar = DSAStack->hasInnermostDSA(
21564 D,
21565 [](OpenMPClauseKind C, bool AppliedToPointee) {
21566 return C == OMPC_reduction && !AppliedToPointee;
21567 },
21568 [](OpenMPDirectiveKind K) {
21569 return isOpenMPParallelDirective(K) ||
21572 },
21573 /*FromParent=*/true);
21574 if (DVar.CKind == OMPC_reduction &&
21575 (isOpenMPParallelDirective(DVar.DKind) ||
21576 isOpenMPWorksharingDirective(DVar.DKind) ||
21577 isOpenMPTeamsDirective(DVar.DKind))) {
21578 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
21579 << getOpenMPDirectiveName(DVar.DKind, OMPVersion);
21581 continue;
21582 }
21583 }
21584
21585 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
21586 // A list item cannot appear in both a map clause and a data-sharing
21587 // attribute clause on the same construct
21588 //
21589 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
21590 // A list item cannot appear in both a map clause and a data-sharing
21591 // attribute clause on the same construct unless the construct is a
21592 // combined construct.
21593 if ((getLangOpts().OpenMP <= 45 &&
21595 CurrDir == OMPD_target) {
21596 OpenMPClauseKind ConflictKind;
21597 if (DSAStack->checkMappableExprComponentListsForDecl(
21598 VD, /*CurrentRegionOnly=*/true,
21599 [&ConflictKind](
21601 OpenMPClauseKind WhereFoundClauseKind) {
21602 ConflictKind = WhereFoundClauseKind;
21603 return true;
21604 })) {
21605 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
21606 << getOpenMPClauseNameForDiag(OMPC_firstprivate)
21607 << getOpenMPClauseNameForDiag(ConflictKind)
21608 << getOpenMPDirectiveName(DSAStack->getCurrentDirective(),
21609 OMPVersion);
21611 continue;
21612 }
21613 }
21614 }
21615
21616 // Variably modified types are not supported for tasks.
21618 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
21619 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
21620 << getOpenMPClauseNameForDiag(OMPC_firstprivate) << Type
21621 << getOpenMPDirectiveName(DSAStack->getCurrentDirective(),
21622 OMPVersion);
21623 bool IsDecl = !VD || VD->isThisDeclarationADefinition(getASTContext()) ==
21625 Diag(D->getLocation(),
21626 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
21627 << D;
21628 continue;
21629 }
21630
21631 Type = Type.getUnqualifiedType();
21632
21633 // For BindingDecls, use the DecompositionDecl's type so all bindings from
21634 // the same decomposition are accessible in the privatized region. We do
21635 // this after conflict checking to preserve diagnostic errors. Don't modify
21636 // RefExpr/SimpleRefExpr to keep diagnostics working.
21637 bool IsBindingDecl = isa<BindingDecl>(D);
21638 VarDecl *PrivateVD = VD;
21639 QualType PrivateType = Type;
21640 if (IsBindingDecl) {
21641 const auto *BD = cast<BindingDecl>(D);
21642 PrivateVD = cast<VarDecl>(BD->getDecomposedDecl());
21643 // PrivateType stays as the BindingDecl's type (Type), not the
21644 // DecompositionDecl's type.
21645 }
21646
21647 // For regular arrays, pass the original var ref. For BindingDecls, don't
21648 // pass the DecompositionDecl ref since VDPrivate has the binding's type,
21649 // not the decomposition type.
21650 VarDecl *VDPrivate = buildVarDecl(SemaRef, ELoc, PrivateType, D->getName(),
21651 D->hasAttrs() ? &D->getAttrs() : nullptr,
21652 (PrivateVD && !IsBindingDecl)
21653 ? cast<DeclRefExpr>(SimpleRefExpr)
21654 : nullptr);
21655
21656 // Generate helper private variable and initialize it with the value of the
21657 // original variable. The address of the original variable is replaced by
21658 // the address of the new private variable in the CodeGen. This new variable
21659 // is not added to IdResolver, so the code in the OpenMP region uses
21660 // original variable for proper diagnostics and variable capturing.
21661 Expr *VDInitRefExpr = nullptr;
21662
21663 // For BindingDecls, VDPrivate should have the binding's type (not the
21664 // DecompositionDecl's type), and will be initialized from the binding's
21665 // field in the original DecompositionDecl.
21666 if (IsBindingDecl && !PrivateType->isArrayType()) {
21667 // For non-array bindings, create a simple copy initialization.
21668 VarDecl *VDInit = buildVarDecl(SemaRef, RefExpr->getExprLoc(),
21669 PrivateType, ".firstprivate.temp");
21670 VDInitRefExpr =
21671 buildDeclRefExpr(SemaRef, VDInit, PrivateType, RefExpr->getExprLoc());
21672
21673 // Initialize VDPrivate from VDInit (which will point to the field).
21674 SemaRef.AddInitializerToDecl(
21675 VDPrivate, SemaRef.DefaultLvalueConversion(VDInitRefExpr).get(),
21676 /*DirectInit=*/false);
21677 } else if (Type->isArrayType()) {
21678 // For arrays generate initializer for single element and replace it by
21679 // the original array element in CodeGen.
21680 VarDecl *VDInit =
21681 buildVarDecl(SemaRef, RefExpr->getExprLoc(), ElemType, D->getName());
21682 VDInitRefExpr = buildDeclRefExpr(SemaRef, VDInit, ElemType, ELoc);
21683 Expr *Init = SemaRef.DefaultLvalueConversion(VDInitRefExpr).get();
21684 ElemType = ElemType.getUnqualifiedType();
21685 VarDecl *VDInitTemp = buildVarDecl(SemaRef, RefExpr->getExprLoc(),
21686 ElemType, ".firstprivate.temp");
21687 InitializedEntity Entity =
21690
21691 InitializationSequence InitSeq(SemaRef, Entity, Kind, Init);
21692 ExprResult Result = InitSeq.Perform(SemaRef, Entity, Kind, Init);
21693 if (Result.isInvalid())
21694 VDPrivate->setInvalidDecl();
21695 else
21696 VDPrivate->setInit(Result.getAs<Expr>());
21697 // Remove temp variable declaration.
21698 getASTContext().Deallocate(VDInitTemp);
21699 } else {
21700 VarDecl *VDInit = buildVarDecl(SemaRef, RefExpr->getExprLoc(), Type,
21701 ".firstprivate.temp");
21702 VDInitRefExpr = buildDeclRefExpr(SemaRef, VDInit, RefExpr->getType(),
21703 RefExpr->getExprLoc());
21704 SemaRef.AddInitializerToDecl(
21705 VDPrivate, SemaRef.DefaultLvalueConversion(VDInitRefExpr).get(),
21706 /*DirectInit=*/false);
21707 }
21708 if (VDPrivate->isInvalidDecl()) {
21709 if (IsImplicitClause) {
21710 Diag(RefExpr->getExprLoc(),
21711 diag::note_omp_task_predetermined_firstprivate_here);
21712 }
21713 continue;
21714 }
21715 SemaRef.CurContext->addDecl(VDPrivate);
21716 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
21717 SemaRef, VDPrivate, RefExpr->getType().getUnqualifiedType(),
21718 RefExpr->getExprLoc());
21719 DeclRefExpr *Ref = nullptr;
21720 if (!VD && !SemaRef.CurContext->isDependentContext()) {
21721 if (TopDVar.CKind == OMPC_lastprivate) {
21722 Ref = TopDVar.PrivateCopy;
21723 } else if (!IsBindingDecl) {
21724 auto *FD = dyn_cast<FieldDecl>(D);
21725 VarDecl *VD = FD ? DSAStack->getImplicitFDCapExprDecl(FD) : nullptr;
21726 if (VD)
21727 Ref =
21729 RefExpr->getExprLoc());
21730 else
21731 Ref = buildCapture(SemaRef, D, SimpleRefExpr, /*WithInit=*/true);
21732 if (VD || !isOpenMPCapturedDecl(D))
21733 ExprCaptures.push_back(Ref->getDecl());
21734 }
21735 }
21736 if (!IsImplicitClause)
21737 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
21738 Vars.push_back(
21739 (VD || IsBindingDecl || SemaRef.CurContext->isDependentContext())
21740 ? RefExpr->IgnoreParens()
21741 : Ref);
21742 PrivateCopies.push_back(VDPrivateRefExpr);
21743 Inits.push_back(VDInitRefExpr);
21744 }
21745
21746 if (Vars.empty())
21747 return nullptr;
21748
21749 return OMPFirstprivateClause::Create(
21750 getASTContext(), StartLoc, LParenLoc, EndLoc, Vars, PrivateCopies, Inits,
21751 buildPreInits(getASTContext(), ExprCaptures));
21752}
21753
21756 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
21757 SourceLocation LParenLoc, SourceLocation EndLoc) {
21758 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
21759 assert(ColonLoc.isValid() && "Colon location must be valid.");
21760 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
21761 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
21762 /*Last=*/OMPC_LASTPRIVATE_unknown)
21763 << getOpenMPClauseNameForDiag(OMPC_lastprivate);
21764 return nullptr;
21765 }
21766
21768 SmallVector<Expr *, 8> SrcExprs;
21769 SmallVector<Expr *, 8> DstExprs;
21770 SmallVector<Expr *, 8> AssignmentOps;
21771 SmallVector<Decl *, 4> ExprCaptures;
21772 SmallVector<Expr *, 4> ExprPostUpdates;
21773 for (Expr *RefExpr : VarList) {
21774 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
21775 SourceLocation ELoc;
21776 SourceRange ERange;
21777 Expr *SimpleRefExpr = RefExpr;
21778 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
21779 if (Res.second) {
21780 // It will be analyzed later.
21781 Vars.push_back(RefExpr);
21782 SrcExprs.push_back(nullptr);
21783 DstExprs.push_back(nullptr);
21784 AssignmentOps.push_back(nullptr);
21785 }
21786 ValueDecl *D = Res.first;
21787 if (!D)
21788 continue;
21789
21790 QualType Type = D->getType();
21791 auto *VD = dyn_cast<VarDecl>(D);
21792
21793 // Structured bindings with conditional modifier are currently not
21794 // supported.
21795 if (LPKind == OMPC_LASTPRIVATE_conditional && isa<BindingDecl>(D)) {
21796 Diag(ELoc, diag::err_omp_unsupported_on_binding) << 1;
21797 Diag(D->getLocation(), diag::note_defined_here) << D;
21798 continue;
21799 }
21800
21801 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
21802 // A variable that appears in a lastprivate clause must not have an
21803 // incomplete type or a reference type.
21804 if (SemaRef.RequireCompleteType(ELoc, Type,
21805 diag::err_omp_lastprivate_incomplete_type))
21806 continue;
21807 Type = Type.getNonReferenceType();
21808
21809 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
21810 // A variable that is privatized must not have a const-qualified type
21811 // unless it is of class type with a mutable member. This restriction does
21812 // not apply to the firstprivate clause.
21813 //
21814 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
21815 // A variable that appears in a lastprivate clause must not have a
21816 // const-qualified type unless it is of class type with a mutable member.
21817 if (rejectConstNotMutableType(SemaRef, D, Type, OMPC_lastprivate, ELoc))
21818 continue;
21819
21820 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
21821 // A list item that appears in a lastprivate clause with the conditional
21822 // modifier must be a scalar variable.
21823 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
21824 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
21825 bool IsDecl = !VD || VD->isThisDeclarationADefinition(getASTContext()) ==
21827 Diag(D->getLocation(),
21828 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
21829 << D;
21830 continue;
21831 }
21832
21833 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
21834 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
21835 // in a Construct]
21836 // Variables with the predetermined data-sharing attributes may not be
21837 // listed in data-sharing attributes clauses, except for the cases
21838 // listed below.
21839 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
21840 // A list item may appear in a firstprivate or lastprivate clause but not
21841 // both.
21842 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
21843 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
21844 (isOpenMPDistributeDirective(CurrDir) ||
21845 DVar.CKind != OMPC_firstprivate) &&
21846 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
21847 Diag(ELoc, diag::err_omp_wrong_dsa)
21848 << getOpenMPClauseNameForDiag(DVar.CKind)
21849 << getOpenMPClauseNameForDiag(OMPC_lastprivate);
21851 continue;
21852 }
21853
21854 // OpenMP [2.14.3.5, Restrictions, p.2]
21855 // A list item that is private within a parallel region, or that appears in
21856 // the reduction clause of a parallel construct, must not appear in a
21857 // lastprivate clause on a worksharing construct if any of the corresponding
21858 // worksharing regions ever binds to any of the corresponding parallel
21859 // regions.
21860 DSAStackTy::DSAVarData TopDVar = DVar;
21861 if (isOpenMPWorksharingDirective(CurrDir) &&
21862 !isOpenMPParallelDirective(CurrDir) &&
21863 !isOpenMPTeamsDirective(CurrDir)) {
21864 DVar = DSAStack->getImplicitDSA(D, true);
21865 if (DVar.CKind != OMPC_shared) {
21866 Diag(ELoc, diag::err_omp_required_access)
21867 << getOpenMPClauseNameForDiag(OMPC_lastprivate)
21868 << getOpenMPClauseNameForDiag(OMPC_shared);
21870 continue;
21871 }
21872 }
21873
21874 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
21875 // A variable of class type (or array thereof) that appears in a
21876 // lastprivate clause requires an accessible, unambiguous default
21877 // constructor for the class type, unless the list item is also specified
21878 // in a firstprivate clause.
21879 // A variable of class type (or array thereof) that appears in a
21880 // lastprivate clause requires an accessible, unambiguous copy assignment
21881 // operator for the class type.
21883 VarDecl *SrcVD = buildVarDecl(SemaRef, ERange.getBegin(),
21884 Type.getUnqualifiedType(), ".lastprivate.src",
21885 D->hasAttrs() ? &D->getAttrs() : nullptr);
21886 DeclRefExpr *PseudoSrcExpr =
21887 buildDeclRefExpr(SemaRef, SrcVD, Type.getUnqualifiedType(), ELoc);
21888 VarDecl *DstVD =
21889 buildVarDecl(SemaRef, ERange.getBegin(), Type, ".lastprivate.dst",
21890 D->hasAttrs() ? &D->getAttrs() : nullptr);
21891 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(SemaRef, DstVD, Type, ELoc);
21892 // For arrays generate assignment operation for single element and replace
21893 // it by the original array element in CodeGen.
21894 ExprResult AssignmentOp = SemaRef.BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
21895 PseudoDstExpr, PseudoSrcExpr);
21896 if (AssignmentOp.isInvalid())
21897 continue;
21898 AssignmentOp = SemaRef.ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
21899 /*DiscardedValue=*/false);
21900 if (AssignmentOp.isInvalid())
21901 continue;
21902
21903 DeclRefExpr *Ref = nullptr;
21904 if (!VD && !SemaRef.CurContext->isDependentContext()) {
21905 if (TopDVar.CKind == OMPC_firstprivate) {
21906 Ref = TopDVar.PrivateCopy;
21907 } else {
21908 Ref = buildCapture(SemaRef, D, SimpleRefExpr, /*WithInit=*/false);
21909 if (!isOpenMPCapturedDecl(D))
21910 ExprCaptures.push_back(Ref->getDecl());
21911 }
21912 if (Ref &&
21913 ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
21914 (!isOpenMPCapturedDecl(D) &&
21915 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()))) {
21916 ExprResult RefRes = SemaRef.DefaultLvalueConversion(Ref);
21917 if (!RefRes.isUsable())
21918 continue;
21919 ExprResult PostUpdateRes =
21920 SemaRef.BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
21921 SimpleRefExpr, RefRes.get());
21922 if (!PostUpdateRes.isUsable())
21923 continue;
21924 ExprPostUpdates.push_back(
21925 SemaRef.IgnoredValueConversions(PostUpdateRes.get()).get());
21926 }
21927 }
21928 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
21929 bool IsBindingDecl = isa<BindingDecl>(D);
21930 Vars.push_back(
21931 (VD || IsBindingDecl || SemaRef.CurContext->isDependentContext())
21932 ? RefExpr->IgnoreParens()
21933 : Ref);
21934 SrcExprs.push_back(PseudoSrcExpr);
21935 DstExprs.push_back(PseudoDstExpr);
21936 AssignmentOps.push_back(AssignmentOp.get());
21937 }
21938
21939 if (Vars.empty())
21940 return nullptr;
21941
21942 return OMPLastprivateClause::Create(
21943 getASTContext(), StartLoc, LParenLoc, EndLoc, Vars, SrcExprs, DstExprs,
21944 AssignmentOps, LPKind, LPKindLoc, ColonLoc,
21945 buildPreInits(getASTContext(), ExprCaptures),
21946 buildPostUpdate(SemaRef, ExprPostUpdates));
21947}
21948
21950 SourceLocation StartLoc,
21951 SourceLocation LParenLoc,
21952 SourceLocation EndLoc) {
21954 for (Expr *RefExpr : VarList) {
21955 assert(RefExpr && "NULL expr in OpenMP shared clause.");
21956 SourceLocation ELoc;
21957 SourceRange ERange;
21958 Expr *SimpleRefExpr = RefExpr;
21959 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
21960 if (Res.second) {
21961 // It will be analyzed later.
21962 Vars.push_back(RefExpr);
21963 }
21964 ValueDecl *D = Res.first;
21965 if (!D)
21966 continue;
21967
21968 auto *VD = dyn_cast<VarDecl>(D);
21969 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
21970 // in a Construct]
21971 // Variables with the predetermined data-sharing attributes may not be
21972 // listed in data-sharing attributes clauses, except for the cases
21973 // listed below. For these exceptions only, listing a predetermined
21974 // variable in a data-sharing attribute clause is allowed and overrides
21975 // the variable's predetermined data-sharing attributes.
21976 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
21977 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
21978 DVar.RefExpr) {
21979 Diag(ELoc, diag::err_omp_wrong_dsa)
21980 << getOpenMPClauseNameForDiag(DVar.CKind)
21981 << getOpenMPClauseNameForDiag(OMPC_shared);
21983 continue;
21984 }
21985
21986 DeclRefExpr *Ref = nullptr;
21987 if (!VD && isOpenMPCapturedDecl(D) &&
21988 !SemaRef.CurContext->isDependentContext())
21989 Ref = buildCapture(SemaRef, D, SimpleRefExpr, /*WithInit=*/true);
21990 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
21991 Vars.push_back((VD || !Ref || SemaRef.CurContext->isDependentContext())
21992 ? RefExpr->IgnoreParens()
21993 : Ref);
21994 }
21995
21996 if (Vars.empty())
21997 return nullptr;
21998
21999 return OMPSharedClause::Create(getASTContext(), StartLoc, LParenLoc, EndLoc,
22000 Vars);
22001}
22002
22003namespace {
22004class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
22005 DSAStackTy *Stack;
22006
22007public:
22008 bool VisitDeclRefExpr(DeclRefExpr *E) {
22009 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
22010 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
22011 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
22012 return false;
22013 if (DVar.CKind != OMPC_unknown)
22014 return true;
22015 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
22016 VD,
22017 [](OpenMPClauseKind C, bool AppliedToPointee, bool) {
22018 return isOpenMPPrivate(C) && !AppliedToPointee;
22019 },
22020 [](OpenMPDirectiveKind) { return true; },
22021 /*FromParent=*/true);
22022 return DVarPrivate.CKind != OMPC_unknown;
22023 }
22024 return false;
22025 }
22026 bool VisitStmt(Stmt *S) {
22027 for (Stmt *Child : S->children()) {
22028 if (Child && Visit(Child))
22029 return true;
22030 }
22031 return false;
22032 }
22033 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
22034};
22035} // namespace
22036
22037namespace {
22038// Transform MemberExpression for specified FieldDecl of current class to
22039// DeclRefExpr to specified OMPCapturedExprDecl.
22040class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
22041 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
22042 ValueDecl *Field = nullptr;
22043 DeclRefExpr *CapturedExpr = nullptr;
22044
22045public:
22046 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
22047 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
22048
22049 ExprResult TransformMemberExpr(MemberExpr *E) {
22051 E->getMemberDecl() == Field) {
22052 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
22053 return CapturedExpr;
22054 }
22055 return BaseTransform::TransformMemberExpr(E);
22056 }
22057 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
22058};
22059} // namespace
22060
22061template <typename T, typename U>
22063 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
22064 for (U &Set : Lookups) {
22065 for (auto *D : Set) {
22066 if (T Res = Gen(cast<ValueDecl>(D)))
22067 return Res;
22068 }
22069 }
22070 return T();
22071}
22072
22074 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
22075
22076 for (auto *RD : D->redecls()) {
22077 // Don't bother with extra checks if we already know this one isn't visible.
22078 if (RD == D)
22079 continue;
22080
22081 auto ND = cast<NamedDecl>(RD);
22082 if (LookupResult::isVisible(SemaRef, ND))
22083 return ND;
22084 }
22085
22086 return nullptr;
22087}
22088
22089static void
22091 SourceLocation Loc, QualType Ty,
22093 // Find all of the associated namespaces and classes based on the
22094 // arguments we have.
22095 Sema::AssociatedNamespaceSet AssociatedNamespaces;
22096 Sema::AssociatedClassSet AssociatedClasses;
22097 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
22098 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
22099 AssociatedClasses);
22100
22101 // C++ [basic.lookup.argdep]p3:
22102 // Let X be the lookup set produced by unqualified lookup (3.4.1)
22103 // and let Y be the lookup set produced by argument dependent
22104 // lookup (defined as follows). If X contains [...] then Y is
22105 // empty. Otherwise Y is the set of declarations found in the
22106 // namespaces associated with the argument types as described
22107 // below. The set of declarations found by the lookup of the name
22108 // is the union of X and Y.
22109 //
22110 // Here, we compute Y and add its members to the overloaded
22111 // candidate set.
22112 for (auto *NS : AssociatedNamespaces) {
22113 // When considering an associated namespace, the lookup is the
22114 // same as the lookup performed when the associated namespace is
22115 // used as a qualifier (3.4.3.2) except that:
22116 //
22117 // -- Any using-directives in the associated namespace are
22118 // ignored.
22119 //
22120 // -- Any namespace-scope friend functions declared in
22121 // associated classes are visible within their respective
22122 // namespaces even if they are not visible during an ordinary
22123 // lookup (11.4).
22124 DeclContext::lookup_result R = NS->lookup(Id.getName());
22125 for (auto *D : R) {
22126 auto *Underlying = D;
22127 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
22128 Underlying = USD->getTargetDecl();
22129
22130 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
22131 !isa<OMPDeclareMapperDecl>(Underlying))
22132 continue;
22133
22134 if (!SemaRef.isVisible(D)) {
22135 D = findAcceptableDecl(SemaRef, D);
22136 if (!D)
22137 continue;
22138 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
22139 Underlying = USD->getTargetDecl();
22140 }
22141 Lookups.emplace_back();
22142 Lookups.back().addDecl(Underlying);
22143 }
22144 }
22145}
22146
22147static ExprResult
22149 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
22150 const DeclarationNameInfo &ReductionId, QualType Ty,
22151 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
22152 if (ReductionIdScopeSpec.isInvalid())
22153 return ExprError();
22154 SmallVector<UnresolvedSet<8>, 4> Lookups;
22155 if (S) {
22156 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
22157 Lookup.suppressDiagnostics();
22158 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec,
22159 /*ObjectType=*/QualType())) {
22160 NamedDecl *D = Lookup.getRepresentativeDecl();
22161 do {
22162 S = S->getParent();
22163 } while (S && !S->isDeclScope(D));
22164 if (S)
22165 S = S->getParent();
22166 Lookups.emplace_back();
22167 Lookups.back().append(Lookup.begin(), Lookup.end());
22168 Lookup.clear();
22169 }
22170 } else if (auto *ULE =
22171 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
22172 Lookups.push_back(UnresolvedSet<8>());
22173 Decl *PrevD = nullptr;
22174 for (NamedDecl *D : ULE->decls()) {
22175 if (D == PrevD)
22176 Lookups.push_back(UnresolvedSet<8>());
22177 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
22178 Lookups.back().addDecl(DRD);
22179 PrevD = D;
22180 }
22181 }
22182 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
22186 return !D->isInvalidDecl() &&
22187 (D->getType()->isDependentType() ||
22188 D->getType()->isInstantiationDependentType() ||
22189 D->getType()->containsUnexpandedParameterPack());
22190 })) {
22191 UnresolvedSet<8> ResSet;
22192 for (const UnresolvedSet<8> &Set : Lookups) {
22193 if (Set.empty())
22194 continue;
22195 ResSet.append(Set.begin(), Set.end());
22196 // The last item marks the end of all declarations at the specified scope.
22197 ResSet.addDecl(Set[Set.size() - 1]);
22198 }
22200 SemaRef.Context, /*NamingClass=*/nullptr,
22201 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
22202 /*ADL=*/true, ResSet.begin(), ResSet.end(), /*KnownDependent=*/false,
22203 /*KnownInstantiationDependent=*/false);
22204 }
22205 // Lookup inside the classes.
22206 // C++ [over.match.oper]p3:
22207 // For a unary operator @ with an operand of a type whose
22208 // cv-unqualified version is T1, and for a binary operator @ with
22209 // a left operand of a type whose cv-unqualified version is T1 and
22210 // a right operand of a type whose cv-unqualified version is T2,
22211 // three sets of candidate functions, designated member
22212 // candidates, non-member candidates and built-in candidates, are
22213 // constructed as follows:
22214 // -- If T1 is a complete class type or a class currently being
22215 // defined, the set of member candidates is the result of the
22216 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
22217 // the set of member candidates is empty.
22218 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
22219 Lookup.suppressDiagnostics();
22220 if (Ty->isRecordType()) {
22221 // Complete the type if it can be completed.
22222 // If the type is neither complete nor being defined, bail out now.
22223 bool IsComplete = SemaRef.isCompleteType(Loc, Ty);
22224 auto *RD = Ty->castAsRecordDecl();
22225 if (IsComplete || RD->isBeingDefined()) {
22226 Lookup.clear();
22227 SemaRef.LookupQualifiedName(Lookup, RD);
22228 if (Lookup.empty()) {
22229 Lookups.emplace_back();
22230 Lookups.back().append(Lookup.begin(), Lookup.end());
22231 }
22232 }
22233 }
22234 // Perform ADL.
22235 if (SemaRef.getLangOpts().CPlusPlus)
22236 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
22238 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
22239 if (!D->isInvalidDecl() &&
22240 SemaRef.Context.hasSameType(D->getType(), Ty))
22241 return D;
22242 return nullptr;
22243 }))
22244 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
22245 VK_LValue, Loc);
22246 if (SemaRef.getLangOpts().CPlusPlus) {
22248 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
22249 if (!D->isInvalidDecl() &&
22250 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
22252 SemaRef.getASTContext()))
22253 return D;
22254 return nullptr;
22255 })) {
22256 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
22257 /*DetectVirtual=*/false);
22258 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
22259 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
22260 VD->getType().getUnqualifiedType()))) {
22261 if (SemaRef.CheckBaseClassAccess(
22262 Loc, VD->getType(), Ty, Paths.front(),
22263 /*DiagID=*/0) != Sema::AR_inaccessible) {
22264 SemaRef.BuildBasePathArray(Paths, BasePath);
22265 return SemaRef.BuildDeclRefExpr(
22266 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
22267 }
22268 }
22269 }
22270 }
22271 }
22272 if (ReductionIdScopeSpec.isSet()) {
22273 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
22274 << Ty << Range;
22275 return ExprError();
22276 }
22277 return ExprEmpty();
22278}
22279
22280namespace {
22281/// Data for the reduction-based clauses.
22282struct ReductionData {
22283 /// List of original reduction items.
22284 SmallVector<Expr *, 8> Vars;
22285 /// List of private copies of the reduction items.
22286 SmallVector<Expr *, 8> Privates;
22287 /// LHS expressions for the reduction_op expressions.
22288 SmallVector<Expr *, 8> LHSs;
22289 /// RHS expressions for the reduction_op expressions.
22290 SmallVector<Expr *, 8> RHSs;
22291 /// Reduction operation expression.
22292 SmallVector<Expr *, 8> ReductionOps;
22293 /// inscan copy operation expressions.
22294 SmallVector<Expr *, 8> InscanCopyOps;
22295 /// inscan copy temp array expressions for prefix sums.
22296 SmallVector<Expr *, 8> InscanCopyArrayTemps;
22297 /// inscan copy temp array element expressions for prefix sums.
22298 SmallVector<Expr *, 8> InscanCopyArrayElems;
22299 /// Taskgroup descriptors for the corresponding reduction items in
22300 /// in_reduction clauses.
22301 SmallVector<Expr *, 8> TaskgroupDescriptors;
22302 /// List of captures for clause.
22303 SmallVector<Decl *, 4> ExprCaptures;
22304 /// List of postupdate expressions.
22305 SmallVector<Expr *, 4> ExprPostUpdates;
22306 /// Reduction modifier.
22307 unsigned RedModifier = 0;
22308 /// Original modifier.
22309 unsigned OrigSharingModifier = 0;
22310 /// Private Variable Reduction
22311 SmallVector<bool, 8> IsPrivateVarReduction;
22312 ReductionData() = delete;
22313 /// Reserves required memory for the reduction data.
22314 ReductionData(unsigned Size, unsigned Modifier = 0, unsigned OrgModifier = 0)
22315 : RedModifier(Modifier), OrigSharingModifier(OrgModifier) {
22316 Vars.reserve(Size);
22317 Privates.reserve(Size);
22318 LHSs.reserve(Size);
22319 RHSs.reserve(Size);
22320 ReductionOps.reserve(Size);
22321 IsPrivateVarReduction.reserve(Size);
22322 if (RedModifier == OMPC_REDUCTION_inscan) {
22323 InscanCopyOps.reserve(Size);
22324 InscanCopyArrayTemps.reserve(Size);
22325 InscanCopyArrayElems.reserve(Size);
22326 }
22327 TaskgroupDescriptors.reserve(Size);
22328 ExprCaptures.reserve(Size);
22329 ExprPostUpdates.reserve(Size);
22330 }
22331 /// Stores reduction item and reduction operation only (required for dependent
22332 /// reduction item).
22333 void push(Expr *Item, Expr *ReductionOp) {
22334 Vars.emplace_back(Item);
22335 Privates.emplace_back(nullptr);
22336 LHSs.emplace_back(nullptr);
22337 RHSs.emplace_back(nullptr);
22338 ReductionOps.emplace_back(ReductionOp);
22339 IsPrivateVarReduction.emplace_back(false);
22340 TaskgroupDescriptors.emplace_back(nullptr);
22341 if (RedModifier == OMPC_REDUCTION_inscan) {
22342 InscanCopyOps.push_back(nullptr);
22343 InscanCopyArrayTemps.push_back(nullptr);
22344 InscanCopyArrayElems.push_back(nullptr);
22345 }
22346 }
22347 /// Stores reduction data.
22348 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
22349 Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
22350 Expr *CopyArrayElem, bool IsPrivate) {
22351 Vars.emplace_back(Item);
22352 Privates.emplace_back(Private);
22353 LHSs.emplace_back(LHS);
22354 RHSs.emplace_back(RHS);
22355 ReductionOps.emplace_back(ReductionOp);
22356 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
22357 if (RedModifier == OMPC_REDUCTION_inscan) {
22358 InscanCopyOps.push_back(CopyOp);
22359 InscanCopyArrayTemps.push_back(CopyArrayTemp);
22360 InscanCopyArrayElems.push_back(CopyArrayElem);
22361 } else {
22362 assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
22363 CopyArrayElem == nullptr &&
22364 "Copy operation must be used for inscan reductions only.");
22365 }
22366 IsPrivateVarReduction.emplace_back(IsPrivate);
22367 }
22368};
22369} // namespace
22370
22372 ASTContext &Context, const ArraySectionExpr *OASE, bool &SingleElement,
22373 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
22374 const Expr *Length = OASE->getLength();
22375 if (Length == nullptr) {
22376 // For array sections of the form [1:] or [:], we would need to analyze
22377 // the lower bound...
22378 if (OASE->getColonLocFirst().isValid())
22379 return false;
22380
22381 // This is an array subscript which has implicit length 1!
22382 SingleElement = true;
22383 ArraySizes.push_back(llvm::APSInt::get(1));
22384 } else {
22386 if (!Length->EvaluateAsInt(Result, Context))
22387 return false;
22388
22389 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
22390 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
22391 ArraySizes.push_back(ConstantLengthValue);
22392 }
22393
22394 // Get the base of this array section and walk up from there.
22395 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
22396
22397 // We require length = 1 for all array sections except the right-most to
22398 // guarantee that the memory region is contiguous and has no holes in it.
22399 while (const auto *TempOASE = dyn_cast<ArraySectionExpr>(Base)) {
22400 Length = TempOASE->getLength();
22401 if (Length == nullptr) {
22402 // For array sections of the form [1:] or [:], we would need to analyze
22403 // the lower bound...
22404 if (OASE->getColonLocFirst().isValid())
22405 return false;
22406
22407 // This is an array subscript which has implicit length 1!
22408 llvm::APSInt ConstantOne = llvm::APSInt::get(1);
22409 ArraySizes.push_back(ConstantOne);
22410 } else {
22412 if (!Length->EvaluateAsInt(Result, Context))
22413 return false;
22414
22415 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
22416 if (ConstantLengthValue.getSExtValue() != 1)
22417 return false;
22418
22419 ArraySizes.push_back(ConstantLengthValue);
22420 }
22421 Base = TempOASE->getBase()->IgnoreParenImpCasts();
22422 }
22423
22424 // If we have a single element, we don't need to add the implicit lengths.
22425 if (!SingleElement) {
22426 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
22427 // Has implicit length 1!
22428 llvm::APSInt ConstantOne = llvm::APSInt::get(1);
22429 ArraySizes.push_back(ConstantOne);
22430 Base = TempASE->getBase()->IgnoreParenImpCasts();
22431 }
22432 }
22433
22434 // This array section can be privatized as a single value or as a constant
22435 // sized array.
22436 return true;
22437}
22438
22439static BinaryOperatorKind
22441 if (BOK == BO_Add)
22442 return BO_AddAssign;
22443 if (BOK == BO_Mul)
22444 return BO_MulAssign;
22445 if (BOK == BO_And)
22446 return BO_AndAssign;
22447 if (BOK == BO_Or)
22448 return BO_OrAssign;
22449 if (BOK == BO_Xor)
22450 return BO_XorAssign;
22451 return BOK;
22452}
22453
22455 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
22456 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
22457 SourceLocation ColonLoc, SourceLocation EndLoc,
22458 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
22459 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
22460 DeclarationName DN = ReductionId.getName();
22462 BinaryOperatorKind BOK = BO_Comma;
22463
22464 ASTContext &Context = S.Context;
22465 // OpenMP [2.14.3.6, reduction clause]
22466 // C
22467 // reduction-identifier is either an identifier or one of the following
22468 // operators: +, -, *, &, |, ^, && and ||
22469 // C++
22470 // reduction-identifier is either an id-expression or one of the following
22471 // operators: +, -, *, &, |, ^, && and ||
22472 switch (OOK) {
22473 case OO_Plus:
22474 BOK = BO_Add;
22475 break;
22476 case OO_Minus:
22477 // Minus(-) operator is not supported in TR11 (OpenMP 6.0). Setting BOK to
22478 // BO_Comma will automatically diagnose it for OpenMP > 52 as not allowed
22479 // reduction identifier.
22480 if (S.LangOpts.OpenMP > 52)
22481 BOK = BO_Comma;
22482 else
22483 BOK = BO_Add;
22484 break;
22485 case OO_Star:
22486 BOK = BO_Mul;
22487 break;
22488 case OO_Amp:
22489 BOK = BO_And;
22490 break;
22491 case OO_Pipe:
22492 BOK = BO_Or;
22493 break;
22494 case OO_Caret:
22495 BOK = BO_Xor;
22496 break;
22497 case OO_AmpAmp:
22498 BOK = BO_LAnd;
22499 break;
22500 case OO_PipePipe:
22501 BOK = BO_LOr;
22502 break;
22503 case OO_New:
22504 case OO_Delete:
22505 case OO_Array_New:
22506 case OO_Array_Delete:
22507 case OO_Slash:
22508 case OO_Percent:
22509 case OO_Tilde:
22510 case OO_Exclaim:
22511 case OO_Equal:
22512 case OO_Less:
22513 case OO_Greater:
22514 case OO_LessEqual:
22515 case OO_GreaterEqual:
22516 case OO_PlusEqual:
22517 case OO_MinusEqual:
22518 case OO_StarEqual:
22519 case OO_SlashEqual:
22520 case OO_PercentEqual:
22521 case OO_CaretEqual:
22522 case OO_AmpEqual:
22523 case OO_PipeEqual:
22524 case OO_LessLess:
22525 case OO_GreaterGreater:
22526 case OO_LessLessEqual:
22527 case OO_GreaterGreaterEqual:
22528 case OO_EqualEqual:
22529 case OO_ExclaimEqual:
22530 case OO_Spaceship:
22531 case OO_PlusPlus:
22532 case OO_MinusMinus:
22533 case OO_Comma:
22534 case OO_ArrowStar:
22535 case OO_Arrow:
22536 case OO_Call:
22537 case OO_Subscript:
22538 case OO_Conditional:
22539 case OO_Coawait:
22541 llvm_unreachable("Unexpected reduction identifier");
22542 case OO_None:
22543 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
22544 if (II->isStr("max"))
22545 BOK = BO_GT;
22546 else if (II->isStr("min"))
22547 BOK = BO_LT;
22548 }
22549 break;
22550 }
22551
22552 // OpenMP 5.2, 5.5.5 (see page 627, line 18) reduction Clause, Restrictions
22553 // A reduction clause with the minus (-) operator was deprecated
22554 if (OOK == OO_Minus && S.LangOpts.OpenMP == 52)
22555 S.Diag(ReductionId.getLoc(), diag::warn_omp_minus_in_reduction_deprecated);
22556
22557 SourceRange ReductionIdRange;
22558 if (ReductionIdScopeSpec.isValid())
22559 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
22560 else
22561 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
22562 ReductionIdRange.setEnd(ReductionId.getEndLoc());
22563
22564 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
22565 bool FirstIter = true;
22566 for (Expr *RefExpr : VarList) {
22567 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
22568 // OpenMP [2.1, C/C++]
22569 // A list item is a variable or array section, subject to the restrictions
22570 // specified in Section 2.4 on page 42 and in each of the sections
22571 // describing clauses and directives for which a list appears.
22572 // OpenMP [2.14.3.3, Restrictions, p.1]
22573 // A variable that is part of another variable (as an array or
22574 // structure element) cannot appear in a private clause.
22575 if (!FirstIter && IR != ER)
22576 ++IR;
22577 FirstIter = false;
22578 SourceLocation ELoc;
22579 SourceRange ERange;
22580 bool IsPrivate = false;
22581 Expr *SimpleRefExpr = RefExpr;
22582 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
22583 /*AllowArraySection=*/true);
22584 if (Res.second) {
22585 // Try to find 'declare reduction' corresponding construct before using
22586 // builtin/overloaded operators.
22587 QualType Type = Context.DependentTy;
22588 CXXCastPath BasePath;
22589 ExprResult DeclareReductionRef = buildDeclareReductionRef(
22590 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
22591 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
22592 Expr *ReductionOp = nullptr;
22593 if (S.CurContext->isDependentContext() &&
22594 (DeclareReductionRef.isUnset() ||
22595 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
22596 ReductionOp = DeclareReductionRef.get();
22597 // It will be analyzed later.
22598 RD.push(RefExpr, ReductionOp);
22599 }
22600 ValueDecl *D = Res.first;
22601 if (!D)
22602 continue;
22603
22604 Expr *TaskgroupDescriptor = nullptr;
22605 QualType Type;
22606 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
22607 auto *OASE = dyn_cast<ArraySectionExpr>(RefExpr->IgnoreParens());
22608 if (ASE) {
22609 Type = ASE->getType().getNonReferenceType();
22610 } else if (OASE) {
22611 QualType BaseType =
22613 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
22614 Type = ATy->getElementType();
22615 else
22616 Type = BaseType->getPointeeType();
22617 Type = Type.getNonReferenceType();
22618 } else {
22619 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
22620 }
22621 auto *VD = dyn_cast<VarDecl>(D);
22622
22623 auto *BD = dyn_cast<BindingDecl>(D);
22624 if (BD) {
22625 // FIXME: reductions on bindings are rejected.
22626 S.Diag(ELoc, diag::err_omp_unsupported_on_binding) << 0;
22627 continue;
22628 }
22629
22630 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
22631 // A variable that appears in a private clause must not have an incomplete
22632 // type or a reference type.
22633 if (S.RequireCompleteType(ELoc, D->getType(),
22634 diag::err_omp_reduction_incomplete_type))
22635 continue;
22636 // OpenMP [2.14.3.6, reduction clause, Restrictions]
22637 // A list item that appears in a reduction clause must not be
22638 // const-qualified.
22639 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
22640 /*AcceptIfMutable=*/false, ASE || OASE))
22641 continue;
22642
22643 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
22644 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
22645 // If a list-item is a reference type then it must bind to the same object
22646 // for all threads of the team.
22647 if (!ASE && !OASE) {
22648 if (VD) {
22649 VarDecl *VDDef = VD->getDefinition();
22650 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
22651 DSARefChecker Check(Stack);
22652 if (Check.Visit(VDDef->getInit())) {
22653 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
22654 << getOpenMPClauseNameForDiag(ClauseKind) << ERange;
22655 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
22656 continue;
22657 }
22658 }
22659 }
22660
22661 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
22662 // in a Construct]
22663 // Variables with the predetermined data-sharing attributes may not be
22664 // listed in data-sharing attributes clauses, except for the cases
22665 // listed below. For these exceptions only, listing a predetermined
22666 // variable in a data-sharing attribute clause is allowed and overrides
22667 // the variable's predetermined data-sharing attributes.
22668 // OpenMP [2.14.3.6, Restrictions, p.3]
22669 // Any number of reduction clauses can be specified on the directive,
22670 // but a list item can appear only once in the reduction clauses for that
22671 // directive.
22672 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
22673 if (DVar.CKind == OMPC_reduction) {
22674 S.Diag(ELoc, diag::err_omp_once_referenced)
22675 << getOpenMPClauseNameForDiag(ClauseKind);
22676 if (DVar.RefExpr)
22677 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
22678 continue;
22679 }
22680 if (DVar.CKind != OMPC_unknown) {
22681 S.Diag(ELoc, diag::err_omp_wrong_dsa)
22682 << getOpenMPClauseNameForDiag(DVar.CKind)
22683 << getOpenMPClauseNameForDiag(OMPC_reduction);
22684 reportOriginalDsa(S, Stack, D, DVar);
22685 continue;
22686 }
22687
22688 // OpenMP [2.14.3.6, Restrictions, p.1]
22689 // A list item that appears in a reduction clause of a worksharing
22690 // construct must be shared in the parallel regions to which any of the
22691 // worksharing regions arising from the worksharing construct bind.
22692
22693 if (S.getLangOpts().OpenMP <= 52 &&
22695 !isOpenMPParallelDirective(CurrDir) &&
22696 !isOpenMPTeamsDirective(CurrDir)) {
22697 DVar = Stack->getImplicitDSA(D, true);
22698 if (DVar.CKind != OMPC_shared) {
22699 S.Diag(ELoc, diag::err_omp_required_access)
22700 << getOpenMPClauseNameForDiag(OMPC_reduction)
22701 << getOpenMPClauseNameForDiag(OMPC_shared);
22702 reportOriginalDsa(S, Stack, D, DVar);
22703 continue;
22704 }
22705 } else if (isOpenMPWorksharingDirective(CurrDir) &&
22706 !isOpenMPParallelDirective(CurrDir) &&
22707 !isOpenMPTeamsDirective(CurrDir)) {
22708 // OpenMP 6.0 [ 7.6.10 ]
22709 // Support Reduction over private variables with reduction clause.
22710 // A list item in a reduction clause can now be private in the enclosing
22711 // context. For orphaned constructs it is assumed to be shared unless
22712 // the original(private) modifier appears in the clause.
22713 DVar = Stack->getImplicitDSA(D, true);
22714 // Determine if the variable should be considered private
22715 IsPrivate = DVar.CKind != OMPC_shared;
22716 bool IsOrphaned = false;
22717 OpenMPDirectiveKind ParentDir = Stack->getParentDirective();
22718 IsOrphaned = ParentDir == OMPD_unknown;
22719 if ((IsOrphaned &&
22720 RD.OrigSharingModifier == OMPC_ORIGINAL_SHARING_private))
22721 IsPrivate = true;
22722 }
22723 } else {
22724 // Threadprivates cannot be shared between threads, so dignose if the base
22725 // is a threadprivate variable.
22726 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
22727 if (DVar.CKind == OMPC_threadprivate) {
22728 S.Diag(ELoc, diag::err_omp_wrong_dsa)
22729 << getOpenMPClauseNameForDiag(DVar.CKind)
22730 << getOpenMPClauseNameForDiag(OMPC_reduction);
22731 reportOriginalDsa(S, Stack, D, DVar);
22732 continue;
22733 }
22734 }
22735
22736 // Try to find 'declare reduction' corresponding construct before using
22737 // builtin/overloaded operators.
22738 CXXCastPath BasePath;
22739 ExprResult DeclareReductionRef = buildDeclareReductionRef(
22740 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
22741 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
22742 if (DeclareReductionRef.isInvalid())
22743 continue;
22744 if (S.CurContext->isDependentContext() &&
22745 (DeclareReductionRef.isUnset() ||
22746 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
22747 RD.push(RefExpr, DeclareReductionRef.get());
22748 // Handle non-dependent inscan reduction variables in dependent contexts.
22749 if (RD.RedModifier == OMPC_REDUCTION_inscan)
22750 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, nullptr,
22751 RD.RedModifier, ASE || OASE);
22752 continue;
22753 }
22754 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
22755 // Not allowed reduction identifier is found.
22756 if (S.LangOpts.OpenMP > 52)
22757 S.Diag(ReductionId.getBeginLoc(),
22758 diag::err_omp_unknown_reduction_identifier_since_omp_6_0)
22759 << Type << ReductionIdRange;
22760 else
22761 S.Diag(ReductionId.getBeginLoc(),
22762 diag::err_omp_unknown_reduction_identifier_prior_omp_6_0)
22763 << Type << ReductionIdRange;
22764 continue;
22765 }
22766
22767 // OpenMP [2.14.3.6, reduction clause, Restrictions]
22768 // The type of a list item that appears in a reduction clause must be valid
22769 // for the reduction-identifier. For a max or min reduction in C, the type
22770 // of the list item must be an allowed arithmetic data type: char, int,
22771 // float, double, or _Bool, possibly modified with long, short, signed, or
22772 // unsigned. For a max or min reduction in C++, the type of the list item
22773 // must be an allowed arithmetic data type: char, wchar_t, int, float,
22774 // double, or bool, possibly modified with long, short, signed, or unsigned.
22775 if (DeclareReductionRef.isUnset()) {
22776 if ((BOK == BO_GT || BOK == BO_LT) &&
22777 !(Type->isScalarType() ||
22778 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
22779 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
22780 << getOpenMPClauseNameForDiag(ClauseKind)
22781 << S.getLangOpts().CPlusPlus;
22782 if (!ASE && !OASE) {
22783 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
22785 S.Diag(D->getLocation(),
22786 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
22787 << D;
22788 }
22789 continue;
22790 }
22791 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
22792 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
22793 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
22794 << getOpenMPClauseNameForDiag(ClauseKind);
22795 if (!ASE && !OASE) {
22796 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
22798 S.Diag(D->getLocation(),
22799 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
22800 << D;
22801 }
22802 continue;
22803 }
22804 }
22805
22806 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
22807 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
22808 D->hasAttrs() ? &D->getAttrs() : nullptr);
22809 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
22810 D->hasAttrs() ? &D->getAttrs() : nullptr);
22811 QualType PrivateTy = Type;
22812
22813 // Try if we can determine constant lengths for all array sections and avoid
22814 // the VLA.
22815 bool ConstantLengthOASE = false;
22816 if (OASE) {
22817 bool SingleElement;
22819 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
22820 Context, OASE, SingleElement, ArraySizes);
22821
22822 // If we don't have a single element, we must emit a constant array type.
22823 if (ConstantLengthOASE && !SingleElement) {
22824 for (llvm::APSInt &Size : ArraySizes)
22825 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
22827 /*IndexTypeQuals=*/0);
22828 }
22829 }
22830
22831 if ((OASE && !ConstantLengthOASE) ||
22832 (!OASE && !ASE &&
22834 if (!Context.getTargetInfo().isVLASupported()) {
22835 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
22836 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
22837 S.Diag(ELoc, diag::note_vla_unsupported);
22838 continue;
22839 } else {
22840 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
22841 S.targetDiag(ELoc, diag::note_vla_unsupported);
22842 }
22843 }
22844 // For arrays/array sections only:
22845 // Create pseudo array type for private copy. The size for this array will
22846 // be generated during codegen.
22847 // For array subscripts or single variables Private Ty is the same as Type
22848 // (type of the variable or single array element).
22849 PrivateTy = Context.getVariableArrayType(
22850 Type,
22851 new (Context)
22852 OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
22853 ArraySizeModifier::Normal, /*IndexTypeQuals=*/0);
22854 } else if (!ASE && !OASE &&
22855 Context.getAsArrayType(D->getType().getNonReferenceType())) {
22856 PrivateTy = D->getType().getNonReferenceType();
22857 }
22858 // Private copy.
22859 VarDecl *PrivateVD =
22860 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
22861 D->hasAttrs() ? &D->getAttrs() : nullptr,
22862 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
22863 // Add initializer for private variable.
22864 Expr *Init = nullptr;
22865 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
22866 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
22867 if (DeclareReductionRef.isUsable()) {
22868 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
22869 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
22870 if (DRD->getInitializer()) {
22871 Init = DRDRef;
22872 RHSVD->setInit(DRDRef);
22874 }
22875 } else {
22876 switch (BOK) {
22877 case BO_Add:
22878 case BO_Xor:
22879 case BO_Or:
22880 case BO_LOr:
22881 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
22883 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
22884 break;
22885 case BO_Mul:
22886 // '*' reduction op - initializer is '1'.
22887 // For C++ class types (e.g. std::complex) the OpenMP built-in
22888 // reduction identifiers are an extension: the standard only defines
22889 // identities for arithmetic (and, in Clang, _Complex) types. Without
22890 // an explicit initializer the private copy would be value-initialized,
22891 // which yields the *additive* identity (e.g. std::complex(0,0)) and is
22892 // wrong for multiplication. Initialize from the integer literal '1'
22893 // instead and let the converting constructor build the multiplicative
22894 // identity (e.g. std::complex(1) == (1,0)).
22895 if (Type->isScalarType() || Type->isAnyComplexType()) {
22896 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
22897 } else if (S.getLangOpts().CPlusPlus && Type->isRecordType()) {
22898 // Only use '1' when the type is actually copy-initializable from it.
22899 // Otherwise fall back to value-initialization (the previous behavior)
22900 // rather than rejecting the reduction, so a class that used to
22901 // compile keeps compiling. Such a class keeps its (possibly
22902 // incorrect) value-initialized identity, matching the pre-existing
22903 // behavior; BO_Add likewise relies on value-initialization for class
22904 // types.
22905 Expr *One = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
22906 InitializedEntity Entity =
22909 InitializationSequence Seq(S, Entity, Kind, One);
22910 if (Seq)
22911 Init = One;
22912 }
22913 break;
22914 case BO_LAnd:
22915 if (Type->isScalarType() || Type->isAnyComplexType()) {
22916 // '&&' reduction ops - initializer is '1'.
22917 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
22918 }
22919 break;
22920 case BO_And: {
22921 // '&' reduction op - initializer is '~0'.
22922 QualType OrigType = Type;
22923 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
22924 Type = ComplexTy->getElementType();
22925 if (Type->isRealFloatingType()) {
22926 llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
22927 Context.getFloatTypeSemantics(Type));
22928 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
22929 Type, ELoc);
22930 } else if (Type->isScalarType()) {
22931 uint64_t Size = Context.getTypeSize(Type);
22932 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
22933 llvm::APInt InitValue = llvm::APInt::getAllOnes(Size);
22934 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
22935 }
22936 if (Init && OrigType->isAnyComplexType()) {
22937 // Init = 0xFFFF + 0xFFFFi;
22938 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
22939 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
22940 }
22941 Type = OrigType;
22942 break;
22943 }
22944 case BO_LT:
22945 case BO_GT: {
22946 // 'min' reduction op - initializer is 'Largest representable number in
22947 // the reduction list item type'.
22948 // 'max' reduction op - initializer is 'Least representable number in
22949 // the reduction list item type'.
22950 if (Type->isIntegerType() || Type->isPointerType()) {
22951 bool IsSigned = Type->hasSignedIntegerRepresentation();
22952 uint64_t Size = Context.getTypeSize(Type);
22953 QualType IntTy =
22954 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
22955 llvm::APInt InitValue =
22956 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
22957 : llvm::APInt::getMinValue(Size)
22958 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
22959 : llvm::APInt::getMaxValue(Size);
22960 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
22961 if (Type->isPointerType()) {
22962 // Cast to pointer type.
22964 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
22965 if (CastExpr.isInvalid())
22966 continue;
22967 Init = CastExpr.get();
22968 }
22969 } else if (Type->isRealFloatingType()) {
22970 llvm::APFloat InitValue = llvm::APFloat::getLargest(
22971 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
22972 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
22973 Type, ELoc);
22974 }
22975 break;
22976 }
22977 case BO_PtrMemD:
22978 case BO_PtrMemI:
22979 case BO_MulAssign:
22980 case BO_Div:
22981 case BO_Rem:
22982 case BO_Sub:
22983 case BO_Shl:
22984 case BO_Shr:
22985 case BO_LE:
22986 case BO_GE:
22987 case BO_EQ:
22988 case BO_NE:
22989 case BO_Cmp:
22990 case BO_AndAssign:
22991 case BO_XorAssign:
22992 case BO_OrAssign:
22993 case BO_Assign:
22994 case BO_AddAssign:
22995 case BO_SubAssign:
22996 case BO_DivAssign:
22997 case BO_RemAssign:
22998 case BO_ShlAssign:
22999 case BO_ShrAssign:
23000 case BO_Comma:
23001 llvm_unreachable("Unexpected reduction operation");
23002 }
23003 }
23004 if (Init && DeclareReductionRef.isUnset()) {
23005 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
23006 // Store initializer for single element in private copy. Will be used
23007 // during codegen.
23008 PrivateVD->setInit(RHSVD->getInit());
23009 PrivateVD->setInitStyle(RHSVD->getInitStyle());
23010 } else if (!Init) {
23011 S.ActOnUninitializedDecl(RHSVD);
23012 // Store initializer for single element in private copy. Will be used
23013 // during codegen.
23014 PrivateVD->setInit(RHSVD->getInit());
23015 PrivateVD->setInitStyle(RHSVD->getInitStyle());
23016 }
23017 if (RHSVD->isInvalidDecl())
23018 continue;
23019 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
23020 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
23021 << Type << ReductionIdRange;
23022 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
23024 S.Diag(D->getLocation(),
23025 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
23026 << D;
23027 continue;
23028 }
23029 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
23030 ExprResult ReductionOp;
23031 if (DeclareReductionRef.isUsable()) {
23032 QualType RedTy = DeclareReductionRef.get()->getType();
23033 QualType PtrRedTy = Context.getPointerType(RedTy);
23034 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
23035 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
23036 if (!BasePath.empty()) {
23037 LHS = S.DefaultLvalueConversion(LHS.get());
23038 RHS = S.DefaultLvalueConversion(RHS.get());
23040 Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
23041 LHS.get()->getValueKind(), FPOptionsOverride());
23043 Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
23044 RHS.get()->getValueKind(), FPOptionsOverride());
23045 }
23047 QualType Params[] = {PtrRedTy, PtrRedTy};
23048 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
23049 auto *OVE = new (Context) OpaqueValueExpr(
23050 ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
23051 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
23052 Expr *Args[] = {LHS.get(), RHS.get()};
23053 ReductionOp =
23054 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
23056 } else {
23058 if (Type->isRecordType() && CombBOK != BOK) {
23060 ReductionOp =
23061 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
23062 CombBOK, LHSDRE, RHSDRE);
23063 }
23064 if (!ReductionOp.isUsable()) {
23065 ReductionOp =
23066 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
23067 LHSDRE, RHSDRE);
23068 if (ReductionOp.isUsable()) {
23069 if (BOK != BO_LT && BOK != BO_GT) {
23070 ReductionOp =
23071 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
23072 BO_Assign, LHSDRE, ReductionOp.get());
23073 } else {
23074 auto *ConditionalOp = new (Context)
23075 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
23076 RHSDRE, Type, VK_LValue, OK_Ordinary);
23077 ReductionOp =
23078 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
23079 BO_Assign, LHSDRE, ConditionalOp);
23080 }
23081 }
23082 }
23083 if (ReductionOp.isUsable())
23084 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
23085 /*DiscardedValue=*/false);
23086 if (!ReductionOp.isUsable())
23087 continue;
23088 }
23089
23090 // Add copy operations for inscan reductions.
23091 // LHS = RHS;
23092 ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
23093 if (ClauseKind == OMPC_reduction &&
23094 RD.RedModifier == OMPC_REDUCTION_inscan) {
23095 ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
23096 CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
23097 RHS.get());
23098 if (!CopyOpRes.isUsable())
23099 continue;
23100 CopyOpRes =
23101 S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
23102 if (!CopyOpRes.isUsable())
23103 continue;
23104 // For simd directive and simd-based directives in simd mode no need to
23105 // construct temp array, need just a single temp element.
23106 if (Stack->getCurrentDirective() == OMPD_simd ||
23107 (S.getLangOpts().OpenMPSimd &&
23108 isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
23109 VarDecl *TempArrayVD =
23110 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
23111 D->hasAttrs() ? &D->getAttrs() : nullptr);
23112 // Add a constructor to the temp decl.
23113 S.ActOnUninitializedDecl(TempArrayVD);
23114 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
23115 } else {
23116 // Build temp array for prefix sum.
23117 auto *Dim = new (S.Context)
23120 PrivateTy, Dim, ArraySizeModifier::Normal,
23121 /*IndexTypeQuals=*/0);
23122 VarDecl *TempArrayVD =
23123 buildVarDecl(S, ELoc, ArrayTy, D->getName(),
23124 D->hasAttrs() ? &D->getAttrs() : nullptr);
23125 // Add a constructor to the temp decl.
23126 S.ActOnUninitializedDecl(TempArrayVD);
23127 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
23128 TempArrayElem =
23129 S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
23130 auto *Idx = new (S.Context)
23132 TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
23133 ELoc, Idx, ELoc);
23134 }
23135 }
23136
23137 // OpenMP [2.15.4.6, Restrictions, p.2]
23138 // A list item that appears in an in_reduction clause of a task construct
23139 // must appear in a task_reduction clause of a construct associated with a
23140 // taskgroup region that includes the participating task in its taskgroup
23141 // set. The construct associated with the innermost region that meets this
23142 // condition must specify the same reduction-identifier as the in_reduction
23143 // clause.
23144 if (ClauseKind == OMPC_in_reduction) {
23145 SourceRange ParentSR;
23146 BinaryOperatorKind ParentBOK;
23147 const Expr *ParentReductionOp = nullptr;
23148 Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
23149 DSAStackTy::DSAVarData ParentBOKDSA =
23150 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
23151 ParentBOKTD);
23152 DSAStackTy::DSAVarData ParentReductionOpDSA =
23153 Stack->getTopMostTaskgroupReductionData(
23154 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
23155 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
23156 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
23157 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
23158 (DeclareReductionRef.isUsable() && IsParentBOK) ||
23159 (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
23160 bool EmitError = true;
23161 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
23162 llvm::FoldingSetNodeID RedId, ParentRedId;
23163 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
23164 DeclareReductionRef.get()->Profile(RedId, Context,
23165 /*Canonical=*/true);
23166 EmitError = RedId != ParentRedId;
23167 }
23168 if (EmitError) {
23169 S.Diag(ReductionId.getBeginLoc(),
23170 diag::err_omp_reduction_identifier_mismatch)
23171 << ReductionIdRange << RefExpr->getSourceRange();
23172 S.Diag(ParentSR.getBegin(),
23173 diag::note_omp_previous_reduction_identifier)
23174 << ParentSR
23175 << (IsParentBOK ? ParentBOKDSA.RefExpr
23176 : ParentReductionOpDSA.RefExpr)
23177 ->getSourceRange();
23178 continue;
23179 }
23180 }
23181 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
23182 }
23183
23184 DeclRefExpr *Ref = nullptr;
23185 Expr *VarsExpr = RefExpr->IgnoreParens();
23186 bool IsBindingDecl = isa<BindingDecl>(D);
23187 if (!VD && !IsBindingDecl && !S.CurContext->isDependentContext()) {
23188 if (ASE || OASE) {
23189 TransformExprToCaptures RebuildToCapture(S, D);
23190 VarsExpr =
23191 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
23192 Ref = RebuildToCapture.getCapturedExpr();
23193 } else {
23194 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
23195 }
23196 if (!S.OpenMP().isOpenMPCapturedDecl(D)) {
23197 RD.ExprCaptures.emplace_back(Ref->getDecl());
23198 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
23199 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
23200 if (!RefRes.isUsable())
23201 continue;
23202 ExprResult PostUpdateRes =
23203 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
23204 RefRes.get());
23205 if (!PostUpdateRes.isUsable())
23206 continue;
23207 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
23208 Stack->getCurrentDirective() == OMPD_taskgroup) {
23209 S.Diag(RefExpr->getExprLoc(),
23210 diag::err_omp_reduction_non_addressable_expression)
23211 << RefExpr->getSourceRange();
23212 continue;
23213 }
23214 RD.ExprPostUpdates.emplace_back(
23215 S.IgnoredValueConversions(PostUpdateRes.get()).get());
23216 }
23217 }
23218 }
23219 // All reduction items are still marked as reduction (to do not increase
23220 // code base size).
23221 unsigned Modifier = RD.RedModifier;
23222 // Consider task_reductions as reductions with task modifier. Required for
23223 // correct analysis of in_reduction clauses.
23224 if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
23225 Modifier = OMPC_REDUCTION_task;
23226 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
23227 ASE || OASE);
23228 if (Modifier == OMPC_REDUCTION_task &&
23229 (CurrDir == OMPD_taskgroup ||
23230 ((isOpenMPParallelDirective(CurrDir) ||
23231 isOpenMPWorksharingDirective(CurrDir)) &&
23232 !isOpenMPSimdDirective(CurrDir)))) {
23233 if (DeclareReductionRef.isUsable())
23234 Stack->addTaskgroupReductionData(D, ReductionIdRange,
23235 DeclareReductionRef.get());
23236 else
23237 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
23238 }
23239 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
23240 TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
23241 TempArrayElem.get(), IsPrivate);
23242 }
23243 return RD.Vars.empty();
23244}
23245
23247 ArrayRef<Expr *> VarList,
23249 SourceLocation StartLoc, SourceLocation LParenLoc,
23250 SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
23251 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
23252 ArrayRef<Expr *> UnresolvedReductions) {
23254 static_cast<OpenMPReductionClauseModifier>(Modifiers.ExtraModifier);
23255 OpenMPOriginalSharingModifier OriginalSharingModifier =
23256 static_cast<OpenMPOriginalSharingModifier>(
23257 Modifiers.OriginalSharingModifier);
23258 if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
23259 Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
23260 << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
23261 /*Last=*/OMPC_REDUCTION_unknown)
23262 << getOpenMPClauseNameForDiag(OMPC_reduction);
23263 return nullptr;
23264 }
23265 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
23266 // A reduction clause with the inscan reduction-modifier may only appear on a
23267 // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
23268 // construct, a parallel worksharing-loop construct or a parallel
23269 // worksharing-loop SIMD construct.
23270 if (Modifier == OMPC_REDUCTION_inscan &&
23271 (DSAStack->getCurrentDirective() != OMPD_for &&
23272 DSAStack->getCurrentDirective() != OMPD_for_simd &&
23273 DSAStack->getCurrentDirective() != OMPD_simd &&
23274 DSAStack->getCurrentDirective() != OMPD_parallel_for &&
23275 DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
23276 Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
23277 return nullptr;
23278 }
23279 ReductionData RD(VarList.size(), Modifier, OriginalSharingModifier);
23280 if (actOnOMPReductionKindClause(SemaRef, DSAStack, OMPC_reduction, VarList,
23281 StartLoc, LParenLoc, ColonLoc, EndLoc,
23282 ReductionIdScopeSpec, ReductionId,
23283 UnresolvedReductions, RD))
23284 return nullptr;
23285
23286 return OMPReductionClause::Create(
23287 getASTContext(), StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
23288 Modifier, RD.Vars,
23289 ReductionIdScopeSpec.getWithLocInContext(getASTContext()), ReductionId,
23290 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
23291 RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
23292 buildPreInits(getASTContext(), RD.ExprCaptures),
23293 buildPostUpdate(SemaRef, RD.ExprPostUpdates), RD.IsPrivateVarReduction,
23294 OriginalSharingModifier);
23295}
23296
23298 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
23299 SourceLocation ColonLoc, SourceLocation EndLoc,
23300 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
23301 ArrayRef<Expr *> UnresolvedReductions) {
23302 ReductionData RD(VarList.size());
23303 if (actOnOMPReductionKindClause(SemaRef, DSAStack, OMPC_task_reduction,
23304 VarList, StartLoc, LParenLoc, ColonLoc,
23305 EndLoc, ReductionIdScopeSpec, ReductionId,
23306 UnresolvedReductions, RD))
23307 return nullptr;
23308
23309 return OMPTaskReductionClause::Create(
23310 getASTContext(), StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
23311 ReductionIdScopeSpec.getWithLocInContext(getASTContext()), ReductionId,
23312 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
23313 buildPreInits(getASTContext(), RD.ExprCaptures),
23314 buildPostUpdate(SemaRef, RD.ExprPostUpdates));
23315}
23316
23318 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
23319 SourceLocation ColonLoc, SourceLocation EndLoc,
23320 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
23321 ArrayRef<Expr *> UnresolvedReductions) {
23322 ReductionData RD(VarList.size());
23323 if (actOnOMPReductionKindClause(SemaRef, DSAStack, OMPC_in_reduction, VarList,
23324 StartLoc, LParenLoc, ColonLoc, EndLoc,
23325 ReductionIdScopeSpec, ReductionId,
23326 UnresolvedReductions, RD))
23327 return nullptr;
23328
23329 return OMPInReductionClause::Create(
23330 getASTContext(), StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
23331 ReductionIdScopeSpec.getWithLocInContext(getASTContext()), ReductionId,
23332 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
23333 buildPreInits(getASTContext(), RD.ExprCaptures),
23334 buildPostUpdate(SemaRef, RD.ExprPostUpdates));
23335}
23336
23338 SourceLocation LinLoc) {
23339 if ((!getLangOpts().CPlusPlus && LinKind != OMPC_LINEAR_val) ||
23340 LinKind == OMPC_LINEAR_unknown || LinKind == OMPC_LINEAR_step) {
23341 Diag(LinLoc, diag::err_omp_wrong_linear_modifier)
23342 << getLangOpts().CPlusPlus;
23343 return true;
23344 }
23345 return false;
23346}
23347
23349 OpenMPLinearClauseKind LinKind,
23350 QualType Type, bool IsDeclareSimd) {
23351 const auto *VD = dyn_cast_or_null<VarDecl>(D);
23352 // A variable must not have an incomplete type or a reference type.
23353 if (SemaRef.RequireCompleteType(ELoc, Type,
23354 diag::err_omp_linear_incomplete_type))
23355 return true;
23356 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
23357 !Type->isReferenceType()) {
23358 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
23359 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
23360 return true;
23361 }
23362 Type = Type.getNonReferenceType();
23363
23364 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
23365 // A variable that is privatized must not have a const-qualified type
23366 // unless it is of class type with a mutable member. This restriction does
23367 // not apply to the firstprivate clause, nor to the linear clause on
23368 // declarative directives (like declare simd).
23369 if (!IsDeclareSimd &&
23370 rejectConstNotMutableType(SemaRef, D, Type, OMPC_linear, ELoc))
23371 return true;
23372
23373 // A list item must be of integral or pointer type.
23374 Type = Type.getUnqualifiedType().getCanonicalType();
23375 const auto *Ty = Type.getTypePtrOrNull();
23376 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
23377 !Ty->isIntegralType(getASTContext()) && !Ty->isPointerType())) {
23378 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
23379 if (D) {
23380 bool IsDecl = !VD || VD->isThisDeclarationADefinition(getASTContext()) ==
23382 Diag(D->getLocation(),
23383 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
23384 << D;
23385 }
23386 return true;
23387 }
23388 return false;
23389}
23390
23392 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
23393 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
23394 SourceLocation LinLoc, SourceLocation ColonLoc,
23395 SourceLocation StepModifierLoc, SourceLocation EndLoc) {
23399 SmallVector<Decl *, 4> ExprCaptures;
23400 SmallVector<Expr *, 4> ExprPostUpdates;
23401 // OpenMP 5.2 [Section 5.4.6, linear clause]
23402 // step-simple-modifier is exclusive, can't be used with 'val', 'uval', or
23403 // 'ref'
23404 if (LinLoc.isValid() && StepModifierLoc.isInvalid() && Step &&
23405 getLangOpts().OpenMP >= 52)
23406 Diag(Step->getBeginLoc(), diag::err_omp_step_simple_modifier_exclusive);
23407 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
23408 LinKind = OMPC_LINEAR_val;
23409 for (Expr *RefExpr : VarList) {
23410 assert(RefExpr && "NULL expr in OpenMP linear clause.");
23411 SourceLocation ELoc;
23412 SourceRange ERange;
23413 Expr *SimpleRefExpr = RefExpr;
23414 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
23415 if (Res.second) {
23416 // It will be analyzed later.
23417 Vars.push_back(RefExpr);
23418 Privates.push_back(nullptr);
23419 Inits.push_back(nullptr);
23420 }
23421 ValueDecl *D = Res.first;
23422 if (!D)
23423 continue;
23424
23425 // Linear on bindings only works for simple simd, not parallel constructs.
23426 if (isa<BindingDecl>(D)) {
23427 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
23428 if (isOpenMPParallelDirective(DKind)) {
23429 Diag(ELoc, diag::err_omp_unsupported_on_binding) << 2;
23430 continue;
23431 }
23432 }
23433
23434 QualType Type = D->getType();
23435 auto *VD = dyn_cast<VarDecl>(D);
23436
23437 // OpenMP [2.14.3.7, linear clause]
23438 // A list-item cannot appear in more than one linear clause.
23439 // A list-item that appears in a linear clause cannot appear in any
23440 // other data-sharing attribute clause.
23441 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
23442 if (DVar.RefExpr) {
23443 Diag(ELoc, diag::err_omp_wrong_dsa)
23444 << getOpenMPClauseNameForDiag(DVar.CKind)
23445 << getOpenMPClauseNameForDiag(OMPC_linear);
23447 continue;
23448 }
23449
23450 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
23451 continue;
23452 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
23453
23454 // Build private copy of original var.
23455 VarDecl *Private =
23456 buildVarDecl(SemaRef, ELoc, Type, D->getName(),
23457 D->hasAttrs() ? &D->getAttrs() : nullptr,
23458 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
23459 DeclRefExpr *PrivateRef = buildDeclRefExpr(SemaRef, Private, Type, ELoc);
23460 // Build var to save initial value.
23461 VarDecl *Init = buildVarDecl(SemaRef, ELoc, Type, ".linear.start");
23462 DeclRefExpr *Ref = nullptr;
23463 bool IsBindingDecl = isa<BindingDecl>(D);
23464 if (!VD && !IsBindingDecl && !SemaRef.CurContext->isDependentContext()) {
23465 Ref = buildCapture(SemaRef, D, SimpleRefExpr, /*WithInit=*/false);
23466 if (!isOpenMPCapturedDecl(D)) {
23467 ExprCaptures.push_back(Ref->getDecl());
23468 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
23469 ExprResult RefRes = SemaRef.DefaultLvalueConversion(Ref);
23470 if (!RefRes.isUsable())
23471 continue;
23472 ExprResult PostUpdateRes =
23473 SemaRef.BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
23474 SimpleRefExpr, RefRes.get());
23475 if (!PostUpdateRes.isUsable())
23476 continue;
23477 ExprPostUpdates.push_back(
23478 SemaRef.IgnoredValueConversions(PostUpdateRes.get()).get());
23479 }
23480 }
23481 }
23482 // Read the initial value through the list item itself for every modifier;
23483 // a 'uval' item is a reference whose referenced value is linear, exactly as
23484 // for 'val', and need not have an initializer (e.g. a reference parameter).
23485 Expr *InitExpr = Ref ? Ref : SimpleRefExpr;
23486 SemaRef.AddInitializerToDecl(
23487 Init, SemaRef.DefaultLvalueConversion(InitExpr).get(),
23488 /*DirectInit=*/false);
23489 DeclRefExpr *InitRef = buildDeclRefExpr(SemaRef, Init, Type, ELoc);
23490
23491 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
23492 Vars.push_back(
23493 (VD || IsBindingDecl || SemaRef.CurContext->isDependentContext())
23494 ? RefExpr->IgnoreParens()
23495 : Ref);
23496 Privates.push_back(PrivateRef);
23497 Inits.push_back(InitRef);
23498 }
23499
23500 if (Vars.empty())
23501 return nullptr;
23502
23503 Expr *StepExpr = Step;
23504 Expr *CalcStepExpr = nullptr;
23505 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
23506 !Step->isInstantiationDependent() &&
23508 SourceLocation StepLoc = Step->getBeginLoc();
23510 if (Val.isInvalid())
23511 return nullptr;
23512 StepExpr = Val.get();
23513
23514 // Build var to save the step value.
23515 VarDecl *SaveVar =
23516 buildVarDecl(SemaRef, StepLoc, StepExpr->getType(), ".linear.step");
23517 ExprResult SaveRef =
23518 buildDeclRefExpr(SemaRef, SaveVar, StepExpr->getType(), StepLoc);
23519 ExprResult CalcStep = SemaRef.BuildBinOp(
23520 SemaRef.getCurScope(), StepLoc, BO_Assign, SaveRef.get(), StepExpr);
23521 CalcStep =
23522 SemaRef.ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue=*/false);
23523
23524 // Warn about zero linear step (it would be probably better specified as
23525 // making corresponding variables 'const').
23526 if (std::optional<llvm::APSInt> Result =
23528 if (!Result->isNegative() && !Result->isStrictlyPositive())
23529 Diag(StepLoc, diag::warn_omp_linear_step_zero)
23530 << Vars[0] << (Vars.size() > 1);
23531 } else if (CalcStep.isUsable()) {
23532 // Calculate the step beforehand instead of doing this on each iteration.
23533 // (This is not used if the number of iterations may be kfold-ed).
23534 CalcStepExpr = CalcStep.get();
23535 }
23536 }
23537
23538 return OMPLinearClause::Create(getASTContext(), StartLoc, LParenLoc, LinKind,
23539 LinLoc, ColonLoc, StepModifierLoc, EndLoc,
23540 Vars, Privates, Inits, StepExpr, CalcStepExpr,
23541 buildPreInits(getASTContext(), ExprCaptures),
23542 buildPostUpdate(SemaRef, ExprPostUpdates));
23543}
23544
23545static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
23546 Expr *NumIterations, Sema &SemaRef,
23547 Scope *S, DSAStackTy *Stack) {
23548 // Walk the vars and build update/final expressions for the CodeGen.
23551 SmallVector<Expr *, 8> UsedExprs;
23552 Expr *Step = Clause.getStep();
23553 Expr *CalcStep = Clause.getCalcStep();
23554 // OpenMP [2.14.3.7, linear clause]
23555 // If linear-step is not specified it is assumed to be 1.
23556 if (!Step)
23557 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
23558 else if (CalcStep)
23559 Step = cast<BinaryOperator>(CalcStep)->getLHS();
23560 bool HasErrors = false;
23561 auto CurInit = Clause.inits().begin();
23562 auto CurPrivate = Clause.privates().begin();
23563 for (Expr *RefExpr : Clause.varlist()) {
23564 SourceLocation ELoc;
23565 SourceRange ERange;
23566 Expr *SimpleRefExpr = RefExpr;
23567 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
23568 ValueDecl *D = Res.first;
23569 if (Res.second || !D) {
23570 Updates.push_back(nullptr);
23571 Finals.push_back(nullptr);
23572 HasErrors = true;
23573 continue;
23574 }
23575 auto &&Info = Stack->isLoopControlVariable(D);
23576 // OpenMP [2.15.11, distribute simd Construct]
23577 // A list item may not appear in a linear clause, unless it is the loop
23578 // iteration variable.
23579 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
23580 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
23581 SemaRef.Diag(ELoc,
23582 diag::err_omp_linear_distribute_var_non_loop_iteration);
23583 Updates.push_back(nullptr);
23584 Finals.push_back(nullptr);
23585 HasErrors = true;
23586 continue;
23587 }
23588 Expr *InitExpr = *CurInit;
23589
23590 // Build privatized reference to the current linear var. The final value is
23591 // written back through the variable itself, also for 'uval' references.
23592 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
23593 Expr *CapturedRef;
23594 if (isa<BindingDecl>(DE->getDecl())) {
23595 CapturedRef = SimpleRefExpr;
23596 } else {
23597 CapturedRef =
23598 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
23599 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
23600 /*RefersToCapture=*/true);
23601 }
23602
23603 // Build update: Var = InitExpr + IV * Step
23605 if (!Info.first)
23607 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
23608 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
23609 else
23610 Update = *CurPrivate;
23611 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
23612 /*DiscardedValue=*/false);
23613
23614 // Build final: Var = PrivCopy;
23615 ExprResult Final;
23616 if (!Info.first)
23617 Final = SemaRef.BuildBinOp(
23618 S, RefExpr->getExprLoc(), BO_Assign, CapturedRef,
23619 SemaRef.DefaultLvalueConversion(*CurPrivate).get());
23620 else
23621 Final = *CurPrivate;
23622 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
23623 /*DiscardedValue=*/false);
23624
23625 if (!Update.isUsable() || !Final.isUsable()) {
23626 Updates.push_back(nullptr);
23627 Finals.push_back(nullptr);
23628 UsedExprs.push_back(nullptr);
23629 HasErrors = true;
23630 } else {
23631 Updates.push_back(Update.get());
23632 Finals.push_back(Final.get());
23633 if (!Info.first)
23634 UsedExprs.push_back(SimpleRefExpr);
23635 }
23636 ++CurInit;
23637 ++CurPrivate;
23638 }
23639 if (Expr *S = Clause.getStep())
23640 UsedExprs.push_back(S);
23641 // Fill the remaining part with the nullptr.
23642 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
23643 Clause.setUpdates(Updates);
23644 Clause.setFinals(Finals);
23645 Clause.setUsedExprs(UsedExprs);
23646 return HasErrors;
23647}
23648
23650 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
23651 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
23653 for (Expr *RefExpr : VarList) {
23654 assert(RefExpr && "NULL expr in OpenMP aligned clause.");
23655 SourceLocation ELoc;
23656 SourceRange ERange;
23657 Expr *SimpleRefExpr = RefExpr;
23658 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
23659 if (Res.second) {
23660 // It will be analyzed later.
23661 Vars.push_back(RefExpr);
23662 }
23663 ValueDecl *D = Res.first;
23664 if (!D)
23665 continue;
23666
23667 QualType QType = D->getType();
23668 auto *VD = dyn_cast<VarDecl>(D);
23669
23670 // OpenMP [2.8.1, simd construct, Restrictions]
23671 // The type of list items appearing in the aligned clause must be
23672 // array, pointer, reference to array, or reference to pointer.
23674 const Type *Ty = QType.getTypePtrOrNull();
23675 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
23676 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
23677 << QType << getLangOpts().CPlusPlus << ERange;
23678 bool IsDecl = !VD || VD->isThisDeclarationADefinition(getASTContext()) ==
23680 Diag(D->getLocation(),
23681 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
23682 << D;
23683 continue;
23684 }
23685
23686 // OpenMP [2.8.1, simd construct, Restrictions]
23687 // A list-item cannot appear in more than one aligned clause.
23688 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
23689 Diag(ELoc, diag::err_omp_used_in_clause_twice)
23690 << 0 << getOpenMPClauseNameForDiag(OMPC_aligned) << ERange;
23691 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
23692 << getOpenMPClauseNameForDiag(OMPC_aligned);
23693 continue;
23694 }
23695
23696 DeclRefExpr *Ref = nullptr;
23697 if (!VD && isOpenMPCapturedDecl(D))
23698 Ref = buildCapture(SemaRef, D, SimpleRefExpr, /*WithInit=*/true);
23699 Vars.push_back(SemaRef
23700 .DefaultFunctionArrayConversion(
23701 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
23702 .get());
23703 }
23704
23705 // OpenMP [2.8.1, simd construct, Description]
23706 // The parameter of the aligned clause, alignment, must be a constant
23707 // positive integer expression.
23708 // If no optional parameter is specified, implementation-defined default
23709 // alignments for SIMD instructions on the target platforms are assumed.
23710 if (Alignment != nullptr) {
23711 ExprResult AlignResult =
23712 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
23713 if (AlignResult.isInvalid())
23714 return nullptr;
23715 Alignment = AlignResult.get();
23716 }
23717 if (Vars.empty())
23718 return nullptr;
23719
23720 return OMPAlignedClause::Create(getASTContext(), StartLoc, LParenLoc,
23721 ColonLoc, EndLoc, Vars, Alignment);
23722}
23723
23725 SourceLocation StartLoc,
23726 SourceLocation LParenLoc,
23727 SourceLocation EndLoc) {
23729 SmallVector<Expr *, 8> SrcExprs;
23730 SmallVector<Expr *, 8> DstExprs;
23731 SmallVector<Expr *, 8> AssignmentOps;
23732 for (Expr *RefExpr : VarList) {
23733 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
23734 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
23735 // It will be analyzed later.
23736 Vars.push_back(RefExpr);
23737 SrcExprs.push_back(nullptr);
23738 DstExprs.push_back(nullptr);
23739 AssignmentOps.push_back(nullptr);
23740 continue;
23741 }
23742
23743 SourceLocation ELoc = RefExpr->getExprLoc();
23744 // OpenMP [2.1, C/C++]
23745 // A list item is a variable name.
23746 // OpenMP [2.14.4.1, Restrictions, p.1]
23747 // A list item that appears in a copyin clause must be threadprivate.
23748 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
23749 if (!DE || !isa<VarDecl>(DE->getDecl())) {
23750 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
23751 << 0 << RefExpr->getSourceRange();
23752 continue;
23753 }
23754
23755 Decl *D = DE->getDecl();
23756 auto *VD = cast<VarDecl>(D);
23757
23758 QualType Type = VD->getType();
23760 // It will be analyzed later.
23761 Vars.push_back(DE);
23762 SrcExprs.push_back(nullptr);
23763 DstExprs.push_back(nullptr);
23764 AssignmentOps.push_back(nullptr);
23765 continue;
23766 }
23767
23768 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
23769 // A list item that appears in a copyin clause must be threadprivate.
23770 if (!DSAStack->isThreadPrivate(VD)) {
23771 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
23772 Diag(ELoc, diag::err_omp_required_access)
23773 << getOpenMPClauseNameForDiag(OMPC_copyin)
23774 << getOpenMPDirectiveName(OMPD_threadprivate, OMPVersion);
23775 continue;
23776 }
23777
23778 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
23779 // A variable of class type (or array thereof) that appears in a
23780 // copyin clause requires an accessible, unambiguous copy assignment
23781 // operator for the class type.
23782 QualType ElemType =
23784 VarDecl *SrcVD =
23785 buildVarDecl(SemaRef, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
23786 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
23787 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
23788 SemaRef, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
23789 VarDecl *DstVD =
23790 buildVarDecl(SemaRef, DE->getBeginLoc(), ElemType, ".copyin.dst",
23791 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
23792 DeclRefExpr *PseudoDstExpr =
23793 buildDeclRefExpr(SemaRef, DstVD, ElemType, DE->getExprLoc());
23794 // For arrays generate assignment operation for single element and replace
23795 // it by the original array element in CodeGen.
23796 ExprResult AssignmentOp =
23797 SemaRef.BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
23798 PseudoDstExpr, PseudoSrcExpr);
23799 if (AssignmentOp.isInvalid())
23800 continue;
23801 AssignmentOp =
23802 SemaRef.ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
23803 /*DiscardedValue=*/false);
23804 if (AssignmentOp.isInvalid())
23805 continue;
23806
23807 DSAStack->addDSA(VD, DE, OMPC_copyin);
23808 Vars.push_back(DE);
23809 SrcExprs.push_back(PseudoSrcExpr);
23810 DstExprs.push_back(PseudoDstExpr);
23811 AssignmentOps.push_back(AssignmentOp.get());
23812 }
23813
23814 if (Vars.empty())
23815 return nullptr;
23816
23817 return OMPCopyinClause::Create(getASTContext(), StartLoc, LParenLoc, EndLoc,
23818 Vars, SrcExprs, DstExprs, AssignmentOps);
23819}
23820
23822 SourceLocation StartLoc,
23823 SourceLocation LParenLoc,
23824 SourceLocation EndLoc) {
23826 SmallVector<Expr *, 8> SrcExprs;
23827 SmallVector<Expr *, 8> DstExprs;
23828 SmallVector<Expr *, 8> AssignmentOps;
23829 for (Expr *RefExpr : VarList) {
23830 assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
23831 SourceLocation ELoc;
23832 SourceRange ERange;
23833 Expr *SimpleRefExpr = RefExpr;
23834 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
23835 if (Res.second) {
23836 // It will be analyzed later.
23837 Vars.push_back(RefExpr);
23838 SrcExprs.push_back(nullptr);
23839 DstExprs.push_back(nullptr);
23840 AssignmentOps.push_back(nullptr);
23841 }
23842 ValueDecl *D = Res.first;
23843 if (!D)
23844 continue;
23845
23846 QualType Type = D->getType();
23847 auto *VD = dyn_cast<VarDecl>(D);
23848
23849 // OpenMP [2.14.4.2, Restrictions, p.2]
23850 // A list item that appears in a copyprivate clause may not appear in a
23851 // private or firstprivate clause on the single construct.
23852 if (!VD || !DSAStack->isThreadPrivate(VD)) {
23853 DSAStackTy::DSAVarData DVar =
23854 DSAStack->getTopDSA(D, /*FromParent=*/false);
23855 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
23856 DVar.RefExpr) {
23857 Diag(ELoc, diag::err_omp_wrong_dsa)
23858 << getOpenMPClauseNameForDiag(DVar.CKind)
23859 << getOpenMPClauseNameForDiag(OMPC_copyprivate);
23861 continue;
23862 }
23863
23864 // OpenMP [2.11.4.2, Restrictions, p.1]
23865 // All list items that appear in a copyprivate clause must be either
23866 // threadprivate or private in the enclosing context.
23867 if (DVar.CKind == OMPC_unknown) {
23868 DVar = DSAStack->getImplicitDSA(D, false);
23869 // A data member is private only if an enclosing construct captured it.
23870 const bool IsShared = DVar.CKind == OMPC_shared;
23871 if (IsShared ||
23872 (isa<FieldDecl>(D) && !SemaRef.CurContext->isDependentContext() &&
23873 !isOpenMPCapturedDecl(D))) {
23874 Diag(ELoc, diag::err_omp_required_access)
23875 << getOpenMPClauseNameForDiag(OMPC_copyprivate)
23876 << "threadprivate or private in the enclosing context";
23877 if (IsShared)
23879 continue;
23880 }
23881 }
23882 }
23883
23884 // Variably modified types are not supported.
23886 llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
23887 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
23888 << getOpenMPClauseNameForDiag(OMPC_copyprivate) << Type
23889 << getOpenMPDirectiveName(DSAStack->getCurrentDirective(),
23890 OMPVersion);
23891 bool IsDecl = !VD || VD->isThisDeclarationADefinition(getASTContext()) ==
23893 Diag(D->getLocation(),
23894 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
23895 << D;
23896 continue;
23897 }
23898
23899 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
23900 // A variable of class type (or array thereof) that appears in a
23901 // copyin clause requires an accessible, unambiguous copy assignment
23902 // operator for the class type.
23904 .getBaseElementType(Type.getNonReferenceType())
23906 VarDecl *SrcVD =
23907 buildVarDecl(SemaRef, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
23908 D->hasAttrs() ? &D->getAttrs() : nullptr);
23909 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(SemaRef, SrcVD, Type, ELoc);
23910 VarDecl *DstVD =
23911 buildVarDecl(SemaRef, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
23912 D->hasAttrs() ? &D->getAttrs() : nullptr);
23913 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(SemaRef, DstVD, Type, ELoc);
23914 ExprResult AssignmentOp = SemaRef.BuildBinOp(
23915 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
23916 if (AssignmentOp.isInvalid())
23917 continue;
23918 AssignmentOp = SemaRef.ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
23919 /*DiscardedValue=*/false);
23920 if (AssignmentOp.isInvalid())
23921 continue;
23922
23923 // No need to mark vars as copyprivate, they are already threadprivate or
23924 // implicitly private.
23925 const bool IsBindingDecl = isa<BindingDecl>(D);
23926 assert(VD || IsBindingDecl || SemaRef.CurContext->isDependentContext() ||
23928 Vars.push_back(
23929 (VD || IsBindingDecl || SemaRef.CurContext->isDependentContext())
23930 ? RefExpr->IgnoreParens()
23931 : buildCapture(SemaRef, D, SimpleRefExpr, /*WithInit=*/false));
23932 SrcExprs.push_back(PseudoSrcExpr);
23933 DstExprs.push_back(PseudoDstExpr);
23934 AssignmentOps.push_back(AssignmentOp.get());
23935 }
23936
23937 if (Vars.empty())
23938 return nullptr;
23939
23940 return OMPCopyprivateClause::Create(getASTContext(), StartLoc, LParenLoc,
23941 EndLoc, Vars, SrcExprs, DstExprs,
23942 AssignmentOps);
23943}
23944
23946 SourceLocation StartLoc,
23947 SourceLocation LParenLoc,
23948 SourceLocation EndLoc) {
23949 if (VarList.empty())
23950 return nullptr;
23951
23952 return OMPFlushClause::Create(getASTContext(), StartLoc, LParenLoc, EndLoc,
23953 VarList);
23954}
23955
23956/// Tries to find omp_depend_t. type.
23957static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
23958 bool Diagnose = true) {
23959 QualType OMPDependT = Stack->getOMPDependT();
23960 if (!OMPDependT.isNull())
23961 return true;
23962 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
23963 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
23964 if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
23965 if (Diagnose)
23966 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
23967 return false;
23968 }
23969 Stack->setOMPDependT(PT.get());
23970 return true;
23971}
23972
23974 SourceLocation StartLoc,
23975 SourceLocation LParenLoc,
23976 SourceLocation EndLoc) {
23977 if (!Depobj)
23978 return nullptr;
23979
23980 bool OMPDependTFound = findOMPDependT(SemaRef, StartLoc, DSAStack);
23981
23982 // OpenMP 5.0, 2.17.10.1 depobj Construct
23983 // depobj is an lvalue expression of type omp_depend_t.
23984 if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
23985 !Depobj->isInstantiationDependent() &&
23987 (OMPDependTFound && !getASTContext().typesAreCompatible(
23988 DSAStack->getOMPDependT(), Depobj->getType(),
23989 /*CompareUnqualified=*/true))) {
23990 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
23991 << 0 << Depobj->getType() << Depobj->getSourceRange();
23992 }
23993
23994 if (!Depobj->isLValue()) {
23995 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
23996 << 1 << Depobj->getSourceRange();
23997 }
23998
23999 return new (getASTContext())
24000 OMPDepobjClause(StartLoc, LParenLoc, EndLoc, Depobj);
24001}
24002
24003namespace {
24004// Utility struct that gathers the related info for doacross clause.
24005struct DoacrossDataInfoTy {
24006 // The list of expressions.
24008 // The OperatorOffset for doacross loop.
24009 DSAStackTy::OperatorOffsetTy OpsOffs;
24010 // The depended loop count.
24011 llvm::APSInt TotalDepCount;
24012};
24013} // namespace
24014static DoacrossDataInfoTy
24016 ArrayRef<Expr *> VarList, DSAStackTy *Stack,
24017 SourceLocation EndLoc) {
24018
24020 DSAStackTy::OperatorOffsetTy OpsOffs;
24021 llvm::APSInt DepCounter(/*BitWidth=*/32);
24022 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
24023
24024 if (const Expr *OrderedCountExpr =
24025 Stack->getParentOrderedRegionParam().first) {
24026 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(SemaRef.Context);
24027 TotalDepCount.setIsUnsigned(/*Val=*/true);
24028 }
24029
24030 for (Expr *RefExpr : VarList) {
24031 assert(RefExpr && "NULL expr in OpenMP doacross clause.");
24032 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
24033 // It will be analyzed later.
24034 Vars.push_back(RefExpr);
24035 continue;
24036 }
24037
24038 SourceLocation ELoc = RefExpr->getExprLoc();
24039 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
24040 if (!IsSource) {
24041 if (Stack->getParentOrderedRegionParam().first &&
24042 DepCounter >= TotalDepCount) {
24043 SemaRef.Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
24044 continue;
24045 }
24046 ++DepCounter;
24047 // OpenMP [2.13.9, Summary]
24048 // depend(dependence-type : vec), where dependence-type is:
24049 // 'sink' and where vec is the iteration vector, which has the form:
24050 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
24051 // where n is the value specified by the ordered clause in the loop
24052 // directive, xi denotes the loop iteration variable of the i-th nested
24053 // loop associated with the loop directive, and di is a constant
24054 // non-negative integer.
24055 if (SemaRef.CurContext->isDependentContext()) {
24056 // It will be analyzed later.
24057 Vars.push_back(RefExpr);
24058 continue;
24059 }
24060 SimpleExpr = SimpleExpr->IgnoreImplicit();
24062 SourceLocation OOLoc;
24063 Expr *LHS = SimpleExpr;
24064 Expr *RHS = nullptr;
24065 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
24066 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
24067 OOLoc = BO->getOperatorLoc();
24068 LHS = BO->getLHS()->IgnoreParenImpCasts();
24069 RHS = BO->getRHS()->IgnoreParenImpCasts();
24070 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
24071 OOK = OCE->getOperator();
24072 OOLoc = OCE->getOperatorLoc();
24073 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
24074 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
24075 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
24076 OOK = MCE->getMethodDecl()
24077 ->getNameInfo()
24078 .getName()
24079 .getCXXOverloadedOperator();
24080 OOLoc = MCE->getCallee()->getExprLoc();
24081 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
24082 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
24083 }
24084 SourceLocation ELoc;
24085 SourceRange ERange;
24086 auto Res = getPrivateItem(SemaRef, LHS, ELoc, ERange);
24087 if (Res.second) {
24088 // It will be analyzed later.
24089 Vars.push_back(RefExpr);
24090 }
24091 ValueDecl *D = Res.first;
24092 if (!D)
24093 continue;
24094
24095 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
24096 SemaRef.Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
24097 continue;
24098 }
24099 if (RHS) {
24100 ExprResult RHSRes =
24102 RHS, OMPC_depend, /*StrictlyPositive=*/false);
24103 if (RHSRes.isInvalid())
24104 continue;
24105 }
24106 if (!SemaRef.CurContext->isDependentContext() &&
24107 Stack->getParentOrderedRegionParam().first &&
24108 DepCounter != Stack->isParentLoopControlVariable(D).first) {
24109 const ValueDecl *VD =
24110 Stack->getParentLoopControlVariable(DepCounter.getZExtValue());
24111 if (VD)
24112 SemaRef.Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
24113 << 1 << VD;
24114 else
24115 SemaRef.Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
24116 << 0;
24117 continue;
24118 }
24119 OpsOffs.emplace_back(RHS, OOK);
24120 }
24121 Vars.push_back(RefExpr->IgnoreParenImpCasts());
24122 }
24123 if (!SemaRef.CurContext->isDependentContext() && !IsSource &&
24124 TotalDepCount > VarList.size() &&
24125 Stack->getParentOrderedRegionParam().first &&
24126 Stack->getParentLoopControlVariable(VarList.size() + 1)) {
24127 SemaRef.Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
24128 << 1 << Stack->getParentLoopControlVariable(VarList.size() + 1);
24129 }
24130 return {Vars, OpsOffs, TotalDepCount};
24131}
24132
24134 const OMPDependClause::DependDataTy &Data, Expr *DepModifier,
24135 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
24136 SourceLocation EndLoc) {
24137 OpenMPDependClauseKind DepKind = Data.DepKind;
24138 SourceLocation DepLoc = Data.DepLoc;
24139 if (DSAStack->getCurrentDirective() == OMPD_ordered_standalone &&
24140 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
24141 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
24142 << "'source' or 'sink'" << getOpenMPClauseNameForDiag(OMPC_depend);
24143 return nullptr;
24144 }
24145 if (DSAStack->getCurrentDirective() == OMPD_taskwait &&
24146 DepKind == OMPC_DEPEND_mutexinoutset) {
24147 Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed);
24148 return nullptr;
24149 }
24150 if ((DSAStack->getCurrentDirective() != OMPD_ordered_standalone ||
24151 DSAStack->getCurrentDirective() == OMPD_depobj) &&
24152 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
24153 DepKind == OMPC_DEPEND_sink ||
24154 ((getLangOpts().OpenMP < 50 ||
24155 DSAStack->getCurrentDirective() == OMPD_depobj) &&
24156 DepKind == OMPC_DEPEND_depobj))) {
24157 SmallVector<unsigned, 6> Except = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
24158 OMPC_DEPEND_outallmemory,
24159 OMPC_DEPEND_inoutallmemory};
24160 if (getLangOpts().OpenMP < 50 ||
24161 DSAStack->getCurrentDirective() == OMPD_depobj)
24162 Except.push_back(OMPC_DEPEND_depobj);
24163 if (getLangOpts().OpenMP < 51)
24164 Except.push_back(OMPC_DEPEND_inoutset);
24165 std::string Expected = (getLangOpts().OpenMP >= 50 && !DepModifier)
24166 ? "depend modifier(iterator) or "
24167 : "";
24168 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
24169 << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
24170 /*Last=*/OMPC_DEPEND_unknown,
24171 Except)
24172 << getOpenMPClauseNameForDiag(OMPC_depend);
24173 return nullptr;
24174 }
24175 if (DepModifier &&
24176 (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
24177 Diag(DepModifier->getExprLoc(),
24178 diag::err_omp_depend_sink_source_with_modifier);
24179 return nullptr;
24180 }
24181 if (DepModifier &&
24182 !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
24183 Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
24184
24186 DSAStackTy::OperatorOffsetTy OpsOffs;
24187 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
24188
24189 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
24190 DoacrossDataInfoTy VarOffset = ProcessOpenMPDoacrossClauseCommon(
24191 SemaRef, DepKind == OMPC_DEPEND_source, VarList, DSAStack, EndLoc);
24192 Vars = VarOffset.Vars;
24193 OpsOffs = VarOffset.OpsOffs;
24194 TotalDepCount = VarOffset.TotalDepCount;
24195 } else {
24196 for (Expr *RefExpr : VarList) {
24197 assert(RefExpr && "NULL expr in OpenMP depend clause.");
24198 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
24199 // It will be analyzed later.
24200 Vars.push_back(RefExpr);
24201 continue;
24202 }
24203
24204 SourceLocation ELoc = RefExpr->getExprLoc();
24205 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
24206 if (DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) {
24207 bool OMPDependTFound = getLangOpts().OpenMP >= 50;
24208 if (OMPDependTFound)
24209 OMPDependTFound = findOMPDependT(SemaRef, StartLoc, DSAStack,
24210 DepKind == OMPC_DEPEND_depobj);
24211 if (DepKind == OMPC_DEPEND_depobj) {
24212 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
24213 // List items used in depend clauses with the depobj dependence type
24214 // must be expressions of the omp_depend_t type.
24215 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
24216 !RefExpr->isInstantiationDependent() &&
24217 !RefExpr->containsUnexpandedParameterPack() &&
24218 (OMPDependTFound &&
24219 !getASTContext().hasSameUnqualifiedType(
24220 DSAStack->getOMPDependT(), RefExpr->getType()))) {
24221 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
24222 << 0 << RefExpr->getType() << RefExpr->getSourceRange();
24223 continue;
24224 }
24225 if (!RefExpr->isLValue()) {
24226 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
24227 << 1 << RefExpr->getType() << RefExpr->getSourceRange();
24228 continue;
24229 }
24230 } else {
24231 // OpenMP 5.0 [2.17.11, Restrictions]
24232 // List items used in depend clauses cannot be zero-length array
24233 // sections.
24234 QualType ExprTy = RefExpr->getType().getNonReferenceType();
24235 const auto *OASE = dyn_cast<ArraySectionExpr>(SimpleExpr);
24236 if (OASE) {
24237 QualType BaseType =
24239 if (BaseType.isNull())
24240 return nullptr;
24241 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
24242 ExprTy = ATy->getElementType();
24243 else
24244 ExprTy = BaseType->getPointeeType();
24245 if (BaseType.isNull() || ExprTy.isNull())
24246 return nullptr;
24247 ExprTy = ExprTy.getNonReferenceType();
24248 const Expr *Length = OASE->getLength();
24250 if (Length && !Length->isValueDependent() &&
24251 Length->EvaluateAsInt(Result, getASTContext()) &&
24252 Result.Val.getInt().isZero()) {
24253 Diag(ELoc,
24254 diag::err_omp_depend_zero_length_array_section_not_allowed)
24255 << SimpleExpr->getSourceRange();
24256 continue;
24257 }
24258 }
24259
24260 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
24261 // List items used in depend clauses with the in, out, inout,
24262 // inoutset, or mutexinoutset dependence types cannot be
24263 // expressions of the omp_depend_t type.
24264 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
24265 !RefExpr->isInstantiationDependent() &&
24266 !RefExpr->containsUnexpandedParameterPack() &&
24267 (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
24268 (OMPDependTFound && DSAStack->getOMPDependT().getTypePtr() ==
24269 ExprTy.getTypePtr()))) {
24270 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
24271 << (getLangOpts().OpenMP >= 50 ? 1 : 0)
24272 << (getLangOpts().OpenMP >= 50 ? 1 : 0)
24273 << RefExpr->getSourceRange();
24274 continue;
24275 }
24276
24277 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
24278 if (ASE && !ASE->getBase()->isTypeDependent() &&
24279 !ASE->getBase()
24280 ->getType()
24281 .getNonReferenceType()
24282 ->isPointerType() &&
24283 !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) {
24284 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
24285 << (getLangOpts().OpenMP >= 50 ? 1 : 0)
24286 << (getLangOpts().OpenMP >= 50 ? 1 : 0)
24287 << RefExpr->getSourceRange();
24288 continue;
24289 }
24290
24291 ExprResult Res;
24292 {
24294 Res = SemaRef.CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
24295 RefExpr->IgnoreParenImpCasts());
24296 }
24297 if (!Res.isUsable() && !isa<ArraySectionExpr>(SimpleExpr) &&
24299 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
24300 << (getLangOpts().OpenMP >= 50 ? 1 : 0)
24301 << (getLangOpts().OpenMP >= 50 ? 1 : 0)
24302 << RefExpr->getSourceRange();
24303 continue;
24304 }
24305 }
24306 }
24307 Vars.push_back(RefExpr->IgnoreParenImpCasts());
24308 }
24309 }
24310
24311 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
24312 DepKind != OMPC_DEPEND_outallmemory &&
24313 DepKind != OMPC_DEPEND_inoutallmemory && Vars.empty())
24314 return nullptr;
24315
24316 auto *C = OMPDependClause::Create(
24317 getASTContext(), StartLoc, LParenLoc, EndLoc,
24318 {DepKind, DepLoc, Data.ColonLoc, Data.OmpAllMemoryLoc}, DepModifier, Vars,
24319 TotalDepCount.getZExtValue());
24320 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
24321 DSAStack->isParentOrderedRegion())
24322 DSAStack->addDoacrossDependClause(C, OpsOffs);
24323 return C;
24324}
24325
24328 SourceLocation LParenLoc, SourceLocation ModifierLoc,
24329 SourceLocation EndLoc) {
24330 assert((ModifierLoc.isInvalid() || getLangOpts().OpenMP >= 50) &&
24331 "Unexpected device modifier in OpenMP < 50.");
24332
24333 bool ErrorFound = false;
24334 if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
24335 std::string Values =
24336 getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
24337 Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
24338 << Values << getOpenMPClauseNameForDiag(OMPC_device);
24339 ErrorFound = true;
24340 }
24341
24342 Expr *ValExpr = Device;
24343 Stmt *HelperValStmt = nullptr;
24344
24345 // OpenMP 5.2 [1.3, Execution Model]: a conforming device number is either
24346 // a non-negative integer that is less than or equal to omp_get_num_devices()
24347 // or equal to omp_initial_device or omp_invalid_device. The predefined
24348 // identifiers were introduced in OpenMP 5.2; earlier versions require a
24349 // non-negative integer.
24350 if (getLangOpts().OpenMP >= 52) {
24351 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
24352 !ValExpr->isInstantiationDependent()) {
24353 SourceLocation Loc = ValExpr->getExprLoc();
24355 if (Value.isInvalid()) {
24356 ErrorFound = true;
24357 } else {
24358 ValExpr = Value.get();
24359 if (std::optional<llvm::APSInt> Result =
24361 if (Result->isSigned() && Result->slt(-2)) {
24362 Diag(Loc, diag::err_omp_device_expression_invalid)
24363 << ValExpr->getSourceRange();
24364 ErrorFound = true;
24365 }
24366 }
24367 }
24368 }
24369 } else {
24370 ErrorFound = !isNonNegativeIntegerValue(ValExpr, SemaRef, OMPC_device,
24371 /*StrictlyPositive=*/false) ||
24372 ErrorFound;
24373 }
24374 if (ErrorFound)
24375 return nullptr;
24376
24377 // OpenMP 5.0 [2.12.5, Restrictions]
24378 // In case of ancestor device-modifier, a requires directive with
24379 // the reverse_offload clause must be specified.
24380 if (Modifier == OMPC_DEVICE_ancestor) {
24381 if (!DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>()) {
24382 SemaRef.targetDiag(
24383 StartLoc,
24384 diag::err_omp_device_ancestor_without_requires_reverse_offload);
24385 ErrorFound = true;
24386 }
24387 }
24388
24389 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
24391 DKind, OMPC_device, getLangOpts().getOpenMPVersion());
24392 if (CaptureRegion != OMPD_unknown &&
24393 !SemaRef.CurContext->isDependentContext()) {
24394 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
24395 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
24396 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
24397 HelperValStmt = buildPreInits(getASTContext(), Captures);
24398 }
24399
24400 return new (getASTContext())
24401 OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
24402 LParenLoc, ModifierLoc, EndLoc);
24403}
24404
24406 DSAStackTy *Stack, QualType QTy,
24407 bool FullCheck = true) {
24408 if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type))
24409 return false;
24410 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
24411 !QTy.isTriviallyCopyableType(SemaRef.Context))
24412 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
24413 return true;
24414}
24415
24416/// Return true if it can be proven that the provided array expression
24417/// (array section or array subscript) does NOT specify the whole size of the
24418/// array whose base type is \a BaseQTy.
24420 const Expr *E,
24421 QualType BaseQTy) {
24422 const auto *OASE = dyn_cast<ArraySectionExpr>(E);
24423
24424 // If this is an array subscript, it refers to the whole size if the size of
24425 // the dimension is constant and equals 1. Also, an array section assumes the
24426 // format of an array subscript if no colon is used.
24427 if (isa<ArraySubscriptExpr>(E) ||
24428 (OASE && OASE->getColonLocFirst().isInvalid())) {
24429 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
24430 return ATy->getSExtSize() != 1;
24431 // Size can't be evaluated statically.
24432 return false;
24433 }
24434
24435 assert(OASE && "Expecting array section if not an array subscript.");
24436 const Expr *LowerBound = OASE->getLowerBound();
24437 const Expr *Length = OASE->getLength();
24438
24439 // If there is a lower bound that does not evaluates to zero, we are not
24440 // covering the whole dimension.
24441 if (LowerBound) {
24443 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
24444 return false; // Can't get the integer value as a constant.
24445
24446 llvm::APSInt ConstLowerBound = Result.Val.getInt();
24447 if (ConstLowerBound.getSExtValue())
24448 return true;
24449 }
24450
24451 // If we don't have a length we covering the whole dimension.
24452 if (!Length)
24453 return false;
24454
24455 // If the base is a pointer, we don't have a way to get the size of the
24456 // pointee.
24457 if (BaseQTy->isPointerType())
24458 return false;
24459
24460 // We can only check if the length is the same as the size of the dimension
24461 // if we have a constant array.
24462 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
24463 if (!CATy)
24464 return false;
24465
24467 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
24468 return false; // Can't get the integer value as a constant.
24469
24470 llvm::APSInt ConstLength = Result.Val.getInt();
24471 return CATy->getSExtSize() != ConstLength.getSExtValue();
24472}
24473
24474// Return true if it can be proven that the provided array expression (array
24475// section or array subscript) does NOT specify a single element of the array
24476// whose base type is \a BaseQTy.
24478 const Expr *E,
24479 QualType BaseQTy) {
24480 const auto *OASE = dyn_cast<ArraySectionExpr>(E);
24481
24482 // An array subscript always refer to a single element. Also, an array section
24483 // assumes the format of an array subscript if no colon is used.
24484 if (isa<ArraySubscriptExpr>(E) ||
24485 (OASE && OASE->getColonLocFirst().isInvalid()))
24486 return false;
24487
24488 assert(OASE && "Expecting array section if not an array subscript.");
24489 const Expr *Length = OASE->getLength();
24490
24491 // If we don't have a length we have to check if the array has unitary size
24492 // for this dimension. Also, we should always expect a length if the base type
24493 // is pointer.
24494 if (!Length) {
24495 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
24496 return ATy->getSExtSize() != 1;
24497 // We cannot assume anything.
24498 return false;
24499 }
24500
24501 // Check if the length evaluates to 1.
24503 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
24504 return false; // Can't get the integer value as a constant.
24505
24506 llvm::APSInt ConstLength = Result.Val.getInt();
24507 return ConstLength.getSExtValue() != 1;
24508}
24509
24510// The base of elements of list in a map clause have to be either:
24511// - a reference to variable or field.
24512// - a member expression.
24513// - an array expression.
24514//
24515// E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
24516// reference to 'r'.
24517//
24518// If we have:
24519//
24520// struct SS {
24521// Bla S;
24522// foo() {
24523// #pragma omp target map (S.Arr[:12]);
24524// }
24525// }
24526//
24527// We want to retrieve the member expression 'this->S';
24528
24529// OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
24530// If a list item is an array section, it must specify contiguous storage.
24531//
24532// For this restriction it is sufficient that we make sure only references
24533// to variables or fields and array expressions, and that no array sections
24534// exist except in the rightmost expression (unless they cover the whole
24535// dimension of the array). E.g. these would be invalid:
24536//
24537// r.ArrS[3:5].Arr[6:7]
24538//
24539// r.ArrS[3:5].x
24540//
24541// but these would be valid:
24542// r.ArrS[3].Arr[6:7]
24543//
24544// r.ArrS[3].x
24545namespace {
24546class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
24547 Sema &SemaRef;
24548 OpenMPClauseKind CKind = OMPC_unknown;
24549 OpenMPDirectiveKind DKind = OMPD_unknown;
24551 bool IsNonContiguous = false;
24552 bool NoDiagnose = false;
24553 const Expr *RelevantExpr = nullptr;
24554 bool AllowUnitySizeArraySection = true;
24555 bool AllowWholeSizeArraySection = true;
24556 bool AllowAnotherPtr = true;
24557 SourceLocation ELoc;
24558 SourceRange ERange;
24559
24560 void emitErrorMsg() {
24561 // If nothing else worked, this is not a valid map clause expression.
24562 if (SemaRef.getLangOpts().OpenMP < 50) {
24563 SemaRef.Diag(ELoc,
24564 diag::err_omp_expected_named_var_member_or_array_expression)
24565 << ERange;
24566 } else {
24567 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
24568 << getOpenMPClauseNameForDiag(CKind) << ERange;
24569 }
24570 }
24571
24572public:
24573 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
24574 ValueDecl *D = DRE->getDecl();
24575 Expr *E = DRE;
24576
24577 // Handle BindingDecls by mapping them as member accesses.
24578 // When the user writes:
24579 // auto [a, b] = p;
24580 // #pragma omp target map(tofrom:a) map(to:b)
24581 // we transform it to:
24582 // #pragma omp target map(tofrom:p.x) map(to:p.y)
24583 // This avoids conflicts when different bindings have different map types.
24584 if (auto *BD = dyn_cast<BindingDecl>(D)) {
24586 Expr *BindingExpr = BD->getBinding();
24587
24588 // Check if the binding is a member expression (struct/class
24589 // decomposition).
24590 if (auto *ME = dyn_cast_or_null<MemberExpr>(BindingExpr)) {
24591
24592 // Use the DecompositionDecl as the base for the member expression.
24593 // The structured binding creates a copy (if initialized from a
24594 // variable) or holds the only storage (if initialized from a prvalue).
24595 // Using DD ensures map clauses reference the correct storage.
24596 Expr *BaseExpr =
24597 SemaRef
24598 .BuildDeclarationNameExpr(
24599 CXXScopeSpec(),
24600 DeclarationNameInfo(DD->getDeclName(), DRE->getLocation()),
24601 DD)
24602 .get();
24603
24604 // Create member expression: base.member.
24606 SemaRef.Context, BaseExpr, /*IsArrow=*/false, ME->getOperatorLoc(),
24607 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
24608 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
24609 /*TemplateArgs=*/nullptr, ME->getType(), ME->getValueKind(),
24610 ME->getObjectKind(), ME->isNonOdrUse());
24611
24612 // Now process this as a member expression, which will properly
24613 // handle the field-level mapping.
24614 return Visit(E);
24615 }
24616 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(BindingExpr)) {
24617 Expr *BaseExpr =
24618 SemaRef
24619 .BuildDeclarationNameExpr(
24620 CXXScopeSpec(),
24621 DeclarationNameInfo(DD->getDeclName(), DRE->getLocation()),
24622 DD)
24623 .get();
24624 E = new (SemaRef.Context) ArraySubscriptExpr(
24625 BaseExpr, ASE->getIdx(), ASE->getType(), ASE->getValueKind(),
24626 ASE->getObjectKind(), ASE->getRBracketLoc());
24627 return Visit(E);
24628 }
24629 // Tuple-like should already be rejected; do not map DD as a silent
24630 // fallback.
24631 SemaRef.Diag(DRE->getExprLoc(),
24632 diag::err_omp_unsupported_structured_binding_init)
24633 << 4;
24634 return false;
24635 }
24636 // Handle DecompositionDecl directly (implicit captures).
24637 else if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
24638 if (const VarDecl *OrigVar =
24639 getOriginalVarOrDiagnose(SemaRef, DD, DRE->getExprLoc())) {
24640 D = const_cast<VarDecl *>(OrigVar);
24641 DeclarationNameInfo NameInfo(D->getDeclName(), DRE->getLocation());
24642 E = DeclRefExpr::Create(SemaRef.Context, DRE->getQualifierLoc(),
24643 DRE->getTemplateKeywordLoc(), D,
24644 /*RefersToEnclosingVariableOrCapture=*/false,
24645 NameInfo, D->getType(), DRE->getValueKind(),
24646 DRE->getFoundDecl(),
24647 /*TemplateArgs=*/nullptr, DRE->isNonOdrUse());
24648 } else {
24649 return false;
24650 }
24651 } else if (!isa<VarDecl>(D)) {
24652 emitErrorMsg();
24653 return false;
24654 }
24655 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
24656 RelevantExpr = E;
24657 // Record the component.
24658 Components.emplace_back(E, D, IsNonContiguous);
24659 return true;
24660 }
24661
24662 bool VisitMemberExpr(MemberExpr *ME) {
24663 Expr *E = ME;
24664 Expr *BaseE = ME->getBase()->IgnoreParenCasts();
24665
24666 if (isa<CXXThisExpr>(BaseE)) {
24667 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
24668 // We found a base expression: this->Val.
24669 RelevantExpr = ME;
24670 } else {
24671 E = BaseE;
24672 }
24673
24674 if (!isa<FieldDecl>(ME->getMemberDecl())) {
24675 if (!NoDiagnose) {
24676 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
24677 << ME->getSourceRange();
24678 return false;
24679 }
24680 if (RelevantExpr)
24681 return false;
24682 return Visit(E);
24683 }
24684
24685 auto *FD = cast<FieldDecl>(ME->getMemberDecl());
24686
24687 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
24688 // A bit-field cannot appear in a map clause.
24689 //
24690 if (FD->isBitField()) {
24691 if (!NoDiagnose) {
24692 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
24693 << ME->getSourceRange() << getOpenMPClauseNameForDiag(CKind);
24694 return false;
24695 }
24696 if (RelevantExpr)
24697 return false;
24698 return Visit(E);
24699 }
24700
24701 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
24702 // If the type of a list item is a reference to a type T then the type
24703 // will be considered to be T for all purposes of this clause.
24704 QualType CurType = BaseE->getType().getNonReferenceType();
24705
24706 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
24707 // A list item cannot be a variable that is a member of a structure with
24708 // a union type.
24709 //
24710 if (CurType->isUnionType()) {
24711 if (!NoDiagnose) {
24712 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
24713 << ME->getSourceRange();
24714 return false;
24715 }
24716 return RelevantExpr || Visit(E);
24717 }
24718
24719 // If we got a member expression, we should not expect any array section
24720 // before that:
24721 //
24722 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
24723 // If a list item is an element of a structure, only the rightmost symbol
24724 // of the variable reference can be an array section.
24725 //
24726 AllowUnitySizeArraySection = false;
24727 AllowWholeSizeArraySection = false;
24728
24729 // Record the component.
24730 Components.emplace_back(ME, FD, IsNonContiguous);
24731 return RelevantExpr || Visit(E);
24732 }
24733
24734 bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
24735 Expr *E = AE->getBase()->IgnoreParenImpCasts();
24736
24737 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
24738 if (!NoDiagnose) {
24739 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
24740 << 0 << AE->getSourceRange();
24741 return false;
24742 }
24743 return RelevantExpr || Visit(E);
24744 }
24745
24746 // If we got an array subscript that express the whole dimension we
24747 // can have any array expressions before. If it only expressing part of
24748 // the dimension, we can only have unitary-size array expressions.
24750 AllowWholeSizeArraySection = false;
24751
24752 if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
24753 Expr::EvalResult Result;
24754 if (!AE->getIdx()->isValueDependent() &&
24755 AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
24756 !Result.Val.getInt().isZero()) {
24757 SemaRef.Diag(AE->getIdx()->getExprLoc(),
24758 diag::err_omp_invalid_map_this_expr);
24759 SemaRef.Diag(AE->getIdx()->getExprLoc(),
24760 diag::note_omp_invalid_subscript_on_this_ptr_map);
24761 }
24762 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
24763 RelevantExpr = TE;
24764 }
24765
24766 // Record the component - we don't have any declaration associated.
24767 Components.emplace_back(AE, nullptr, IsNonContiguous);
24768
24769 return RelevantExpr || Visit(E);
24770 }
24771
24772 bool VisitArraySectionExpr(ArraySectionExpr *OASE) {
24773 // After OMP 5.0 Array section in reduction clause will be implicitly
24774 // mapped
24775 assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) &&
24776 "Array sections cannot be implicitly mapped.");
24777 Expr *E = OASE->getBase()->IgnoreParenImpCasts();
24778 QualType CurType =
24780
24781 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
24782 // If the type of a list item is a reference to a type T then the type
24783 // will be considered to be T for all purposes of this clause.
24784 if (CurType->isReferenceType())
24785 CurType = CurType->getPointeeType();
24786
24787 bool IsPointer = CurType->isAnyPointerType();
24788
24789 if (!IsPointer && !CurType->isArrayType()) {
24790 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
24791 << 0 << OASE->getSourceRange();
24792 return false;
24793 }
24794
24795 bool NotWhole =
24796 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
24797 bool NotUnity =
24798 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
24799
24800 if (AllowWholeSizeArraySection) {
24801 // Any array section is currently allowed. Allowing a whole size array
24802 // section implies allowing a unity array section as well.
24803 //
24804 // If this array section refers to the whole dimension we can still
24805 // accept other array sections before this one, except if the base is a
24806 // pointer. Otherwise, only unitary sections are accepted.
24807 if (NotWhole || IsPointer)
24808 AllowWholeSizeArraySection = false;
24809 } else if (DKind == OMPD_target_update &&
24810 SemaRef.getLangOpts().OpenMP >= 50) {
24811 if (IsPointer && !AllowAnotherPtr)
24812 SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
24813 << /*array of unknown bound */ 1;
24814 else
24815 IsNonContiguous = true;
24816 } else if (AllowUnitySizeArraySection && NotUnity) {
24817 // A unity or whole array section is not allowed and that is not
24818 // compatible with the properties of the current array section.
24819 if (NoDiagnose)
24820 return false;
24821 SemaRef.Diag(ELoc,
24822 diag::err_array_section_does_not_specify_contiguous_storage)
24823 << OASE->getSourceRange();
24824 return false;
24825 }
24826
24827 if (IsPointer)
24828 AllowAnotherPtr = false;
24829
24830 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
24831 Expr::EvalResult ResultR;
24832 Expr::EvalResult ResultL;
24833 if (!OASE->getLength()->isValueDependent() &&
24834 OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
24835 !ResultR.Val.getInt().isOne()) {
24836 SemaRef.Diag(OASE->getLength()->getExprLoc(),
24837 diag::err_omp_invalid_map_this_expr);
24838 SemaRef.Diag(OASE->getLength()->getExprLoc(),
24839 diag::note_omp_invalid_length_on_this_ptr_mapping);
24840 }
24841 if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
24842 OASE->getLowerBound()->EvaluateAsInt(ResultL,
24843 SemaRef.getASTContext()) &&
24844 !ResultL.Val.getInt().isZero()) {
24845 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
24846 diag::err_omp_invalid_map_this_expr);
24847 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
24848 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
24849 }
24850 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
24851 RelevantExpr = TE;
24852 }
24853
24854 // Record the component - we don't have any declaration associated.
24855 Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
24856 return RelevantExpr || Visit(E);
24857 }
24858 bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
24859 Expr *Base = E->getBase();
24860
24861 // Record the component - we don't have any declaration associated.
24862 Components.emplace_back(E, nullptr, IsNonContiguous);
24863
24864 return Visit(Base->IgnoreParenImpCasts());
24865 }
24866
24867 bool VisitUnaryOperator(UnaryOperator *UO) {
24868 if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
24869 UO->getOpcode() != UO_Deref) {
24870 emitErrorMsg();
24871 return false;
24872 }
24873 if (!RelevantExpr) {
24874 // Record the component if haven't found base decl.
24875 Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
24876 }
24877 return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
24878 }
24879 bool VisitBinaryOperator(BinaryOperator *BO) {
24880 // Since OpenMP 5.0 only pointer arithmetic (pointer +/- integer offset)
24881 // may lead to the base, which is in the pointer operand.
24882 Expr *PtrE = nullptr;
24883 if (SemaRef.getLangOpts().OpenMP >= 50 && BO->isAdditiveOp() &&
24884 BO->getType()->isPointerType()) {
24885 Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
24886 Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
24887 if (LE->getType()->isPointerType())
24888 PtrE = LE;
24889 else if (BO->getOpcode() == BO_Add && RE->getType()->isPointerType())
24890 PtrE = RE;
24891 }
24892 if (!PtrE) {
24893 emitErrorMsg();
24894 return false;
24895 }
24896 Components.emplace_back(BO, nullptr, /*IsNonContiguous=*/false);
24897 return RelevantExpr || Visit(PtrE);
24898 }
24899 bool VisitCXXThisExpr(CXXThisExpr *CTE) {
24900 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
24901 RelevantExpr = CTE;
24902 Components.emplace_back(CTE, nullptr, IsNonContiguous);
24903 return true;
24904 }
24905 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
24906 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
24907 Components.emplace_back(COCE, nullptr, IsNonContiguous);
24908 return true;
24909 }
24910 bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
24911 Expr *Source = E->getSourceExpr();
24912 if (!Source) {
24913 emitErrorMsg();
24914 return false;
24915 }
24916 return Visit(Source);
24917 }
24918 bool VisitStmt(Stmt *) {
24919 emitErrorMsg();
24920 return false;
24921 }
24922 const Expr *getFoundBase() const { return RelevantExpr; }
24923 explicit MapBaseChecker(
24924 Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
24926 bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
24927 : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
24928 NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
24929};
24930} // namespace
24931
24932/// Return the expression of the base of the mappable expression or null if it
24933/// cannot be determined and do all the necessary checks to see if the
24934/// expression is valid as a standalone mappable expression. In the process,
24935/// record all the components of the expression.
24937 Sema &SemaRef, Expr *E,
24939 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
24940 SourceLocation ELoc = E->getExprLoc();
24941 SourceRange ERange = E->getSourceRange();
24942 MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
24943 ERange);
24944 if (Checker.Visit(E->IgnoreParens())) {
24945 // Check if the highest dimension array section has length specified
24946 if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
24947 (CKind == OMPC_to || CKind == OMPC_from)) {
24948 auto CI = CurComponents.rbegin();
24949 auto CE = CurComponents.rend();
24950 for (; CI != CE; ++CI) {
24951 const auto *OASE =
24952 dyn_cast<ArraySectionExpr>(CI->getAssociatedExpression());
24953 if (!OASE)
24954 continue;
24955 if (OASE && OASE->getLength())
24956 break;
24957 SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
24958 << ERange;
24959 }
24960 }
24961 return Checker.getFoundBase();
24962 }
24963 return nullptr;
24964}
24965
24966// Return true if expression E associated with value VD has conflicts with other
24967// map information.
24969 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
24970 bool CurrentRegionOnly,
24972 OpenMPClauseKind CKind) {
24973 assert(VD && E);
24974 SourceLocation ELoc = E->getExprLoc();
24975 SourceRange ERange = E->getSourceRange();
24976
24977 // In order to easily check the conflicts we need to match each component of
24978 // the expression under test with the components of the expressions that are
24979 // already in the stack.
24980
24981 assert(!CurComponents.empty() && "Map clause expression with no components!");
24982 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
24983 "Map clause expression with unexpected base!");
24984
24985 // Variables to help detecting enclosing problems in data environment nests.
24986 bool IsEnclosedByDataEnvironmentExpr = false;
24987 const Expr *EnclosingExpr = nullptr;
24988
24989 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
24990 VD, CurrentRegionOnly,
24991 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
24992 ERange, CKind, &EnclosingExpr,
24994 StackComponents,
24995 OpenMPClauseKind Kind) {
24996 if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
24997 return false;
24998 assert(!StackComponents.empty() &&
24999 "Map clause expression with no components!");
25000 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
25001 "Map clause expression with unexpected base!");
25002 (void)VD;
25003
25004 // The whole expression in the stack.
25005 const Expr *RE = StackComponents.front().getAssociatedExpression();
25006
25007 // Expressions must start from the same base. Here we detect at which
25008 // point both expressions diverge from each other and see if we can
25009 // detect if the memory referred to both expressions is contiguous and
25010 // do not overlap.
25011 auto CI = CurComponents.rbegin();
25012 auto CE = CurComponents.rend();
25013 auto SI = StackComponents.rbegin();
25014 auto SE = StackComponents.rend();
25015 for (; CI != CE && SI != SE; ++CI, ++SI) {
25016
25017 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
25018 // At most one list item can be an array item derived from a given
25019 // variable in map clauses of the same construct.
25020 if (CurrentRegionOnly &&
25021 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
25022 isa<ArraySectionExpr>(CI->getAssociatedExpression()) ||
25023 isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
25024 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
25025 isa<ArraySectionExpr>(SI->getAssociatedExpression()) ||
25026 isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
25027 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
25028 diag::err_omp_multiple_array_items_in_map_clause)
25029 << CI->getAssociatedExpression()->getSourceRange();
25030 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
25031 diag::note_used_here)
25032 << SI->getAssociatedExpression()->getSourceRange();
25033 return true;
25034 }
25035
25036 // Do both expressions have the same kind?
25037 if (CI->getAssociatedExpression()->getStmtClass() !=
25038 SI->getAssociatedExpression()->getStmtClass())
25039 break;
25040
25041 // Are we dealing with different variables/fields?
25042 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
25043 break;
25044 }
25045 // Check if the extra components of the expressions in the enclosing
25046 // data environment are redundant for the current base declaration.
25047 // If they are, the maps completely overlap, which is legal.
25048 for (; SI != SE; ++SI) {
25049 QualType Type;
25050 if (const auto *ASE =
25051 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
25052 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
25053 } else if (const auto *OASE = dyn_cast<ArraySectionExpr>(
25054 SI->getAssociatedExpression())) {
25055 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
25057 } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
25058 SI->getAssociatedExpression())) {
25059 Type = OASE->getBase()->getType()->getPointeeType();
25060 }
25061 if (Type.isNull() || Type->isAnyPointerType() ||
25063 SemaRef, SI->getAssociatedExpression(), Type))
25064 break;
25065 }
25066
25067 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
25068 // List items of map clauses in the same construct must not share
25069 // original storage.
25070 //
25071 // If the expressions are exactly the same or one is a subset of the
25072 // other, it means they are sharing storage.
25073 if (CI == CE && SI == SE) {
25074 if (CurrentRegionOnly) {
25075 if (CKind == OMPC_map) {
25076 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
25077 } else {
25078 assert(CKind == OMPC_to || CKind == OMPC_from);
25079 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
25080 << ERange;
25081 }
25082 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
25083 << RE->getSourceRange();
25084 return true;
25085 }
25086 // If we find the same expression in the enclosing data environment,
25087 // that is legal.
25088 IsEnclosedByDataEnvironmentExpr = true;
25089 return false;
25090 }
25091
25092 QualType DerivedType =
25093 std::prev(CI)->getAssociatedDeclaration()->getType();
25094 SourceLocation DerivedLoc =
25095 std::prev(CI)->getAssociatedExpression()->getExprLoc();
25096
25097 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
25098 // If the type of a list item is a reference to a type T then the type
25099 // will be considered to be T for all purposes of this clause.
25100 DerivedType = DerivedType.getNonReferenceType();
25101
25102 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
25103 // A variable for which the type is pointer and an array section
25104 // derived from that variable must not appear as list items of map
25105 // clauses of the same construct.
25106 //
25107 // Also, cover one of the cases in:
25108 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
25109 // If any part of the original storage of a list item has corresponding
25110 // storage in the device data environment, all of the original storage
25111 // must have corresponding storage in the device data environment.
25112 //
25113 if (DerivedType->isAnyPointerType()) {
25114 if (CI == CE || SI == SE) {
25115 SemaRef.Diag(
25116 DerivedLoc,
25117 diag::err_omp_pointer_mapped_along_with_derived_section)
25118 << DerivedLoc;
25119 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
25120 << RE->getSourceRange();
25121 return true;
25122 }
25123 if (CI->getAssociatedExpression()->getStmtClass() !=
25124 SI->getAssociatedExpression()->getStmtClass() ||
25125 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
25126 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
25127 assert(CI != CE && SI != SE);
25128 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
25129 << DerivedLoc;
25130 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
25131 << RE->getSourceRange();
25132 return true;
25133 }
25134 }
25135
25136 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
25137 // List items of map clauses in the same construct must not share
25138 // original storage.
25139 //
25140 // An expression is a subset of the other.
25141 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
25142 if (CKind == OMPC_map) {
25143 if (CI != CE || SI != SE) {
25144 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
25145 // a pointer.
25146 auto Begin =
25147 CI != CE ? CurComponents.begin() : StackComponents.begin();
25148 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
25149 auto It = Begin;
25150 while (It != End && !It->getAssociatedDeclaration())
25151 std::advance(It, 1);
25152 assert(It != End &&
25153 "Expected at least one component with the declaration.");
25154 if (It != Begin && It->getAssociatedDeclaration()
25155 ->getType()
25156 .getCanonicalType()
25157 ->isAnyPointerType()) {
25158 IsEnclosedByDataEnvironmentExpr = false;
25159 EnclosingExpr = nullptr;
25160 return false;
25161 }
25162 }
25163 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
25164 } else {
25165 assert(CKind == OMPC_to || CKind == OMPC_from);
25166 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
25167 << ERange;
25168 }
25169 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
25170 << RE->getSourceRange();
25171 return true;
25172 }
25173
25174 // The current expression uses the same base as other expression in the
25175 // data environment but does not contain it completely.
25176 if (!CurrentRegionOnly && SI != SE)
25177 EnclosingExpr = RE;
25178
25179 // The current expression is a subset of the expression in the data
25180 // environment.
25181 IsEnclosedByDataEnvironmentExpr |=
25182 (!CurrentRegionOnly && CI != CE && SI == SE);
25183
25184 return false;
25185 });
25186
25187 if (CurrentRegionOnly)
25188 return FoundError;
25189
25190 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
25191 // If any part of the original storage of a list item has corresponding
25192 // storage in the device data environment, all of the original storage must
25193 // have corresponding storage in the device data environment.
25194 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
25195 // If a list item is an element of a structure, and a different element of
25196 // the structure has a corresponding list item in the device data environment
25197 // prior to a task encountering the construct associated with the map clause,
25198 // then the list item must also have a corresponding list item in the device
25199 // data environment prior to the task encountering the construct.
25200 //
25201 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
25202 SemaRef.Diag(ELoc,
25203 diag::err_omp_original_storage_is_shared_and_does_not_contain)
25204 << ERange;
25205 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
25206 << EnclosingExpr->getSourceRange();
25207 return true;
25208 }
25209
25210 return FoundError;
25211}
25212
25213// Look up the user-defined mapper given the mapper name and mapped type, and
25214// build a reference to it. \a ItemLoc is the location of the mapped list item;
25215// it is used as the point of instantiation since \a MapperId has no location
25216// for implicit map clauses.
25218 CXXScopeSpec &MapperIdScopeSpec,
25219 const DeclarationNameInfo &MapperId,
25220 QualType Type,
25221 Expr *UnresolvedMapper,
25222 SourceLocation ItemLoc) {
25223 if (MapperIdScopeSpec.isInvalid())
25224 return ExprError();
25225 // Get the actual type for the array type.
25226 if (Type->isArrayType()) {
25227 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
25229 }
25230 // Find all user-defined mappers with the given MapperId.
25231 SmallVector<UnresolvedSet<8>, 4> Lookups;
25232 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
25233 Lookup.suppressDiagnostics();
25234 if (S) {
25235 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec,
25236 /*ObjectType=*/QualType())) {
25237 NamedDecl *D = Lookup.getRepresentativeDecl();
25238 while (S && !S->isDeclScope(D))
25239 S = S->getParent();
25240 if (S)
25241 S = S->getParent();
25242 Lookups.emplace_back();
25243 Lookups.back().append(Lookup.begin(), Lookup.end());
25244 Lookup.clear();
25245 }
25246 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
25247 // Extract the user-defined mappers with the given MapperId.
25248 Lookups.push_back(UnresolvedSet<8>());
25249 for (NamedDecl *D : ULE->decls()) {
25250 auto *DMD = cast<OMPDeclareMapperDecl>(D);
25251 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
25252 Lookups.back().addDecl(DMD);
25253 }
25254 }
25255 // Defer the lookup for dependent types. The results will be passed through
25256 // UnresolvedMapper on instantiation.
25257 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
25261 return !D->isInvalidDecl() &&
25262 (D->getType()->isDependentType() ||
25263 D->getType()->isInstantiationDependentType() ||
25264 D->getType()->containsUnexpandedParameterPack());
25265 })) {
25266 UnresolvedSet<8> URS;
25267 for (const UnresolvedSet<8> &Set : Lookups) {
25268 if (Set.empty())
25269 continue;
25270 URS.append(Set.begin(), Set.end());
25271 }
25273 SemaRef.Context, /*NamingClass=*/nullptr,
25274 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
25275 /*ADL=*/false, URS.begin(), URS.end(), /*KnownDependent=*/false,
25276 /*KnownInstantiationDependent=*/false);
25277 }
25278 SourceLocation Loc = MapperId.getLoc();
25279 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
25280 // The type must be of struct, union or class type in C and C++
25282 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
25283 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
25284 return ExprError();
25285 }
25286 // Perform argument dependent lookup.
25287 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
25288 argumentDependentLookup(SemaRef, MapperId, ItemLoc, Type, Lookups);
25289 // Return the first user-defined mapper with the desired type.
25291 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
25292 if (!D->isInvalidDecl() &&
25293 SemaRef.Context.hasSameType(D->getType(), Type))
25294 return D;
25295 return nullptr;
25296 }))
25297 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
25298 // Find the first user-defined mapper with a type derived from the desired
25299 // type.
25301 Lookups, [&SemaRef, Type, ItemLoc](ValueDecl *D) -> ValueDecl * {
25302 if (!D->isInvalidDecl() &&
25303 SemaRef.IsDerivedFrom(ItemLoc, Type, D->getType()) &&
25304 !Type.isMoreQualifiedThan(D->getType(),
25305 SemaRef.getASTContext()))
25306 return D;
25307 return nullptr;
25308 })) {
25309 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
25310 /*DetectVirtual=*/false);
25311 if (SemaRef.IsDerivedFrom(ItemLoc, Type, VD->getType(), Paths)) {
25312 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
25313 VD->getType().getUnqualifiedType()))) {
25314 if (SemaRef.CheckBaseClassAccess(
25315 ItemLoc, VD->getType(), Type, Paths.front(),
25316 /*DiagID=*/0) != Sema::AR_inaccessible) {
25317 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
25318 }
25319 }
25320 }
25321 }
25322 // Report error if a mapper is specified, but cannot be found.
25323 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
25324 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
25325 << Type << MapperId.getName();
25326 return ExprError();
25327 }
25328 return ExprEmpty();
25329}
25330
25331namespace {
25332// Utility struct that gathers all the related lists associated with a mappable
25333// expression.
25334struct MappableVarListInfo {
25335 // The list of expressions.
25336 ArrayRef<Expr *> VarList;
25337 // The list of processed expressions.
25338 SmallVector<Expr *, 16> ProcessedVarList;
25339 // The mappble components for each expression.
25341 // The base declaration of the variable.
25342 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
25343 // The reference to the user-defined mapper associated with every expression.
25344 SmallVector<Expr *, 16> UDMapperList;
25345
25346 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
25347 // We have a list of components and base declarations for each entry in the
25348 // variable list.
25349 VarComponents.reserve(VarList.size());
25350 VarBaseDeclarations.reserve(VarList.size());
25351 }
25352};
25353} // namespace
25354
25356 DSAStackTy *Stack,
25358
25359 const RecordDecl *RD = BaseType->getAsRecordDecl();
25360 SourceRange Range = RD->getSourceRange();
25361 DeclarationNameInfo ImplicitName;
25362 // Dummy variable _s for Mapper.
25363 VarDecl *VD = buildVarDecl(S, Range.getEnd(), BaseType, "_s");
25364 DeclRefExpr *MapperVarRef =
25365 buildDeclRefExpr(S, VD, BaseType, SourceLocation());
25366
25367 // Create implicit map clause for mapper.
25369 for (auto *FD : RD->fields()) {
25370 Expr *BE = S.BuildMemberExpr(
25371 MapperVarRef, /*IsArrow=*/false, Range.getBegin(),
25372 NestedNameSpecifierLoc(), Range.getBegin(), FD,
25374 /*HadMultipleCandidates=*/false,
25376 FD->getType(), VK_LValue, OK_Ordinary);
25377 SExprs.push_back(BE);
25378 }
25379 CXXScopeSpec MapperIdScopeSpec;
25380 DeclarationNameInfo MapperId;
25381 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
25382
25383 OMPClause *MapClause = S.OpenMP().ActOnOpenMPMapClause(
25384 nullptr, OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec,
25385 MapperId, DKind == OMPD_target_enter_data ? OMPC_MAP_to : OMPC_MAP_tofrom,
25386 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), SExprs,
25387 OMPVarListLocTy());
25388 Maps.push_back(MapClause);
25389 return MapperVarRef;
25390}
25391
25393 DSAStackTy *Stack) {
25394
25395 // Build impilicit map for mapper
25397 DeclRefExpr *MapperVarRef = buildImplicitMap(S, BaseType, Stack, Maps);
25398
25399 const RecordDecl *RD = BaseType->getAsRecordDecl();
25400 // AST context is RD's ParentASTContext().
25401 ASTContext &Ctx = RD->getParentASTContext();
25402 // DeclContext is RD's DeclContext.
25403 DeclContext *DCT = const_cast<DeclContext *>(RD->getDeclContext());
25404
25405 // Create implicit default mapper for "RD".
25406 DeclarationName MapperId;
25407 auto &DeclNames = Ctx.DeclarationNames;
25408 MapperId = DeclNames.getIdentifier(&Ctx.Idents.get("default"));
25409 auto *DMD = OMPDeclareMapperDecl::Create(Ctx, DCT, SourceLocation(), MapperId,
25410 BaseType, MapperId, Maps, nullptr);
25411 Scope *Scope = S.getScopeForContext(DCT);
25412 if (Scope)
25413 S.PushOnScopeChains(DMD, Scope, /*AddToContext=*/false);
25414 DCT->addDecl(DMD);
25415 DMD->setAccess(clang::AS_none);
25416 auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
25417 VD->setDeclContext(DMD);
25418 VD->setLexicalDeclContext(DMD);
25419 DMD->addDecl(VD);
25420 DMD->setMapperVarRef(MapperVarRef);
25421 FieldDecl *FD = *RD->field_begin();
25422 // create mapper refence.
25424 DMD, false, SourceLocation(), BaseType, VK_LValue);
25425}
25426
25427// Look up the user-defined mapper given the mapper name and mapper type,
25428// return true if found one.
25429static bool hasUserDefinedMapper(Sema &SemaRef, Scope *S,
25430 CXXScopeSpec &MapperIdScopeSpec,
25431 const DeclarationNameInfo &MapperId,
25432 QualType Type) {
25433 // Find all user-defined mappers with the given MapperId.
25434 SmallVector<UnresolvedSet<8>, 4> Lookups;
25435 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
25436 Lookup.suppressDiagnostics();
25437 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec,
25438 /*ObjectType=*/QualType())) {
25439 NamedDecl *D = Lookup.getRepresentativeDecl();
25440 while (S && !S->isDeclScope(D))
25441 S = S->getParent();
25442 if (S)
25443 S = S->getParent();
25444 Lookups.emplace_back();
25445 Lookups.back().append(Lookup.begin(), Lookup.end());
25446 Lookup.clear();
25447 }
25448 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
25452 return !D->isInvalidDecl() &&
25453 (D->getType()->isDependentType() ||
25454 D->getType()->isInstantiationDependentType() ||
25455 D->getType()->containsUnexpandedParameterPack());
25456 }))
25457 return false;
25458 // Perform argument dependent lookup.
25459 SourceLocation Loc = MapperId.getLoc();
25460 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
25461 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
25463 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
25464 if (!D->isInvalidDecl() &&
25465 SemaRef.Context.hasSameType(D->getType(), Type))
25466 return D;
25467 return nullptr;
25468 }))
25469 return true;
25470 // Find the first user-defined mapper with a type derived from the desired
25471 // type.
25473 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
25474 if (!D->isInvalidDecl() &&
25475 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
25476 !Type.isMoreQualifiedThan(D->getType(), SemaRef.getASTContext()))
25477 return D;
25478 return nullptr;
25479 });
25480 if (!VD)
25481 return false;
25482 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
25483 /*DetectVirtual=*/false);
25484 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
25485 bool IsAmbiguous = !Paths.isAmbiguous(
25487 if (IsAmbiguous)
25488 return false;
25489 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Type, Paths.front(),
25490 /*DiagID=*/0) != Sema::AR_inaccessible)
25491 return true;
25492 }
25493 return false;
25494}
25495
25496static bool isImplicitMapperNeeded(Sema &S, DSAStackTy *Stack,
25497 QualType CanonType, const Expr *E) {
25498
25499 // DFS over data members in structures/classes.
25501 {CanonType, nullptr});
25502 llvm::DenseMap<const Type *, bool> Visited;
25503 SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(1, {nullptr, 1});
25504 while (!Types.empty()) {
25505 auto [BaseType, CurFD] = Types.pop_back_val();
25506 while (ParentChain.back().second == 0)
25507 ParentChain.pop_back();
25508 --ParentChain.back().second;
25509 if (BaseType.isNull())
25510 continue;
25511 // Only structs/classes are allowed to have mappers.
25512 const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
25513 if (!RD)
25514 continue;
25515 auto It = Visited.find(BaseType.getTypePtr());
25516 if (It == Visited.end()) {
25517 // Try to find the associated user-defined mapper.
25518 CXXScopeSpec MapperIdScopeSpec;
25519 DeclarationNameInfo DefaultMapperId;
25521 &S.Context.Idents.get("default")));
25522 DefaultMapperId.setLoc(E->getExprLoc());
25523 bool HasUDMapper =
25524 hasUserDefinedMapper(S, Stack->getCurScope(), MapperIdScopeSpec,
25525 DefaultMapperId, BaseType);
25526 It = Visited.try_emplace(BaseType.getTypePtr(), HasUDMapper).first;
25527 }
25528 // Found default mapper.
25529 if (It->second)
25530 return true;
25531 // Check for the "default" mapper for data members.
25532 bool FirstIter = true;
25533 for (FieldDecl *FD : RD->fields()) {
25534 if (!FD)
25535 continue;
25536 QualType FieldTy = FD->getType();
25537 if (FieldTy.isNull() ||
25538 !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
25539 continue;
25540 if (FirstIter) {
25541 FirstIter = false;
25542 ParentChain.emplace_back(CurFD, 1);
25543 } else {
25544 ++ParentChain.back().second;
25545 }
25546 Types.emplace_back(FieldTy, FD);
25547 }
25548 }
25549 return false;
25550}
25551
25552// Check the validity of the provided variable list for the provided clause kind
25553// \a CKind. In the check process the valid expressions, mappable expression
25554// components, variables, and user-defined mappers are extracted and used to
25555// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
25556// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
25557// and \a MapperId are expected to be valid if the clause kind is 'map'.
25559 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
25560 MappableVarListInfo &MVLI, SourceLocation StartLoc,
25561 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
25562 ArrayRef<Expr *> UnresolvedMappers,
25564 ArrayRef<OpenMPMapModifierKind> Modifiers = {},
25565 bool IsMapTypeImplicit = false, bool NoDiagnose = false) {
25566 // We only expect mappable expressions in 'to', 'from', 'map', and
25567 // 'use_device_addr' clauses.
25568 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from ||
25569 CKind == OMPC_use_device_addr) &&
25570 "Unexpected clause kind with mappable expressions!");
25571 llvm::omp::Version OMPVersion = SemaRef.getLangOpts().getOpenMPVersion();
25572
25573 // If the identifier of user-defined mapper is not specified, it is "default".
25574 // We do not change the actual name in this clause to distinguish whether a
25575 // mapper is specified explicitly, i.e., it is not explicitly specified when
25576 // MapperId.getName() is empty.
25577 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
25578 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
25579 MapperId.setName(DeclNames.getIdentifier(
25580 &SemaRef.getASTContext().Idents.get("default")));
25581 MapperId.setLoc(StartLoc);
25582 }
25583
25584 // Iterators to find the current unresolved mapper expression.
25585 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
25586 bool UpdateUMIt = false;
25587 Expr *UnresolvedMapper = nullptr;
25588
25589 bool HasHoldModifier =
25590 llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold);
25591
25592 // Keep track of the mappable components and base declarations in this clause.
25593 // Each entry in the list is going to have a list of components associated. We
25594 // record each set of the components so that we can build the clause later on.
25595 // In the end we should have the same amount of declarations and component
25596 // lists.
25597
25598 for (Expr *RE : MVLI.VarList) {
25599 assert(RE && "Null expr in omp to/from/map clause");
25600 SourceLocation ELoc = RE->getExprLoc();
25601
25602 // Find the current unresolved mapper expression.
25603 if (UpdateUMIt && UMIt != UMEnd) {
25604 UMIt++;
25605 assert(
25606 UMIt != UMEnd &&
25607 "Expect the size of UnresolvedMappers to match with that of VarList");
25608 }
25609 UpdateUMIt = true;
25610 if (UMIt != UMEnd)
25611 UnresolvedMapper = *UMIt;
25612
25613 const Expr *VE = RE->IgnoreParenLValueCasts();
25614
25615 if (VE->isValueDependent() || VE->isTypeDependent() ||
25616 VE->isInstantiationDependent() ||
25617 VE->containsUnexpandedParameterPack()) {
25618 // Try to find the associated user-defined mapper.
25620 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
25621 VE->getType().getCanonicalType(), UnresolvedMapper, ELoc);
25622 if (ER.isInvalid())
25623 continue;
25624 MVLI.UDMapperList.push_back(ER.get());
25625 // We can only analyze this information once the missing information is
25626 // resolved.
25627 MVLI.ProcessedVarList.push_back(RE);
25628 continue;
25629 }
25630
25632 if (!RE->isLValue()) {
25633 if (SemaRef.getLangOpts().OpenMP < 50) {
25634 SemaRef.Diag(
25635 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
25636 << RE->getSourceRange();
25637 } else {
25638 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
25639 << getOpenMPClauseNameForDiag(CKind) << RE->getSourceRange();
25640 }
25641 continue;
25642 }
25643
25644 // Check for unsupported structured bindings early.
25645 if (!NoDiagnose) {
25646 if (const auto *DRE = dyn_cast<DeclRefExpr>(SimpleExpr)) {
25647 const DecompositionDecl *DD = nullptr;
25648 const BindingDecl *BD = nullptr;
25649 if (const auto *B = dyn_cast<BindingDecl>(DRE->getDecl())) {
25650 BD = B;
25651 DD = cast<DecompositionDecl>(B->getDecomposedDecl());
25652 } else if (const auto *D =
25653 dyn_cast<DecompositionDecl>(DRE->getDecl())) {
25654 DD = D;
25655 }
25656 if (DD) {
25657 if (BD && BD->getHoldingVar()) {
25658 SemaRef.Diag(ELoc,
25659 diag::err_omp_unsupported_structured_binding_init)
25660 << 4;
25661 continue;
25662 }
25663 if (!getOriginalVarOrDiagnose(SemaRef, DD, ELoc))
25664 continue;
25665 }
25666 }
25667 }
25669 ValueDecl *CurDeclaration = nullptr;
25670
25671 // Obtain the array or member expression bases if required. Also, fill the
25672 // components array with all the components identified in the process.
25673 const Expr *BE =
25674 checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind,
25675 DSAS->getCurrentDirective(), NoDiagnose);
25676 if (!BE)
25677 continue;
25678
25679 assert(!CurComponents.empty() &&
25680 "Invalid mappable expression information.");
25681
25682 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
25683 // Add store "this" pointer to class in DSAStackTy for future checking
25684 DSAS->addMappedClassesQualTypes(TE->getType());
25685 // Try to find the associated user-defined mapper.
25687 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
25688 VE->getType().getCanonicalType(), UnresolvedMapper, ELoc);
25689 if (ER.isInvalid())
25690 continue;
25691 MVLI.UDMapperList.push_back(ER.get());
25692 // Skip restriction checking for variable or field declarations
25693 MVLI.ProcessedVarList.push_back(RE);
25694 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
25695 MVLI.VarComponents.back().append(CurComponents.begin(),
25696 CurComponents.end());
25697 MVLI.VarBaseDeclarations.push_back(nullptr);
25698 continue;
25699 }
25700
25701 // For the following checks, we rely on the base declaration which is
25702 // expected to be associated with the last component. The declaration is
25703 // expected to be a variable or a field (if 'this' is being mapped).
25704 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
25705 assert(CurDeclaration && "Null decl on map clause.");
25706 assert(
25707 CurDeclaration->isCanonicalDecl() &&
25708 "Expecting components to have associated only canonical declarations.");
25709
25710 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
25711 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
25712
25713 assert((VD || FD) && "Only variables or fields are expected here!");
25714 (void)FD;
25715
25716 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
25717 // threadprivate variables cannot appear in a map clause.
25718 // OpenMP 4.5 [2.10.5, target update Construct]
25719 // threadprivate variables cannot appear in a from clause.
25720 if (VD && DSAS->isThreadPrivate(VD)) {
25721 if (NoDiagnose)
25722 continue;
25723 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
25724 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
25726 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
25727 continue;
25728 }
25729
25730 // OpenMP 6.0 [7.9.6, map Clause, Restrictions, p. 386]
25731 // A device-local variable must not appear as a list item in a map clause.
25732 if (VD && CKind == OMPC_map) {
25733 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
25734 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
25735 if (*Res == OMPDeclareTargetDeclAttr::MT_Local) {
25736 if (NoDiagnose)
25737 continue;
25738 SemaRef.Diag(ELoc, diag::err_omp_device_local_in_clause)
25739 << VD << getOpenMPClauseNameForDiag(CKind);
25740 continue;
25741 }
25742 }
25743 }
25744
25745 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
25746 // A list item cannot appear in both a map clause and a data-sharing
25747 // attribute clause on the same construct.
25748
25749 // Check conflicts with other map clause expressions. We check the conflicts
25750 // with the current construct separately from the enclosing data
25751 // environment, because the restrictions are different. We only have to
25752 // check conflicts across regions for the map clauses.
25753 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
25754 /*CurrentRegionOnly=*/true, CurComponents, CKind))
25755 break;
25756 if (CKind == OMPC_map &&
25757 (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
25758 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
25759 /*CurrentRegionOnly=*/false, CurComponents, CKind))
25760 break;
25761
25762 // OpenMP 4.5 [2.10.5, target update Construct]
25763 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
25764 // If the type of a list item is a reference to a type T then the type will
25765 // be considered to be T for all purposes of this clause.
25766 auto I = llvm::find_if(
25767 CurComponents,
25768 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
25769 return MC.getAssociatedDeclaration();
25770 });
25771 assert(I != CurComponents.end() && "Null decl on map clause.");
25772 (void)I;
25773 QualType Type;
25774 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
25775 auto *OASE = dyn_cast<ArraySectionExpr>(VE->IgnoreParens());
25776 auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
25777 if (ASE) {
25778 Type = ASE->getType().getNonReferenceType();
25779 } else if (OASE) {
25780 QualType BaseType =
25782 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
25783 Type = ATy->getElementType();
25784 else
25785 Type = BaseType->getPointeeType();
25786 Type = Type.getNonReferenceType();
25787 } else if (OAShE) {
25788 Type = OAShE->getBase()->getType()->getPointeeType();
25789 } else {
25790 Type = VE->getType();
25791 }
25792
25793 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
25794 // A list item in a to or from clause must have a mappable type.
25795 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
25796 // A list item must have a mappable type.
25797 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
25798 DSAS, Type, /*FullCheck=*/true))
25799 continue;
25800
25801 if (CKind == OMPC_map) {
25802 // target enter data
25803 // OpenMP [2.10.2, Restrictions, p. 99]
25804 // A map-type must be specified in all map clauses and must be either
25805 // to or alloc. Starting with OpenMP 5.2 the default map type is `to` if
25806 // no map type is present.
25807 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
25808 if (DKind == OMPD_target_enter_data &&
25809 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc ||
25810 SemaRef.getLangOpts().OpenMP >= 52)) {
25811 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
25812 << (IsMapTypeImplicit ? 1 : 0)
25813 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
25814 << getOpenMPDirectiveName(DKind, OMPVersion);
25815 continue;
25816 }
25817
25818 // target exit_data
25819 // OpenMP [2.10.3, Restrictions, p. 102]
25820 // A map-type must be specified in all map clauses and must be either
25821 // from, release, or delete. Starting with OpenMP 5.2 the default map
25822 // type is `from` if no map type is present.
25823 if (DKind == OMPD_target_exit_data &&
25824 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
25825 MapType == OMPC_MAP_delete || SemaRef.getLangOpts().OpenMP >= 52)) {
25826 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
25827 << (IsMapTypeImplicit ? 1 : 0)
25828 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
25829 << getOpenMPDirectiveName(DKind, OMPVersion);
25830 continue;
25831 }
25832
25833 // The 'ompx_hold' modifier is specifically intended to be used on a
25834 // 'target' or 'target data' directive to prevent data from being unmapped
25835 // during the associated statement. It is not permitted on a 'target
25836 // enter data' or 'target exit data' directive, which have no associated
25837 // statement.
25838 if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) &&
25839 HasHoldModifier) {
25840 SemaRef.Diag(StartLoc,
25841 diag::err_omp_invalid_map_type_modifier_for_directive)
25843 OMPC_MAP_MODIFIER_ompx_hold)
25844 << getOpenMPDirectiveName(DKind, OMPVersion);
25845 continue;
25846 }
25847
25848 // target, target data
25849 // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
25850 // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
25851 // A map-type in a map clause must be to, from, tofrom or alloc
25852 if ((DKind == OMPD_target_data ||
25854 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
25855 MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
25856 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
25857 << (IsMapTypeImplicit ? 1 : 0)
25858 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
25859 << getOpenMPDirectiveName(DKind, OMPVersion);
25860 continue;
25861 }
25862
25863 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
25864 // A list item cannot appear in both a map clause and a data-sharing
25865 // attribute clause on the same construct
25866 //
25867 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
25868 // A list item cannot appear in both a map clause and a data-sharing
25869 // attribute clause on the same construct unless the construct is a
25870 // combined construct.
25871 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
25873 DKind == OMPD_target)) {
25874 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
25875 if (isOpenMPPrivate(DVar.CKind)) {
25876 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
25877 << getOpenMPClauseNameForDiag(DVar.CKind)
25878 << getOpenMPClauseNameForDiag(OMPC_map)
25879 << getOpenMPDirectiveName(DSAS->getCurrentDirective(),
25880 OMPVersion);
25881 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
25882 continue;
25883 }
25884 }
25885 }
25886
25887 // Try to find the associated user-defined mapper.
25889 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
25890 Type.getCanonicalType(), UnresolvedMapper, ELoc);
25891 if (ER.isInvalid())
25892 continue;
25893
25894 // If no user-defined mapper is found, we need to create an implicit one for
25895 // arrays/array-sections on structs that have members that have
25896 // user-defined mappers. This is needed to ensure that the mapper for the
25897 // member is invoked when mapping each element of the array/array-section.
25898 if (!ER.get()) {
25899 QualType BaseType;
25900
25902 BaseType = VE->getType().getCanonicalType();
25903 if (BaseType->isSpecificBuiltinType(BuiltinType::ArraySection)) {
25904 const auto *OASE = cast<ArraySectionExpr>(VE->IgnoreParenImpCasts());
25905 QualType BType =
25907 QualType ElemType;
25908 if (const auto *ATy = BType->getAsArrayTypeUnsafe())
25909 ElemType = ATy->getElementType();
25910 else
25911 ElemType = BType->getPointeeType();
25912 BaseType = ElemType.getCanonicalType();
25913 }
25914 } else if (VE->getType()->isArrayType()) {
25915 const ArrayType *AT = VE->getType()->getAsArrayTypeUnsafe();
25916 const QualType ElemType = AT->getElementType();
25917 BaseType = ElemType.getCanonicalType();
25918 }
25919
25920 if (!BaseType.isNull() && BaseType->getAsRecordDecl() &&
25921 isImplicitMapperNeeded(SemaRef, DSAS, BaseType, VE)) {
25922 ER = buildImplicitMapper(SemaRef, BaseType, DSAS);
25923 }
25924 }
25925 MVLI.UDMapperList.push_back(ER.get());
25926
25927 // Save the current expression.
25928 MVLI.ProcessedVarList.push_back(RE);
25929
25930 // Store the components in the stack so that they can be used to check
25931 // against other clauses later on.
25932 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
25933 /*WhereFoundClauseKind=*/OMPC_map);
25934
25935 // Save the components and declaration to create the clause. For purposes of
25936 // the clause creation, any component list that has base 'this' uses
25937 // null as base declaration.
25938 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
25939 MVLI.VarComponents.back().append(CurComponents.begin(),
25940 CurComponents.end());
25941 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
25942 : CurDeclaration);
25943 }
25944}
25945
25947 Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
25948 ArrayRef<SourceLocation> MapTypeModifiersLoc,
25949 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
25950 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
25951 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
25952 const OMPVarListLocTy &Locs, bool NoDiagnose,
25953 ArrayRef<Expr *> UnresolvedMappers) {
25954 OpenMPMapModifierKind Modifiers[] = {
25960
25961 if (IteratorModifier && !IteratorModifier->getType()->isSpecificBuiltinType(
25962 BuiltinType::OMPIterator))
25963 Diag(IteratorModifier->getExprLoc(),
25964 diag::err_omp_map_modifier_not_iterator);
25965
25966 // Process map-type-modifiers, flag errors for duplicate modifiers.
25967 unsigned Count = 0;
25968 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
25969 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
25970 llvm::is_contained(Modifiers, MapTypeModifiers[I])) {
25971 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
25972 continue;
25973 }
25974 assert(Count < NumberOfOMPMapClauseModifiers &&
25975 "Modifiers exceed the allowed number of map type modifiers");
25976 Modifiers[Count] = MapTypeModifiers[I];
25977 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
25978 ++Count;
25979 }
25980
25981 MappableVarListInfo MVLI(VarList);
25982 // Per OpenMP 6.0 p299 lines 3-4, a list item with the const specifier and
25983 // no mutable members is ignored for 'from' clauses. A const-qualified
25984 // variable cannot be modified on the device, so copying back to the host
25985 // is unnecessary and potentially unsafe. Strip the FROM component:
25986 // map(tofrom:) -> map(to:), map(from:) -> map(alloc:).
25987 for (auto *E : VarList) {
25988 if ((MapType == OMPC_MAP_from || MapType == OMPC_MAP_tofrom) &&
25990 MapType = (MapType == OMPC_MAP_tofrom) ? OMPC_MAP_to : OMPC_MAP_alloc;
25991 }
25993 MapperIdScopeSpec, MapperId, UnresolvedMappers,
25994 MapType, Modifiers, IsMapTypeImplicit,
25995 NoDiagnose);
25996
25997 // We need to produce a map clause even if we don't have variables so that
25998 // other diagnostics related with non-existing map clauses are accurate.
25999 return OMPMapClause::Create(
26000 getASTContext(), Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
26001 MVLI.VarComponents, MVLI.UDMapperList, IteratorModifier, Modifiers,
26002 ModifiersLoc, MapperIdScopeSpec.getWithLocInContext(getASTContext()),
26003 MapperId, MapType, IsMapTypeImplicit, MapLoc);
26004}
26005
26008 assert(ParsedType.isUsable());
26009
26010 QualType ReductionType = SemaRef.GetTypeFromParser(ParsedType.get());
26011 if (ReductionType.isNull())
26012 return QualType();
26013
26014 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
26015 // A type name in a declare reduction directive cannot be a function type, an
26016 // array type, a reference type, or a type qualified with const, volatile or
26017 // restrict.
26018 if (ReductionType.hasQualifiers()) {
26019 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
26020 return QualType();
26021 }
26022
26023 if (ReductionType->isFunctionType()) {
26024 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
26025 return QualType();
26026 }
26027 if (ReductionType->isReferenceType()) {
26028 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
26029 return QualType();
26030 }
26031 if (ReductionType->isArrayType()) {
26032 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
26033 return QualType();
26034 }
26035 return ReductionType;
26036}
26037
26040 Scope *S, DeclContext *DC, DeclarationName Name,
26041 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
26042 AccessSpecifier AS, Decl *PrevDeclInScope) {
26044 Decls.reserve(ReductionTypes.size());
26045
26046 LookupResult Lookup(SemaRef, Name, SourceLocation(),
26048 SemaRef.forRedeclarationInCurContext());
26049 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
26050 // A reduction-identifier may not be re-declared in the current scope for the
26051 // same type or for a type that is compatible according to the base language
26052 // rules.
26053 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
26054 OMPDeclareReductionDecl *PrevDRD = nullptr;
26055 bool InCompoundScope = true;
26056 if (S != nullptr) {
26057 // Find previous declaration with the same name not referenced in other
26058 // declarations.
26059 FunctionScopeInfo *ParentFn = SemaRef.getEnclosingFunction();
26060 InCompoundScope =
26061 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
26062 SemaRef.LookupName(Lookup, S);
26063 SemaRef.FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
26064 /*AllowInlineNamespace=*/false);
26065 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
26066 LookupResult::Filter Filter = Lookup.makeFilter();
26067 while (Filter.hasNext()) {
26068 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
26069 if (InCompoundScope) {
26070 UsedAsPrevious.try_emplace(PrevDecl, false);
26071 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
26072 UsedAsPrevious[D] = true;
26073 }
26074 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
26075 PrevDecl->getLocation();
26076 }
26077 Filter.done();
26078 if (InCompoundScope) {
26079 for (const auto &PrevData : UsedAsPrevious) {
26080 if (!PrevData.second) {
26081 PrevDRD = PrevData.first;
26082