1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements semantic analysis for OpenMP directives and
10 /// clauses.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclOpenMP.h"
21 #include "clang/AST/StmtCXX.h"
22 #include "clang/AST/StmtOpenMP.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/AST/TypeOrdering.h"
25 #include "clang/Basic/OpenMPKinds.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/ScopeInfo.h"
30 #include "clang/Sema/SemaInternal.h"
31 #include "llvm/ADT/PointerEmbeddedInt.h"
32 using namespace clang;
33 
34 //===----------------------------------------------------------------------===//
35 // Stack of data-sharing attributes for variables
36 //===----------------------------------------------------------------------===//
37 
38 static const Expr *checkMapClauseExpressionBase(
39     Sema &SemaRef, Expr *E,
40     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
41     OpenMPClauseKind CKind, bool NoDiagnose);
42 
43 namespace {
44 /// Default data sharing attributes, which can be applied to directive.
45 enum DefaultDataSharingAttributes {
46   DSA_unspecified = 0, /// Data sharing attribute not specified.
47   DSA_none = 1 << 0,   /// Default data sharing attribute 'none'.
48   DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
49 };
50 
51 /// Attributes of the defaultmap clause.
52 enum DefaultMapAttributes {
53   DMA_unspecified,   /// Default mapping is not specified.
54   DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
55 };
56 
57 /// Stack for tracking declarations used in OpenMP directives and
58 /// clauses and their data-sharing attributes.
59 class DSAStackTy {
60 public:
61   struct DSAVarData {
62     OpenMPDirectiveKind DKind = OMPD_unknown;
63     OpenMPClauseKind CKind = OMPC_unknown;
64     const Expr *RefExpr = nullptr;
65     DeclRefExpr *PrivateCopy = nullptr;
66     SourceLocation ImplicitDSALoc;
67     DSAVarData() = default;
68     DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69                const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70                SourceLocation ImplicitDSALoc)
71         : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72           PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
73   };
74   using OperatorOffsetTy =
75       llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
76   using DoacrossDependMapTy =
77       llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
78 
79 private:
80   struct DSAInfo {
81     OpenMPClauseKind Attributes = OMPC_unknown;
82     /// Pointer to a reference expression and a flag which shows that the
83     /// variable is marked as lastprivate(true) or not (false).
84     llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
85     DeclRefExpr *PrivateCopy = nullptr;
86   };
87   using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88   using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89   using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90   using LoopControlVariablesMapTy =
91       llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
92   /// Struct that associates a component with the clause kind where they are
93   /// found.
94   struct MappedExprComponentTy {
95     OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96     OpenMPClauseKind Kind = OMPC_unknown;
97   };
98   using MappedExprComponentsTy =
99       llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100   using CriticalsWithHintsTy =
101       llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
102   struct ReductionData {
103     using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
104     SourceRange ReductionRange;
105     llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
106     ReductionData() = default;
107     void set(BinaryOperatorKind BO, SourceRange RR) {
108       ReductionRange = RR;
109       ReductionOp = BO;
110     }
111     void set(const Expr *RefExpr, SourceRange RR) {
112       ReductionRange = RR;
113       ReductionOp = RefExpr;
114     }
115   };
116   using DeclReductionMapTy =
117       llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
118 
119   struct SharingMapTy {
120     DeclSAMapTy SharingMap;
121     DeclReductionMapTy ReductionMap;
122     AlignedMapTy AlignedMap;
123     MappedExprComponentsTy MappedExprComponents;
124     LoopControlVariablesMapTy LCVMap;
125     DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
126     SourceLocation DefaultAttrLoc;
127     DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128     SourceLocation DefaultMapAttrLoc;
129     OpenMPDirectiveKind Directive = OMPD_unknown;
130     DeclarationNameInfo DirectiveName;
131     Scope *CurScope = nullptr;
132     SourceLocation ConstructLoc;
133     /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134     /// get the data (loop counters etc.) about enclosing loop-based construct.
135     /// This data is required during codegen.
136     DoacrossDependMapTy DoacrossDepends;
137     /// First argument (Expr *) contains optional argument of the
138     /// 'ordered' clause, the second one is true if the regions has 'ordered'
139     /// clause, false otherwise.
140     llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
141     unsigned AssociatedLoops = 1;
142     const Decl *PossiblyLoopCounter = nullptr;
143     bool NowaitRegion = false;
144     bool CancelRegion = false;
145     bool LoopStart = false;
146     SourceLocation InnerTeamsRegionLoc;
147     /// Reference to the taskgroup task_reduction reference expression.
148     Expr *TaskgroupReductionRef = nullptr;
149     llvm::DenseSet<QualType> MappedClassesQualTypes;
150     SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
151                  Scope *CurScope, SourceLocation Loc)
152         : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
153           ConstructLoc(Loc) {}
154     SharingMapTy() = default;
155   };
156 
157   using StackTy = SmallVector<SharingMapTy, 4>;
158 
159   /// Stack of used declaration and their data-sharing attributes.
160   DeclSAMapTy Threadprivates;
161   const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
162   SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
163   /// true, if check for DSA must be from parent directive, false, if
164   /// from current directive.
165   OpenMPClauseKind ClauseKindMode = OMPC_unknown;
166   Sema &SemaRef;
167   bool ForceCapturing = false;
168   /// true if all the vaiables in the target executable directives must be
169   /// captured by reference.
170   bool ForceCaptureByReferenceInTargetExecutable = false;
171   CriticalsWithHintsTy Criticals;
172 
173   using iterator = StackTy::const_reverse_iterator;
174 
175   DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
176 
177   /// Checks if the variable is a local for OpenMP region.
178   bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
179 
180   bool isStackEmpty() const {
181     return Stack.empty() ||
182            Stack.back().second != CurrentNonCapturingFunctionScope ||
183            Stack.back().first.empty();
184   }
185 
186   /// Vector of previously declared requires directives
187   SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
188 
189 public:
190   explicit DSAStackTy(Sema &S) : SemaRef(S) {}
191 
192   bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
193   OpenMPClauseKind getClauseParsingMode() const {
194     assert(isClauseParsingMode() && "Must be in clause parsing mode.");
195     return ClauseKindMode;
196   }
197   void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
198 
199   bool isForceVarCapturing() const { return ForceCapturing; }
200   void setForceVarCapturing(bool V) { ForceCapturing = V; }
201 
202   void setForceCaptureByReferenceInTargetExecutable(bool V) {
203     ForceCaptureByReferenceInTargetExecutable = V;
204   }
205   bool isForceCaptureByReferenceInTargetExecutable() const {
206     return ForceCaptureByReferenceInTargetExecutable;
207   }
208 
209   void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
210             Scope *CurScope, SourceLocation Loc) {
211     if (Stack.empty() ||
212         Stack.back().second != CurrentNonCapturingFunctionScope)
213       Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
214     Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
215     Stack.back().first.back().DefaultAttrLoc = Loc;
216   }
217 
218   void pop() {
219     assert(!Stack.back().first.empty() &&
220            "Data-sharing attributes stack is empty!");
221     Stack.back().first.pop_back();
222   }
223 
224   /// Marks that we're started loop parsing.
225   void loopInit() {
226     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
227            "Expected loop-based directive.");
228     Stack.back().first.back().LoopStart = true;
229   }
230   /// Start capturing of the variables in the loop context.
231   void loopStart() {
232     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
233            "Expected loop-based directive.");
234     Stack.back().first.back().LoopStart = false;
235   }
236   /// true, if variables are captured, false otherwise.
237   bool isLoopStarted() const {
238     assert(isOpenMPLoopDirective(getCurrentDirective()) &&
239            "Expected loop-based directive.");
240     return !Stack.back().first.back().LoopStart;
241   }
242   /// Marks (or clears) declaration as possibly loop counter.
243   void resetPossibleLoopCounter(const Decl *D = nullptr) {
244     Stack.back().first.back().PossiblyLoopCounter =
245         D ? D->getCanonicalDecl() : D;
246   }
247   /// Gets the possible loop counter decl.
248   const Decl *getPossiblyLoopCunter() const {
249     return Stack.back().first.back().PossiblyLoopCounter;
250   }
251   /// Start new OpenMP region stack in new non-capturing function.
252   void pushFunction() {
253     const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
254     assert(!isa<CapturingScopeInfo>(CurFnScope));
255     CurrentNonCapturingFunctionScope = CurFnScope;
256   }
257   /// Pop region stack for non-capturing function.
258   void popFunction(const FunctionScopeInfo *OldFSI) {
259     if (!Stack.empty() && Stack.back().second == OldFSI) {
260       assert(Stack.back().first.empty());
261       Stack.pop_back();
262     }
263     CurrentNonCapturingFunctionScope = nullptr;
264     for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
265       if (!isa<CapturingScopeInfo>(FSI)) {
266         CurrentNonCapturingFunctionScope = FSI;
267         break;
268       }
269     }
270   }
271 
272   void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
273     Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
274   }
275   const std::pair<const OMPCriticalDirective *, llvm::APSInt>
276   getCriticalWithHint(const DeclarationNameInfo &Name) const {
277     auto I = Criticals.find(Name.getAsString());
278     if (I != Criticals.end())
279       return I->second;
280     return std::make_pair(nullptr, llvm::APSInt());
281   }
282   /// If 'aligned' declaration for given variable \a D was not seen yet,
283   /// add it and return NULL; otherwise return previous occurrence's expression
284   /// for diagnostics.
285   const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
286 
287   /// Register specified variable as loop control variable.
288   void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
289   /// Check if the specified variable is a loop control variable for
290   /// current region.
291   /// \return The index of the loop control variable in the list of associated
292   /// for-loops (from outer to inner).
293   const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
294   /// Check if the specified variable is a loop control variable for
295   /// parent region.
296   /// \return The index of the loop control variable in the list of associated
297   /// for-loops (from outer to inner).
298   const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
299   /// Get the loop control variable for the I-th loop (or nullptr) in
300   /// parent directive.
301   const ValueDecl *getParentLoopControlVariable(unsigned I) const;
302 
303   /// Adds explicit data sharing attribute to the specified declaration.
304   void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
305               DeclRefExpr *PrivateCopy = nullptr);
306 
307   /// Adds additional information for the reduction items with the reduction id
308   /// represented as an operator.
309   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
310                                  BinaryOperatorKind BOK);
311   /// Adds additional information for the reduction items with the reduction id
312   /// represented as reduction identifier.
313   void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
314                                  const Expr *ReductionRef);
315   /// Returns the location and reduction operation from the innermost parent
316   /// region for the given \p D.
317   const DSAVarData
318   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
319                                    BinaryOperatorKind &BOK,
320                                    Expr *&TaskgroupDescriptor) const;
321   /// Returns the location and reduction operation from the innermost parent
322   /// region for the given \p D.
323   const DSAVarData
324   getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
325                                    const Expr *&ReductionRef,
326                                    Expr *&TaskgroupDescriptor) const;
327   /// Return reduction reference expression for the current taskgroup.
328   Expr *getTaskgroupReductionRef() const {
329     assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
330            "taskgroup reference expression requested for non taskgroup "
331            "directive.");
332     return Stack.back().first.back().TaskgroupReductionRef;
333   }
334   /// Checks if the given \p VD declaration is actually a taskgroup reduction
335   /// descriptor variable at the \p Level of OpenMP regions.
336   bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
337     return Stack.back().first[Level].TaskgroupReductionRef &&
338            cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
339                    ->getDecl() == VD;
340   }
341 
342   /// Returns data sharing attributes from top of the stack for the
343   /// specified declaration.
344   const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
345   /// Returns data-sharing attributes for the specified declaration.
346   const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
347   /// Checks if the specified variables has data-sharing attributes which
348   /// match specified \a CPred predicate in any directive which matches \a DPred
349   /// predicate.
350   const DSAVarData
351   hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
352          const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
353          bool FromParent) const;
354   /// Checks if the specified variables has data-sharing attributes which
355   /// match specified \a CPred predicate in any innermost directive which
356   /// matches \a DPred predicate.
357   const DSAVarData
358   hasInnermostDSA(ValueDecl *D,
359                   const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
360                   const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
361                   bool FromParent) const;
362   /// Checks if the specified variables has explicit data-sharing
363   /// attributes which match specified \a CPred predicate at the specified
364   /// OpenMP region.
365   bool hasExplicitDSA(const ValueDecl *D,
366                       const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
367                       unsigned Level, bool NotLastprivate = false) const;
368 
369   /// Returns true if the directive at level \Level matches in the
370   /// specified \a DPred predicate.
371   bool hasExplicitDirective(
372       const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
373       unsigned Level) const;
374 
375   /// Finds a directive which matches specified \a DPred predicate.
376   bool hasDirective(
377       const llvm::function_ref<bool(
378           OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
379           DPred,
380       bool FromParent) const;
381 
382   /// Returns currently analyzed directive.
383   OpenMPDirectiveKind getCurrentDirective() const {
384     return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
385   }
386   /// Returns directive kind at specified level.
387   OpenMPDirectiveKind getDirective(unsigned Level) const {
388     assert(!isStackEmpty() && "No directive at specified level.");
389     return Stack.back().first[Level].Directive;
390   }
391   /// Returns parent directive.
392   OpenMPDirectiveKind getParentDirective() const {
393     if (isStackEmpty() || Stack.back().first.size() == 1)
394       return OMPD_unknown;
395     return std::next(Stack.back().first.rbegin())->Directive;
396   }
397 
398   /// Add requires decl to internal vector
399   void addRequiresDecl(OMPRequiresDecl *RD) {
400     RequiresDecls.push_back(RD);
401   }
402 
403   /// Checks for a duplicate clause amongst previously declared requires
404   /// directives
405   bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
406     bool IsDuplicate = false;
407     for (OMPClause *CNew : ClauseList) {
408       for (const OMPRequiresDecl *D : RequiresDecls) {
409         for (const OMPClause *CPrev : D->clauselists()) {
410           if (CNew->getClauseKind() == CPrev->getClauseKind()) {
411             SemaRef.Diag(CNew->getBeginLoc(),
412                          diag::err_omp_requires_clause_redeclaration)
413                 << getOpenMPClauseName(CNew->getClauseKind());
414             SemaRef.Diag(CPrev->getBeginLoc(),
415                          diag::note_omp_requires_previous_clause)
416                 << getOpenMPClauseName(CPrev->getClauseKind());
417             IsDuplicate = true;
418           }
419         }
420       }
421     }
422     return IsDuplicate;
423   }
424 
425   /// Set default data sharing attribute to none.
426   void setDefaultDSANone(SourceLocation Loc) {
427     assert(!isStackEmpty());
428     Stack.back().first.back().DefaultAttr = DSA_none;
429     Stack.back().first.back().DefaultAttrLoc = Loc;
430   }
431   /// Set default data sharing attribute to shared.
432   void setDefaultDSAShared(SourceLocation Loc) {
433     assert(!isStackEmpty());
434     Stack.back().first.back().DefaultAttr = DSA_shared;
435     Stack.back().first.back().DefaultAttrLoc = Loc;
436   }
437   /// Set default data mapping attribute to 'tofrom:scalar'.
438   void setDefaultDMAToFromScalar(SourceLocation Loc) {
439     assert(!isStackEmpty());
440     Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
441     Stack.back().first.back().DefaultMapAttrLoc = Loc;
442   }
443 
444   DefaultDataSharingAttributes getDefaultDSA() const {
445     return isStackEmpty() ? DSA_unspecified
446                           : Stack.back().first.back().DefaultAttr;
447   }
448   SourceLocation getDefaultDSALocation() const {
449     return isStackEmpty() ? SourceLocation()
450                           : Stack.back().first.back().DefaultAttrLoc;
451   }
452   DefaultMapAttributes getDefaultDMA() const {
453     return isStackEmpty() ? DMA_unspecified
454                           : Stack.back().first.back().DefaultMapAttr;
455   }
456   DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
457     return Stack.back().first[Level].DefaultMapAttr;
458   }
459   SourceLocation getDefaultDMALocation() const {
460     return isStackEmpty() ? SourceLocation()
461                           : Stack.back().first.back().DefaultMapAttrLoc;
462   }
463 
464   /// Checks if the specified variable is a threadprivate.
465   bool isThreadPrivate(VarDecl *D) {
466     const DSAVarData DVar = getTopDSA(D, false);
467     return isOpenMPThreadPrivate(DVar.CKind);
468   }
469 
470   /// Marks current region as ordered (it has an 'ordered' clause).
471   void setOrderedRegion(bool IsOrdered, const Expr *Param,
472                         OMPOrderedClause *Clause) {
473     assert(!isStackEmpty());
474     if (IsOrdered)
475       Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
476     else
477       Stack.back().first.back().OrderedRegion.reset();
478   }
479   /// Returns true, if region is ordered (has associated 'ordered' clause),
480   /// false - otherwise.
481   bool isOrderedRegion() const {
482     if (isStackEmpty())
483       return false;
484     return Stack.back().first.rbegin()->OrderedRegion.hasValue();
485   }
486   /// Returns optional parameter for the ordered region.
487   std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
488     if (isStackEmpty() ||
489         !Stack.back().first.rbegin()->OrderedRegion.hasValue())
490       return std::make_pair(nullptr, nullptr);
491     return Stack.back().first.rbegin()->OrderedRegion.getValue();
492   }
493   /// Returns true, if parent region is ordered (has associated
494   /// 'ordered' clause), false - otherwise.
495   bool isParentOrderedRegion() const {
496     if (isStackEmpty() || Stack.back().first.size() == 1)
497       return false;
498     return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
499   }
500   /// Returns optional parameter for the ordered region.
501   std::pair<const Expr *, OMPOrderedClause *>
502   getParentOrderedRegionParam() const {
503     if (isStackEmpty() || Stack.back().first.size() == 1 ||
504         !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
505       return std::make_pair(nullptr, nullptr);
506     return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
507   }
508   /// Marks current region as nowait (it has a 'nowait' clause).
509   void setNowaitRegion(bool IsNowait = true) {
510     assert(!isStackEmpty());
511     Stack.back().first.back().NowaitRegion = IsNowait;
512   }
513   /// Returns true, if parent region is nowait (has associated
514   /// 'nowait' clause), false - otherwise.
515   bool isParentNowaitRegion() const {
516     if (isStackEmpty() || Stack.back().first.size() == 1)
517       return false;
518     return std::next(Stack.back().first.rbegin())->NowaitRegion;
519   }
520   /// Marks parent region as cancel region.
521   void setParentCancelRegion(bool Cancel = true) {
522     if (!isStackEmpty() && Stack.back().first.size() > 1) {
523       auto &StackElemRef = *std::next(Stack.back().first.rbegin());
524       StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
525     }
526   }
527   /// Return true if current region has inner cancel construct.
528   bool isCancelRegion() const {
529     return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
530   }
531 
532   /// Set collapse value for the region.
533   void setAssociatedLoops(unsigned Val) {
534     assert(!isStackEmpty());
535     Stack.back().first.back().AssociatedLoops = Val;
536   }
537   /// Return collapse value for region.
538   unsigned getAssociatedLoops() const {
539     return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
540   }
541 
542   /// Marks current target region as one with closely nested teams
543   /// region.
544   void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
545     if (!isStackEmpty() && Stack.back().first.size() > 1) {
546       std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
547           TeamsRegionLoc;
548     }
549   }
550   /// Returns true, if current region has closely nested teams region.
551   bool hasInnerTeamsRegion() const {
552     return getInnerTeamsRegionLoc().isValid();
553   }
554   /// Returns location of the nested teams region (if any).
555   SourceLocation getInnerTeamsRegionLoc() const {
556     return isStackEmpty() ? SourceLocation()
557                           : Stack.back().first.back().InnerTeamsRegionLoc;
558   }
559 
560   Scope *getCurScope() const {
561     return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
562   }
563   SourceLocation getConstructLoc() const {
564     return isStackEmpty() ? SourceLocation()
565                           : Stack.back().first.back().ConstructLoc;
566   }
567 
568   /// Do the check specified in \a Check to all component lists and return true
569   /// if any issue is found.
570   bool checkMappableExprComponentListsForDecl(
571       const ValueDecl *VD, bool CurrentRegionOnly,
572       const llvm::function_ref<
573           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
574                OpenMPClauseKind)>
575           Check) const {
576     if (isStackEmpty())
577       return false;
578     auto SI = Stack.back().first.rbegin();
579     auto SE = Stack.back().first.rend();
580 
581     if (SI == SE)
582       return false;
583 
584     if (CurrentRegionOnly)
585       SE = std::next(SI);
586     else
587       std::advance(SI, 1);
588 
589     for (; SI != SE; ++SI) {
590       auto MI = SI->MappedExprComponents.find(VD);
591       if (MI != SI->MappedExprComponents.end())
592         for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
593              MI->second.Components)
594           if (Check(L, MI->second.Kind))
595             return true;
596     }
597     return false;
598   }
599 
600   /// Do the check specified in \a Check to all component lists at a given level
601   /// and return true if any issue is found.
602   bool checkMappableExprComponentListsForDeclAtLevel(
603       const ValueDecl *VD, unsigned Level,
604       const llvm::function_ref<
605           bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
606                OpenMPClauseKind)>
607           Check) const {
608     if (isStackEmpty())
609       return false;
610 
611     auto StartI = Stack.back().first.begin();
612     auto EndI = Stack.back().first.end();
613     if (std::distance(StartI, EndI) <= (int)Level)
614       return false;
615     std::advance(StartI, Level);
616 
617     auto MI = StartI->MappedExprComponents.find(VD);
618     if (MI != StartI->MappedExprComponents.end())
619       for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
620            MI->second.Components)
621         if (Check(L, MI->second.Kind))
622           return true;
623     return false;
624   }
625 
626   /// Create a new mappable expression component list associated with a given
627   /// declaration and initialize it with the provided list of components.
628   void addMappableExpressionComponents(
629       const ValueDecl *VD,
630       OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
631       OpenMPClauseKind WhereFoundClauseKind) {
632     assert(!isStackEmpty() &&
633            "Not expecting to retrieve components from a empty stack!");
634     MappedExprComponentTy &MEC =
635         Stack.back().first.back().MappedExprComponents[VD];
636     // Create new entry and append the new components there.
637     MEC.Components.resize(MEC.Components.size() + 1);
638     MEC.Components.back().append(Components.begin(), Components.end());
639     MEC.Kind = WhereFoundClauseKind;
640   }
641 
642   unsigned getNestingLevel() const {
643     assert(!isStackEmpty());
644     return Stack.back().first.size() - 1;
645   }
646   void addDoacrossDependClause(OMPDependClause *C,
647                                const OperatorOffsetTy &OpsOffs) {
648     assert(!isStackEmpty() && Stack.back().first.size() > 1);
649     SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
650     assert(isOpenMPWorksharingDirective(StackElem.Directive));
651     StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
652   }
653   llvm::iterator_range<DoacrossDependMapTy::const_iterator>
654   getDoacrossDependClauses() const {
655     assert(!isStackEmpty());
656     const SharingMapTy &StackElem = Stack.back().first.back();
657     if (isOpenMPWorksharingDirective(StackElem.Directive)) {
658       const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
659       return llvm::make_range(Ref.begin(), Ref.end());
660     }
661     return llvm::make_range(StackElem.DoacrossDepends.end(),
662                             StackElem.DoacrossDepends.end());
663   }
664 
665   // Store types of classes which have been explicitly mapped
666   void addMappedClassesQualTypes(QualType QT) {
667     SharingMapTy &StackElem = Stack.back().first.back();
668     StackElem.MappedClassesQualTypes.insert(QT);
669   }
670 
671   // Return set of mapped classes types
672   bool isClassPreviouslyMapped(QualType QT) const {
673     const SharingMapTy &StackElem = Stack.back().first.back();
674     return StackElem.MappedClassesQualTypes.count(QT) != 0;
675   }
676 
677 };
678 
679 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
680   return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
681 }
682 
683 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
684   return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
685 }
686 
687 } // namespace
688 
689 static const Expr *getExprAsWritten(const Expr *E) {
690   if (const auto *FE = dyn_cast<FullExpr>(E))
691     E = FE->getSubExpr();
692 
693   if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
694     E = MTE->GetTemporaryExpr();
695 
696   while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
697     E = Binder->getSubExpr();
698 
699   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
700     E = ICE->getSubExprAsWritten();
701   return E->IgnoreParens();
702 }
703 
704 static Expr *getExprAsWritten(Expr *E) {
705   return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
706 }
707 
708 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
709   if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
710     if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
711       D = ME->getMemberDecl();
712   const auto *VD = dyn_cast<VarDecl>(D);
713   const auto *FD = dyn_cast<FieldDecl>(D);
714   if (VD != nullptr) {
715     VD = VD->getCanonicalDecl();
716     D = VD;
717   } else {
718     assert(FD);
719     FD = FD->getCanonicalDecl();
720     D = FD;
721   }
722   return D;
723 }
724 
725 static ValueDecl *getCanonicalDecl(ValueDecl *D) {
726   return const_cast<ValueDecl *>(
727       getCanonicalDecl(const_cast<const ValueDecl *>(D)));
728 }
729 
730 DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
731                                           ValueDecl *D) const {
732   D = getCanonicalDecl(D);
733   auto *VD = dyn_cast<VarDecl>(D);
734   const auto *FD = dyn_cast<FieldDecl>(D);
735   DSAVarData DVar;
736   if (isStackEmpty() || Iter == Stack.back().first.rend()) {
737     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
738     // in a region but not in construct]
739     //  File-scope or namespace-scope variables referenced in called routines
740     //  in the region are shared unless they appear in a threadprivate
741     //  directive.
742     if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
743       DVar.CKind = OMPC_shared;
744 
745     // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
746     // in a region but not in construct]
747     //  Variables with static storage duration that are declared in called
748     //  routines in the region are shared.
749     if (VD && VD->hasGlobalStorage())
750       DVar.CKind = OMPC_shared;
751 
752     // Non-static data members are shared by default.
753     if (FD)
754       DVar.CKind = OMPC_shared;
755 
756     return DVar;
757   }
758 
759   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
760   // in a Construct, C/C++, predetermined, p.1]
761   // Variables with automatic storage duration that are declared in a scope
762   // inside the construct are private.
763   if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
764       (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
765     DVar.CKind = OMPC_private;
766     return DVar;
767   }
768 
769   DVar.DKind = Iter->Directive;
770   // Explicitly specified attributes and local variables with predetermined
771   // attributes.
772   if (Iter->SharingMap.count(D)) {
773     const DSAInfo &Data = Iter->SharingMap.lookup(D);
774     DVar.RefExpr = Data.RefExpr.getPointer();
775     DVar.PrivateCopy = Data.PrivateCopy;
776     DVar.CKind = Data.Attributes;
777     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
778     return DVar;
779   }
780 
781   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
782   // in a Construct, C/C++, implicitly determined, p.1]
783   //  In a parallel or task construct, the data-sharing attributes of these
784   //  variables are determined by the default clause, if present.
785   switch (Iter->DefaultAttr) {
786   case DSA_shared:
787     DVar.CKind = OMPC_shared;
788     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
789     return DVar;
790   case DSA_none:
791     return DVar;
792   case DSA_unspecified:
793     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
794     // in a Construct, implicitly determined, p.2]
795     //  In a parallel construct, if no default clause is present, these
796     //  variables are shared.
797     DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
798     if (isOpenMPParallelDirective(DVar.DKind) ||
799         isOpenMPTeamsDirective(DVar.DKind)) {
800       DVar.CKind = OMPC_shared;
801       return DVar;
802     }
803 
804     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
805     // in a Construct, implicitly determined, p.4]
806     //  In a task construct, if no default clause is present, a variable that in
807     //  the enclosing context is determined to be shared by all implicit tasks
808     //  bound to the current team is shared.
809     if (isOpenMPTaskingDirective(DVar.DKind)) {
810       DSAVarData DVarTemp;
811       iterator I = Iter, E = Stack.back().first.rend();
812       do {
813         ++I;
814         // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
815         // Referenced in a Construct, implicitly determined, p.6]
816         //  In a task construct, if no default clause is present, a variable
817         //  whose data-sharing attribute is not determined by the rules above is
818         //  firstprivate.
819         DVarTemp = getDSA(I, D);
820         if (DVarTemp.CKind != OMPC_shared) {
821           DVar.RefExpr = nullptr;
822           DVar.CKind = OMPC_firstprivate;
823           return DVar;
824         }
825       } while (I != E && !isImplicitTaskingRegion(I->Directive));
826       DVar.CKind =
827           (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
828       return DVar;
829     }
830   }
831   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
832   // in a Construct, implicitly determined, p.3]
833   //  For constructs other than task, if no default clause is present, these
834   //  variables inherit their data-sharing attributes from the enclosing
835   //  context.
836   return getDSA(++Iter, D);
837 }
838 
839 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
840                                          const Expr *NewDE) {
841   assert(!isStackEmpty() && "Data sharing attributes stack is empty");
842   D = getCanonicalDecl(D);
843   SharingMapTy &StackElem = Stack.back().first.back();
844   auto It = StackElem.AlignedMap.find(D);
845   if (It == StackElem.AlignedMap.end()) {
846     assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
847     StackElem.AlignedMap[D] = NewDE;
848     return nullptr;
849   }
850   assert(It->second && "Unexpected nullptr expr in the aligned map");
851   return It->second;
852 }
853 
854 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
855   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
856   D = getCanonicalDecl(D);
857   SharingMapTy &StackElem = Stack.back().first.back();
858   StackElem.LCVMap.try_emplace(
859       D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
860 }
861 
862 const DSAStackTy::LCDeclInfo
863 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
864   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
865   D = getCanonicalDecl(D);
866   const SharingMapTy &StackElem = Stack.back().first.back();
867   auto It = StackElem.LCVMap.find(D);
868   if (It != StackElem.LCVMap.end())
869     return It->second;
870   return {0, nullptr};
871 }
872 
873 const DSAStackTy::LCDeclInfo
874 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
875   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
876          "Data-sharing attributes stack is empty");
877   D = getCanonicalDecl(D);
878   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
879   auto It = StackElem.LCVMap.find(D);
880   if (It != StackElem.LCVMap.end())
881     return It->second;
882   return {0, nullptr};
883 }
884 
885 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
886   assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
887          "Data-sharing attributes stack is empty");
888   const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
889   if (StackElem.LCVMap.size() < I)
890     return nullptr;
891   for (const auto &Pair : StackElem.LCVMap)
892     if (Pair.second.first == I)
893       return Pair.first;
894   return nullptr;
895 }
896 
897 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
898                         DeclRefExpr *PrivateCopy) {
899   D = getCanonicalDecl(D);
900   if (A == OMPC_threadprivate) {
901     DSAInfo &Data = Threadprivates[D];
902     Data.Attributes = A;
903     Data.RefExpr.setPointer(E);
904     Data.PrivateCopy = nullptr;
905   } else {
906     assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
907     DSAInfo &Data = Stack.back().first.back().SharingMap[D];
908     assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
909            (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
910            (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
911            (isLoopControlVariable(D).first && A == OMPC_private));
912     if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
913       Data.RefExpr.setInt(/*IntVal=*/true);
914       return;
915     }
916     const bool IsLastprivate =
917         A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
918     Data.Attributes = A;
919     Data.RefExpr.setPointerAndInt(E, IsLastprivate);
920     Data.PrivateCopy = PrivateCopy;
921     if (PrivateCopy) {
922       DSAInfo &Data =
923           Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
924       Data.Attributes = A;
925       Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
926       Data.PrivateCopy = nullptr;
927     }
928   }
929 }
930 
931 /// Build a variable declaration for OpenMP loop iteration variable.
932 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
933                              StringRef Name, const AttrVec *Attrs = nullptr,
934                              DeclRefExpr *OrigRef = nullptr) {
935   DeclContext *DC = SemaRef.CurContext;
936   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
937   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
938   auto *Decl =
939       VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
940   if (Attrs) {
941     for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
942          I != E; ++I)
943       Decl->addAttr(*I);
944   }
945   Decl->setImplicit();
946   if (OrigRef) {
947     Decl->addAttr(
948         OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
949   }
950   return Decl;
951 }
952 
953 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
954                                      SourceLocation Loc,
955                                      bool RefersToCapture = false) {
956   D->setReferenced();
957   D->markUsed(S.Context);
958   return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
959                              SourceLocation(), D, RefersToCapture, Loc, Ty,
960                              VK_LValue);
961 }
962 
963 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
964                                            BinaryOperatorKind BOK) {
965   D = getCanonicalDecl(D);
966   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
967   assert(
968       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
969       "Additional reduction info may be specified only for reduction items.");
970   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
971   assert(ReductionData.ReductionRange.isInvalid() &&
972          Stack.back().first.back().Directive == OMPD_taskgroup &&
973          "Additional reduction info may be specified only once for reduction "
974          "items.");
975   ReductionData.set(BOK, SR);
976   Expr *&TaskgroupReductionRef =
977       Stack.back().first.back().TaskgroupReductionRef;
978   if (!TaskgroupReductionRef) {
979     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
980                                SemaRef.Context.VoidPtrTy, ".task_red.");
981     TaskgroupReductionRef =
982         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
983   }
984 }
985 
986 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
987                                            const Expr *ReductionRef) {
988   D = getCanonicalDecl(D);
989   assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
990   assert(
991       Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
992       "Additional reduction info may be specified only for reduction items.");
993   ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
994   assert(ReductionData.ReductionRange.isInvalid() &&
995          Stack.back().first.back().Directive == OMPD_taskgroup &&
996          "Additional reduction info may be specified only once for reduction "
997          "items.");
998   ReductionData.set(ReductionRef, SR);
999   Expr *&TaskgroupReductionRef =
1000       Stack.back().first.back().TaskgroupReductionRef;
1001   if (!TaskgroupReductionRef) {
1002     VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1003                                SemaRef.Context.VoidPtrTy, ".task_red.");
1004     TaskgroupReductionRef =
1005         buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
1006   }
1007 }
1008 
1009 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1010     const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1011     Expr *&TaskgroupDescriptor) const {
1012   D = getCanonicalDecl(D);
1013   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1014   if (Stack.back().first.empty())
1015       return DSAVarData();
1016   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1017                 E = Stack.back().first.rend();
1018        I != E; std::advance(I, 1)) {
1019     const DSAInfo &Data = I->SharingMap.lookup(D);
1020     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1021       continue;
1022     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1023     if (!ReductionData.ReductionOp ||
1024         ReductionData.ReductionOp.is<const Expr *>())
1025       return DSAVarData();
1026     SR = ReductionData.ReductionRange;
1027     BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
1028     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1029                                        "expression for the descriptor is not "
1030                                        "set.");
1031     TaskgroupDescriptor = I->TaskgroupReductionRef;
1032     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1033                       Data.PrivateCopy, I->DefaultAttrLoc);
1034   }
1035   return DSAVarData();
1036 }
1037 
1038 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1039     const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1040     Expr *&TaskgroupDescriptor) const {
1041   D = getCanonicalDecl(D);
1042   assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1043   if (Stack.back().first.empty())
1044       return DSAVarData();
1045   for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1046                 E = Stack.back().first.rend();
1047        I != E; std::advance(I, 1)) {
1048     const DSAInfo &Data = I->SharingMap.lookup(D);
1049     if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
1050       continue;
1051     const ReductionData &ReductionData = I->ReductionMap.lookup(D);
1052     if (!ReductionData.ReductionOp ||
1053         !ReductionData.ReductionOp.is<const Expr *>())
1054       return DSAVarData();
1055     SR = ReductionData.ReductionRange;
1056     ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
1057     assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1058                                        "expression for the descriptor is not "
1059                                        "set.");
1060     TaskgroupDescriptor = I->TaskgroupReductionRef;
1061     return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1062                       Data.PrivateCopy, I->DefaultAttrLoc);
1063   }
1064   return DSAVarData();
1065 }
1066 
1067 bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
1068   D = D->getCanonicalDecl();
1069   if (!isStackEmpty()) {
1070     iterator I = Iter, E = Stack.back().first.rend();
1071     Scope *TopScope = nullptr;
1072     while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
1073            !isOpenMPTargetExecutionDirective(I->Directive))
1074       ++I;
1075     if (I == E)
1076       return false;
1077     TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1078     Scope *CurScope = getCurScope();
1079     while (CurScope != TopScope && !CurScope->isDeclScope(D))
1080       CurScope = CurScope->getParent();
1081     return CurScope != TopScope;
1082   }
1083   return false;
1084 }
1085 
1086 static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1087                                   bool AcceptIfMutable = true,
1088                                   bool *IsClassType = nullptr) {
1089   ASTContext &Context = SemaRef.getASTContext();
1090   Type = Type.getNonReferenceType().getCanonicalType();
1091   bool IsConstant = Type.isConstant(Context);
1092   Type = Context.getBaseElementType(Type);
1093   const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1094                                 ? Type->getAsCXXRecordDecl()
1095                                 : nullptr;
1096   if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1097     if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1098       RD = CTD->getTemplatedDecl();
1099   if (IsClassType)
1100     *IsClassType = RD;
1101   return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1102                          RD->hasDefinition() && RD->hasMutableFields());
1103 }
1104 
1105 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1106                                       QualType Type, OpenMPClauseKind CKind,
1107                                       SourceLocation ELoc,
1108                                       bool AcceptIfMutable = true,
1109                                       bool ListItemNotVar = false) {
1110   ASTContext &Context = SemaRef.getASTContext();
1111   bool IsClassType;
1112   if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1113     unsigned Diag = ListItemNotVar
1114                         ? diag::err_omp_const_list_item
1115                         : IsClassType ? diag::err_omp_const_not_mutable_variable
1116                                       : diag::err_omp_const_variable;
1117     SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1118     if (!ListItemNotVar && D) {
1119       const VarDecl *VD = dyn_cast<VarDecl>(D);
1120       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1121                                VarDecl::DeclarationOnly;
1122       SemaRef.Diag(D->getLocation(),
1123                    IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1124           << D;
1125     }
1126     return true;
1127   }
1128   return false;
1129 }
1130 
1131 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1132                                                    bool FromParent) {
1133   D = getCanonicalDecl(D);
1134   DSAVarData DVar;
1135 
1136   auto *VD = dyn_cast<VarDecl>(D);
1137   auto TI = Threadprivates.find(D);
1138   if (TI != Threadprivates.end()) {
1139     DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
1140     DVar.CKind = OMPC_threadprivate;
1141     return DVar;
1142   }
1143   if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
1144     DVar.RefExpr = buildDeclRefExpr(
1145         SemaRef, VD, D->getType().getNonReferenceType(),
1146         VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1147     DVar.CKind = OMPC_threadprivate;
1148     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1149     return DVar;
1150   }
1151   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1152   // in a Construct, C/C++, predetermined, p.1]
1153   //  Variables appearing in threadprivate directives are threadprivate.
1154   if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1155        !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1156          SemaRef.getLangOpts().OpenMPUseTLS &&
1157          SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1158       (VD && VD->getStorageClass() == SC_Register &&
1159        VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1160     DVar.RefExpr = buildDeclRefExpr(
1161         SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1162     DVar.CKind = OMPC_threadprivate;
1163     addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1164     return DVar;
1165   }
1166   if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1167       VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1168       !isLoopControlVariable(D).first) {
1169     iterator IterTarget =
1170         std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1171                      [](const SharingMapTy &Data) {
1172                        return isOpenMPTargetExecutionDirective(Data.Directive);
1173                      });
1174     if (IterTarget != Stack.back().first.rend()) {
1175       iterator ParentIterTarget = std::next(IterTarget, 1);
1176       for (iterator Iter = Stack.back().first.rbegin();
1177            Iter != ParentIterTarget; std::advance(Iter, 1)) {
1178         if (isOpenMPLocal(VD, Iter)) {
1179           DVar.RefExpr =
1180               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1181                                D->getLocation());
1182           DVar.CKind = OMPC_threadprivate;
1183           return DVar;
1184         }
1185       }
1186       if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1187         auto DSAIter = IterTarget->SharingMap.find(D);
1188         if (DSAIter != IterTarget->SharingMap.end() &&
1189             isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1190           DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1191           DVar.CKind = OMPC_threadprivate;
1192           return DVar;
1193         }
1194         iterator End = Stack.back().first.rend();
1195         if (!SemaRef.isOpenMPCapturedByRef(
1196                 D, std::distance(ParentIterTarget, End))) {
1197           DVar.RefExpr =
1198               buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1199                                IterTarget->ConstructLoc);
1200           DVar.CKind = OMPC_threadprivate;
1201           return DVar;
1202         }
1203       }
1204     }
1205   }
1206 
1207   if (isStackEmpty())
1208     // Not in OpenMP execution region and top scope was already checked.
1209     return DVar;
1210 
1211   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1212   // in a Construct, C/C++, predetermined, p.4]
1213   //  Static data members are shared.
1214   // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1215   // in a Construct, C/C++, predetermined, p.7]
1216   //  Variables with static storage duration that are declared in a scope
1217   //  inside the construct are shared.
1218   auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
1219   if (VD && VD->isStaticDataMember()) {
1220     DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
1221     if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1222       return DVar;
1223 
1224     DVar.CKind = OMPC_shared;
1225     return DVar;
1226   }
1227 
1228   // The predetermined shared attribute for const-qualified types having no
1229   // mutable members was removed after OpenMP 3.1.
1230   if (SemaRef.LangOpts.OpenMP <= 31) {
1231     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1232     // in a Construct, C/C++, predetermined, p.6]
1233     //  Variables with const qualified type having no mutable member are
1234     //  shared.
1235     if (isConstNotMutableType(SemaRef, D->getType())) {
1236       // Variables with const-qualified type having no mutable member may be
1237       // listed in a firstprivate clause, even if they are static data members.
1238       DSAVarData DVarTemp = hasInnermostDSA(
1239           D,
1240           [](OpenMPClauseKind C) {
1241             return C == OMPC_firstprivate || C == OMPC_shared;
1242           },
1243           MatchesAlways, FromParent);
1244       if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1245         return DVarTemp;
1246 
1247       DVar.CKind = OMPC_shared;
1248       return DVar;
1249     }
1250   }
1251 
1252   // Explicitly specified attributes and local variables with predetermined
1253   // attributes.
1254   iterator I = Stack.back().first.rbegin();
1255   iterator EndI = Stack.back().first.rend();
1256   if (FromParent && I != EndI)
1257     std::advance(I, 1);
1258   auto It = I->SharingMap.find(D);
1259   if (It != I->SharingMap.end()) {
1260     const DSAInfo &Data = It->getSecond();
1261     DVar.RefExpr = Data.RefExpr.getPointer();
1262     DVar.PrivateCopy = Data.PrivateCopy;
1263     DVar.CKind = Data.Attributes;
1264     DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1265     DVar.DKind = I->Directive;
1266   }
1267 
1268   return DVar;
1269 }
1270 
1271 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1272                                                         bool FromParent) const {
1273   if (isStackEmpty()) {
1274     iterator I;
1275     return getDSA(I, D);
1276   }
1277   D = getCanonicalDecl(D);
1278   iterator StartI = Stack.back().first.rbegin();
1279   iterator EndI = Stack.back().first.rend();
1280   if (FromParent && StartI != EndI)
1281     std::advance(StartI, 1);
1282   return getDSA(StartI, D);
1283 }
1284 
1285 const DSAStackTy::DSAVarData
1286 DSAStackTy::hasDSA(ValueDecl *D,
1287                    const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1288                    const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1289                    bool FromParent) const {
1290   if (isStackEmpty())
1291     return {};
1292   D = getCanonicalDecl(D);
1293   iterator I = Stack.back().first.rbegin();
1294   iterator EndI = Stack.back().first.rend();
1295   if (FromParent && I != EndI)
1296     std::advance(I, 1);
1297   for (; I != EndI; std::advance(I, 1)) {
1298     if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
1299       continue;
1300     iterator NewI = I;
1301     DSAVarData DVar = getDSA(NewI, D);
1302     if (I == NewI && CPred(DVar.CKind))
1303       return DVar;
1304   }
1305   return {};
1306 }
1307 
1308 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1309     ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1310     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1311     bool FromParent) const {
1312   if (isStackEmpty())
1313     return {};
1314   D = getCanonicalDecl(D);
1315   iterator StartI = Stack.back().first.rbegin();
1316   iterator EndI = Stack.back().first.rend();
1317   if (FromParent && StartI != EndI)
1318     std::advance(StartI, 1);
1319   if (StartI == EndI || !DPred(StartI->Directive))
1320     return {};
1321   iterator NewI = StartI;
1322   DSAVarData DVar = getDSA(NewI, D);
1323   return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
1324 }
1325 
1326 bool DSAStackTy::hasExplicitDSA(
1327     const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1328     unsigned Level, bool NotLastprivate) const {
1329   if (isStackEmpty())
1330     return false;
1331   D = getCanonicalDecl(D);
1332   auto StartI = Stack.back().first.begin();
1333   auto EndI = Stack.back().first.end();
1334   if (std::distance(StartI, EndI) <= (int)Level)
1335     return false;
1336   std::advance(StartI, Level);
1337   auto I = StartI->SharingMap.find(D);
1338   if ((I != StartI->SharingMap.end()) &&
1339          I->getSecond().RefExpr.getPointer() &&
1340          CPred(I->getSecond().Attributes) &&
1341          (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1342     return true;
1343   // Check predetermined rules for the loop control variables.
1344   auto LI = StartI->LCVMap.find(D);
1345   if (LI != StartI->LCVMap.end())
1346     return CPred(OMPC_private);
1347   return false;
1348 }
1349 
1350 bool DSAStackTy::hasExplicitDirective(
1351     const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1352     unsigned Level) const {
1353   if (isStackEmpty())
1354     return false;
1355   auto StartI = Stack.back().first.begin();
1356   auto EndI = Stack.back().first.end();
1357   if (std::distance(StartI, EndI) <= (int)Level)
1358     return false;
1359   std::advance(StartI, Level);
1360   return DPred(StartI->Directive);
1361 }
1362 
1363 bool DSAStackTy::hasDirective(
1364     const llvm::function_ref<bool(OpenMPDirectiveKind,
1365                                   const DeclarationNameInfo &, SourceLocation)>
1366         DPred,
1367     bool FromParent) const {
1368   // We look only in the enclosing region.
1369   if (isStackEmpty())
1370     return false;
1371   auto StartI = std::next(Stack.back().first.rbegin());
1372   auto EndI = Stack.back().first.rend();
1373   if (FromParent && StartI != EndI)
1374     StartI = std::next(StartI);
1375   for (auto I = StartI, EE = EndI; I != EE; ++I) {
1376     if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1377       return true;
1378   }
1379   return false;
1380 }
1381 
1382 void Sema::InitDataSharingAttributesStack() {
1383   VarDataSharingAttributesStack = new DSAStackTy(*this);
1384 }
1385 
1386 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1387 
1388 void Sema::pushOpenMPFunctionRegion() {
1389   DSAStack->pushFunction();
1390 }
1391 
1392 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1393   DSAStack->popFunction(OldFSI);
1394 }
1395 
1396 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
1397   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1398 
1399   ASTContext &Ctx = getASTContext();
1400   bool IsByRef = true;
1401 
1402   // Find the directive that is associated with the provided scope.
1403   D = cast<ValueDecl>(D->getCanonicalDecl());
1404   QualType Ty = D->getType();
1405 
1406   if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
1407     // This table summarizes how a given variable should be passed to the device
1408     // given its type and the clauses where it appears. This table is based on
1409     // the description in OpenMP 4.5 [2.10.4, target Construct] and
1410     // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1411     //
1412     // =========================================================================
1413     // | type |  defaultmap   | pvt | first | is_device_ptr |    map   | res.  |
1414     // |      |(tofrom:scalar)|     |  pvt  |               |          |       |
1415     // =========================================================================
1416     // | scl  |               |     |       |       -       |          | bycopy|
1417     // | scl  |               |  -  |   x   |       -       |     -    | bycopy|
1418     // | scl  |               |  x  |   -   |       -       |     -    | null  |
1419     // | scl  |       x       |     |       |       -       |          | byref |
1420     // | scl  |       x       |  -  |   x   |       -       |     -    | bycopy|
1421     // | scl  |       x       |  x  |   -   |       -       |     -    | null  |
1422     // | scl  |               |  -  |   -   |       -       |     x    | byref |
1423     // | scl  |       x       |  -  |   -   |       -       |     x    | byref |
1424     //
1425     // | agg  |      n.a.     |     |       |       -       |          | byref |
1426     // | agg  |      n.a.     |  -  |   x   |       -       |     -    | byref |
1427     // | agg  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1428     // | agg  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1429     // | agg  |      n.a.     |  -  |   -   |       -       |    x[]   | byref |
1430     //
1431     // | ptr  |      n.a.     |     |       |       -       |          | bycopy|
1432     // | ptr  |      n.a.     |  -  |   x   |       -       |     -    | bycopy|
1433     // | ptr  |      n.a.     |  x  |   -   |       -       |     -    | null  |
1434     // | ptr  |      n.a.     |  -  |   -   |       -       |     x    | byref |
1435     // | ptr  |      n.a.     |  -  |   -   |       -       |    x[]   | bycopy|
1436     // | ptr  |      n.a.     |  -  |   -   |       x       |          | bycopy|
1437     // | ptr  |      n.a.     |  -  |   -   |       x       |     x    | bycopy|
1438     // | ptr  |      n.a.     |  -  |   -   |       x       |    x[]   | bycopy|
1439     // =========================================================================
1440     // Legend:
1441     //  scl - scalar
1442     //  ptr - pointer
1443     //  agg - aggregate
1444     //  x - applies
1445     //  - - invalid in this combination
1446     //  [] - mapped with an array section
1447     //  byref - should be mapped by reference
1448     //  byval - should be mapped by value
1449     //  null - initialize a local variable to null on the device
1450     //
1451     // Observations:
1452     //  - All scalar declarations that show up in a map clause have to be passed
1453     //    by reference, because they may have been mapped in the enclosing data
1454     //    environment.
1455     //  - If the scalar value does not fit the size of uintptr, it has to be
1456     //    passed by reference, regardless the result in the table above.
1457     //  - For pointers mapped by value that have either an implicit map or an
1458     //    array section, the runtime library may pass the NULL value to the
1459     //    device instead of the value passed to it by the compiler.
1460 
1461     if (Ty->isReferenceType())
1462       Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1463 
1464     // Locate map clauses and see if the variable being captured is referred to
1465     // in any of those clauses. Here we only care about variables, not fields,
1466     // because fields are part of aggregates.
1467     bool IsVariableUsedInMapClause = false;
1468     bool IsVariableAssociatedWithSection = false;
1469 
1470     DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1471         D, Level,
1472         [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1473             OMPClauseMappableExprCommon::MappableExprComponentListRef
1474                 MapExprComponents,
1475             OpenMPClauseKind WhereFoundClauseKind) {
1476           // Only the map clause information influences how a variable is
1477           // captured. E.g. is_device_ptr does not require changing the default
1478           // behavior.
1479           if (WhereFoundClauseKind != OMPC_map)
1480             return false;
1481 
1482           auto EI = MapExprComponents.rbegin();
1483           auto EE = MapExprComponents.rend();
1484 
1485           assert(EI != EE && "Invalid map expression!");
1486 
1487           if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1488             IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1489 
1490           ++EI;
1491           if (EI == EE)
1492             return false;
1493 
1494           if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1495               isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1496               isa<MemberExpr>(EI->getAssociatedExpression())) {
1497             IsVariableAssociatedWithSection = true;
1498             // There is nothing more we need to know about this variable.
1499             return true;
1500           }
1501 
1502           // Keep looking for more map info.
1503           return false;
1504         });
1505 
1506     if (IsVariableUsedInMapClause) {
1507       // If variable is identified in a map clause it is always captured by
1508       // reference except if it is a pointer that is dereferenced somehow.
1509       IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1510     } else {
1511       // By default, all the data that has a scalar type is mapped by copy
1512       // (except for reduction variables).
1513       IsByRef =
1514           (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1515            !Ty->isAnyPointerType()) ||
1516           !Ty->isScalarType() ||
1517           DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1518           DSAStack->hasExplicitDSA(
1519               D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
1520     }
1521   }
1522 
1523   if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
1524     IsByRef =
1525         ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1526           !Ty->isAnyPointerType()) ||
1527          !DSAStack->hasExplicitDSA(
1528              D,
1529              [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1530              Level, /*NotLastprivate=*/true)) &&
1531         // If the variable is artificial and must be captured by value - try to
1532         // capture by value.
1533         !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1534           !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
1535   }
1536 
1537   // When passing data by copy, we need to make sure it fits the uintptr size
1538   // and alignment, because the runtime library only deals with uintptr types.
1539   // If it does not fit the uintptr size, we need to pass the data by reference
1540   // instead.
1541   if (!IsByRef &&
1542       (Ctx.getTypeSizeInChars(Ty) >
1543            Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
1544        Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
1545     IsByRef = true;
1546   }
1547 
1548   return IsByRef;
1549 }
1550 
1551 unsigned Sema::getOpenMPNestingLevel() const {
1552   assert(getLangOpts().OpenMP);
1553   return DSAStack->getNestingLevel();
1554 }
1555 
1556 bool Sema::isInOpenMPTargetExecutionDirective() const {
1557   return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1558           !DSAStack->isClauseParsingMode()) ||
1559          DSAStack->hasDirective(
1560              [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1561                 SourceLocation) -> bool {
1562                return isOpenMPTargetExecutionDirective(K);
1563              },
1564              false);
1565 }
1566 
1567 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
1568   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1569   D = getCanonicalDecl(D);
1570 
1571   // If we are attempting to capture a global variable in a directive with
1572   // 'target' we return true so that this global is also mapped to the device.
1573   //
1574   auto *VD = dyn_cast<VarDecl>(D);
1575   if (VD && !VD->hasLocalStorage()) {
1576     if (isInOpenMPDeclareTargetContext() &&
1577         (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1578       // Try to mark variable as declare target if it is used in capturing
1579       // regions.
1580       if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1581         checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
1582       return nullptr;
1583     } else if (isInOpenMPTargetExecutionDirective()) {
1584       // If the declaration is enclosed in a 'declare target' directive,
1585       // then it should not be captured.
1586       //
1587       if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1588         return nullptr;
1589       return VD;
1590     }
1591   }
1592   // Capture variables captured by reference in lambdas for target-based
1593   // directives.
1594   if (VD && !DSAStack->isClauseParsingMode()) {
1595     if (const auto *RD = VD->getType()
1596                              .getCanonicalType()
1597                              .getNonReferenceType()
1598                              ->getAsCXXRecordDecl()) {
1599       bool SavedForceCaptureByReferenceInTargetExecutable =
1600           DSAStack->isForceCaptureByReferenceInTargetExecutable();
1601       DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
1602       if (RD->isLambda()) {
1603         llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1604         FieldDecl *ThisCapture;
1605         RD->getCaptureFields(Captures, ThisCapture);
1606         for (const LambdaCapture &LC : RD->captures()) {
1607           if (LC.getCaptureKind() == LCK_ByRef) {
1608             VarDecl *VD = LC.getCapturedVar();
1609             DeclContext *VDC = VD->getDeclContext();
1610             if (!VDC->Encloses(CurContext))
1611               continue;
1612             DSAStackTy::DSAVarData DVarPrivate =
1613                 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1614             // Do not capture already captured variables.
1615             if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1616                 DVarPrivate.CKind == OMPC_unknown &&
1617                 !DSAStack->checkMappableExprComponentListsForDecl(
1618                     D, /*CurrentRegionOnly=*/true,
1619                     [](OMPClauseMappableExprCommon::
1620                            MappableExprComponentListRef,
1621                        OpenMPClauseKind) { return true; }))
1622               MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1623           } else if (LC.getCaptureKind() == LCK_This) {
1624             QualType ThisTy = getCurrentThisType();
1625             if (!ThisTy.isNull() &&
1626                 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1627               CheckCXXThisCapture(LC.getLocation());
1628           }
1629         }
1630       }
1631       DSAStack->setForceCaptureByReferenceInTargetExecutable(
1632           SavedForceCaptureByReferenceInTargetExecutable);
1633     }
1634   }
1635 
1636   if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1637       (!DSAStack->isClauseParsingMode() ||
1638        DSAStack->getParentDirective() != OMPD_unknown)) {
1639     auto &&Info = DSAStack->isLoopControlVariable(D);
1640     if (Info.first ||
1641         (VD && VD->hasLocalStorage() &&
1642          isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
1643         (VD && DSAStack->isForceVarCapturing()))
1644       return VD ? VD : Info.second;
1645     DSAStackTy::DSAVarData DVarPrivate =
1646         DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
1647     if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
1648       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1649     DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1650                                    [](OpenMPDirectiveKind) { return true; },
1651                                    DSAStack->isClauseParsingMode());
1652     if (DVarPrivate.CKind != OMPC_unknown)
1653       return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
1654   }
1655   return nullptr;
1656 }
1657 
1658 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1659                                         unsigned Level) const {
1660   SmallVector<OpenMPDirectiveKind, 4> Regions;
1661   getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1662   FunctionScopesIndex -= Regions.size();
1663 }
1664 
1665 void Sema::startOpenMPLoop() {
1666   assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1667   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1668     DSAStack->loopInit();
1669 }
1670 
1671 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
1672   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1673   if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1674     if (DSAStack->getAssociatedLoops() > 0 &&
1675         !DSAStack->isLoopStarted()) {
1676       DSAStack->resetPossibleLoopCounter(D);
1677       DSAStack->loopStart();
1678       return true;
1679     }
1680     if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1681          DSAStack->isLoopControlVariable(D).first) &&
1682         !DSAStack->hasExplicitDSA(
1683             D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1684         !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1685       return true;
1686   }
1687   return DSAStack->hasExplicitDSA(
1688              D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
1689          (DSAStack->isClauseParsingMode() &&
1690           DSAStack->getClauseParsingMode() == OMPC_private) ||
1691          // Consider taskgroup reduction descriptor variable a private to avoid
1692          // possible capture in the region.
1693          (DSAStack->hasExplicitDirective(
1694               [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1695               Level) &&
1696           DSAStack->isTaskgroupReductionRef(D, Level));
1697 }
1698 
1699 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1700                                 unsigned Level) {
1701   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1702   D = getCanonicalDecl(D);
1703   OpenMPClauseKind OMPC = OMPC_unknown;
1704   for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1705     const unsigned NewLevel = I - 1;
1706     if (DSAStack->hasExplicitDSA(D,
1707                                  [&OMPC](const OpenMPClauseKind K) {
1708                                    if (isOpenMPPrivate(K)) {
1709                                      OMPC = K;
1710                                      return true;
1711                                    }
1712                                    return false;
1713                                  },
1714                                  NewLevel))
1715       break;
1716     if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1717             D, NewLevel,
1718             [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1719                OpenMPClauseKind) { return true; })) {
1720       OMPC = OMPC_map;
1721       break;
1722     }
1723     if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1724                                        NewLevel)) {
1725       OMPC = OMPC_map;
1726       if (D->getType()->isScalarType() &&
1727           DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1728               DefaultMapAttributes::DMA_tofrom_scalar)
1729         OMPC = OMPC_firstprivate;
1730       break;
1731     }
1732   }
1733   if (OMPC != OMPC_unknown)
1734     FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1735 }
1736 
1737 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1738                                       unsigned Level) const {
1739   assert(LangOpts.OpenMP && "OpenMP is not allowed");
1740   // Return true if the current level is no longer enclosed in a target region.
1741 
1742   const auto *VD = dyn_cast<VarDecl>(D);
1743   return VD && !VD->hasLocalStorage() &&
1744          DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1745                                         Level);
1746 }
1747 
1748 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
1749 
1750 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1751                                const DeclarationNameInfo &DirName,
1752                                Scope *CurScope, SourceLocation Loc) {
1753   DSAStack->push(DKind, DirName, CurScope, Loc);
1754   PushExpressionEvaluationContext(
1755       ExpressionEvaluationContext::PotentiallyEvaluated);
1756 }
1757 
1758 void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1759   DSAStack->setClauseParsingMode(K);
1760 }
1761 
1762 void Sema::EndOpenMPClause() {
1763   DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
1764 }
1765 
1766 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
1767   // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1768   //  A variable of class type (or array thereof) that appears in a lastprivate
1769   //  clause requires an accessible, unambiguous default constructor for the
1770   //  class type, unless the list item is also specified in a firstprivate
1771   //  clause.
1772   if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1773     for (OMPClause *C : D->clauses()) {
1774       if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1775         SmallVector<Expr *, 8> PrivateCopies;
1776         for (Expr *DE : Clause->varlists()) {
1777           if (DE->isValueDependent() || DE->isTypeDependent()) {
1778             PrivateCopies.push_back(nullptr);
1779             continue;
1780           }
1781           auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
1782           auto *VD = cast<VarDecl>(DRE->getDecl());
1783           QualType Type = VD->getType().getNonReferenceType();
1784           const DSAStackTy::DSAVarData DVar =
1785               DSAStack->getTopDSA(VD, /*FromParent=*/false);
1786           if (DVar.CKind == OMPC_lastprivate) {
1787             // Generate helper private variable and initialize it with the
1788             // default value. The address of the original variable is replaced
1789             // by the address of the new private variable in CodeGen. This new
1790             // variable is not added to IdResolver, so the code in the OpenMP
1791             // region uses original variable for proper diagnostics.
1792             VarDecl *VDPrivate = buildVarDecl(
1793                 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
1794                 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
1795             ActOnUninitializedDecl(VDPrivate);
1796             if (VDPrivate->isInvalidDecl())
1797               continue;
1798             PrivateCopies.push_back(buildDeclRefExpr(
1799                 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
1800           } else {
1801             // The variable is also a firstprivate, so initialization sequence
1802             // for private copy is generated already.
1803             PrivateCopies.push_back(nullptr);
1804           }
1805         }
1806         // Set initializers to private copies if no errors were found.
1807         if (PrivateCopies.size() == Clause->varlist_size())
1808           Clause->setPrivateCopies(PrivateCopies);
1809       }
1810     }
1811   }
1812 
1813   DSAStack->pop();
1814   DiscardCleanupsInEvaluationContext();
1815   PopExpressionEvaluationContext();
1816 }
1817 
1818 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1819                                      Expr *NumIterations, Sema &SemaRef,
1820                                      Scope *S, DSAStackTy *Stack);
1821 
1822 namespace {
1823 
1824 class VarDeclFilterCCC final : public CorrectionCandidateCallback {
1825 private:
1826   Sema &SemaRef;
1827 
1828 public:
1829   explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
1830   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1831     NamedDecl *ND = Candidate.getCorrectionDecl();
1832     if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
1833       return VD->hasGlobalStorage() &&
1834              SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1835                                    SemaRef.getCurScope());
1836     }
1837     return false;
1838   }
1839 };
1840 
1841 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
1842 private:
1843   Sema &SemaRef;
1844 
1845 public:
1846   explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1847   bool ValidateCandidate(const TypoCorrection &Candidate) override {
1848     NamedDecl *ND = Candidate.getCorrectionDecl();
1849     if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
1850       return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1851                                    SemaRef.getCurScope());
1852     }
1853     return false;
1854   }
1855 };
1856 
1857 } // namespace
1858 
1859 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1860                                          CXXScopeSpec &ScopeSpec,
1861                                          const DeclarationNameInfo &Id) {
1862   LookupResult Lookup(*this, Id, LookupOrdinaryName);
1863   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1864 
1865   if (Lookup.isAmbiguous())
1866     return ExprError();
1867 
1868   VarDecl *VD;
1869   if (!Lookup.isSingleResult()) {
1870     if (TypoCorrection Corrected = CorrectTypo(
1871             Id, LookupOrdinaryName, CurScope, nullptr,
1872             llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
1873       diagnoseTypo(Corrected,
1874                    PDiag(Lookup.empty()
1875                              ? diag::err_undeclared_var_use_suggest
1876                              : diag::err_omp_expected_var_arg_suggest)
1877                        << Id.getName());
1878       VD = Corrected.getCorrectionDeclAs<VarDecl>();
1879     } else {
1880       Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1881                                        : diag::err_omp_expected_var_arg)
1882           << Id.getName();
1883       return ExprError();
1884     }
1885   } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1886     Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1887     Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1888     return ExprError();
1889   }
1890   Lookup.suppressDiagnostics();
1891 
1892   // OpenMP [2.9.2, Syntax, C/C++]
1893   //   Variables must be file-scope, namespace-scope, or static block-scope.
1894   if (!VD->hasGlobalStorage()) {
1895     Diag(Id.getLoc(), diag::err_omp_global_var_arg)
1896         << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1897     bool IsDecl =
1898         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1899     Diag(VD->getLocation(),
1900          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1901         << VD;
1902     return ExprError();
1903   }
1904 
1905   VarDecl *CanonicalVD = VD->getCanonicalDecl();
1906   NamedDecl *ND = CanonicalVD;
1907   // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1908   //   A threadprivate directive for file-scope variables must appear outside
1909   //   any definition or declaration.
1910   if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1911       !getCurLexicalContext()->isTranslationUnit()) {
1912     Diag(Id.getLoc(), diag::err_omp_var_scope)
1913         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1914     bool IsDecl =
1915         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1916     Diag(VD->getLocation(),
1917          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1918         << VD;
1919     return ExprError();
1920   }
1921   // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1922   //   A threadprivate directive for static class member variables must appear
1923   //   in the class definition, in the same scope in which the member
1924   //   variables are declared.
1925   if (CanonicalVD->isStaticDataMember() &&
1926       !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1927     Diag(Id.getLoc(), diag::err_omp_var_scope)
1928         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1929     bool IsDecl =
1930         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1931     Diag(VD->getLocation(),
1932          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1933         << VD;
1934     return ExprError();
1935   }
1936   // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1937   //   A threadprivate directive for namespace-scope variables must appear
1938   //   outside any definition or declaration other than the namespace
1939   //   definition itself.
1940   if (CanonicalVD->getDeclContext()->isNamespace() &&
1941       (!getCurLexicalContext()->isFileContext() ||
1942        !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1943     Diag(Id.getLoc(), diag::err_omp_var_scope)
1944         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1945     bool IsDecl =
1946         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1947     Diag(VD->getLocation(),
1948          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1949         << VD;
1950     return ExprError();
1951   }
1952   // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1953   //   A threadprivate directive for static block-scope variables must appear
1954   //   in the scope of the variable and not in a nested scope.
1955   if (CanonicalVD->isStaticLocal() && CurScope &&
1956       !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
1957     Diag(Id.getLoc(), diag::err_omp_var_scope)
1958         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1959     bool IsDecl =
1960         VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1961     Diag(VD->getLocation(),
1962          IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1963         << VD;
1964     return ExprError();
1965   }
1966 
1967   // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1968   //   A threadprivate directive must lexically precede all references to any
1969   //   of the variables in its list.
1970   if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
1971     Diag(Id.getLoc(), diag::err_omp_var_used)
1972         << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1973     return ExprError();
1974   }
1975 
1976   QualType ExprType = VD->getType().getNonReferenceType();
1977   return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1978                              SourceLocation(), VD,
1979                              /*RefersToEnclosingVariableOrCapture=*/false,
1980                              Id.getLoc(), ExprType, VK_LValue);
1981 }
1982 
1983 Sema::DeclGroupPtrTy
1984 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1985                                         ArrayRef<Expr *> VarList) {
1986   if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
1987     CurContext->addDecl(D);
1988     return DeclGroupPtrTy::make(DeclGroupRef(D));
1989   }
1990   return nullptr;
1991 }
1992 
1993 namespace {
1994 class LocalVarRefChecker final
1995     : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1996   Sema &SemaRef;
1997 
1998 public:
1999   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2000     if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2001       if (VD->hasLocalStorage()) {
2002         SemaRef.Diag(E->getBeginLoc(),
2003                      diag::err_omp_local_var_in_threadprivate_init)
2004             << E->getSourceRange();
2005         SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2006             << VD << VD->getSourceRange();
2007         return true;
2008       }
2009     }
2010     return false;
2011   }
2012   bool VisitStmt(const Stmt *S) {
2013     for (const Stmt *Child : S->children()) {
2014       if (Child && Visit(Child))
2015         return true;
2016     }
2017     return false;
2018   }
2019   explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
2020 };
2021 } // namespace
2022 
2023 OMPThreadPrivateDecl *
2024 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
2025   SmallVector<Expr *, 8> Vars;
2026   for (Expr *RefExpr : VarList) {
2027     auto *DE = cast<DeclRefExpr>(RefExpr);
2028     auto *VD = cast<VarDecl>(DE->getDecl());
2029     SourceLocation ILoc = DE->getExprLoc();
2030 
2031     // Mark variable as used.
2032     VD->setReferenced();
2033     VD->markUsed(Context);
2034 
2035     QualType QType = VD->getType();
2036     if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2037       // It will be analyzed later.
2038       Vars.push_back(DE);
2039       continue;
2040     }
2041 
2042     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2043     //   A threadprivate variable must not have an incomplete type.
2044     if (RequireCompleteType(ILoc, VD->getType(),
2045                             diag::err_omp_threadprivate_incomplete_type)) {
2046       continue;
2047     }
2048 
2049     // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2050     //   A threadprivate variable must not have a reference type.
2051     if (VD->getType()->isReferenceType()) {
2052       Diag(ILoc, diag::err_omp_ref_type_arg)
2053           << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2054       bool IsDecl =
2055           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2056       Diag(VD->getLocation(),
2057            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2058           << VD;
2059       continue;
2060     }
2061 
2062     // Check if this is a TLS variable. If TLS is not being supported, produce
2063     // the corresponding diagnostic.
2064     if ((VD->getTLSKind() != VarDecl::TLS_None &&
2065          !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2066            getLangOpts().OpenMPUseTLS &&
2067            getASTContext().getTargetInfo().isTLSSupported())) ||
2068         (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2069          !VD->isLocalVarDecl())) {
2070       Diag(ILoc, diag::err_omp_var_thread_local)
2071           << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
2072       bool IsDecl =
2073           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2074       Diag(VD->getLocation(),
2075            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2076           << VD;
2077       continue;
2078     }
2079 
2080     // Check if initial value of threadprivate variable reference variable with
2081     // local storage (it is not supported by runtime).
2082     if (const Expr *Init = VD->getAnyInitializer()) {
2083       LocalVarRefChecker Checker(*this);
2084       if (Checker.Visit(Init))
2085         continue;
2086     }
2087 
2088     Vars.push_back(RefExpr);
2089     DSAStack->addDSA(VD, DE, OMPC_threadprivate);
2090     VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2091         Context, SourceRange(Loc, Loc)));
2092     if (ASTMutationListener *ML = Context.getASTMutationListener())
2093       ML->DeclarationMarkedOpenMPThreadPrivate(VD);
2094   }
2095   OMPThreadPrivateDecl *D = nullptr;
2096   if (!Vars.empty()) {
2097     D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2098                                      Vars);
2099     D->setAccess(AS_public);
2100   }
2101   return D;
2102 }
2103 
2104 Sema::DeclGroupPtrTy
2105 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2106                                    ArrayRef<OMPClause *> ClauseList) {
2107   OMPRequiresDecl *D = nullptr;
2108   if (!CurContext->isFileContext()) {
2109     Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2110   } else {
2111     D = CheckOMPRequiresDecl(Loc, ClauseList);
2112     if (D) {
2113       CurContext->addDecl(D);
2114       DSAStack->addRequiresDecl(D);
2115     }
2116   }
2117   return DeclGroupPtrTy::make(DeclGroupRef(D));
2118 }
2119 
2120 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2121                                             ArrayRef<OMPClause *> ClauseList) {
2122   if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2123     return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2124                                    ClauseList);
2125   return nullptr;
2126 }
2127 
2128 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2129                               const ValueDecl *D,
2130                               const DSAStackTy::DSAVarData &DVar,
2131                               bool IsLoopIterVar = false) {
2132   if (DVar.RefExpr) {
2133     SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2134         << getOpenMPClauseName(DVar.CKind);
2135     return;
2136   }
2137   enum {
2138     PDSA_StaticMemberShared,
2139     PDSA_StaticLocalVarShared,
2140     PDSA_LoopIterVarPrivate,
2141     PDSA_LoopIterVarLinear,
2142     PDSA_LoopIterVarLastprivate,
2143     PDSA_ConstVarShared,
2144     PDSA_GlobalVarShared,
2145     PDSA_TaskVarFirstprivate,
2146     PDSA_LocalVarPrivate,
2147     PDSA_Implicit
2148   } Reason = PDSA_Implicit;
2149   bool ReportHint = false;
2150   auto ReportLoc = D->getLocation();
2151   auto *VD = dyn_cast<VarDecl>(D);
2152   if (IsLoopIterVar) {
2153     if (DVar.CKind == OMPC_private)
2154       Reason = PDSA_LoopIterVarPrivate;
2155     else if (DVar.CKind == OMPC_lastprivate)
2156       Reason = PDSA_LoopIterVarLastprivate;
2157     else
2158       Reason = PDSA_LoopIterVarLinear;
2159   } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2160              DVar.CKind == OMPC_firstprivate) {
2161     Reason = PDSA_TaskVarFirstprivate;
2162     ReportLoc = DVar.ImplicitDSALoc;
2163   } else if (VD && VD->isStaticLocal())
2164     Reason = PDSA_StaticLocalVarShared;
2165   else if (VD && VD->isStaticDataMember())
2166     Reason = PDSA_StaticMemberShared;
2167   else if (VD && VD->isFileVarDecl())
2168     Reason = PDSA_GlobalVarShared;
2169   else if (D->getType().isConstant(SemaRef.getASTContext()))
2170     Reason = PDSA_ConstVarShared;
2171   else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
2172     ReportHint = true;
2173     Reason = PDSA_LocalVarPrivate;
2174   }
2175   if (Reason != PDSA_Implicit) {
2176     SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
2177         << Reason << ReportHint
2178         << getOpenMPDirectiveName(Stack->getCurrentDirective());
2179   } else if (DVar.ImplicitDSALoc.isValid()) {
2180     SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2181         << getOpenMPClauseName(DVar.CKind);
2182   }
2183 }
2184 
2185 namespace {
2186 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
2187   DSAStackTy *Stack;
2188   Sema &SemaRef;
2189   bool ErrorFound = false;
2190   CapturedStmt *CS = nullptr;
2191   llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2192   llvm::SmallVector<Expr *, 4> ImplicitMap;
2193   Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2194   llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
2195 
2196   void VisitSubCaptures(OMPExecutableDirective *S) {
2197     // Check implicitly captured variables.
2198     if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2199       return;
2200     for (const CapturedStmt::Capture &Cap :
2201          S->getInnermostCapturedStmt()->captures()) {
2202       if (!Cap.capturesVariable())
2203         continue;
2204       VarDecl *VD = Cap.getCapturedVar();
2205       // Do not try to map the variable if it or its sub-component was mapped
2206       // already.
2207       if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2208           Stack->checkMappableExprComponentListsForDecl(
2209               VD, /*CurrentRegionOnly=*/true,
2210               [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2211                  OpenMPClauseKind) { return true; }))
2212         continue;
2213       DeclRefExpr *DRE = buildDeclRefExpr(
2214           SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2215           Cap.getLocation(), /*RefersToCapture=*/true);
2216       Visit(DRE);
2217     }
2218   }
2219 
2220 public:
2221   void VisitDeclRefExpr(DeclRefExpr *E) {
2222     if (E->isTypeDependent() || E->isValueDependent() ||
2223         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2224       return;
2225     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
2226       VD = VD->getCanonicalDecl();
2227       // Skip internally declared variables.
2228       if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
2229         return;
2230 
2231       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
2232       // Check if the variable has explicit DSA set and stop analysis if it so.
2233       if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
2234         return;
2235 
2236       // Skip internally declared static variables.
2237       llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2238           OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2239       if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2240           (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
2241         return;
2242 
2243       SourceLocation ELoc = E->getExprLoc();
2244       OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2245       // The default(none) clause requires that each variable that is referenced
2246       // in the construct, and does not have a predetermined data-sharing
2247       // attribute, must have its data-sharing attribute explicitly determined
2248       // by being listed in a data-sharing attribute clause.
2249       if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
2250           isImplicitOrExplicitTaskingRegion(DKind) &&
2251           VarsWithInheritedDSA.count(VD) == 0) {
2252         VarsWithInheritedDSA[VD] = E;
2253         return;
2254       }
2255 
2256       if (isOpenMPTargetExecutionDirective(DKind) &&
2257           !Stack->isLoopControlVariable(VD).first) {
2258         if (!Stack->checkMappableExprComponentListsForDecl(
2259                 VD, /*CurrentRegionOnly=*/true,
2260                 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2261                        StackComponents,
2262                    OpenMPClauseKind) {
2263                   // Variable is used if it has been marked as an array, array
2264                   // section or the variable iself.
2265                   return StackComponents.size() == 1 ||
2266                          std::all_of(
2267                              std::next(StackComponents.rbegin()),
2268                              StackComponents.rend(),
2269                              [](const OMPClauseMappableExprCommon::
2270                                     MappableComponent &MC) {
2271                                return MC.getAssociatedDeclaration() ==
2272                                           nullptr &&
2273                                       (isa<OMPArraySectionExpr>(
2274                                            MC.getAssociatedExpression()) ||
2275                                        isa<ArraySubscriptExpr>(
2276                                            MC.getAssociatedExpression()));
2277                              });
2278                 })) {
2279           bool IsFirstprivate = false;
2280           // By default lambdas are captured as firstprivates.
2281           if (const auto *RD =
2282                   VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
2283             IsFirstprivate = RD->isLambda();
2284           IsFirstprivate =
2285               IsFirstprivate ||
2286               (VD->getType().getNonReferenceType()->isScalarType() &&
2287                Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
2288           if (IsFirstprivate)
2289             ImplicitFirstprivate.emplace_back(E);
2290           else
2291             ImplicitMap.emplace_back(E);
2292           return;
2293         }
2294       }
2295 
2296       // OpenMP [2.9.3.6, Restrictions, p.2]
2297       //  A list item that appears in a reduction clause of the innermost
2298       //  enclosing worksharing or parallel construct may not be accessed in an
2299       //  explicit task.
2300       DVar = Stack->hasInnermostDSA(
2301           VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2302           [](OpenMPDirectiveKind K) {
2303             return isOpenMPParallelDirective(K) ||
2304                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2305           },
2306           /*FromParent=*/true);
2307       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2308         ErrorFound = true;
2309         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2310         reportOriginalDsa(SemaRef, Stack, VD, DVar);
2311         return;
2312       }
2313 
2314       // Define implicit data-sharing attributes for task.
2315       DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
2316       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2317           !Stack->isLoopControlVariable(VD).first)
2318         ImplicitFirstprivate.push_back(E);
2319     }
2320   }
2321   void VisitMemberExpr(MemberExpr *E) {
2322     if (E->isTypeDependent() || E->isValueDependent() ||
2323         E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2324       return;
2325     auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2326     OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
2327     if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
2328       if (!FD)
2329         return;
2330       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
2331       // Check if the variable has explicit DSA set and stop analysis if it
2332       // so.
2333       if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2334         return;
2335 
2336       if (isOpenMPTargetExecutionDirective(DKind) &&
2337           !Stack->isLoopControlVariable(FD).first &&
2338           !Stack->checkMappableExprComponentListsForDecl(
2339               FD, /*CurrentRegionOnly=*/true,
2340               [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2341                      StackComponents,
2342                  OpenMPClauseKind) {
2343                 return isa<CXXThisExpr>(
2344                     cast<MemberExpr>(
2345                         StackComponents.back().getAssociatedExpression())
2346                         ->getBase()
2347                         ->IgnoreParens());
2348               })) {
2349         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2350         //  A bit-field cannot appear in a map clause.
2351         //
2352         if (FD->isBitField())
2353           return;
2354 
2355         // Check to see if the member expression is referencing a class that
2356         // has already been explicitly mapped
2357         if (Stack->isClassPreviouslyMapped(TE->getType()))
2358           return;
2359 
2360         ImplicitMap.emplace_back(E);
2361         return;
2362       }
2363 
2364       SourceLocation ELoc = E->getExprLoc();
2365       // OpenMP [2.9.3.6, Restrictions, p.2]
2366       //  A list item that appears in a reduction clause of the innermost
2367       //  enclosing worksharing or parallel construct may not be accessed in
2368       //  an  explicit task.
2369       DVar = Stack->hasInnermostDSA(
2370           FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2371           [](OpenMPDirectiveKind K) {
2372             return isOpenMPParallelDirective(K) ||
2373                    isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2374           },
2375           /*FromParent=*/true);
2376       if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2377         ErrorFound = true;
2378         SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2379         reportOriginalDsa(SemaRef, Stack, FD, DVar);
2380         return;
2381       }
2382 
2383       // Define implicit data-sharing attributes for task.
2384       DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
2385       if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2386           !Stack->isLoopControlVariable(FD).first) {
2387         // Check if there is a captured expression for the current field in the
2388         // region. Do not mark it as firstprivate unless there is no captured
2389         // expression.
2390         // TODO: try to make it firstprivate.
2391         if (DVar.CKind != OMPC_unknown)
2392           ImplicitFirstprivate.push_back(E);
2393       }
2394       return;
2395     }
2396     if (isOpenMPTargetExecutionDirective(DKind)) {
2397       OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
2398       if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2399                                         /*NoDiagnose=*/true))
2400         return;
2401       const auto *VD = cast<ValueDecl>(
2402           CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2403       if (!Stack->checkMappableExprComponentListsForDecl(
2404               VD, /*CurrentRegionOnly=*/true,
2405               [&CurComponents](
2406                   OMPClauseMappableExprCommon::MappableExprComponentListRef
2407                       StackComponents,
2408                   OpenMPClauseKind) {
2409                 auto CCI = CurComponents.rbegin();
2410                 auto CCE = CurComponents.rend();
2411                 for (const auto &SC : llvm::reverse(StackComponents)) {
2412                   // Do both expressions have the same kind?
2413                   if (CCI->getAssociatedExpression()->getStmtClass() !=
2414                       SC.getAssociatedExpression()->getStmtClass())
2415                     if (!(isa<OMPArraySectionExpr>(
2416                               SC.getAssociatedExpression()) &&
2417                           isa<ArraySubscriptExpr>(
2418                               CCI->getAssociatedExpression())))
2419                       return false;
2420 
2421                   const Decl *CCD = CCI->getAssociatedDeclaration();
2422                   const Decl *SCD = SC.getAssociatedDeclaration();
2423                   CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2424                   SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2425                   if (SCD != CCD)
2426                     return false;
2427                   std::advance(CCI, 1);
2428                   if (CCI == CCE)
2429                     break;
2430                 }
2431                 return true;
2432               })) {
2433         Visit(E->getBase());
2434       }
2435     } else {
2436       Visit(E->getBase());
2437     }
2438   }
2439   void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
2440     for (OMPClause *C : S->clauses()) {
2441       // Skip analysis of arguments of implicitly defined firstprivate clause
2442       // for task|target directives.
2443       // Skip analysis of arguments of implicitly defined map clause for target
2444       // directives.
2445       if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2446                  C->isImplicit())) {
2447         for (Stmt *CC : C->children()) {
2448           if (CC)
2449             Visit(CC);
2450         }
2451       }
2452     }
2453     // Check implicitly captured variables.
2454     VisitSubCaptures(S);
2455   }
2456   void VisitStmt(Stmt *S) {
2457     for (Stmt *C : S->children()) {
2458       if (C) {
2459         // Check implicitly captured variables in the task-based directives to
2460         // check if they must be firstprivatized.
2461         Visit(C);
2462       }
2463     }
2464   }
2465 
2466   bool isErrorFound() const { return ErrorFound; }
2467   ArrayRef<Expr *> getImplicitFirstprivate() const {
2468     return ImplicitFirstprivate;
2469   }
2470   ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
2471   const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
2472     return VarsWithInheritedDSA;
2473   }
2474 
2475   DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2476       : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
2477 };
2478 } // namespace
2479 
2480 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
2481   switch (DKind) {
2482   case OMPD_parallel:
2483   case OMPD_parallel_for:
2484   case OMPD_parallel_for_simd:
2485   case OMPD_parallel_sections:
2486   case OMPD_teams:
2487   case OMPD_teams_distribute:
2488   case OMPD_teams_distribute_simd: {
2489     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2490     QualType KmpInt32PtrTy =
2491         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2492     Sema::CapturedParamNameType Params[] = {
2493         std::make_pair(".global_tid.", KmpInt32PtrTy),
2494         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2495         std::make_pair(StringRef(), QualType()) // __context with shared vars
2496     };
2497     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2498                              Params);
2499     break;
2500   }
2501   case OMPD_target_teams:
2502   case OMPD_target_parallel:
2503   case OMPD_target_parallel_for:
2504   case OMPD_target_parallel_for_simd:
2505   case OMPD_target_teams_distribute:
2506   case OMPD_target_teams_distribute_simd: {
2507     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2508     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2509     QualType KmpInt32PtrTy =
2510         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2511     QualType Args[] = {VoidPtrTy};
2512     FunctionProtoType::ExtProtoInfo EPI;
2513     EPI.Variadic = true;
2514     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2515     Sema::CapturedParamNameType Params[] = {
2516         std::make_pair(".global_tid.", KmpInt32Ty),
2517         std::make_pair(".part_id.", KmpInt32PtrTy),
2518         std::make_pair(".privates.", VoidPtrTy),
2519         std::make_pair(
2520             ".copy_fn.",
2521             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2522         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2523         std::make_pair(StringRef(), QualType()) // __context with shared vars
2524     };
2525     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2526                              Params);
2527     // Mark this captured region as inlined, because we don't use outlined
2528     // function directly.
2529     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2530         AlwaysInlineAttr::CreateImplicit(
2531             Context, AlwaysInlineAttr::Keyword_forceinline));
2532     Sema::CapturedParamNameType ParamsTarget[] = {
2533         std::make_pair(StringRef(), QualType()) // __context with shared vars
2534     };
2535     // Start a captured region for 'target' with no implicit parameters.
2536     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2537                              ParamsTarget);
2538     Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
2539         std::make_pair(".global_tid.", KmpInt32PtrTy),
2540         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2541         std::make_pair(StringRef(), QualType()) // __context with shared vars
2542     };
2543     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2544     // the same implicit parameters.
2545     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2546                              ParamsTeamsOrParallel);
2547     break;
2548   }
2549   case OMPD_target:
2550   case OMPD_target_simd: {
2551     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2552     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2553     QualType KmpInt32PtrTy =
2554         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2555     QualType Args[] = {VoidPtrTy};
2556     FunctionProtoType::ExtProtoInfo EPI;
2557     EPI.Variadic = true;
2558     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2559     Sema::CapturedParamNameType Params[] = {
2560         std::make_pair(".global_tid.", KmpInt32Ty),
2561         std::make_pair(".part_id.", KmpInt32PtrTy),
2562         std::make_pair(".privates.", VoidPtrTy),
2563         std::make_pair(
2564             ".copy_fn.",
2565             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2566         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2567         std::make_pair(StringRef(), QualType()) // __context with shared vars
2568     };
2569     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2570                              Params);
2571     // Mark this captured region as inlined, because we don't use outlined
2572     // function directly.
2573     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2574         AlwaysInlineAttr::CreateImplicit(
2575             Context, AlwaysInlineAttr::Keyword_forceinline));
2576     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2577                              std::make_pair(StringRef(), QualType()));
2578     break;
2579   }
2580   case OMPD_simd:
2581   case OMPD_for:
2582   case OMPD_for_simd:
2583   case OMPD_sections:
2584   case OMPD_section:
2585   case OMPD_single:
2586   case OMPD_master:
2587   case OMPD_critical:
2588   case OMPD_taskgroup:
2589   case OMPD_distribute:
2590   case OMPD_distribute_simd:
2591   case OMPD_ordered:
2592   case OMPD_atomic:
2593   case OMPD_target_data: {
2594     Sema::CapturedParamNameType Params[] = {
2595         std::make_pair(StringRef(), QualType()) // __context with shared vars
2596     };
2597     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2598                              Params);
2599     break;
2600   }
2601   case OMPD_task: {
2602     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2603     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2604     QualType KmpInt32PtrTy =
2605         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2606     QualType Args[] = {VoidPtrTy};
2607     FunctionProtoType::ExtProtoInfo EPI;
2608     EPI.Variadic = true;
2609     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2610     Sema::CapturedParamNameType Params[] = {
2611         std::make_pair(".global_tid.", KmpInt32Ty),
2612         std::make_pair(".part_id.", KmpInt32PtrTy),
2613         std::make_pair(".privates.", VoidPtrTy),
2614         std::make_pair(
2615             ".copy_fn.",
2616             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2617         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2618         std::make_pair(StringRef(), QualType()) // __context with shared vars
2619     };
2620     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2621                              Params);
2622     // Mark this captured region as inlined, because we don't use outlined
2623     // function directly.
2624     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2625         AlwaysInlineAttr::CreateImplicit(
2626             Context, AlwaysInlineAttr::Keyword_forceinline));
2627     break;
2628   }
2629   case OMPD_taskloop:
2630   case OMPD_taskloop_simd: {
2631     QualType KmpInt32Ty =
2632         Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2633             .withConst();
2634     QualType KmpUInt64Ty =
2635         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2636             .withConst();
2637     QualType KmpInt64Ty =
2638         Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2639             .withConst();
2640     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2641     QualType KmpInt32PtrTy =
2642         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2643     QualType Args[] = {VoidPtrTy};
2644     FunctionProtoType::ExtProtoInfo EPI;
2645     EPI.Variadic = true;
2646     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2647     Sema::CapturedParamNameType Params[] = {
2648         std::make_pair(".global_tid.", KmpInt32Ty),
2649         std::make_pair(".part_id.", KmpInt32PtrTy),
2650         std::make_pair(".privates.", VoidPtrTy),
2651         std::make_pair(
2652             ".copy_fn.",
2653             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2654         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2655         std::make_pair(".lb.", KmpUInt64Ty),
2656         std::make_pair(".ub.", KmpUInt64Ty),
2657         std::make_pair(".st.", KmpInt64Ty),
2658         std::make_pair(".liter.", KmpInt32Ty),
2659         std::make_pair(".reductions.", VoidPtrTy),
2660         std::make_pair(StringRef(), QualType()) // __context with shared vars
2661     };
2662     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2663                              Params);
2664     // Mark this captured region as inlined, because we don't use outlined
2665     // function directly.
2666     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2667         AlwaysInlineAttr::CreateImplicit(
2668             Context, AlwaysInlineAttr::Keyword_forceinline));
2669     break;
2670   }
2671   case OMPD_distribute_parallel_for_simd:
2672   case OMPD_distribute_parallel_for: {
2673     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2674     QualType KmpInt32PtrTy =
2675         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2676     Sema::CapturedParamNameType Params[] = {
2677         std::make_pair(".global_tid.", KmpInt32PtrTy),
2678         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2679         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2680         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2681         std::make_pair(StringRef(), QualType()) // __context with shared vars
2682     };
2683     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2684                              Params);
2685     break;
2686   }
2687   case OMPD_target_teams_distribute_parallel_for:
2688   case OMPD_target_teams_distribute_parallel_for_simd: {
2689     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2690     QualType KmpInt32PtrTy =
2691         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2692     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2693 
2694     QualType Args[] = {VoidPtrTy};
2695     FunctionProtoType::ExtProtoInfo EPI;
2696     EPI.Variadic = true;
2697     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2698     Sema::CapturedParamNameType Params[] = {
2699         std::make_pair(".global_tid.", KmpInt32Ty),
2700         std::make_pair(".part_id.", KmpInt32PtrTy),
2701         std::make_pair(".privates.", VoidPtrTy),
2702         std::make_pair(
2703             ".copy_fn.",
2704             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2705         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2706         std::make_pair(StringRef(), QualType()) // __context with shared vars
2707     };
2708     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2709                              Params);
2710     // Mark this captured region as inlined, because we don't use outlined
2711     // function directly.
2712     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2713         AlwaysInlineAttr::CreateImplicit(
2714             Context, AlwaysInlineAttr::Keyword_forceinline));
2715     Sema::CapturedParamNameType ParamsTarget[] = {
2716         std::make_pair(StringRef(), QualType()) // __context with shared vars
2717     };
2718     // Start a captured region for 'target' with no implicit parameters.
2719     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2720                              ParamsTarget);
2721 
2722     Sema::CapturedParamNameType ParamsTeams[] = {
2723         std::make_pair(".global_tid.", KmpInt32PtrTy),
2724         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2725         std::make_pair(StringRef(), QualType()) // __context with shared vars
2726     };
2727     // Start a captured region for 'target' with no implicit parameters.
2728     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2729                              ParamsTeams);
2730 
2731     Sema::CapturedParamNameType ParamsParallel[] = {
2732         std::make_pair(".global_tid.", KmpInt32PtrTy),
2733         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2734         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2735         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2736         std::make_pair(StringRef(), QualType()) // __context with shared vars
2737     };
2738     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2739     // the same implicit parameters.
2740     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2741                              ParamsParallel);
2742     break;
2743   }
2744 
2745   case OMPD_teams_distribute_parallel_for:
2746   case OMPD_teams_distribute_parallel_for_simd: {
2747     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2748     QualType KmpInt32PtrTy =
2749         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2750 
2751     Sema::CapturedParamNameType ParamsTeams[] = {
2752         std::make_pair(".global_tid.", KmpInt32PtrTy),
2753         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2754         std::make_pair(StringRef(), QualType()) // __context with shared vars
2755     };
2756     // Start a captured region for 'target' with no implicit parameters.
2757     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2758                              ParamsTeams);
2759 
2760     Sema::CapturedParamNameType ParamsParallel[] = {
2761         std::make_pair(".global_tid.", KmpInt32PtrTy),
2762         std::make_pair(".bound_tid.", KmpInt32PtrTy),
2763         std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2764         std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
2765         std::make_pair(StringRef(), QualType()) // __context with shared vars
2766     };
2767     // Start a captured region for 'teams' or 'parallel'.  Both regions have
2768     // the same implicit parameters.
2769     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2770                              ParamsParallel);
2771     break;
2772   }
2773   case OMPD_target_update:
2774   case OMPD_target_enter_data:
2775   case OMPD_target_exit_data: {
2776     QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2777     QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2778     QualType KmpInt32PtrTy =
2779         Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2780     QualType Args[] = {VoidPtrTy};
2781     FunctionProtoType::ExtProtoInfo EPI;
2782     EPI.Variadic = true;
2783     QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2784     Sema::CapturedParamNameType Params[] = {
2785         std::make_pair(".global_tid.", KmpInt32Ty),
2786         std::make_pair(".part_id.", KmpInt32PtrTy),
2787         std::make_pair(".privates.", VoidPtrTy),
2788         std::make_pair(
2789             ".copy_fn.",
2790             Context.getPointerType(CopyFnType).withConst().withRestrict()),
2791         std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2792         std::make_pair(StringRef(), QualType()) // __context with shared vars
2793     };
2794     ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2795                              Params);
2796     // Mark this captured region as inlined, because we don't use outlined
2797     // function directly.
2798     getCurCapturedRegion()->TheCapturedDecl->addAttr(
2799         AlwaysInlineAttr::CreateImplicit(
2800             Context, AlwaysInlineAttr::Keyword_forceinline));
2801     break;
2802   }
2803   case OMPD_threadprivate:
2804   case OMPD_taskyield:
2805   case OMPD_barrier:
2806   case OMPD_taskwait:
2807   case OMPD_cancellation_point:
2808   case OMPD_cancel:
2809   case OMPD_flush:
2810   case OMPD_declare_reduction:
2811   case OMPD_declare_mapper:
2812   case OMPD_declare_simd:
2813   case OMPD_declare_target:
2814   case OMPD_end_declare_target:
2815   case OMPD_requires:
2816     llvm_unreachable("OpenMP Directive is not allowed");
2817   case OMPD_unknown:
2818     llvm_unreachable("Unknown OpenMP directive");
2819   }
2820 }
2821 
2822 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2823   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2824   getOpenMPCaptureRegions(CaptureRegions, DKind);
2825   return CaptureRegions.size();
2826 }
2827 
2828 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
2829                                              Expr *CaptureExpr, bool WithInit,
2830                                              bool AsExpression) {
2831   assert(CaptureExpr);
2832   ASTContext &C = S.getASTContext();
2833   Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
2834   QualType Ty = Init->getType();
2835   if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
2836     if (S.getLangOpts().CPlusPlus) {
2837       Ty = C.getLValueReferenceType(Ty);
2838     } else {
2839       Ty = C.getPointerType(Ty);
2840       ExprResult Res =
2841           S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2842       if (!Res.isUsable())
2843         return nullptr;
2844       Init = Res.get();
2845     }
2846     WithInit = true;
2847   }
2848   auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2849                                           CaptureExpr->getBeginLoc());
2850   if (!WithInit)
2851     CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
2852   S.CurContext->addHiddenDecl(CED);
2853   S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
2854   return CED;
2855 }
2856 
2857 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2858                                  bool WithInit) {
2859   OMPCapturedExprDecl *CD;
2860   if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
2861     CD = cast<OMPCapturedExprDecl>(VD);
2862   else
2863     CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2864                           /*AsExpression=*/false);
2865   return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2866                           CaptureExpr->getExprLoc());
2867 }
2868 
2869 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
2870   CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
2871   if (!Ref) {
2872     OMPCapturedExprDecl *CD = buildCaptureDecl(
2873         S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2874         /*WithInit=*/true, /*AsExpression=*/true);
2875     Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2876                            CaptureExpr->getExprLoc());
2877   }
2878   ExprResult Res = Ref;
2879   if (!S.getLangOpts().CPlusPlus &&
2880       CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
2881       Ref->getType()->isPointerType()) {
2882     Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
2883     if (!Res.isUsable())
2884       return ExprError();
2885   }
2886   return S.DefaultLvalueConversion(Res.get());
2887 }
2888 
2889 namespace {
2890 // OpenMP directives parsed in this section are represented as a
2891 // CapturedStatement with an associated statement.  If a syntax error
2892 // is detected during the parsing of the associated statement, the
2893 // compiler must abort processing and close the CapturedStatement.
2894 //
2895 // Combined directives such as 'target parallel' have more than one
2896 // nested CapturedStatements.  This RAII ensures that we unwind out
2897 // of all the nested CapturedStatements when an error is found.
2898 class CaptureRegionUnwinderRAII {
2899 private:
2900   Sema &S;
2901   bool &ErrorFound;
2902   OpenMPDirectiveKind DKind = OMPD_unknown;
2903 
2904 public:
2905   CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2906                             OpenMPDirectiveKind DKind)
2907       : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2908   ~CaptureRegionUnwinderRAII() {
2909     if (ErrorFound) {
2910       int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2911       while (--ThisCaptureLevel >= 0)
2912         S.ActOnCapturedRegionError();
2913     }
2914   }
2915 };
2916 } // namespace
2917 
2918 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2919                                       ArrayRef<OMPClause *> Clauses) {
2920   bool ErrorFound = false;
2921   CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2922       *this, ErrorFound, DSAStack->getCurrentDirective());
2923   if (!S.isUsable()) {
2924     ErrorFound = true;
2925     return StmtError();
2926   }
2927 
2928   SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2929   getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
2930   OMPOrderedClause *OC = nullptr;
2931   OMPScheduleClause *SC = nullptr;
2932   SmallVector<const OMPLinearClause *, 4> LCs;
2933   SmallVector<const OMPClauseWithPreInit *, 4> PICs;
2934   // This is required for proper codegen.
2935   for (OMPClause *Clause : Clauses) {
2936     if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2937         Clause->getClauseKind() == OMPC_in_reduction) {
2938       // Capture taskgroup task_reduction descriptors inside the tasking regions
2939       // with the corresponding in_reduction items.
2940       auto *IRC = cast<OMPInReductionClause>(Clause);
2941       for (Expr *E : IRC->taskgroup_descriptors())
2942         if (E)
2943           MarkDeclarationsReferencedInExpr(E);
2944     }
2945     if (isOpenMPPrivate(Clause->getClauseKind()) ||
2946         Clause->getClauseKind() == OMPC_copyprivate ||
2947         (getLangOpts().OpenMPUseTLS &&
2948          getASTContext().getTargetInfo().isTLSSupported() &&
2949          Clause->getClauseKind() == OMPC_copyin)) {
2950       DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
2951       // Mark all variables in private list clauses as used in inner region.
2952       for (Stmt *VarRef : Clause->children()) {
2953         if (auto *E = cast_or_null<Expr>(VarRef)) {
2954           MarkDeclarationsReferencedInExpr(E);
2955         }
2956       }
2957       DSAStack->setForceVarCapturing(/*V=*/false);
2958     } else if (CaptureRegions.size() > 1 ||
2959                CaptureRegions.back() != OMPD_unknown) {
2960       if (auto *C = OMPClauseWithPreInit::get(Clause))
2961         PICs.push_back(C);
2962       if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2963         if (Expr *E = C->getPostUpdateExpr())
2964           MarkDeclarationsReferencedInExpr(E);
2965       }
2966     }
2967     if (Clause->getClauseKind() == OMPC_schedule)
2968       SC = cast<OMPScheduleClause>(Clause);
2969     else if (Clause->getClauseKind() == OMPC_ordered)
2970       OC = cast<OMPOrderedClause>(Clause);
2971     else if (Clause->getClauseKind() == OMPC_linear)
2972       LCs.push_back(cast<OMPLinearClause>(Clause));
2973   }
2974   // OpenMP, 2.7.1 Loop Construct, Restrictions
2975   // The nonmonotonic modifier cannot be specified if an ordered clause is
2976   // specified.
2977   if (SC &&
2978       (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2979        SC->getSecondScheduleModifier() ==
2980            OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2981       OC) {
2982     Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2983              ? SC->getFirstScheduleModifierLoc()
2984              : SC->getSecondScheduleModifierLoc(),
2985          diag::err_omp_schedule_nonmonotonic_ordered)
2986         << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
2987     ErrorFound = true;
2988   }
2989   if (!LCs.empty() && OC && OC->getNumForLoops()) {
2990     for (const OMPLinearClause *C : LCs) {
2991       Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
2992           << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
2993     }
2994     ErrorFound = true;
2995   }
2996   if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2997       isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2998       OC->getNumForLoops()) {
2999     Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
3000         << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3001     ErrorFound = true;
3002   }
3003   if (ErrorFound) {
3004     return StmtError();
3005   }
3006   StmtResult SR = S;
3007   for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
3008     // Mark all variables in private list clauses as used in inner region.
3009     // Required for proper codegen of combined directives.
3010     // TODO: add processing for other clauses.
3011     if (ThisCaptureRegion != OMPD_unknown) {
3012       for (const clang::OMPClauseWithPreInit *C : PICs) {
3013         OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3014         // Find the particular capture region for the clause if the
3015         // directive is a combined one with multiple capture regions.
3016         // If the directive is not a combined one, the capture region
3017         // associated with the clause is OMPD_unknown and is generated
3018         // only once.
3019         if (CaptureRegion == ThisCaptureRegion ||
3020             CaptureRegion == OMPD_unknown) {
3021           if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
3022             for (Decl *D : DS->decls())
3023               MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3024           }
3025         }
3026       }
3027     }
3028     SR = ActOnCapturedRegionEnd(SR.get());
3029   }
3030   return SR;
3031 }
3032 
3033 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3034                               OpenMPDirectiveKind CancelRegion,
3035                               SourceLocation StartLoc) {
3036   // CancelRegion is only needed for cancel and cancellation_point.
3037   if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3038     return false;
3039 
3040   if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3041       CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3042     return false;
3043 
3044   SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3045       << getOpenMPDirectiveName(CancelRegion);
3046   return true;
3047 }
3048 
3049 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
3050                                   OpenMPDirectiveKind CurrentRegion,
3051                                   const DeclarationNameInfo &CurrentName,
3052                                   OpenMPDirectiveKind CancelRegion,
3053                                   SourceLocation StartLoc) {
3054   if (Stack->getCurScope()) {
3055     OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3056     OpenMPDirectiveKind OffendingRegion = ParentRegion;
3057     bool NestingProhibited = false;
3058     bool CloseNesting = true;
3059     bool OrphanSeen = false;
3060     enum {
3061       NoRecommend,
3062       ShouldBeInParallelRegion,
3063       ShouldBeInOrderedRegion,
3064       ShouldBeInTargetRegion,
3065       ShouldBeInTeamsRegion
3066     } Recommend = NoRecommend;
3067     if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
3068       // OpenMP [2.16, Nesting of Regions]
3069       // OpenMP constructs may not be nested inside a simd region.
3070       // OpenMP [2.8.1,simd Construct, Restrictions]
3071       // An ordered construct with the simd clause is the only OpenMP
3072       // construct that can appear in the simd region.
3073       // Allowing a SIMD construct nested in another SIMD construct is an
3074       // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3075       // message.
3076       SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3077                                  ? diag::err_omp_prohibited_region_simd
3078                                  : diag::warn_omp_nesting_simd);
3079       return CurrentRegion != OMPD_simd;
3080     }
3081     if (ParentRegion == OMPD_atomic) {
3082       // OpenMP [2.16, Nesting of Regions]
3083       // OpenMP constructs may not be nested inside an atomic region.
3084       SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3085       return true;
3086     }
3087     if (CurrentRegion == OMPD_section) {
3088       // OpenMP [2.7.2, sections Construct, Restrictions]
3089       // Orphaned section directives are prohibited. That is, the section
3090       // directives must appear within the sections construct and must not be
3091       // encountered elsewhere in the sections region.
3092       if (ParentRegion != OMPD_sections &&
3093           ParentRegion != OMPD_parallel_sections) {
3094         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3095             << (ParentRegion != OMPD_unknown)
3096             << getOpenMPDirectiveName(ParentRegion);
3097         return true;
3098       }
3099       return false;
3100     }
3101     // Allow some constructs (except teams and cancellation constructs) to be
3102     // orphaned (they could be used in functions, called from OpenMP regions
3103     // with the required preconditions).
3104     if (ParentRegion == OMPD_unknown &&
3105         !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3106         CurrentRegion != OMPD_cancellation_point &&
3107         CurrentRegion != OMPD_cancel)
3108       return false;
3109     if (CurrentRegion == OMPD_cancellation_point ||
3110         CurrentRegion == OMPD_cancel) {
3111       // OpenMP [2.16, Nesting of Regions]
3112       // A cancellation point construct for which construct-type-clause is
3113       // taskgroup must be nested inside a task construct. A cancellation
3114       // point construct for which construct-type-clause is not taskgroup must
3115       // be closely nested inside an OpenMP construct that matches the type
3116       // specified in construct-type-clause.
3117       // A cancel construct for which construct-type-clause is taskgroup must be
3118       // nested inside a task construct. A cancel construct for which
3119       // construct-type-clause is not taskgroup must be closely nested inside an
3120       // OpenMP construct that matches the type specified in
3121       // construct-type-clause.
3122       NestingProhibited =
3123           !((CancelRegion == OMPD_parallel &&
3124              (ParentRegion == OMPD_parallel ||
3125               ParentRegion == OMPD_target_parallel)) ||
3126             (CancelRegion == OMPD_for &&
3127              (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
3128               ParentRegion == OMPD_target_parallel_for ||
3129               ParentRegion == OMPD_distribute_parallel_for ||
3130               ParentRegion == OMPD_teams_distribute_parallel_for ||
3131               ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
3132             (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3133             (CancelRegion == OMPD_sections &&
3134              (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3135               ParentRegion == OMPD_parallel_sections)));
3136       OrphanSeen = ParentRegion == OMPD_unknown;
3137     } else if (CurrentRegion == OMPD_master) {
3138       // OpenMP [2.16, Nesting of Regions]
3139       // A master region may not be closely nested inside a worksharing,
3140       // atomic, or explicit task region.
3141       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3142                           isOpenMPTaskingDirective(ParentRegion);
3143     } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3144       // OpenMP [2.16, Nesting of Regions]
3145       // A critical region may not be nested (closely or otherwise) inside a
3146       // critical region with the same name. Note that this restriction is not
3147       // sufficient to prevent deadlock.
3148       SourceLocation PreviousCriticalLoc;
3149       bool DeadLock = Stack->hasDirective(
3150           [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3151                                               const DeclarationNameInfo &DNI,
3152                                               SourceLocation Loc) {
3153             if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3154               PreviousCriticalLoc = Loc;
3155               return true;
3156             }
3157             return false;
3158           },
3159           false /* skip top directive */);
3160       if (DeadLock) {
3161         SemaRef.Diag(StartLoc,
3162                      diag::err_omp_prohibited_region_critical_same_name)
3163             << CurrentName.getName();
3164         if (PreviousCriticalLoc.isValid())
3165           SemaRef.Diag(PreviousCriticalLoc,
3166                        diag::note_omp_previous_critical_region);
3167         return true;
3168       }
3169     } else if (CurrentRegion == OMPD_barrier) {
3170       // OpenMP [2.16, Nesting of Regions]
3171       // A barrier region may not be closely nested inside a worksharing,
3172       // explicit task, critical, ordered, atomic, or master region.
3173       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3174                           isOpenMPTaskingDirective(ParentRegion) ||
3175                           ParentRegion == OMPD_master ||
3176                           ParentRegion == OMPD_critical ||
3177                           ParentRegion == OMPD_ordered;
3178     } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
3179                !isOpenMPParallelDirective(CurrentRegion) &&
3180                !isOpenMPTeamsDirective(CurrentRegion)) {
3181       // OpenMP [2.16, Nesting of Regions]
3182       // A worksharing region may not be closely nested inside a worksharing,
3183       // explicit task, critical, ordered, atomic, or master region.
3184       NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3185                           isOpenMPTaskingDirective(ParentRegion) ||
3186                           ParentRegion == OMPD_master ||
3187                           ParentRegion == OMPD_critical ||
3188                           ParentRegion == OMPD_ordered;
3189       Recommend = ShouldBeInParallelRegion;
3190     } else if (CurrentRegion == OMPD_ordered) {
3191       // OpenMP [2.16, Nesting of Regions]
3192       // An ordered region may not be closely nested inside a critical,
3193       // atomic, or explicit task region.
3194       // An ordered region must be closely nested inside a loop region (or
3195       // parallel loop region) with an ordered clause.
3196       // OpenMP [2.8.1,simd Construct, Restrictions]
3197       // An ordered construct with the simd clause is the only OpenMP construct
3198       // that can appear in the simd region.
3199       NestingProhibited = ParentRegion == OMPD_critical ||
3200                           isOpenMPTaskingDirective(ParentRegion) ||
3201                           !(isOpenMPSimdDirective(ParentRegion) ||
3202                             Stack->isParentOrderedRegion());
3203       Recommend = ShouldBeInOrderedRegion;
3204     } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
3205       // OpenMP [2.16, Nesting of Regions]
3206       // If specified, a teams construct must be contained within a target
3207       // construct.
3208       NestingProhibited = ParentRegion != OMPD_target;
3209       OrphanSeen = ParentRegion == OMPD_unknown;
3210       Recommend = ShouldBeInTargetRegion;
3211     }
3212     if (!NestingProhibited &&
3213         !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3214         !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3215         (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
3216       // OpenMP [2.16, Nesting of Regions]
3217       // distribute, parallel, parallel sections, parallel workshare, and the
3218       // parallel loop and parallel loop SIMD constructs are the only OpenMP
3219       // constructs that can be closely nested in the teams region.
3220       NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3221                           !isOpenMPDistributeDirective(CurrentRegion);
3222       Recommend = ShouldBeInParallelRegion;
3223     }
3224     if (!NestingProhibited &&
3225         isOpenMPNestingDistributeDirective(CurrentRegion)) {
3226       // OpenMP 4.5 [2.17 Nesting of Regions]
3227       // The region associated with the distribute construct must be strictly
3228       // nested inside a teams region
3229       NestingProhibited =
3230           (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
3231       Recommend = ShouldBeInTeamsRegion;
3232     }
3233     if (!NestingProhibited &&
3234         (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3235          isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3236       // OpenMP 4.5 [2.17 Nesting of Regions]
3237       // If a target, target update, target data, target enter data, or
3238       // target exit data construct is encountered during execution of a
3239       // target region, the behavior is unspecified.
3240       NestingProhibited = Stack->hasDirective(
3241           [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
3242                              SourceLocation) {
3243             if (isOpenMPTargetExecutionDirective(K)) {
3244               OffendingRegion = K;
3245               return true;
3246             }
3247             return false;
3248           },
3249           false /* don't skip top directive */);
3250       CloseNesting = false;
3251     }
3252     if (NestingProhibited) {
3253       if (OrphanSeen) {
3254         SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3255             << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3256       } else {
3257         SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3258             << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3259             << Recommend << getOpenMPDirectiveName(CurrentRegion);
3260       }
3261       return true;
3262     }
3263   }
3264   return false;
3265 }
3266 
3267 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3268                            ArrayRef<OMPClause *> Clauses,
3269                            ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3270   bool ErrorFound = false;
3271   unsigned NamedModifiersNumber = 0;
3272   SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3273       OMPD_unknown + 1);
3274   SmallVector<SourceLocation, 4> NameModifierLoc;
3275   for (const OMPClause *C : Clauses) {
3276     if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3277       // At most one if clause without a directive-name-modifier can appear on
3278       // the directive.
3279       OpenMPDirectiveKind CurNM = IC->getNameModifier();
3280       if (FoundNameModifiers[CurNM]) {
3281         S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
3282             << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3283             << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3284         ErrorFound = true;
3285       } else if (CurNM != OMPD_unknown) {
3286         NameModifierLoc.push_back(IC->getNameModifierLoc());
3287         ++NamedModifiersNumber;
3288       }
3289       FoundNameModifiers[CurNM] = IC;
3290       if (CurNM == OMPD_unknown)
3291         continue;
3292       // Check if the specified name modifier is allowed for the current
3293       // directive.
3294       // At most one if clause with the particular directive-name-modifier can
3295       // appear on the directive.
3296       bool MatchFound = false;
3297       for (auto NM : AllowedNameModifiers) {
3298         if (CurNM == NM) {
3299           MatchFound = true;
3300           break;
3301         }
3302       }
3303       if (!MatchFound) {
3304         S.Diag(IC->getNameModifierLoc(),
3305                diag::err_omp_wrong_if_directive_name_modifier)
3306             << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3307         ErrorFound = true;
3308       }
3309     }
3310   }
3311   // If any if clause on the directive includes a directive-name-modifier then
3312   // all if clauses on the directive must include a directive-name-modifier.
3313   if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3314     if (NamedModifiersNumber == AllowedNameModifiers.size()) {
3315       S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
3316              diag::err_omp_no_more_if_clause);
3317     } else {
3318       std::string Values;
3319       std::string Sep(", ");
3320       unsigned AllowedCnt = 0;
3321       unsigned TotalAllowedNum =
3322           AllowedNameModifiers.size() - NamedModifiersNumber;
3323       for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3324            ++Cnt) {
3325         OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3326         if (!FoundNameModifiers[NM]) {
3327           Values += "'";
3328           Values += getOpenMPDirectiveName(NM);
3329           Values += "'";
3330           if (AllowedCnt + 2 == TotalAllowedNum)
3331             Values += " or ";
3332           else if (AllowedCnt + 1 != TotalAllowedNum)
3333             Values += Sep;
3334           ++AllowedCnt;
3335         }
3336       }
3337       S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
3338              diag::err_omp_unnamed_if_clause)
3339           << (TotalAllowedNum > 1) << Values;
3340     }
3341     for (SourceLocation Loc : NameModifierLoc) {
3342       S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3343     }
3344     ErrorFound = true;
3345   }
3346   return ErrorFound;
3347 }
3348 
3349 StmtResult Sema::ActOnOpenMPExecutableDirective(
3350     OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3351     OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3352     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
3353   StmtResult Res = StmtError();
3354   // First check CancelRegion which is then used in checkNestingOfRegions.
3355   if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3356       checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
3357                             StartLoc))
3358     return StmtError();
3359 
3360   llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
3361   VarsWithInheritedDSAType VarsWithInheritedDSA;
3362   bool ErrorFound = false;
3363   ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
3364   if (AStmt && !CurContext->isDependentContext()) {
3365     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3366 
3367     // Check default data sharing attributes for referenced variables.
3368     DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
3369     int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3370     Stmt *S = AStmt;
3371     while (--ThisCaptureLevel >= 0)
3372       S = cast<CapturedStmt>(S)->getCapturedStmt();
3373     DSAChecker.Visit(S);
3374     if (DSAChecker.isErrorFound())
3375       return StmtError();
3376     // Generate list of implicitly defined firstprivate variables.
3377     VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
3378 
3379     SmallVector<Expr *, 4> ImplicitFirstprivates(
3380         DSAChecker.getImplicitFirstprivate().begin(),
3381         DSAChecker.getImplicitFirstprivate().end());
3382     SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3383                                         DSAChecker.getImplicitMap().end());
3384     // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3385     for (OMPClause *C : Clauses) {
3386       if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3387         for (Expr *E : IRC->taskgroup_descriptors())
3388           if (E)
3389             ImplicitFirstprivates.emplace_back(E);
3390       }
3391     }
3392     if (!ImplicitFirstprivates.empty()) {
3393       if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
3394               ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3395               SourceLocation())) {
3396         ClausesWithImplicit.push_back(Implicit);
3397         ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
3398                      ImplicitFirstprivates.size();
3399       } else {
3400         ErrorFound = true;
3401       }
3402     }
3403     if (!ImplicitMaps.empty()) {
3404       if (OMPClause *Implicit = ActOnOpenMPMapClause(
3405               llvm::None, llvm::None, OMPC_MAP_tofrom,
3406               /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
3407               ImplicitMaps, SourceLocation(), SourceLocation(),
3408               SourceLocation())) {
3409         ClausesWithImplicit.emplace_back(Implicit);
3410         ErrorFound |=
3411             cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3412       } else {
3413         ErrorFound = true;
3414       }
3415     }
3416   }
3417 
3418   llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
3419   switch (Kind) {
3420   case OMPD_parallel:
3421     Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3422                                        EndLoc);
3423     AllowedNameModifiers.push_back(OMPD_parallel);
3424     break;
3425   case OMPD_simd:
3426     Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3427                                    VarsWithInheritedDSA);
3428     break;
3429   case OMPD_for:
3430     Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3431                                   VarsWithInheritedDSA);
3432     break;
3433   case OMPD_for_simd:
3434     Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3435                                       EndLoc, VarsWithInheritedDSA);
3436     break;
3437   case OMPD_sections:
3438     Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3439                                        EndLoc);
3440     break;
3441   case OMPD_section:
3442     assert(ClausesWithImplicit.empty() &&
3443            "No clauses are allowed for 'omp section' directive");
3444     Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3445     break;
3446   case OMPD_single:
3447     Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3448                                      EndLoc);
3449     break;
3450   case OMPD_master:
3451     assert(ClausesWithImplicit.empty() &&
3452            "No clauses are allowed for 'omp master' directive");
3453     Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3454     break;
3455   case OMPD_critical:
3456     Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3457                                        StartLoc, EndLoc);
3458     break;
3459   case OMPD_parallel_for:
3460     Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3461                                           EndLoc, VarsWithInheritedDSA);
3462     AllowedNameModifiers.push_back(OMPD_parallel);
3463     break;
3464   case OMPD_parallel_for_simd:
3465     Res = ActOnOpenMPParallelForSimdDirective(
3466         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3467     AllowedNameModifiers.push_back(OMPD_parallel);
3468     break;
3469   case OMPD_parallel_sections:
3470     Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3471                                                StartLoc, EndLoc);
3472     AllowedNameModifiers.push_back(OMPD_parallel);
3473     break;
3474   case OMPD_task:
3475     Res =
3476         ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3477     AllowedNameModifiers.push_back(OMPD_task);
3478     break;
3479   case OMPD_taskyield:
3480     assert(ClausesWithImplicit.empty() &&
3481            "No clauses are allowed for 'omp taskyield' directive");
3482     assert(AStmt == nullptr &&
3483            "No associated statement allowed for 'omp taskyield' directive");
3484     Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3485     break;
3486   case OMPD_barrier:
3487     assert(ClausesWithImplicit.empty() &&
3488            "No clauses are allowed for 'omp barrier' directive");
3489     assert(AStmt == nullptr &&
3490            "No associated statement allowed for 'omp barrier' directive");
3491     Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3492     break;
3493   case OMPD_taskwait:
3494     assert(ClausesWithImplicit.empty() &&
3495            "No clauses are allowed for 'omp taskwait' directive");
3496     assert(AStmt == nullptr &&
3497            "No associated statement allowed for 'omp taskwait' directive");
3498     Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3499     break;
3500   case OMPD_taskgroup:
3501     Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3502                                         EndLoc);
3503     break;
3504   case OMPD_flush:
3505     assert(AStmt == nullptr &&
3506            "No associated statement allowed for 'omp flush' directive");
3507     Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3508     break;
3509   case OMPD_ordered:
3510     Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3511                                       EndLoc);
3512     break;
3513   case OMPD_atomic:
3514     Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3515                                      EndLoc);
3516     break;
3517   case OMPD_teams:
3518     Res =
3519         ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3520     break;
3521   case OMPD_target:
3522     Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3523                                      EndLoc);
3524     AllowedNameModifiers.push_back(OMPD_target);
3525     break;
3526   case OMPD_target_parallel:
3527     Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3528                                              StartLoc, EndLoc);
3529     AllowedNameModifiers.push_back(OMPD_target);
3530     AllowedNameModifiers.push_back(OMPD_parallel);
3531     break;
3532   case OMPD_target_parallel_for:
3533     Res = ActOnOpenMPTargetParallelForDirective(
3534         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3535     AllowedNameModifiers.push_back(OMPD_target);
3536     AllowedNameModifiers.push_back(OMPD_parallel);
3537     break;
3538   case OMPD_cancellation_point:
3539     assert(ClausesWithImplicit.empty() &&
3540            "No clauses are allowed for 'omp cancellation point' directive");
3541     assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3542                                "cancellation point' directive");
3543     Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3544     break;
3545   case OMPD_cancel:
3546     assert(AStmt == nullptr &&
3547            "No associated statement allowed for 'omp cancel' directive");
3548     Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3549                                      CancelRegion);
3550     AllowedNameModifiers.push_back(OMPD_cancel);
3551     break;
3552   case OMPD_target_data:
3553     Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3554                                          EndLoc);
3555     AllowedNameModifiers.push_back(OMPD_target_data);
3556     break;
3557   case OMPD_target_enter_data:
3558     Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
3559                                               EndLoc, AStmt);
3560     AllowedNameModifiers.push_back(OMPD_target_enter_data);
3561     break;
3562   case OMPD_target_exit_data:
3563     Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
3564                                              EndLoc, AStmt);
3565     AllowedNameModifiers.push_back(OMPD_target_exit_data);
3566     break;
3567   case OMPD_taskloop:
3568     Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3569                                        EndLoc, VarsWithInheritedDSA);
3570     AllowedNameModifiers.push_back(OMPD_taskloop);
3571     break;
3572   case OMPD_taskloop_simd:
3573     Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3574                                            EndLoc, VarsWithInheritedDSA);
3575     AllowedNameModifiers.push_back(OMPD_taskloop);
3576     break;
3577   case OMPD_distribute:
3578     Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3579                                          EndLoc, VarsWithInheritedDSA);
3580     break;
3581   case OMPD_target_update:
3582     Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3583                                            EndLoc, AStmt);
3584     AllowedNameModifiers.push_back(OMPD_target_update);
3585     break;
3586   case OMPD_distribute_parallel_for:
3587     Res = ActOnOpenMPDistributeParallelForDirective(
3588         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3589     AllowedNameModifiers.push_back(OMPD_parallel);
3590     break;
3591   case OMPD_distribute_parallel_for_simd:
3592     Res = ActOnOpenMPDistributeParallelForSimdDirective(
3593         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3594     AllowedNameModifiers.push_back(OMPD_parallel);
3595     break;
3596   case OMPD_distribute_simd:
3597     Res = ActOnOpenMPDistributeSimdDirective(
3598         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3599     break;
3600   case OMPD_target_parallel_for_simd:
3601     Res = ActOnOpenMPTargetParallelForSimdDirective(
3602         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3603     AllowedNameModifiers.push_back(OMPD_target);
3604     AllowedNameModifiers.push_back(OMPD_parallel);
3605     break;
3606   case OMPD_target_simd:
3607     Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3608                                          EndLoc, VarsWithInheritedDSA);
3609     AllowedNameModifiers.push_back(OMPD_target);
3610     break;
3611   case OMPD_teams_distribute:
3612     Res = ActOnOpenMPTeamsDistributeDirective(
3613         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3614     break;
3615   case OMPD_teams_distribute_simd:
3616     Res = ActOnOpenMPTeamsDistributeSimdDirective(
3617         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3618     break;
3619   case OMPD_teams_distribute_parallel_for_simd:
3620     Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3621         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3622     AllowedNameModifiers.push_back(OMPD_parallel);
3623     break;
3624   case OMPD_teams_distribute_parallel_for:
3625     Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3626         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3627     AllowedNameModifiers.push_back(OMPD_parallel);
3628     break;
3629   case OMPD_target_teams:
3630     Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3631                                           EndLoc);
3632     AllowedNameModifiers.push_back(OMPD_target);
3633     break;
3634   case OMPD_target_teams_distribute:
3635     Res = ActOnOpenMPTargetTeamsDistributeDirective(
3636         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3637     AllowedNameModifiers.push_back(OMPD_target);
3638     break;
3639   case OMPD_target_teams_distribute_parallel_for:
3640     Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3641         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3642     AllowedNameModifiers.push_back(OMPD_target);
3643     AllowedNameModifiers.push_back(OMPD_parallel);
3644     break;
3645   case OMPD_target_teams_distribute_parallel_for_simd:
3646     Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3647         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3648     AllowedNameModifiers.push_back(OMPD_target);
3649     AllowedNameModifiers.push_back(OMPD_parallel);
3650     break;
3651   case OMPD_target_teams_distribute_simd:
3652     Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3653         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3654     AllowedNameModifiers.push_back(OMPD_target);
3655     break;
3656   case OMPD_declare_target:
3657   case OMPD_end_declare_target:
3658   case OMPD_threadprivate:
3659   case OMPD_declare_reduction:
3660   case OMPD_declare_mapper:
3661   case OMPD_declare_simd:
3662   case OMPD_requires:
3663     llvm_unreachable("OpenMP Directive is not allowed");
3664   case OMPD_unknown:
3665     llvm_unreachable("Unknown OpenMP directive");
3666   }
3667 
3668   for (const auto &P : VarsWithInheritedDSA) {
3669     Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3670         << P.first << P.second->getSourceRange();
3671   }
3672   ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3673 
3674   if (!AllowedNameModifiers.empty())
3675     ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3676                  ErrorFound;
3677 
3678   if (ErrorFound)
3679     return StmtError();
3680   return Res;
3681 }
3682 
3683 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3684     DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
3685     ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
3686     ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3687     ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
3688   assert(Aligneds.size() == Alignments.size());
3689   assert(Linears.size() == LinModifiers.size());
3690   assert(Linears.size() == Steps.size());
3691   if (!DG || DG.get().isNull())
3692     return DeclGroupPtrTy();
3693 
3694   if (!DG.get().isSingleDecl()) {
3695     Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
3696     return DG;
3697   }
3698   Decl *ADecl = DG.get().getSingleDecl();
3699   if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3700     ADecl = FTD->getTemplatedDecl();
3701 
3702   auto *FD = dyn_cast<FunctionDecl>(ADecl);
3703   if (!FD) {
3704     Diag(ADecl->getLocation(), diag::err_omp_function_expected);
3705     return DeclGroupPtrTy();
3706   }
3707 
3708   // OpenMP [2.8.2, declare simd construct, Description]
3709   // The parameter of the simdlen clause must be a constant positive integer
3710   // expression.
3711   ExprResult SL;
3712   if (Simdlen)
3713     SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
3714   // OpenMP [2.8.2, declare simd construct, Description]
3715   // The special this pointer can be used as if was one of the arguments to the
3716   // function in any of the linear, aligned, or uniform clauses.
3717   // The uniform clause declares one or more arguments to have an invariant
3718   // value for all concurrent invocations of the function in the execution of a
3719   // single SIMD loop.
3720   llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3721   const Expr *UniformedLinearThis = nullptr;
3722   for (const Expr *E : Uniforms) {
3723     E = E->IgnoreParenImpCasts();
3724     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3725       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3726         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3727             FD->getParamDecl(PVD->getFunctionScopeIndex())
3728                     ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3729           UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
3730           continue;
3731         }
3732     if (isa<CXXThisExpr>(E)) {
3733       UniformedLinearThis = E;
3734       continue;
3735     }
3736     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3737         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3738   }
3739   // OpenMP [2.8.2, declare simd construct, Description]
3740   // The aligned clause declares that the object to which each list item points
3741   // is aligned to the number of bytes expressed in the optional parameter of
3742   // the aligned clause.
3743   // The special this pointer can be used as if was one of the arguments to the
3744   // function in any of the linear, aligned, or uniform clauses.
3745   // The type of list items appearing in the aligned clause must be array,
3746   // pointer, reference to array, or reference to pointer.
3747   llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3748   const Expr *AlignedThis = nullptr;
3749   for (const Expr *E : Aligneds) {
3750     E = E->IgnoreParenImpCasts();
3751     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3752       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3753         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3754         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3755             FD->getParamDecl(PVD->getFunctionScopeIndex())
3756                     ->getCanonicalDecl() == CanonPVD) {
3757           // OpenMP  [2.8.1, simd construct, Restrictions]
3758           // A list-item cannot appear in more than one aligned clause.
3759           if (AlignedArgs.count(CanonPVD) > 0) {
3760             Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3761                 << 1 << E->getSourceRange();
3762             Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3763                  diag::note_omp_explicit_dsa)
3764                 << getOpenMPClauseName(OMPC_aligned);
3765             continue;
3766           }
3767           AlignedArgs[CanonPVD] = E;
3768           QualType QTy = PVD->getType()
3769                              .getNonReferenceType()
3770                              .getUnqualifiedType()
3771                              .getCanonicalType();
3772           const Type *Ty = QTy.getTypePtrOrNull();
3773           if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3774             Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3775                 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3776             Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3777           }
3778           continue;
3779         }
3780       }
3781     if (isa<CXXThisExpr>(E)) {
3782       if (AlignedThis) {
3783         Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3784             << 2 << E->getSourceRange();
3785         Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3786             << getOpenMPClauseName(OMPC_aligned);
3787       }
3788       AlignedThis = E;
3789       continue;
3790     }
3791     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3792         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3793   }
3794   // The optional parameter of the aligned clause, alignment, must be a constant
3795   // positive integer expression. If no optional parameter is specified,
3796   // implementation-defined default alignments for SIMD instructions on the
3797   // target platforms are assumed.
3798   SmallVector<const Expr *, 4> NewAligns;
3799   for (Expr *E : Alignments) {
3800     ExprResult Align;
3801     if (E)
3802       Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3803     NewAligns.push_back(Align.get());
3804   }
3805   // OpenMP [2.8.2, declare simd construct, Description]
3806   // The linear clause declares one or more list items to be private to a SIMD
3807   // lane and to have a linear relationship with respect to the iteration space
3808   // of a loop.
3809   // The special this pointer can be used as if was one of the arguments to the
3810   // function in any of the linear, aligned, or uniform clauses.
3811   // When a linear-step expression is specified in a linear clause it must be
3812   // either a constant integer expression or an integer-typed parameter that is
3813   // specified in a uniform clause on the directive.
3814   llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
3815   const bool IsUniformedThis = UniformedLinearThis != nullptr;
3816   auto MI = LinModifiers.begin();
3817   for (const Expr *E : Linears) {
3818     auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3819     ++MI;
3820     E = E->IgnoreParenImpCasts();
3821     if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3822       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3823         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3824         if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3825             FD->getParamDecl(PVD->getFunctionScopeIndex())
3826                     ->getCanonicalDecl() == CanonPVD) {
3827           // OpenMP  [2.15.3.7, linear Clause, Restrictions]
3828           // A list-item cannot appear in more than one linear clause.
3829           if (LinearArgs.count(CanonPVD) > 0) {
3830             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3831                 << getOpenMPClauseName(OMPC_linear)
3832                 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3833             Diag(LinearArgs[CanonPVD]->getExprLoc(),
3834                  diag::note_omp_explicit_dsa)
3835                 << getOpenMPClauseName(OMPC_linear);
3836             continue;
3837           }
3838           // Each argument can appear in at most one uniform or linear clause.
3839           if (UniformedArgs.count(CanonPVD) > 0) {
3840             Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3841                 << getOpenMPClauseName(OMPC_linear)
3842                 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3843             Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3844                  diag::note_omp_explicit_dsa)
3845                 << getOpenMPClauseName(OMPC_uniform);
3846             continue;
3847           }
3848           LinearArgs[CanonPVD] = E;
3849           if (E->isValueDependent() || E->isTypeDependent() ||
3850               E->isInstantiationDependent() ||
3851               E->containsUnexpandedParameterPack())
3852             continue;
3853           (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3854                                       PVD->getOriginalType());
3855           continue;
3856         }
3857       }
3858     if (isa<CXXThisExpr>(E)) {
3859       if (UniformedLinearThis) {
3860         Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3861             << getOpenMPClauseName(OMPC_linear)
3862             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3863             << E->getSourceRange();
3864         Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3865             << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3866                                                    : OMPC_linear);
3867         continue;
3868       }
3869       UniformedLinearThis = E;
3870       if (E->isValueDependent() || E->isTypeDependent() ||
3871           E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3872         continue;
3873       (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3874                                   E->getType());
3875       continue;
3876     }
3877     Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3878         << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3879   }
3880   Expr *Step = nullptr;
3881   Expr *NewStep = nullptr;
3882   SmallVector<Expr *, 4> NewSteps;
3883   for (Expr *E : Steps) {
3884     // Skip the same step expression, it was checked already.
3885     if (Step == E || !E) {
3886       NewSteps.push_back(E ? NewStep : nullptr);
3887       continue;
3888     }
3889     Step = E;
3890     if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
3891       if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3892         const VarDecl *CanonPVD = PVD->getCanonicalDecl();
3893         if (UniformedArgs.count(CanonPVD) == 0) {
3894           Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3895               << Step->getSourceRange();
3896         } else if (E->isValueDependent() || E->isTypeDependent() ||
3897                    E->isInstantiationDependent() ||
3898                    E->containsUnexpandedParameterPack() ||
3899                    CanonPVD->getType()->hasIntegerRepresentation()) {
3900           NewSteps.push_back(Step);
3901         } else {
3902           Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3903               << Step->getSourceRange();
3904         }
3905         continue;
3906       }
3907     NewStep = Step;
3908     if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3909         !Step->isInstantiationDependent() &&
3910         !Step->containsUnexpandedParameterPack()) {
3911       NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3912                     .get();
3913       if (NewStep)
3914         NewStep = VerifyIntegerConstantExpression(NewStep).get();
3915     }
3916     NewSteps.push_back(NewStep);
3917   }
3918   auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3919       Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
3920       Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
3921       const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3922       const_cast<Expr **>(Linears.data()), Linears.size(),
3923       const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3924       NewSteps.data(), NewSteps.size(), SR);
3925   ADecl->addAttr(NewAttr);
3926   return ConvertDeclToDeclGroup(ADecl);
3927 }
3928 
3929 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3930                                               Stmt *AStmt,
3931                                               SourceLocation StartLoc,
3932                                               SourceLocation EndLoc) {
3933   if (!AStmt)
3934     return StmtError();
3935 
3936   auto *CS = cast<CapturedStmt>(AStmt);
3937   // 1.2.2 OpenMP Language Terminology
3938   // Structured block - An executable statement with a single entry at the
3939   // top and a single exit at the bottom.
3940   // The point of exit cannot be a branch out of the structured block.
3941   // longjmp() and throw() must not violate the entry/exit criteria.
3942   CS->getCapturedDecl()->setNothrow();
3943 
3944   setFunctionHasBranchProtectedScope();
3945 
3946   return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3947                                       DSAStack->isCancelRegion());
3948 }
3949 
3950 namespace {
3951 /// Helper class for checking canonical form of the OpenMP loops and
3952 /// extracting iteration space of each loop in the loop nest, that will be used
3953 /// for IR generation.
3954 class OpenMPIterationSpaceChecker {
3955   /// Reference to Sema.
3956   Sema &SemaRef;
3957   /// A location for diagnostics (when there is no some better location).
3958   SourceLocation DefaultLoc;
3959   /// A location for diagnostics (when increment is not compatible).
3960   SourceLocation ConditionLoc;
3961   /// A source location for referring to loop init later.
3962   SourceRange InitSrcRange;
3963   /// A source location for referring to condition later.
3964   SourceRange ConditionSrcRange;
3965   /// A source location for referring to increment later.
3966   SourceRange IncrementSrcRange;
3967   /// Loop variable.
3968   ValueDecl *LCDecl = nullptr;
3969   /// Reference to loop variable.
3970   Expr *LCRef = nullptr;
3971   /// Lower bound (initializer for the var).
3972   Expr *LB = nullptr;
3973   /// Upper bound.
3974   Expr *UB = nullptr;
3975   /// Loop step (increment).
3976   Expr *Step = nullptr;
3977   /// This flag is true when condition is one of:
3978   ///   Var <  UB
3979   ///   Var <= UB
3980   ///   UB  >  Var
3981   ///   UB  >= Var
3982   /// This will have no value when the condition is !=
3983   llvm::Optional<bool> TestIsLessOp;
3984   /// This flag is true when condition is strict ( < or > ).
3985   bool TestIsStrictOp = false;
3986   /// This flag is true when step is subtracted on each iteration.
3987   bool SubtractStep = false;
3988 
3989 public:
3990   OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
3991       : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
3992   /// Check init-expr for canonical loop form and save loop counter
3993   /// variable - #Var and its initialization value - #LB.
3994   bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
3995   /// Check test-expr for canonical form, save upper-bound (#UB), flags
3996   /// for less/greater and for strict/non-strict comparison.
3997   bool checkAndSetCond(Expr *S);
3998   /// Check incr-expr for canonical loop form and return true if it
3999   /// does not conform, otherwise save loop step (#Step).
4000   bool checkAndSetInc(Expr *S);
4001   /// Return the loop counter variable.
4002   ValueDecl *getLoopDecl() const { return LCDecl; }
4003   /// Return the reference expression to loop counter variable.
4004   Expr *getLoopDeclRefExpr() const { return LCRef; }
4005   /// Source range of the loop init.
4006   SourceRange getInitSrcRange() const { return InitSrcRange; }
4007   /// Source range of the loop condition.
4008   SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
4009   /// Source range of the loop increment.
4010   SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
4011   /// True if the step should be subtracted.
4012   bool shouldSubtractStep() const { return SubtractStep; }
4013   /// True, if the compare operator is strict (<, > or !=).
4014   bool isStrictTestOp() const { return TestIsStrictOp; }
4015   /// Build the expression to calculate the number of iterations.
4016   Expr *buildNumIterations(
4017       Scope *S, const bool LimitedType,
4018       llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
4019   /// Build the precondition expression for the loops.
4020   Expr *
4021   buildPreCond(Scope *S, Expr *Cond,
4022                llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
4023   /// Build reference expression to the counter be used for codegen.
4024   DeclRefExpr *
4025   buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4026                   DSAStackTy &DSA) const;
4027   /// Build reference expression to the private counter be used for
4028   /// codegen.
4029   Expr *buildPrivateCounterVar() const;
4030   /// Build initialization of the counter be used for codegen.
4031   Expr *buildCounterInit() const;
4032   /// Build step of the counter be used for codegen.
4033   Expr *buildCounterStep() const;
4034   /// Build loop data with counter value for depend clauses in ordered
4035   /// directives.
4036   Expr *
4037   buildOrderedLoopData(Scope *S, Expr *Counter,
4038                        llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4039                        SourceLocation Loc, Expr *Inc = nullptr,
4040                        OverloadedOperatorKind OOK = OO_Amp);
4041   /// Return true if any expression is dependent.
4042   bool dependent() const;
4043 
4044 private:
4045   /// Check the right-hand side of an assignment in the increment
4046   /// expression.
4047   bool checkAndSetIncRHS(Expr *RHS);
4048   /// Helper to set loop counter variable and its initializer.
4049   bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
4050   /// Helper to set upper bound.
4051   bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4052              SourceRange SR, SourceLocation SL);
4053   /// Helper to set loop increment.
4054   bool setStep(Expr *NewStep, bool Subtract);
4055 };
4056 
4057 bool OpenMPIterationSpaceChecker::dependent() const {
4058   if (!LCDecl) {
4059     assert(!LB && !UB && !Step);
4060     return false;
4061   }
4062   return LCDecl->getType()->isDependentType() ||
4063          (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4064          (Step && Step->isValueDependent());
4065 }
4066 
4067 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
4068                                                  Expr *NewLCRefExpr,
4069                                                  Expr *NewLB) {
4070   // State consistency checking to ensure correct usage.
4071   assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
4072          UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
4073   if (!NewLCDecl || !NewLB)
4074     return true;
4075   LCDecl = getCanonicalDecl(NewLCDecl);
4076   LCRef = NewLCRefExpr;
4077   if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4078     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4079       if ((Ctor->isCopyOrMoveConstructor() ||
4080            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4081           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4082         NewLB = CE->getArg(0)->IgnoreParenImpCasts();
4083   LB = NewLB;
4084   return false;
4085 }
4086 
4087 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4088                                         llvm::Optional<bool> LessOp,
4089                                         bool StrictOp, SourceRange SR,
4090                                         SourceLocation SL) {
4091   // State consistency checking to ensure correct usage.
4092   assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4093          Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
4094   if (!NewUB)
4095     return true;
4096   UB = NewUB;
4097   if (LessOp)
4098     TestIsLessOp = LessOp;
4099   TestIsStrictOp = StrictOp;
4100   ConditionSrcRange = SR;
4101   ConditionLoc = SL;
4102   return false;
4103 }
4104 
4105 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
4106   // State consistency checking to ensure correct usage.
4107   assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
4108   if (!NewStep)
4109     return true;
4110   if (!NewStep->isValueDependent()) {
4111     // Check that the step is integer expression.
4112     SourceLocation StepLoc = NewStep->getBeginLoc();
4113     ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4114         StepLoc, getExprAsWritten(NewStep));
4115     if (Val.isInvalid())
4116       return true;
4117     NewStep = Val.get();
4118 
4119     // OpenMP [2.6, Canonical Loop Form, Restrictions]
4120     //  If test-expr is of form var relational-op b and relational-op is < or
4121     //  <= then incr-expr must cause var to increase on each iteration of the
4122     //  loop. If test-expr is of form var relational-op b and relational-op is
4123     //  > or >= then incr-expr must cause var to decrease on each iteration of
4124     //  the loop.
4125     //  If test-expr is of form b relational-op var and relational-op is < or
4126     //  <= then incr-expr must cause var to decrease on each iteration of the
4127     //  loop. If test-expr is of form b relational-op var and relational-op is
4128     //  > or >= then incr-expr must cause var to increase on each iteration of
4129     //  the loop.
4130     llvm::APSInt Result;
4131     bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4132     bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4133     bool IsConstNeg =
4134         IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
4135     bool IsConstPos =
4136         IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
4137     bool IsConstZero = IsConstant && !Result.getBoolValue();
4138 
4139     // != with increment is treated as <; != with decrement is treated as >
4140     if (!TestIsLessOp.hasValue())
4141       TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
4142     if (UB && (IsConstZero ||
4143                (TestIsLessOp.getValue() ?
4144                   (IsConstNeg || (IsUnsigned && Subtract)) :
4145                   (IsConstPos || (IsUnsigned && !Subtract))))) {
4146       SemaRef.Diag(NewStep->getExprLoc(),
4147                    diag::err_omp_loop_incr_not_compatible)
4148           << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
4149       SemaRef.Diag(ConditionLoc,
4150                    diag::note_omp_loop_cond_requres_compatible_incr)
4151           << TestIsLessOp.getValue() << ConditionSrcRange;
4152       return true;
4153     }
4154     if (TestIsLessOp.getValue() == Subtract) {
4155       NewStep =
4156           SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4157               .get();
4158       Subtract = !Subtract;
4159     }
4160   }
4161 
4162   Step = NewStep;
4163   SubtractStep = Subtract;
4164   return false;
4165 }
4166 
4167 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
4168   // Check init-expr for canonical loop form and save loop counter
4169   // variable - #Var and its initialization value - #LB.
4170   // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4171   //   var = lb
4172   //   integer-type var = lb
4173   //   random-access-iterator-type var = lb
4174   //   pointer-type var = lb
4175   //
4176   if (!S) {
4177     if (EmitDiags) {
4178       SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4179     }
4180     return true;
4181   }
4182   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4183     if (!ExprTemp->cleanupsHaveSideEffects())
4184       S = ExprTemp->getSubExpr();
4185 
4186   InitSrcRange = S->getSourceRange();
4187   if (Expr *E = dyn_cast<Expr>(S))
4188     S = E->IgnoreParens();
4189   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4190     if (BO->getOpcode() == BO_Assign) {
4191       Expr *LHS = BO->getLHS()->IgnoreParens();
4192       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4193         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4194           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4195             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4196         return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
4197       }
4198       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4199         if (ME->isArrow() &&
4200             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4201           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4202       }
4203     }
4204   } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
4205     if (DS->isSingleDecl()) {
4206       if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
4207         if (Var->hasInit() && !Var->getType()->isReferenceType()) {
4208           // Accept non-canonical init form here but emit ext. warning.
4209           if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
4210             SemaRef.Diag(S->getBeginLoc(),
4211                          diag::ext_omp_loop_not_canonical_init)
4212                 << S->getSourceRange();
4213           return setLCDeclAndLB(
4214               Var,
4215               buildDeclRefExpr(SemaRef, Var,
4216                                Var->getType().getNonReferenceType(),
4217                                DS->getBeginLoc()),
4218               Var->getInit());
4219         }
4220       }
4221     }
4222   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4223     if (CE->getOperator() == OO_Equal) {
4224       Expr *LHS = CE->getArg(0);
4225       if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4226         if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4227           if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
4228             return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4229         return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
4230       }
4231       if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4232         if (ME->isArrow() &&
4233             isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4234           return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4235       }
4236     }
4237   }
4238 
4239   if (dependent() || SemaRef.CurContext->isDependentContext())
4240     return false;
4241   if (EmitDiags) {
4242     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
4243         << S->getSourceRange();
4244   }
4245   return true;
4246 }
4247 
4248 /// Ignore parenthesizes, implicit casts, copy constructor and return the
4249 /// variable (which may be the loop variable) if possible.
4250 static const ValueDecl *getInitLCDecl(const Expr *E) {
4251   if (!E)
4252     return nullptr;
4253   E = getExprAsWritten(E);
4254   if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
4255     if (const CXXConstructorDecl *Ctor = CE->getConstructor())
4256       if ((Ctor->isCopyOrMoveConstructor() ||
4257            Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4258           CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
4259         E = CE->getArg(0)->IgnoreParenImpCasts();
4260   if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4261     if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4262       return getCanonicalDecl(VD);
4263   }
4264   if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
4265     if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4266       return getCanonicalDecl(ME->getMemberDecl());
4267   return nullptr;
4268 }
4269 
4270 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
4271   // Check test-expr for canonical form, save upper-bound UB, flags for
4272   // less/greater and for strict/non-strict comparison.
4273   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4274   //   var relational-op b
4275   //   b relational-op var
4276   //
4277   if (!S) {
4278     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
4279     return true;
4280   }
4281   S = getExprAsWritten(S);
4282   SourceLocation CondLoc = S->getBeginLoc();
4283   if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4284     if (BO->isRelationalOp()) {
4285       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4286         return setUB(BO->getRHS(),
4287                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4288                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4289                      BO->getSourceRange(), BO->getOperatorLoc());
4290       if (getInitLCDecl(BO->getRHS()) == LCDecl)
4291         return setUB(BO->getLHS(),
4292                      (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4293                      (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4294                      BO->getSourceRange(), BO->getOperatorLoc());
4295     } else if (BO->getOpcode() == BO_NE)
4296         return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4297                        BO->getRHS() : BO->getLHS(),
4298                      /*LessOp=*/llvm::None,
4299                      /*StrictOp=*/true,
4300                      BO->getSourceRange(), BO->getOperatorLoc());
4301   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4302     if (CE->getNumArgs() == 2) {
4303       auto Op = CE->getOperator();
4304       switch (Op) {
4305       case OO_Greater:
4306       case OO_GreaterEqual:
4307       case OO_Less:
4308       case OO_LessEqual:
4309         if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4310           return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
4311                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4312                        CE->getOperatorLoc());
4313         if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4314           return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
4315                        Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4316                        CE->getOperatorLoc());
4317         break;
4318       case OO_ExclaimEqual:
4319         return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4320                      CE->getArg(1) : CE->getArg(0),
4321                      /*LessOp=*/llvm::None,
4322                      /*StrictOp=*/true,
4323                      CE->getSourceRange(),
4324                      CE->getOperatorLoc());
4325         break;
4326       default:
4327         break;
4328       }
4329     }
4330   }
4331   if (dependent() || SemaRef.CurContext->isDependentContext())
4332     return false;
4333   SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
4334       << S->getSourceRange() << LCDecl;
4335   return true;
4336 }
4337 
4338 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
4339   // RHS of canonical loop form increment can be:
4340   //   var + incr
4341   //   incr + var
4342   //   var - incr
4343   //
4344   RHS = RHS->IgnoreParenImpCasts();
4345   if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
4346     if (BO->isAdditiveOp()) {
4347       bool IsAdd = BO->getOpcode() == BO_Add;
4348       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4349         return setStep(BO->getRHS(), !IsAdd);
4350       if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4351         return setStep(BO->getLHS(), /*Subtract=*/false);
4352     }
4353   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
4354     bool IsAdd = CE->getOperator() == OO_Plus;
4355     if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
4356       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4357         return setStep(CE->getArg(1), !IsAdd);
4358       if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4359         return setStep(CE->getArg(0), /*Subtract=*/false);
4360     }
4361   }
4362   if (dependent() || SemaRef.CurContext->isDependentContext())
4363     return false;
4364   SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4365       << RHS->getSourceRange() << LCDecl;
4366   return true;
4367 }
4368 
4369 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
4370   // Check incr-expr for canonical loop form and return true if it
4371   // does not conform.
4372   // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4373   //   ++var
4374   //   var++
4375   //   --var
4376   //   var--
4377   //   var += incr
4378   //   var -= incr
4379   //   var = var + incr
4380   //   var = incr + var
4381   //   var = var - incr
4382   //
4383   if (!S) {
4384     SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
4385     return true;
4386   }
4387   if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4388     if (!ExprTemp->cleanupsHaveSideEffects())
4389       S = ExprTemp->getSubExpr();
4390 
4391   IncrementSrcRange = S->getSourceRange();
4392   S = S->IgnoreParens();
4393   if (auto *UO = dyn_cast<UnaryOperator>(S)) {
4394     if (UO->isIncrementDecrementOp() &&
4395         getInitLCDecl(UO->getSubExpr()) == LCDecl)
4396       return setStep(SemaRef
4397                          .ActOnIntegerConstant(UO->getBeginLoc(),
4398                                                (UO->isDecrementOp() ? -1 : 1))
4399                          .get(),
4400                      /*Subtract=*/false);
4401   } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
4402     switch (BO->getOpcode()) {
4403     case BO_AddAssign:
4404     case BO_SubAssign:
4405       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4406         return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4407       break;
4408     case BO_Assign:
4409       if (getInitLCDecl(BO->getLHS()) == LCDecl)
4410         return checkAndSetIncRHS(BO->getRHS());
4411       break;
4412     default:
4413       break;
4414     }
4415   } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
4416     switch (CE->getOperator()) {
4417     case OO_PlusPlus:
4418     case OO_MinusMinus:
4419       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4420         return setStep(SemaRef
4421                            .ActOnIntegerConstant(
4422                                CE->getBeginLoc(),
4423                                ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4424                            .get(),
4425                        /*Subtract=*/false);
4426       break;
4427     case OO_PlusEqual:
4428     case OO_MinusEqual:
4429       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4430         return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4431       break;
4432     case OO_Equal:
4433       if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4434         return checkAndSetIncRHS(CE->getArg(1));
4435       break;
4436     default:
4437       break;
4438     }
4439   }
4440   if (dependent() || SemaRef.CurContext->isDependentContext())
4441     return false;
4442   SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
4443       << S->getSourceRange() << LCDecl;
4444   return true;
4445 }
4446 
4447 static ExprResult
4448 tryBuildCapture(Sema &SemaRef, Expr *Capture,
4449                 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4450   if (SemaRef.CurContext->isDependentContext())
4451     return ExprResult(Capture);
4452   if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4453     return SemaRef.PerformImplicitConversion(
4454         Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4455         /*AllowExplicit=*/true);
4456   auto I = Captures.find(Capture);
4457   if (I != Captures.end())
4458     return buildCapture(SemaRef, Capture, I->second);
4459   DeclRefExpr *Ref = nullptr;
4460   ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4461   Captures[Capture] = Ref;
4462   return Res;
4463 }
4464 
4465 /// Build the expression to calculate the number of iterations.
4466 Expr *OpenMPIterationSpaceChecker::buildNumIterations(
4467     Scope *S, const bool LimitedType,
4468     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4469   ExprResult Diff;
4470   QualType VarType = LCDecl->getType().getNonReferenceType();
4471   if (VarType->isIntegerType() || VarType->isPointerType() ||
4472       SemaRef.getLangOpts().CPlusPlus) {
4473     // Upper - Lower
4474     Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4475     Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
4476     Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4477     Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
4478     if (!Upper || !Lower)
4479       return nullptr;
4480 
4481     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4482 
4483     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4484       // BuildBinOp already emitted error, this one is to point user to upper
4485       // and lower bound, and to tell what is passed to 'operator-'.
4486       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4487           << Upper->getSourceRange() << Lower->getSourceRange();
4488       return nullptr;
4489     }
4490   }
4491 
4492   if (!Diff.isUsable())
4493     return nullptr;
4494 
4495   // Upper - Lower [- 1]
4496   if (TestIsStrictOp)
4497     Diff = SemaRef.BuildBinOp(
4498         S, DefaultLoc, BO_Sub, Diff.get(),
4499         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4500   if (!Diff.isUsable())
4501     return nullptr;
4502 
4503   // Upper - Lower [- 1] + Step
4504   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4505   if (!NewStep.isUsable())
4506     return nullptr;
4507   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
4508   if (!Diff.isUsable())
4509     return nullptr;
4510 
4511   // Parentheses (for dumping/debugging purposes only).
4512   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4513   if (!Diff.isUsable())
4514     return nullptr;
4515 
4516   // (Upper - Lower [- 1] + Step) / Step
4517   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4518   if (!Diff.isUsable())
4519     return nullptr;
4520 
4521   // OpenMP runtime requires 32-bit or 64-bit loop variables.
4522   QualType Type = Diff.get()->getType();
4523   ASTContext &C = SemaRef.Context;
4524   bool UseVarType = VarType->hasIntegerRepresentation() &&
4525                     C.getTypeSize(Type) > C.getTypeSize(VarType);
4526   if (!Type->isIntegerType() || UseVarType) {
4527     unsigned NewSize =
4528         UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4529     bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4530                                : Type->hasSignedIntegerRepresentation();
4531     Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
4532     if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4533       Diff = SemaRef.PerformImplicitConversion(
4534           Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4535       if (!Diff.isUsable())
4536         return nullptr;
4537     }
4538   }
4539   if (LimitedType) {
4540     unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4541     if (NewSize != C.getTypeSize(Type)) {
4542       if (NewSize < C.getTypeSize(Type)) {
4543         assert(NewSize == 64 && "incorrect loop var size");
4544         SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4545             << InitSrcRange << ConditionSrcRange;
4546       }
4547       QualType NewType = C.getIntTypeForBitwidth(
4548           NewSize, Type->hasSignedIntegerRepresentation() ||
4549                        C.getTypeSize(Type) < NewSize);
4550       if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4551         Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4552                                                  Sema::AA_Converting, true);
4553         if (!Diff.isUsable())
4554           return nullptr;
4555       }
4556     }
4557   }
4558 
4559   return Diff.get();
4560 }
4561 
4562 Expr *OpenMPIterationSpaceChecker::buildPreCond(
4563     Scope *S, Expr *Cond,
4564     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
4565   // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4566   bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4567   SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4568 
4569   ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4570   ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
4571   if (!NewLB.isUsable() || !NewUB.isUsable())
4572     return nullptr;
4573 
4574   ExprResult CondExpr =
4575       SemaRef.BuildBinOp(S, DefaultLoc,
4576                          TestIsLessOp.getValue() ?
4577                            (TestIsStrictOp ? BO_LT : BO_LE) :
4578                            (TestIsStrictOp ? BO_GT : BO_GE),
4579                          NewLB.get(), NewUB.get());
4580   if (CondExpr.isUsable()) {
4581     if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4582                                                 SemaRef.Context.BoolTy))
4583       CondExpr = SemaRef.PerformImplicitConversion(
4584           CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4585           /*AllowExplicit=*/true);
4586   }
4587   SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4588   // Otherwise use original loop condition and evaluate it in runtime.
4589   return CondExpr.isUsable() ? CondExpr.get() : Cond;
4590 }
4591 
4592 /// Build reference expression to the counter be used for codegen.
4593 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
4594     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4595     DSAStackTy &DSA) const {
4596   auto *VD = dyn_cast<VarDecl>(LCDecl);
4597   if (!VD) {
4598     VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4599     DeclRefExpr *Ref = buildDeclRefExpr(
4600         SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
4601     const DSAStackTy::DSAVarData Data =
4602         DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4603     // If the loop control decl is explicitly marked as private, do not mark it
4604     // as captured again.
4605     if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4606       Captures.insert(std::make_pair(LCRef, Ref));
4607     return Ref;
4608   }
4609   return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
4610                           DefaultLoc);
4611 }
4612 
4613 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
4614   if (LCDecl && !LCDecl->isInvalidDecl()) {
4615     QualType Type = LCDecl->getType().getNonReferenceType();
4616     VarDecl *PrivateVar = buildVarDecl(
4617         SemaRef, DefaultLoc, Type, LCDecl->getName(),
4618         LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4619         isa<VarDecl>(LCDecl)
4620             ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4621             : nullptr);
4622     if (PrivateVar->isInvalidDecl())
4623       return nullptr;
4624     return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4625   }
4626   return nullptr;
4627 }
4628 
4629 /// Build initialization of the counter to be used for codegen.
4630 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
4631 
4632 /// Build step of the counter be used for codegen.
4633 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
4634 
4635 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4636     Scope *S, Expr *Counter,
4637     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4638     Expr *Inc, OverloadedOperatorKind OOK) {
4639   Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4640   if (!Cnt)
4641     return nullptr;
4642   if (Inc) {
4643     assert((OOK == OO_Plus || OOK == OO_Minus) &&
4644            "Expected only + or - operations for depend clauses.");
4645     BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4646     Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4647     if (!Cnt)
4648       return nullptr;
4649   }
4650   ExprResult Diff;
4651   QualType VarType = LCDecl->getType().getNonReferenceType();
4652   if (VarType->isIntegerType() || VarType->isPointerType() ||
4653       SemaRef.getLangOpts().CPlusPlus) {
4654     // Upper - Lower
4655     Expr *Upper = TestIsLessOp.getValue()
4656                       ? Cnt
4657                       : tryBuildCapture(SemaRef, UB, Captures).get();
4658     Expr *Lower = TestIsLessOp.getValue()
4659                       ? tryBuildCapture(SemaRef, LB, Captures).get()
4660                       : Cnt;
4661     if (!Upper || !Lower)
4662       return nullptr;
4663 
4664     Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4665 
4666     if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4667       // BuildBinOp already emitted error, this one is to point user to upper
4668       // and lower bound, and to tell what is passed to 'operator-'.
4669       SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4670           << Upper->getSourceRange() << Lower->getSourceRange();
4671       return nullptr;
4672     }
4673   }
4674 
4675   if (!Diff.isUsable())
4676     return nullptr;
4677 
4678   // Parentheses (for dumping/debugging purposes only).
4679   Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4680   if (!Diff.isUsable())
4681     return nullptr;
4682 
4683   ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4684   if (!NewStep.isUsable())
4685     return nullptr;
4686   // (Upper - Lower) / Step
4687   Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4688   if (!Diff.isUsable())
4689     return nullptr;
4690 
4691   return Diff.get();
4692 }
4693 
4694 /// Iteration space of a single for loop.
4695 struct LoopIterationSpace final {
4696   /// True if the condition operator is the strict compare operator (<, > or
4697   /// !=).
4698   bool IsStrictCompare = false;
4699   /// Condition of the loop.
4700   Expr *PreCond = nullptr;
4701   /// This expression calculates the number of iterations in the loop.
4702   /// It is always possible to calculate it before starting the loop.
4703   Expr *NumIterations = nullptr;
4704   /// The loop counter variable.
4705   Expr *CounterVar = nullptr;
4706   /// Private loop counter variable.
4707   Expr *PrivateCounterVar = nullptr;
4708   /// This is initializer for the initial value of #CounterVar.
4709   Expr *CounterInit = nullptr;
4710   /// This is step for the #CounterVar used to generate its update:
4711   /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
4712   Expr *CounterStep = nullptr;
4713   /// Should step be subtracted?
4714   bool Subtract = false;
4715   /// Source range of the loop init.
4716   SourceRange InitSrcRange;
4717   /// Source range of the loop condition.
4718   SourceRange CondSrcRange;
4719   /// Source range of the loop increment.
4720   SourceRange IncSrcRange;
4721 };
4722 
4723 } // namespace
4724 
4725 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4726   assert(getLangOpts().OpenMP && "OpenMP is not active.");
4727   assert(Init && "Expected loop in canonical form.");
4728   unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4729   if (AssociatedLoops > 0 &&
4730       isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4731     DSAStack->loopStart();
4732     OpenMPIterationSpaceChecker ISC(*this, ForLoc);
4733     if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4734       if (ValueDecl *D = ISC.getLoopDecl()) {
4735         auto *VD = dyn_cast<VarDecl>(D);
4736         if (!VD) {
4737           if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
4738             VD = Private;
4739           } else {
4740             DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4741                                             /*WithInit=*/false);
4742             VD = cast<VarDecl>(Ref->getDecl());
4743           }
4744         }
4745         DSAStack->addLoopControlVariable(D, VD);
4746         const Decl *LD = DSAStack->getPossiblyLoopCunter();
4747         if (LD != D->getCanonicalDecl()) {
4748           DSAStack->resetPossibleLoopCounter();
4749           if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
4750             MarkDeclarationsReferencedInExpr(
4751                 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
4752                                  Var->getType().getNonLValueExprType(Context),
4753                                  ForLoc, /*RefersToCapture=*/true));
4754         }
4755       }
4756     }
4757     DSAStack->setAssociatedLoops(AssociatedLoops - 1);
4758   }
4759 }
4760 
4761 /// Called on a for stmt to check and extract its iteration space
4762 /// for further processing (such as collapsing).
4763 static bool checkOpenMPIterationSpace(
4764     OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4765     unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
4766     unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
4767     Expr *OrderedLoopCountExpr,
4768     Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
4769     LoopIterationSpace &ResultIterSpace,
4770     llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4771   // OpenMP [2.6, Canonical Loop Form]
4772   //   for (init-expr; test-expr; incr-expr) structured-block
4773   auto *For = dyn_cast_or_null<ForStmt>(S);
4774   if (!For) {
4775     SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
4776         << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4777         << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
4778         << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4779     if (TotalNestedLoopCount > 1) {
4780       if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4781         SemaRef.Diag(DSA.getConstructLoc(),
4782                      diag::note_omp_collapse_ordered_expr)
4783             << 2 << CollapseLoopCountExpr->getSourceRange()
4784             << OrderedLoopCountExpr->getSourceRange();
4785       else if (CollapseLoopCountExpr)
4786         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4787                      diag::note_omp_collapse_ordered_expr)
4788             << 0 << CollapseLoopCountExpr->getSourceRange();
4789       else
4790         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4791                      diag::note_omp_collapse_ordered_expr)
4792             << 1 << OrderedLoopCountExpr->getSourceRange();
4793     }
4794     return true;
4795   }
4796   assert(For->getBody());
4797 
4798   OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4799 
4800   // Check init.
4801   Stmt *Init = For->getInit();
4802   if (ISC.checkAndSetInit(Init))
4803     return true;
4804 
4805   bool HasErrors = false;
4806 
4807   // Check loop variable's type.
4808   if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4809     Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
4810 
4811     // OpenMP [2.6, Canonical Loop Form]
4812     // Var is one of the following:
4813     //   A variable of signed or unsigned integer type.
4814     //   For C++, a variable of a random access iterator type.
4815     //   For C, a variable of a pointer type.
4816     QualType VarType = LCDecl->getType().getNonReferenceType();
4817     if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4818         !VarType->isPointerType() &&
4819         !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4820       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
4821           << SemaRef.getLangOpts().CPlusPlus;
4822       HasErrors = true;
4823     }
4824 
4825     // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4826     // a Construct
4827     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4828     // parallel for construct is (are) private.
4829     // The loop iteration variable in the associated for-loop of a simd
4830     // construct with just one associated for-loop is linear with a
4831     // constant-linear-step that is the increment of the associated for-loop.
4832     // Exclude loop var from the list of variables with implicitly defined data
4833     // sharing attributes.
4834     VarsWithImplicitDSA.erase(LCDecl);
4835 
4836     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4837     // in a Construct, C/C++].
4838     // The loop iteration variable in the associated for-loop of a simd
4839     // construct with just one associated for-loop may be listed in a linear
4840     // clause with a constant-linear-step that is the increment of the
4841     // associated for-loop.
4842     // The loop iteration variable(s) in the associated for-loop(s) of a for or
4843     // parallel for construct may be listed in a private or lastprivate clause.
4844     DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4845     // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4846     // declared in the loop and it is predetermined as a private.
4847     OpenMPClauseKind PredeterminedCKind =
4848         isOpenMPSimdDirective(DKind)
4849             ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4850             : OMPC_private;
4851     if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4852           DVar.CKind != PredeterminedCKind) ||
4853          ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4854            isOpenMPDistributeDirective(DKind)) &&
4855           !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4856           DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4857         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4858       SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
4859           << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4860           << getOpenMPClauseName(PredeterminedCKind);
4861       if (DVar.RefExpr == nullptr)
4862         DVar.CKind = PredeterminedCKind;
4863       reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4864       HasErrors = true;
4865     } else if (LoopDeclRefExpr != nullptr) {
4866       // Make the loop iteration variable private (for worksharing constructs),
4867       // linear (for simd directives with the only one associated loop) or
4868       // lastprivate (for simd directives with several collapsed or ordered
4869       // loops).
4870       if (DVar.CKind == OMPC_unknown)
4871         DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4872     }
4873 
4874     assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4875 
4876     // Check test-expr.
4877     HasErrors |= ISC.checkAndSetCond(For->getCond());
4878 
4879     // Check incr-expr.
4880     HasErrors |= ISC.checkAndSetInc(For->getInc());
4881   }
4882 
4883   if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
4884     return HasErrors;
4885 
4886   // Build the loop's iteration space representation.
4887   ResultIterSpace.PreCond =
4888       ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4889   ResultIterSpace.NumIterations = ISC.buildNumIterations(
4890       DSA.getCurScope(),
4891       (isOpenMPWorksharingDirective(DKind) ||
4892        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4893       Captures);
4894   ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
4895   ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
4896   ResultIterSpace.CounterInit = ISC.buildCounterInit();
4897   ResultIterSpace.CounterStep = ISC.buildCounterStep();
4898   ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
4899   ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
4900   ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
4901   ResultIterSpace.Subtract = ISC.shouldSubtractStep();
4902   ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
4903 
4904   HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4905                 ResultIterSpace.NumIterations == nullptr ||
4906                 ResultIterSpace.CounterVar == nullptr ||
4907                 ResultIterSpace.PrivateCounterVar == nullptr ||
4908                 ResultIterSpace.CounterInit == nullptr ||
4909                 ResultIterSpace.CounterStep == nullptr);
4910   if (!HasErrors && DSA.isOrderedRegion()) {
4911     if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
4912       if (CurrentNestedLoopCount <
4913           DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
4914         DSA.getOrderedRegionParam().second->setLoopNumIterations(
4915             CurrentNestedLoopCount, ResultIterSpace.NumIterations);
4916         DSA.getOrderedRegionParam().second->setLoopCounter(
4917             CurrentNestedLoopCount, ResultIterSpace.CounterVar);
4918       }
4919     }
4920     for (auto &Pair : DSA.getDoacrossDependClauses()) {
4921       if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
4922         // Erroneous case - clause has some problems.
4923         continue;
4924       }
4925       if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
4926           Pair.second.size() <= CurrentNestedLoopCount) {
4927         // Erroneous case - clause has some problems.
4928         Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
4929         continue;
4930       }
4931       Expr *CntValue;
4932       if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4933         CntValue = ISC.buildOrderedLoopData(
4934             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4935             Pair.first->getDependencyLoc());
4936       else
4937         CntValue = ISC.buildOrderedLoopData(
4938             DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4939             Pair.first->getDependencyLoc(),
4940             Pair.second[CurrentNestedLoopCount].first,
4941             Pair.second[CurrentNestedLoopCount].second);
4942       Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
4943     }
4944   }
4945 
4946   return HasErrors;
4947 }
4948 
4949 /// Build 'VarRef = Start.
4950 static ExprResult
4951 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4952                  ExprResult Start,
4953                  llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
4954   // Build 'VarRef = Start.
4955   ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4956   if (!NewStart.isUsable())
4957     return ExprError();
4958   if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
4959                                    VarRef.get()->getType())) {
4960     NewStart = SemaRef.PerformImplicitConversion(
4961         NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4962         /*AllowExplicit=*/true);
4963     if (!NewStart.isUsable())
4964       return ExprError();
4965   }
4966 
4967   ExprResult Init =
4968       SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4969   return Init;
4970 }
4971 
4972 /// Build 'VarRef = Start + Iter * Step'.
4973 static ExprResult buildCounterUpdate(
4974     Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4975     ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
4976     llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
4977   // Add parentheses (for debugging purposes only).
4978   Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4979   if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4980       !Step.isUsable())
4981     return ExprError();
4982 
4983   ExprResult NewStep = Step;
4984   if (Captures)
4985     NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
4986   if (NewStep.isInvalid())
4987     return ExprError();
4988   ExprResult Update =
4989       SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
4990   if (!Update.isUsable())
4991     return ExprError();
4992 
4993   // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4994   // 'VarRef = Start (+|-) Iter * Step'.
4995   ExprResult NewStart = Start;
4996   if (Captures)
4997     NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
4998   if (NewStart.isInvalid())
4999     return ExprError();
5000 
5001   // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5002   ExprResult SavedUpdate = Update;
5003   ExprResult UpdateVal;
5004   if (VarRef.get()->getType()->isOverloadableType() ||
5005       NewStart.get()->getType()->isOverloadableType() ||
5006       Update.get()->getType()->isOverloadableType()) {
5007     bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5008     SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5009     Update =
5010         SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5011     if (Update.isUsable()) {
5012       UpdateVal =
5013           SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5014                              VarRef.get(), SavedUpdate.get());
5015       if (UpdateVal.isUsable()) {
5016         Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5017                                             UpdateVal.get());
5018       }
5019     }
5020     SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5021   }
5022 
5023   // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5024   if (!Update.isUsable() || !UpdateVal.isUsable()) {
5025     Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5026                                 NewStart.get(), SavedUpdate.get());
5027     if (!Update.isUsable())
5028       return ExprError();
5029 
5030     if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5031                                      VarRef.get()->getType())) {
5032       Update = SemaRef.PerformImplicitConversion(
5033           Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5034       if (!Update.isUsable())
5035         return ExprError();
5036     }
5037 
5038     Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5039   }
5040   return Update;
5041 }
5042 
5043 /// Convert integer expression \a E to make it have at least \a Bits
5044 /// bits.
5045 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
5046   if (E == nullptr)
5047     return ExprError();
5048   ASTContext &C = SemaRef.Context;
5049   QualType OldType = E->getType();
5050   unsigned HasBits = C.getTypeSize(OldType);
5051   if (HasBits >= Bits)
5052     return ExprResult(E);
5053   // OK to convert to signed, because new type has more bits than old.
5054   QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5055   return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5056                                            true);
5057 }
5058 
5059 /// Check if the given expression \a E is a constant integer that fits
5060 /// into \a Bits bits.
5061 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
5062   if (E == nullptr)
5063     return false;
5064   llvm::APSInt Result;
5065   if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5066     return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5067   return false;
5068 }
5069 
5070 /// Build preinits statement for the given declarations.
5071 static Stmt *buildPreInits(ASTContext &Context,
5072                            MutableArrayRef<Decl *> PreInits) {
5073   if (!PreInits.empty()) {
5074     return new (Context) DeclStmt(
5075         DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5076         SourceLocation(), SourceLocation());
5077   }
5078   return nullptr;
5079 }
5080 
5081 /// Build preinits statement for the given declarations.
5082 static Stmt *
5083 buildPreInits(ASTContext &Context,
5084               const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
5085   if (!Captures.empty()) {
5086     SmallVector<Decl *, 16> PreInits;
5087     for (const auto &Pair : Captures)
5088       PreInits.push_back(Pair.second->getDecl());
5089     return buildPreInits(Context, PreInits);
5090   }
5091   return nullptr;
5092 }
5093 
5094 /// Build postupdate expression for the given list of postupdates expressions.
5095 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5096   Expr *PostUpdate = nullptr;
5097   if (!PostUpdates.empty()) {
5098     for (Expr *E : PostUpdates) {
5099       Expr *ConvE = S.BuildCStyleCastExpr(
5100                          E->getExprLoc(),
5101                          S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5102                          E->getExprLoc(), E)
5103                         .get();
5104       PostUpdate = PostUpdate
5105                        ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5106                                               PostUpdate, ConvE)
5107                              .get()
5108                        : ConvE;
5109     }
5110   }
5111   return PostUpdate;
5112 }
5113 
5114 /// Called on a for stmt to check itself and nested loops (if any).
5115 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5116 /// number of collapsed loops otherwise.
5117 static unsigned
5118 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
5119                 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5120                 DSAStackTy &DSA,
5121                 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
5122                 OMPLoopDirective::HelperExprs &Built) {
5123   unsigned NestedLoopCount = 1;
5124   if (CollapseLoopCountExpr) {
5125     // Found 'collapse' clause - calculate collapse number.
5126     Expr::EvalResult Result;
5127     if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
5128       NestedLoopCount = Result.Val.getInt().getLimitedValue();
5129   }
5130   unsigned OrderedLoopCount = 1;
5131   if (OrderedLoopCountExpr) {
5132     // Found 'ordered' clause - calculate collapse number.
5133     Expr::EvalResult EVResult;
5134     if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5135       llvm::APSInt Result = EVResult.Val.getInt();
5136       if (Result.getLimitedValue() < NestedLoopCount) {
5137         SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5138                      diag::err_omp_wrong_ordered_loop_count)
5139             << OrderedLoopCountExpr->getSourceRange();
5140         SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5141                      diag::note_collapse_loop_count)
5142             << CollapseLoopCountExpr->getSourceRange();
5143       }
5144       OrderedLoopCount = Result.getLimitedValue();
5145     }
5146   }
5147   // This is helper routine for loop directives (e.g., 'for', 'simd',
5148   // 'for simd', etc.).
5149   llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
5150   SmallVector<LoopIterationSpace, 4> IterSpaces(
5151       std::max(OrderedLoopCount, NestedLoopCount));
5152   Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
5153   for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
5154     if (checkOpenMPIterationSpace(
5155             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5156             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5157             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5158             Captures))
5159       return 0;
5160     // Move on to the next nested for loop, or to the loop body.
5161     // OpenMP [2.8.1, simd construct, Restrictions]
5162     // All loops associated with the construct must be perfectly nested; that
5163     // is, there must be no intervening code nor any OpenMP directive between
5164     // any two loops.
5165     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5166   }
5167   for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5168     if (checkOpenMPIterationSpace(
5169             DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5170             std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5171             OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5172             Captures))
5173       return 0;
5174     if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5175       // Handle initialization of captured loop iterator variables.
5176       auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5177       if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5178         Captures[DRE] = DRE;
5179       }
5180     }
5181     // Move on to the next nested for loop, or to the loop body.
5182     // OpenMP [2.8.1, simd construct, Restrictions]
5183     // All loops associated with the construct must be perfectly nested; that
5184     // is, there must be no intervening code nor any OpenMP directive between
5185     // any two loops.
5186     CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5187   }
5188 
5189   Built.clear(/* size */ NestedLoopCount);
5190 
5191   if (SemaRef.CurContext->isDependentContext())
5192     return NestedLoopCount;
5193 
5194   // An example of what is generated for the following code:
5195   //
5196   //   #pragma omp simd collapse(2) ordered(2)
5197   //   for (i = 0; i < NI; ++i)
5198   //     for (k = 0; k < NK; ++k)
5199   //       for (j = J0; j < NJ; j+=2) {
5200   //         <loop body>
5201   //       }
5202   //
5203   // We generate the code below.
5204   // Note: the loop body may be outlined in CodeGen.
5205   // Note: some counters may be C++ classes, operator- is used to find number of
5206   // iterations and operator+= to calculate counter value.
5207   // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5208   // or i64 is currently supported).
5209   //
5210   //   #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5211   //   for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5212   //     .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5213   //     .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5214   //     // similar updates for vars in clauses (e.g. 'linear')
5215   //     <loop body (using local i and j)>
5216   //   }
5217   //   i = NI; // assign final values of counters
5218   //   j = NJ;
5219   //
5220 
5221   // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5222   // the iteration counts of the collapsed for loops.
5223   // Precondition tests if there is at least one iteration (all conditions are
5224   // true).
5225   auto PreCond = ExprResult(IterSpaces[0].PreCond);
5226   Expr *N0 = IterSpaces[0].NumIterations;
5227   ExprResult LastIteration32 =
5228       widenIterationCount(/*Bits=*/32,
5229                           SemaRef
5230                               .PerformImplicitConversion(
5231                                   N0->IgnoreImpCasts(), N0->getType(),
5232                                   Sema::AA_Converting, /*AllowExplicit=*/true)
5233                               .get(),
5234                           SemaRef);
5235   ExprResult LastIteration64 = widenIterationCount(
5236       /*Bits=*/64,
5237       SemaRef
5238           .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5239                                      Sema::AA_Converting,
5240                                      /*AllowExplicit=*/true)
5241           .get(),
5242       SemaRef);
5243 
5244   if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5245     return NestedLoopCount;
5246 
5247   ASTContext &C = SemaRef.Context;
5248   bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5249 
5250   Scope *CurScope = DSA.getCurScope();
5251   for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
5252     if (PreCond.isUsable()) {
5253       PreCond =
5254           SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5255                              PreCond.get(), IterSpaces[Cnt].PreCond);
5256     }
5257     Expr *N = IterSpaces[Cnt].NumIterations;
5258     SourceLocation Loc = N->getExprLoc();
5259     AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5260     if (LastIteration32.isUsable())
5261       LastIteration32 = SemaRef.BuildBinOp(
5262           CurScope, Loc, BO_Mul, LastIteration32.get(),
5263           SemaRef
5264               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5265                                          Sema::AA_Converting,
5266                                          /*AllowExplicit=*/true)
5267               .get());
5268     if (LastIteration64.isUsable())
5269       LastIteration64 = SemaRef.BuildBinOp(
5270           CurScope, Loc, BO_Mul, LastIteration64.get(),
5271           SemaRef
5272               .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5273                                          Sema::AA_Converting,
5274                                          /*AllowExplicit=*/true)
5275               .get());
5276   }
5277 
5278   // Choose either the 32-bit or 64-bit version.
5279   ExprResult LastIteration = LastIteration64;
5280   if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5281       (LastIteration32.isUsable() &&
5282        C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5283        (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5284         fitsInto(
5285             /*Bits=*/32,
5286             LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5287             LastIteration64.get(), SemaRef))))
5288     LastIteration = LastIteration32;
5289   QualType VType = LastIteration.get()->getType();
5290   QualType RealVType = VType;
5291   QualType StrideVType = VType;
5292   if (isOpenMPTaskLoopDirective(DKind)) {
5293     VType =
5294         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5295     StrideVType =
5296         SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5297   }
5298 
5299   if (!LastIteration.isUsable())
5300     return 0;
5301 
5302   // Save the number of iterations.
5303   ExprResult NumIterations = LastIteration;
5304   {
5305     LastIteration = SemaRef.BuildBinOp(
5306         CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5307         LastIteration.get(),
5308         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5309     if (!LastIteration.isUsable())
5310       return 0;
5311   }
5312 
5313   // Calculate the last iteration number beforehand instead of doing this on
5314   // each iteration. Do not do this if the number of iterations may be kfold-ed.
5315   llvm::APSInt Result;
5316   bool IsConstant =
5317       LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5318   ExprResult CalcLastIteration;
5319   if (!IsConstant) {
5320     ExprResult SaveRef =
5321         tryBuildCapture(SemaRef, LastIteration.get(), Captures);
5322     LastIteration = SaveRef;
5323 
5324     // Prepare SaveRef + 1.
5325     NumIterations = SemaRef.BuildBinOp(
5326         CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
5327         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5328     if (!NumIterations.isUsable())
5329       return 0;
5330   }
5331 
5332   SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5333 
5334   // Build variables passed into runtime, necessary for worksharing directives.
5335   ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
5336   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5337       isOpenMPDistributeDirective(DKind)) {
5338     // Lower bound variable, initialized with zero.
5339     VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5340     LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
5341     SemaRef.AddInitializerToDecl(LBDecl,
5342                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5343                                  /*DirectInit*/ false);
5344 
5345     // Upper bound variable, initialized with last iteration number.
5346     VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5347     UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
5348     SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
5349                                  /*DirectInit*/ false);
5350 
5351     // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5352     // This will be used to implement clause 'lastprivate'.
5353     QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
5354     VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5355     IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
5356     SemaRef.AddInitializerToDecl(ILDecl,
5357                                  SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5358                                  /*DirectInit*/ false);
5359 
5360     // Stride variable returned by runtime (we initialize it to 1 by default).
5361     VarDecl *STDecl =
5362         buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5363     ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
5364     SemaRef.AddInitializerToDecl(STDecl,
5365                                  SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5366                                  /*DirectInit*/ false);
5367 
5368     // Build expression: UB = min(UB, LastIteration)
5369     // It is necessary for CodeGen of directives with static scheduling.
5370     ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5371                                                 UB.get(), LastIteration.get());
5372     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5373         LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5374         LastIteration.get(), UB.get());
5375     EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5376                              CondOp.get());
5377     EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
5378 
5379     // If we have a combined directive that combines 'distribute', 'for' or
5380     // 'simd' we need to be able to access the bounds of the schedule of the
5381     // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5382     // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5383     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5384       // Lower bound variable, initialized with zero.
5385       VarDecl *CombLBDecl =
5386           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5387       CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5388       SemaRef.AddInitializerToDecl(
5389           CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5390           /*DirectInit*/ false);
5391 
5392       // Upper bound variable, initialized with last iteration number.
5393       VarDecl *CombUBDecl =
5394           buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5395       CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5396       SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5397                                    /*DirectInit*/ false);
5398 
5399       ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5400           CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5401       ExprResult CombCondOp =
5402           SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5403                                      LastIteration.get(), CombUB.get());
5404       CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5405                                    CombCondOp.get());
5406       CombEUB =
5407           SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
5408 
5409       const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
5410       // We expect to have at least 2 more parameters than the 'parallel'
5411       // directive does - the lower and upper bounds of the previous schedule.
5412       assert(CD->getNumParams() >= 4 &&
5413              "Unexpected number of parameters in loop combined directive");
5414 
5415       // Set the proper type for the bounds given what we learned from the
5416       // enclosed loops.
5417       ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5418       ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
5419 
5420       // Previous lower and upper bounds are obtained from the region
5421       // parameters.
5422       PrevLB =
5423           buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5424       PrevUB =
5425           buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5426     }
5427   }
5428 
5429   // Build the iteration variable and its initialization before loop.
5430   ExprResult IV;
5431   ExprResult Init, CombInit;
5432   {
5433     VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5434     IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
5435     Expr *RHS =
5436         (isOpenMPWorksharingDirective(DKind) ||
5437          isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5438             ? LB.get()
5439             : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5440     Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
5441     Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
5442 
5443     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5444       Expr *CombRHS =
5445           (isOpenMPWorksharingDirective(DKind) ||
5446            isOpenMPTaskLoopDirective(DKind) ||
5447            isOpenMPDistributeDirective(DKind))
5448               ? CombLB.get()
5449               : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5450       CombInit =
5451           SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
5452       CombInit =
5453           SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
5454     }
5455   }
5456 
5457   bool UseStrictCompare =
5458       RealVType->hasUnsignedIntegerRepresentation() &&
5459       llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5460         return LIS.IsStrictCompare;
5461       });
5462   // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5463   // unsigned IV)) for worksharing loops.
5464   SourceLocation CondLoc = AStmt->getBeginLoc();
5465   Expr *BoundUB = UB.get();
5466   if (UseStrictCompare) {
5467     BoundUB =
5468         SemaRef
5469             .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5470                         SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5471             .get();
5472     BoundUB =
5473         SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5474   }
5475   ExprResult Cond =
5476       (isOpenMPWorksharingDirective(DKind) ||
5477        isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5478           ? SemaRef.BuildBinOp(CurScope, CondLoc,
5479                                UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5480                                BoundUB)
5481           : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5482                                NumIterations.get());
5483   ExprResult CombDistCond;
5484   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5485     CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5486                                       NumIterations.get());
5487   }
5488 
5489   ExprResult CombCond;
5490   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5491     Expr *BoundCombUB = CombUB.get();
5492     if (UseStrictCompare) {
5493       BoundCombUB =
5494           SemaRef
5495               .BuildBinOp(
5496                   CurScope, CondLoc, BO_Add, BoundCombUB,
5497                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5498               .get();
5499       BoundCombUB =
5500           SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5501               .get();
5502     }
5503     CombCond =
5504         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5505                            IV.get(), BoundCombUB);
5506   }
5507   // Loop increment (IV = IV + 1)
5508   SourceLocation IncLoc = AStmt->getBeginLoc();
5509   ExprResult Inc =
5510       SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5511                          SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5512   if (!Inc.isUsable())
5513     return 0;
5514   Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
5515   Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
5516   if (!Inc.isUsable())
5517     return 0;
5518 
5519   // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5520   // Used for directives with static scheduling.
5521   // In combined construct, add combined version that use CombLB and CombUB
5522   // base variables for the update
5523   ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
5524   if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5525       isOpenMPDistributeDirective(DKind)) {
5526     // LB + ST
5527     NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5528     if (!NextLB.isUsable())
5529       return 0;
5530     // LB = LB + ST
5531     NextLB =
5532         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
5533     NextLB =
5534         SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
5535     if (!NextLB.isUsable())
5536       return 0;
5537     // UB + ST
5538     NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5539     if (!NextUB.isUsable())
5540       return 0;
5541     // UB = UB + ST
5542     NextUB =
5543         SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
5544     NextUB =
5545         SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
5546     if (!NextUB.isUsable())
5547       return 0;
5548     if (isOpenMPLoopBoundSharingDirective(DKind)) {
5549       CombNextLB =
5550           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5551       if (!NextLB.isUsable())
5552         return 0;
5553       // LB = LB + ST
5554       CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5555                                       CombNextLB.get());
5556       CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5557                                                /*DiscardedValue*/ false);
5558       if (!CombNextLB.isUsable())
5559         return 0;
5560       // UB + ST
5561       CombNextUB =
5562           SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5563       if (!CombNextUB.isUsable())
5564         return 0;
5565       // UB = UB + ST
5566       CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5567                                       CombNextUB.get());
5568       CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5569                                                /*DiscardedValue*/ false);
5570       if (!CombNextUB.isUsable())
5571         return 0;
5572     }
5573   }
5574 
5575   // Create increment expression for distribute loop when combined in a same
5576   // directive with for as IV = IV + ST; ensure upper bound expression based
5577   // on PrevUB instead of NumIterations - used to implement 'for' when found
5578   // in combination with 'distribute', like in 'distribute parallel for'
5579   SourceLocation DistIncLoc = AStmt->getBeginLoc();
5580   ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
5581   if (isOpenMPLoopBoundSharingDirective(DKind)) {
5582     DistCond = SemaRef.BuildBinOp(
5583         CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
5584     assert(DistCond.isUsable() && "distribute cond expr was not built");
5585 
5586     DistInc =
5587         SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5588     assert(DistInc.isUsable() && "distribute inc expr was not built");
5589     DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5590                                  DistInc.get());
5591     DistInc =
5592         SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
5593     assert(DistInc.isUsable() && "distribute inc expr was not built");
5594 
5595     // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5596     // construct
5597     SourceLocation DistEUBLoc = AStmt->getBeginLoc();
5598     ExprResult IsUBGreater =
5599         SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5600     ExprResult CondOp = SemaRef.ActOnConditionalOp(
5601         DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5602     PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5603                                  CondOp.get());
5604     PrevEUB =
5605         SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
5606 
5607     // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5608     // parallel for is in combination with a distribute directive with
5609     // schedule(static, 1)
5610     Expr *BoundPrevUB = PrevUB.get();
5611     if (UseStrictCompare) {
5612       BoundPrevUB =
5613           SemaRef
5614               .BuildBinOp(
5615                   CurScope, CondLoc, BO_Add, BoundPrevUB,
5616                   SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5617               .get();
5618       BoundPrevUB =
5619           SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5620               .get();
5621     }
5622     ParForInDistCond =
5623         SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5624                            IV.get(), BoundPrevUB);
5625   }
5626 
5627   // Build updates and final values of the loop counters.
5628   bool HasErrors = false;
5629   Built.Counters.resize(NestedLoopCount);
5630   Built.Inits.resize(NestedLoopCount);
5631   Built.Updates.resize(NestedLoopCount);
5632   Built.Finals.resize(NestedLoopCount);
5633   {
5634     // We implement the following algorithm for obtaining the
5635     // original loop iteration variable values based on the
5636     // value of the collapsed loop iteration variable IV.
5637     //
5638     // Let n+1 be the number of collapsed loops in the nest.
5639     // Iteration variables (I0, I1, .... In)
5640     // Iteration counts (N0, N1, ... Nn)
5641     //
5642     // Acc = IV;
5643     //
5644     // To compute Ik for loop k, 0 <= k <= n, generate:
5645     //    Prod = N(k+1) * N(k+2) * ... * Nn;
5646     //    Ik = Acc / Prod;
5647     //    Acc -= Ik * Prod;
5648     //
5649     ExprResult Acc = IV;
5650     for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
5651       LoopIterationSpace &IS = IterSpaces[Cnt];
5652       SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5653       ExprResult Iter;
5654 
5655       // Compute prod
5656       ExprResult Prod =
5657           SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5658       for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5659         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5660                                   IterSpaces[K].NumIterations);
5661 
5662       // Iter = Acc / Prod
5663       // If there is at least one more inner loop to avoid
5664       // multiplication by 1.
5665       if (Cnt + 1 < NestedLoopCount)
5666         Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5667                                   Acc.get(), Prod.get());
5668       else
5669         Iter = Acc;
5670       if (!Iter.isUsable()) {
5671         HasErrors = true;
5672         break;
5673       }
5674 
5675       // Update Acc:
5676       // Acc -= Iter * Prod
5677       // Check if there is at least one more inner loop to avoid
5678       // multiplication by 1.
5679       if (Cnt + 1 < NestedLoopCount)
5680         Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5681                                   Iter.get(), Prod.get());
5682       else
5683         Prod = Iter;
5684       Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5685                                Acc.get(), Prod.get());
5686 
5687       // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
5688       auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5689       DeclRefExpr *CounterVar = buildDeclRefExpr(
5690           SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5691           /*RefersToCapture=*/true);
5692       ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
5693                                          IS.CounterInit, Captures);
5694       if (!Init.isUsable()) {
5695         HasErrors = true;
5696         break;
5697       }
5698       ExprResult Update = buildCounterUpdate(
5699           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5700           IS.CounterStep, IS.Subtract, &Captures);
5701       if (!Update.isUsable()) {
5702         HasErrors = true;
5703         break;
5704       }
5705 
5706       // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5707       ExprResult Final = buildCounterUpdate(
5708           SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
5709           IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
5710       if (!Final.isUsable()) {
5711         HasErrors = true;
5712         break;
5713       }
5714 
5715       if (!Update.isUsable() || !Final.isUsable()) {
5716         HasErrors = true;
5717         break;
5718       }
5719       // Save results
5720       Built.Counters[Cnt] = IS.CounterVar;
5721       Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
5722       Built.Inits[Cnt] = Init.get();
5723       Built.Updates[Cnt] = Update.get();
5724       Built.Finals[Cnt] = Final.get();
5725     }
5726   }
5727 
5728   if (HasErrors)
5729     return 0;
5730 
5731   // Save results
5732   Built.IterationVarRef = IV.get();
5733   Built.LastIteration = LastIteration.get();
5734   Built.NumIterations = NumIterations.get();
5735   Built.CalcLastIteration = SemaRef
5736                                 .ActOnFinishFullExpr(CalcLastIteration.get(),
5737                                                      /*DiscardedValue*/ false)
5738                                 .get();
5739   Built.PreCond = PreCond.get();
5740   Built.PreInits = buildPreInits(C, Captures);
5741   Built.Cond = Cond.get();
5742   Built.Init = Init.get();
5743   Built.Inc = Inc.get();
5744   Built.LB = LB.get();
5745   Built.UB = UB.get();
5746   Built.IL = IL.get();
5747   Built.ST = ST.get();
5748   Built.EUB = EUB.get();
5749   Built.NLB = NextLB.get();
5750   Built.NUB = NextUB.get();
5751   Built.PrevLB = PrevLB.get();
5752   Built.PrevUB = PrevUB.get();
5753   Built.DistInc = DistInc.get();
5754   Built.PrevEUB = PrevEUB.get();
5755   Built.DistCombinedFields.LB = CombLB.get();
5756   Built.DistCombinedFields.UB = CombUB.get();
5757   Built.DistCombinedFields.EUB = CombEUB.get();
5758   Built.DistCombinedFields.Init = CombInit.get();
5759   Built.DistCombinedFields.Cond = CombCond.get();
5760   Built.DistCombinedFields.NLB = CombNextLB.get();
5761   Built.DistCombinedFields.NUB = CombNextUB.get();
5762   Built.DistCombinedFields.DistCond = CombDistCond.get();
5763   Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
5764 
5765   return NestedLoopCount;
5766 }
5767 
5768 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
5769   auto CollapseClauses =
5770       OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5771   if (CollapseClauses.begin() != CollapseClauses.end())
5772     return (*CollapseClauses.begin())->getNumForLoops();
5773   return nullptr;
5774 }
5775 
5776 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
5777   auto OrderedClauses =
5778       OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5779   if (OrderedClauses.begin() != OrderedClauses.end())
5780     return (*OrderedClauses.begin())->getNumForLoops();
5781   return nullptr;
5782 }
5783 
5784 static bool checkSimdlenSafelenSpecified(Sema &S,
5785                                          const ArrayRef<OMPClause *> Clauses) {
5786   const OMPSafelenClause *Safelen = nullptr;
5787   const OMPSimdlenClause *Simdlen = nullptr;
5788 
5789   for (const OMPClause *Clause : Clauses) {
5790     if (Clause->getClauseKind() == OMPC_safelen)
5791       Safelen = cast<OMPSafelenClause>(Clause);
5792     else if (Clause->getClauseKind() == OMPC_simdlen)
5793       Simdlen = cast<OMPSimdlenClause>(Clause);
5794     if (Safelen && Simdlen)
5795       break;
5796   }
5797 
5798   if (Simdlen && Safelen) {
5799     const Expr *SimdlenLength = Simdlen->getSimdlen();
5800     const Expr *SafelenLength = Safelen->getSafelen();
5801     if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5802         SimdlenLength->isInstantiationDependent() ||
5803         SimdlenLength->containsUnexpandedParameterPack())
5804       return false;
5805     if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5806         SafelenLength->isInstantiationDependent() ||
5807         SafelenLength->containsUnexpandedParameterPack())
5808       return false;
5809     Expr::EvalResult SimdlenResult, SafelenResult;
5810     SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
5811     SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
5812     llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
5813     llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
5814     // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5815     // If both simdlen and safelen clauses are specified, the value of the
5816     // simdlen parameter must be less than or equal to the value of the safelen
5817     // parameter.
5818     if (SimdlenRes > SafelenRes) {
5819       S.Diag(SimdlenLength->getExprLoc(),
5820              diag::err_omp_wrong_simdlen_safelen_values)
5821           << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5822       return true;
5823     }
5824   }
5825   return false;
5826 }
5827 
5828 StmtResult
5829 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5830                                SourceLocation StartLoc, SourceLocation EndLoc,
5831                                VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5832   if (!AStmt)
5833     return StmtError();
5834 
5835   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5836   OMPLoopDirective::HelperExprs B;
5837   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5838   // define the nested loops number.
5839   unsigned NestedLoopCount = checkOpenMPLoop(
5840       OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5841       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5842   if (NestedLoopCount == 0)
5843     return StmtError();
5844 
5845   assert((CurContext->isDependentContext() || B.builtAll()) &&
5846          "omp simd loop exprs were not built");
5847 
5848   if (!CurContext->isDependentContext()) {
5849     // Finalize the clauses that need pre-built expressions for CodeGen.
5850     for (OMPClause *C : Clauses) {
5851       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5852         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5853                                      B.NumIterations, *this, CurScope,
5854                                      DSAStack))
5855           return StmtError();
5856     }
5857   }
5858 
5859   if (checkSimdlenSafelenSpecified(*this, Clauses))
5860     return StmtError();
5861 
5862   setFunctionHasBranchProtectedScope();
5863   return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5864                                   Clauses, AStmt, B);
5865 }
5866 
5867 StmtResult
5868 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5869                               SourceLocation StartLoc, SourceLocation EndLoc,
5870                               VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5871   if (!AStmt)
5872     return StmtError();
5873 
5874   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5875   OMPLoopDirective::HelperExprs B;
5876   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5877   // define the nested loops number.
5878   unsigned NestedLoopCount = checkOpenMPLoop(
5879       OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5880       AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
5881   if (NestedLoopCount == 0)
5882     return StmtError();
5883 
5884   assert((CurContext->isDependentContext() || B.builtAll()) &&
5885          "omp for loop exprs were not built");
5886 
5887   if (!CurContext->isDependentContext()) {
5888     // Finalize the clauses that need pre-built expressions for CodeGen.
5889     for (OMPClause *C : Clauses) {
5890       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5891         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5892                                      B.NumIterations, *this, CurScope,
5893                                      DSAStack))
5894           return StmtError();
5895     }
5896   }
5897 
5898   setFunctionHasBranchProtectedScope();
5899   return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5900                                  Clauses, AStmt, B, DSAStack->isCancelRegion());
5901 }
5902 
5903 StmtResult Sema::ActOnOpenMPForSimdDirective(
5904     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5905     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
5906   if (!AStmt)
5907     return StmtError();
5908 
5909   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5910   OMPLoopDirective::HelperExprs B;
5911   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5912   // define the nested loops number.
5913   unsigned NestedLoopCount =
5914       checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5915                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5916                       VarsWithImplicitDSA, B);
5917   if (NestedLoopCount == 0)
5918     return StmtError();
5919 
5920   assert((CurContext->isDependentContext() || B.builtAll()) &&
5921          "omp for simd loop exprs were not built");
5922 
5923   if (!CurContext->isDependentContext()) {
5924     // Finalize the clauses that need pre-built expressions for CodeGen.
5925     for (OMPClause *C : Clauses) {
5926       if (auto *LC = dyn_cast<OMPLinearClause>(C))
5927         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
5928                                      B.NumIterations, *this, CurScope,
5929                                      DSAStack))
5930           return StmtError();
5931     }
5932   }
5933 
5934   if (checkSimdlenSafelenSpecified(*this, Clauses))
5935     return StmtError();
5936 
5937   setFunctionHasBranchProtectedScope();
5938   return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5939                                      Clauses, AStmt, B);
5940 }
5941 
5942 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5943                                               Stmt *AStmt,
5944                                               SourceLocation StartLoc,
5945                                               SourceLocation EndLoc) {
5946   if (!AStmt)
5947     return StmtError();
5948 
5949   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5950   auto BaseStmt = AStmt;
5951   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
5952     BaseStmt = CS->getCapturedStmt();
5953   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
5954     auto S = C->children();
5955     if (S.begin() == S.end())
5956       return StmtError();
5957     // All associated statements must be '#pragma omp section' except for
5958     // the first one.
5959     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
5960       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5961         if (SectionStmt)
5962           Diag(SectionStmt->getBeginLoc(),
5963                diag::err_omp_sections_substmt_not_section);
5964         return StmtError();
5965       }
5966       cast<OMPSectionDirective>(SectionStmt)
5967           ->setHasCancel(DSAStack->isCancelRegion());
5968     }
5969   } else {
5970     Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
5971     return StmtError();
5972   }
5973 
5974   setFunctionHasBranchProtectedScope();
5975 
5976   return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5977                                       DSAStack->isCancelRegion());
5978 }
5979 
5980 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5981                                              SourceLocation StartLoc,
5982                                              SourceLocation EndLoc) {
5983   if (!AStmt)
5984     return StmtError();
5985 
5986   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5987 
5988   setFunctionHasBranchProtectedScope();
5989   DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
5990 
5991   return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5992                                      DSAStack->isCancelRegion());
5993 }
5994 
5995 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5996                                             Stmt *AStmt,
5997                                             SourceLocation StartLoc,
5998                                             SourceLocation EndLoc) {
5999   if (!AStmt)
6000     return StmtError();
6001 
6002   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6003 
6004   setFunctionHasBranchProtectedScope();
6005 
6006   // OpenMP [2.7.3, single Construct, Restrictions]
6007   // The copyprivate clause must not be used with the nowait clause.
6008   const OMPClause *Nowait = nullptr;
6009   const OMPClause *Copyprivate = nullptr;
6010   for (const OMPClause *Clause : Clauses) {
6011     if (Clause->getClauseKind() == OMPC_nowait)
6012       Nowait = Clause;
6013     else if (Clause->getClauseKind() == OMPC_copyprivate)
6014       Copyprivate = Clause;
6015     if (Copyprivate && Nowait) {
6016       Diag(Copyprivate->getBeginLoc(),
6017            diag::err_omp_single_copyprivate_with_nowait);
6018       Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
6019       return StmtError();
6020     }
6021   }
6022 
6023   return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6024 }
6025 
6026 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6027                                             SourceLocation StartLoc,
6028                                             SourceLocation EndLoc) {
6029   if (!AStmt)
6030     return StmtError();
6031 
6032   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6033 
6034   setFunctionHasBranchProtectedScope();
6035 
6036   return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6037 }
6038 
6039 StmtResult Sema::ActOnOpenMPCriticalDirective(
6040     const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6041     Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
6042   if (!AStmt)
6043     return StmtError();
6044 
6045   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6046 
6047   bool ErrorFound = false;
6048   llvm::APSInt Hint;
6049   SourceLocation HintLoc;
6050   bool DependentHint = false;
6051   for (const OMPClause *C : Clauses) {
6052     if (C->getClauseKind() == OMPC_hint) {
6053       if (!DirName.getName()) {
6054         Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
6055         ErrorFound = true;
6056       }
6057       Expr *E = cast<OMPHintClause>(C)->getHint();
6058       if (E->isTypeDependent() || E->isValueDependent() ||
6059           E->isInstantiationDependent()) {
6060         DependentHint = true;
6061       } else {
6062         Hint = E->EvaluateKnownConstInt(Context);
6063         HintLoc = C->getBeginLoc();
6064       }
6065     }
6066   }
6067   if (ErrorFound)
6068     return StmtError();
6069   const auto Pair = DSAStack->getCriticalWithHint(DirName);
6070   if (Pair.first && DirName.getName() && !DependentHint) {
6071     if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6072       Diag(StartLoc, diag::err_omp_critical_with_hint);
6073       if (HintLoc.isValid())
6074         Diag(HintLoc, diag::note_omp_critical_hint_here)
6075             << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
6076       else
6077         Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
6078       if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
6079         Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
6080             << 1
6081             << C->getHint()->EvaluateKnownConstInt(Context).toString(
6082                    /*Radix=*/10, /*Signed=*/false);
6083       } else {
6084         Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
6085       }
6086     }
6087   }
6088 
6089   setFunctionHasBranchProtectedScope();
6090 
6091   auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6092                                            Clauses, AStmt);
6093   if (!Pair.first && DirName.getName() && !DependentHint)
6094     DSAStack->addCriticalWithHint(Dir, Hint);
6095   return Dir;
6096 }
6097 
6098 StmtResult Sema::ActOnOpenMPParallelForDirective(
6099     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6100     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6101   if (!AStmt)
6102     return StmtError();
6103 
6104   auto *CS = cast<CapturedStmt>(AStmt);
6105   // 1.2.2 OpenMP Language Terminology
6106   // Structured block - An executable statement with a single entry at the
6107   // top and a single exit at the bottom.
6108   // The point of exit cannot be a branch out of the structured block.
6109   // longjmp() and throw() must not violate the entry/exit criteria.
6110   CS->getCapturedDecl()->setNothrow();
6111 
6112   OMPLoopDirective::HelperExprs B;
6113   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6114   // define the nested loops number.
6115   unsigned NestedLoopCount =
6116       checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
6117                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6118                       VarsWithImplicitDSA, B);
6119   if (NestedLoopCount == 0)
6120     return StmtError();
6121 
6122   assert((CurContext->isDependentContext() || B.builtAll()) &&
6123          "omp parallel for loop exprs were not built");
6124 
6125   if (!CurContext->isDependentContext()) {
6126     // Finalize the clauses that need pre-built expressions for CodeGen.
6127     for (OMPClause *C : Clauses) {
6128       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6129         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6130                                      B.NumIterations, *this, CurScope,
6131                                      DSAStack))
6132           return StmtError();
6133     }
6134   }
6135 
6136   setFunctionHasBranchProtectedScope();
6137   return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
6138                                          NestedLoopCount, Clauses, AStmt, B,
6139                                          DSAStack->isCancelRegion());
6140 }
6141 
6142 StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6143     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6144     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
6145   if (!AStmt)
6146     return StmtError();
6147 
6148   auto *CS = cast<CapturedStmt>(AStmt);
6149   // 1.2.2 OpenMP Language Terminology
6150   // Structured block - An executable statement with a single entry at the
6151   // top and a single exit at the bottom.
6152   // The point of exit cannot be a branch out of the structured block.
6153   // longjmp() and throw() must not violate the entry/exit criteria.
6154   CS->getCapturedDecl()->setNothrow();
6155 
6156   OMPLoopDirective::HelperExprs B;
6157   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6158   // define the nested loops number.
6159   unsigned NestedLoopCount =
6160       checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
6161                       getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6162                       VarsWithImplicitDSA, B);
6163   if (NestedLoopCount == 0)
6164     return StmtError();
6165 
6166   if (!CurContext->isDependentContext()) {
6167     // Finalize the clauses that need pre-built expressions for CodeGen.
6168     for (OMPClause *C : Clauses) {
6169       if (auto *LC = dyn_cast<OMPLinearClause>(C))
6170         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6171                                      B.NumIterations, *this, CurScope,
6172                                      DSAStack))
6173           return StmtError();
6174     }
6175   }
6176 
6177   if (checkSimdlenSafelenSpecified(*this, Clauses))
6178     return StmtError();
6179 
6180   setFunctionHasBranchProtectedScope();
6181   return OMPParallelForSimdDirective::Create(
6182       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
6183 }
6184 
6185 StmtResult
6186 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6187                                            Stmt *AStmt, SourceLocation StartLoc,
6188                                            SourceLocation EndLoc) {
6189   if (!AStmt)
6190     return StmtError();
6191 
6192   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6193   auto BaseStmt = AStmt;
6194   while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
6195     BaseStmt = CS->getCapturedStmt();
6196   if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
6197     auto S = C->children();
6198     if (S.begin() == S.end())
6199       return StmtError();
6200     // All associated statements must be '#pragma omp section' except for
6201     // the first one.
6202     for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
6203       if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6204         if (SectionStmt)
6205           Diag(SectionStmt->getBeginLoc(),
6206                diag::err_omp_parallel_sections_substmt_not_section);
6207         return StmtError();
6208       }
6209       cast<OMPSectionDirective>(SectionStmt)
6210           ->setHasCancel(DSAStack->isCancelRegion());
6211     }
6212   } else {
6213     Diag(AStmt->getBeginLoc(),
6214          diag::err_omp_parallel_sections_not_compound_stmt);
6215     return StmtError();
6216   }
6217 
6218   setFunctionHasBranchProtectedScope();
6219 
6220   return OMPParallelSectionsDirective::Create(
6221       Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
6222 }
6223 
6224 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6225                                           Stmt *AStmt, SourceLocation StartLoc,
6226                                           SourceLocation EndLoc) {
6227   if (!AStmt)
6228     return StmtError();
6229 
6230   auto *CS = cast<CapturedStmt>(AStmt);
6231   // 1.2.2 OpenMP Language Terminology
6232   // Structured block - An executable statement with a single entry at the
6233   // top and a single exit at the bottom.
6234   // The point of exit cannot be a branch out of the structured block.
6235   // longjmp() and throw() must not violate the entry/exit criteria.
6236   CS->getCapturedDecl()->setNothrow();
6237 
6238   setFunctionHasBranchProtectedScope();
6239 
6240   return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6241                                   DSAStack->isCancelRegion());
6242 }
6243 
6244 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6245                                                SourceLocation EndLoc) {
6246   return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6247 }
6248 
6249 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6250                                              SourceLocation EndLoc) {
6251   return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6252 }
6253 
6254 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6255                                               SourceLocation EndLoc) {
6256   return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6257 }
6258 
6259 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6260                                                Stmt *AStmt,
6261                                                SourceLocation StartLoc,
6262                                                SourceLocation EndLoc) {
6263   if (!AStmt)
6264     return StmtError();
6265 
6266   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6267 
6268   setFunctionHasBranchProtectedScope();
6269 
6270   return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
6271                                        AStmt,
6272                                        DSAStack->getTaskgroupReductionRef());
6273 }
6274 
6275 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6276                                            SourceLocation StartLoc,
6277                                            SourceLocation EndLoc) {
6278   assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6279   return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6280 }
6281 
6282 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6283                                              Stmt *AStmt,
6284                                              SourceLocation StartLoc,
6285                                              SourceLocation EndLoc) {
6286   const OMPClause *DependFound = nullptr;
6287   const OMPClause *DependSourceClause = nullptr;
6288   const OMPClause *DependSinkClause = nullptr;
6289   bool ErrorFound = false;
6290   const OMPThreadsClause *TC = nullptr;
6291   const OMPSIMDClause *SC = nullptr;
6292   for (const OMPClause *C : Clauses) {
6293     if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6294       DependFound = C;
6295       if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6296         if (DependSourceClause) {
6297           Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
6298               << getOpenMPDirectiveName(OMPD_ordered)
6299               << getOpenMPClauseName(OMPC_depend) << 2;
6300           ErrorFound = true;
6301         } else {
6302           DependSourceClause = C;
6303         }
6304         if (DependSinkClause) {
6305           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6306               << 0;
6307           ErrorFound = true;
6308         }
6309       } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6310         if (DependSourceClause) {
6311           Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
6312               << 1;
6313           ErrorFound = true;
6314         }
6315         DependSinkClause = C;
6316       }
6317     } else if (C->getClauseKind() == OMPC_threads) {
6318       TC = cast<OMPThreadsClause>(C);
6319     } else if (C->getClauseKind() == OMPC_simd) {
6320       SC = cast<OMPSIMDClause>(C);
6321     }
6322   }
6323   if (!ErrorFound && !SC &&
6324       isOpenMPSimdDirective(DSAStack->getParentDirective())) {
6325     // OpenMP [2.8.1,simd Construct, Restrictions]
6326     // An ordered construct with the simd clause is the only OpenMP construct
6327     // that can appear in the simd region.
6328     Diag(StartLoc, diag::err_omp_prohibited_region_simd);
6329     ErrorFound = true;
6330   } else if (DependFound && (TC || SC)) {
6331     Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
6332         << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6333     ErrorFound = true;
6334   } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
6335     Diag(DependFound->getBeginLoc(),
6336          diag::err_omp_ordered_directive_without_param);
6337     ErrorFound = true;
6338   } else if (TC || Clauses.empty()) {
6339     if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
6340       SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
6341       Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6342           << (TC != nullptr);
6343       Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
6344       ErrorFound = true;
6345     }
6346   }
6347   if ((!AStmt && !DependFound) || ErrorFound)
6348     return StmtError();
6349 
6350   if (AStmt) {
6351     assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6352 
6353     setFunctionHasBranchProtectedScope();
6354   }
6355 
6356   return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6357 }
6358 
6359 namespace {
6360 /// Helper class for checking expression in 'omp atomic [update]'
6361 /// construct.
6362 class OpenMPAtomicUpdateChecker {
6363   /// Error results for atomic update expressions.
6364   enum ExprAnalysisErrorCode {
6365     /// A statement is not an expression statement.
6366     NotAnExpression,
6367     /// Expression is not builtin binary or unary operation.
6368     NotABinaryOrUnaryExpression,
6369     /// Unary operation is not post-/pre- increment/decrement operation.
6370     NotAnUnaryIncDecExpression,
6371     /// An expression is not of scalar type.
6372     NotAScalarType,
6373     /// A binary operation is not an assignment operation.
6374     NotAnAssignmentOp,
6375     /// RHS part of the binary operation is not a binary expression.
6376     NotABinaryExpression,
6377     /// RHS part is not additive/multiplicative/shift/biwise binary
6378     /// expression.
6379     NotABinaryOperator,
6380     /// RHS binary operation does not have reference to the updated LHS
6381     /// part.
6382     NotAnUpdateExpression,
6383     /// No errors is found.
6384     NoError
6385   };
6386   /// Reference to Sema.
6387   Sema &SemaRef;
6388   /// A location for note diagnostics (when error is found).
6389   SourceLocation NoteLoc;
6390   /// 'x' lvalue part of the source atomic expression.
6391   Expr *X;
6392   /// 'expr' rvalue part of the source atomic expression.
6393   Expr *E;
6394   /// Helper expression of the form
6395   /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6396   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6397   Expr *UpdateExpr;
6398   /// Is 'x' a LHS in a RHS part of full update expression. It is
6399   /// important for non-associative operations.
6400   bool IsXLHSInRHSPart;
6401   BinaryOperatorKind Op;
6402   SourceLocation OpLoc;
6403   /// true if the source expression is a postfix unary operation, false
6404   /// if it is a prefix unary operation.
6405   bool IsPostfixUpdate;
6406 
6407 public:
6408   OpenMPAtomicUpdateChecker(Sema &SemaRef)
6409       : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
6410         IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
6411   /// Check specified statement that it is suitable for 'atomic update'
6412   /// constructs and extract 'x', 'expr' and Operation from the original
6413   /// expression. If DiagId and NoteId == 0, then only check is performed
6414   /// without error notification.
6415   /// \param DiagId Diagnostic which should be emitted if error is found.
6416   /// \param NoteId Diagnostic note for the main error message.
6417   /// \return true if statement is not an update expression, false otherwise.
6418   bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
6419   /// Return the 'x' lvalue part of the source atomic expression.
6420   Expr *getX() const { return X; }
6421   /// Return the 'expr' rvalue part of the source atomic expression.
6422   Expr *getExpr() const { return E; }
6423   /// Return the update expression used in calculation of the updated
6424   /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6425   /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6426   Expr *getUpdateExpr() const { return UpdateExpr; }
6427   /// Return true if 'x' is LHS in RHS part of full update expression,
6428   /// false otherwise.
6429   bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6430 
6431   /// true if the source expression is a postfix unary operation, false
6432   /// if it is a prefix unary operation.
6433   bool isPostfixUpdate() const { return IsPostfixUpdate; }
6434 
6435 private:
6436   bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6437                             unsigned NoteId = 0);
6438 };
6439 } // namespace
6440 
6441 bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6442     BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6443   ExprAnalysisErrorCode ErrorFound = NoError;
6444   SourceLocation ErrorLoc, NoteLoc;
6445   SourceRange ErrorRange, NoteRange;
6446   // Allowed constructs are:
6447   //  x = x binop expr;
6448   //  x = expr binop x;
6449   if (AtomicBinOp->getOpcode() == BO_Assign) {
6450     X = AtomicBinOp->getLHS();
6451     if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
6452             AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6453       if (AtomicInnerBinOp->isMultiplicativeOp() ||
6454           AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6455           AtomicInnerBinOp->isBitwiseOp()) {
6456         Op = AtomicInnerBinOp->getOpcode();
6457         OpLoc = AtomicInnerBinOp->getOperatorLoc();
6458         Expr *LHS = AtomicInnerBinOp->getLHS();
6459         Expr *RHS = AtomicInnerBinOp->getRHS();
6460         llvm::FoldingSetNodeID XId, LHSId, RHSId;
6461         X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6462                                           /*Canonical=*/true);
6463         LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6464                                             /*Canonical=*/true);
6465         RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6466                                             /*Canonical=*/true);
6467         if (XId == LHSId) {
6468           E = RHS;
6469           IsXLHSInRHSPart = true;
6470         } else if (XId == RHSId) {
6471           E = LHS;
6472           IsXLHSInRHSPart = false;
6473         } else {
6474           ErrorLoc = AtomicInnerBinOp->getExprLoc();
6475           ErrorRange = AtomicInnerBinOp->getSourceRange();
6476           NoteLoc = X->getExprLoc();
6477           NoteRange = X->getSourceRange();
6478           ErrorFound = NotAnUpdateExpression;
6479         }
6480       } else {
6481         ErrorLoc = AtomicInnerBinOp->getExprLoc();
6482         ErrorRange = AtomicInnerBinOp->getSourceRange();
6483         NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6484         NoteRange = SourceRange(NoteLoc, NoteLoc);
6485         ErrorFound = NotABinaryOperator;
6486       }
6487     } else {
6488       NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6489       NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6490       ErrorFound = NotABinaryExpression;
6491     }
6492   } else {
6493     ErrorLoc = AtomicBinOp->getExprLoc();
6494     ErrorRange = AtomicBinOp->getSourceRange();
6495     NoteLoc = AtomicBinOp->getOperatorLoc();
6496     NoteRange = SourceRange(NoteLoc, NoteLoc);
6497     ErrorFound = NotAnAssignmentOp;
6498   }
6499   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6500     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6501     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6502     return true;
6503   }
6504   if (SemaRef.CurContext->isDependentContext())
6505     E = X = UpdateExpr = nullptr;
6506   return ErrorFound != NoError;
6507 }
6508 
6509 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6510                                                unsigned NoteId) {
6511   ExprAnalysisErrorCode ErrorFound = NoError;
6512   SourceLocation ErrorLoc, NoteLoc;
6513   SourceRange ErrorRange, NoteRange;
6514   // Allowed constructs are:
6515   //  x++;
6516   //  x--;
6517   //  ++x;
6518   //  --x;
6519   //  x binop= expr;
6520   //  x = x binop expr;
6521   //  x = expr binop x;
6522   if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6523     AtomicBody = AtomicBody->IgnoreParenImpCasts();
6524     if (AtomicBody->getType()->isScalarType() ||
6525         AtomicBody->isInstantiationDependent()) {
6526       if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
6527               AtomicBody->IgnoreParenImpCasts())) {
6528         // Check for Compound Assignment Operation
6529         Op = BinaryOperator::getOpForCompoundAssignment(
6530             AtomicCompAssignOp->getOpcode());
6531         OpLoc = AtomicCompAssignOp->getOperatorLoc();
6532         E = AtomicCompAssignOp->getRHS();
6533         X = AtomicCompAssignOp->getLHS()->IgnoreParens();
6534         IsXLHSInRHSPart = true;
6535       } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6536                      AtomicBody->IgnoreParenImpCasts())) {
6537         // Check for Binary Operation
6538         if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
6539           return true;
6540       } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
6541                      AtomicBody->IgnoreParenImpCasts())) {
6542         // Check for Unary Operation
6543         if (AtomicUnaryOp->isIncrementDecrementOp()) {
6544           IsPostfixUpdate = AtomicUnaryOp->isPostfix();
6545           Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6546           OpLoc = AtomicUnaryOp->getOperatorLoc();
6547           X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
6548           E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6549           IsXLHSInRHSPart = true;
6550         } else {
6551           ErrorFound = NotAnUnaryIncDecExpression;
6552           ErrorLoc = AtomicUnaryOp->getExprLoc();
6553           ErrorRange = AtomicUnaryOp->getSourceRange();
6554           NoteLoc = AtomicUnaryOp->getOperatorLoc();
6555           NoteRange = SourceRange(NoteLoc, NoteLoc);
6556         }
6557       } else if (!AtomicBody->isInstantiationDependent()) {
6558         ErrorFound = NotABinaryOrUnaryExpression;
6559         NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6560         NoteRange = ErrorRange = AtomicBody->getSourceRange();
6561       }
6562     } else {
6563       ErrorFound = NotAScalarType;
6564       NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
6565       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6566     }
6567   } else {
6568     ErrorFound = NotAnExpression;
6569     NoteLoc = ErrorLoc = S->getBeginLoc();
6570     NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6571   }
6572   if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
6573     SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6574     SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6575     return true;
6576   }
6577   if (SemaRef.CurContext->isDependentContext())
6578     E = X = UpdateExpr = nullptr;
6579   if (ErrorFound == NoError && E && X) {
6580     // Build an update expression of form 'OpaqueValueExpr(x) binop
6581     // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6582     // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6583     auto *OVEX = new (SemaRef.getASTContext())
6584         OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6585     auto *OVEExpr = new (SemaRef.getASTContext())
6586         OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6587     ExprResult Update =
6588         SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6589                                    IsXLHSInRHSPart ? OVEExpr : OVEX);
6590     if (Update.isInvalid())
6591       return true;
6592     Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6593                                                Sema::AA_Casting);
6594     if (Update.isInvalid())
6595       return true;
6596     UpdateExpr = Update.get();
6597   }
6598   return ErrorFound != NoError;
6599 }
6600 
6601 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6602                                             Stmt *AStmt,
6603                                             SourceLocation StartLoc,
6604                                             SourceLocation EndLoc) {
6605   if (!AStmt)
6606     return StmtError();
6607 
6608   auto *CS = cast<CapturedStmt>(AStmt);
6609   // 1.2.2 OpenMP Language Terminology
6610   // Structured block - An executable statement with a single entry at the
6611   // top and a single exit at the bottom.
6612   // The point of exit cannot be a branch out of the structured block.
6613   // longjmp() and throw() must not violate the entry/exit criteria.
6614   OpenMPClauseKind AtomicKind = OMPC_unknown;
6615   SourceLocation AtomicKindLoc;
6616   for (const OMPClause *C : Clauses) {
6617     if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
6618         C->getClauseKind() == OMPC_update ||
6619         C->getClauseKind() == OMPC_capture) {
6620       if (AtomicKind != OMPC_unknown) {
6621         Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
6622             << SourceRange(C->getBeginLoc(), C->getEndLoc());
6623         Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6624             << getOpenMPClauseName(AtomicKind);
6625       } else {
6626         AtomicKind = C->getClauseKind();
6627         AtomicKindLoc = C->getBeginLoc();
6628       }
6629     }
6630   }
6631 
6632   Stmt *Body = CS->getCapturedStmt();
6633   if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6634     Body = EWC->getSubExpr();
6635 
6636   Expr *X = nullptr;
6637   Expr *V = nullptr;
6638   Expr *E = nullptr;
6639   Expr *UE = nullptr;
6640   bool IsXLHSInRHSPart = false;
6641   bool IsPostfixUpdate = false;
6642   // OpenMP [2.12.6, atomic Construct]
6643   // In the next expressions:
6644   // * x and v (as applicable) are both l-value expressions with scalar type.
6645   // * During the execution of an atomic region, multiple syntactic
6646   // occurrences of x must designate the same storage location.
6647   // * Neither of v and expr (as applicable) may access the storage location
6648   // designated by x.
6649   // * Neither of x and expr (as applicable) may access the storage location
6650   // designated by v.
6651   // * expr is an expression with scalar type.
6652   // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6653   // * binop, binop=, ++, and -- are not overloaded operators.
6654   // * The expression x binop expr must be numerically equivalent to x binop
6655   // (expr). This requirement is satisfied if the operators in expr have
6656   // precedence greater than binop, or by using parentheses around expr or
6657   // subexpressions of expr.
6658   // * The expression expr binop x must be numerically equivalent to (expr)
6659   // binop x. This requirement is satisfied if the operators in expr have
6660   // precedence equal to or greater than binop, or by using parentheses around
6661   // expr or subexpressions of expr.
6662   // * For forms that allow multiple occurrences of x, the number of times
6663   // that x is evaluated is unspecified.
6664   if (AtomicKind == OMPC_read) {
6665     enum {
6666       NotAnExpression,
6667       NotAnAssignmentOp,
6668       NotAScalarType,
6669       NotAnLValue,
6670       NoError
6671     } ErrorFound = NoError;
6672     SourceLocation ErrorLoc, NoteLoc;
6673     SourceRange ErrorRange, NoteRange;
6674     // If clause is read:
6675     //  v = x;
6676     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6677       const auto *AtomicBinOp =
6678           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6679       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6680         X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6681         V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6682         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6683             (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6684           if (!X->isLValue() || !V->isLValue()) {
6685             const Expr *NotLValueExpr = X->isLValue() ? V : X;
6686             ErrorFound = NotAnLValue;
6687             ErrorLoc = AtomicBinOp->getExprLoc();
6688             ErrorRange = AtomicBinOp->getSourceRange();
6689             NoteLoc = NotLValueExpr->getExprLoc();
6690             NoteRange = NotLValueExpr->getSourceRange();
6691           }
6692         } else if (!X->isInstantiationDependent() ||
6693                    !V->isInstantiationDependent()) {
6694           const Expr *NotScalarExpr =
6695               (X->isInstantiationDependent() || X->getType()->isScalarType())
6696                   ? V
6697                   : X;
6698           ErrorFound = NotAScalarType;
6699           ErrorLoc = AtomicBinOp->getExprLoc();
6700           ErrorRange = AtomicBinOp->getSourceRange();
6701           NoteLoc = NotScalarExpr->getExprLoc();
6702           NoteRange = NotScalarExpr->getSourceRange();
6703         }
6704       } else if (!AtomicBody->isInstantiationDependent()) {
6705         ErrorFound = NotAnAssignmentOp;
6706         ErrorLoc = AtomicBody->getExprLoc();
6707         ErrorRange = AtomicBody->getSourceRange();
6708         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6709                               : AtomicBody->getExprLoc();
6710         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6711                                 : AtomicBody->getSourceRange();
6712       }
6713     } else {
6714       ErrorFound = NotAnExpression;
6715       NoteLoc = ErrorLoc = Body->getBeginLoc();
6716       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6717     }
6718     if (ErrorFound != NoError) {
6719       Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6720           << ErrorRange;
6721       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6722                                                       << NoteRange;
6723       return StmtError();
6724     }
6725     if (CurContext->isDependentContext())
6726       V = X = nullptr;
6727   } else if (AtomicKind == OMPC_write) {
6728     enum {
6729       NotAnExpression,
6730       NotAnAssignmentOp,
6731       NotAScalarType,
6732       NotAnLValue,
6733       NoError
6734     } ErrorFound = NoError;
6735     SourceLocation ErrorLoc, NoteLoc;
6736     SourceRange ErrorRange, NoteRange;
6737     // If clause is write:
6738     //  x = expr;
6739     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6740       const auto *AtomicBinOp =
6741           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6742       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6743         X = AtomicBinOp->getLHS();
6744         E = AtomicBinOp->getRHS();
6745         if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6746             (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6747           if (!X->isLValue()) {
6748             ErrorFound = NotAnLValue;
6749             ErrorLoc = AtomicBinOp->getExprLoc();
6750             ErrorRange = AtomicBinOp->getSourceRange();
6751             NoteLoc = X->getExprLoc();
6752             NoteRange = X->getSourceRange();
6753           }
6754         } else if (!X->isInstantiationDependent() ||
6755                    !E->isInstantiationDependent()) {
6756           const Expr *NotScalarExpr =
6757               (X->isInstantiationDependent() || X->getType()->isScalarType())
6758                   ? E
6759                   : X;
6760           ErrorFound = NotAScalarType;
6761           ErrorLoc = AtomicBinOp->getExprLoc();
6762           ErrorRange = AtomicBinOp->getSourceRange();
6763           NoteLoc = NotScalarExpr->getExprLoc();
6764           NoteRange = NotScalarExpr->getSourceRange();
6765         }
6766       } else if (!AtomicBody->isInstantiationDependent()) {
6767         ErrorFound = NotAnAssignmentOp;
6768         ErrorLoc = AtomicBody->getExprLoc();
6769         ErrorRange = AtomicBody->getSourceRange();
6770         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6771                               : AtomicBody->getExprLoc();
6772         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6773                                 : AtomicBody->getSourceRange();
6774       }
6775     } else {
6776       ErrorFound = NotAnExpression;
6777       NoteLoc = ErrorLoc = Body->getBeginLoc();
6778       NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6779     }
6780     if (ErrorFound != NoError) {
6781       Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6782           << ErrorRange;
6783       Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6784                                                       << NoteRange;
6785       return StmtError();
6786     }
6787     if (CurContext->isDependentContext())
6788       E = X = nullptr;
6789   } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
6790     // If clause is update:
6791     //  x++;
6792     //  x--;
6793     //  ++x;
6794     //  --x;
6795     //  x binop= expr;
6796     //  x = x binop expr;
6797     //  x = expr binop x;
6798     OpenMPAtomicUpdateChecker Checker(*this);
6799     if (Checker.checkStatement(
6800             Body, (AtomicKind == OMPC_update)
6801                       ? diag::err_omp_atomic_update_not_expression_statement
6802                       : diag::err_omp_atomic_not_expression_statement,
6803             diag::note_omp_atomic_update))
6804       return StmtError();
6805     if (!CurContext->isDependentContext()) {
6806       E = Checker.getExpr();
6807       X = Checker.getX();
6808       UE = Checker.getUpdateExpr();
6809       IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6810     }
6811   } else if (AtomicKind == OMPC_capture) {
6812     enum {
6813       NotAnAssignmentOp,
6814       NotACompoundStatement,
6815       NotTwoSubstatements,
6816       NotASpecificExpression,
6817       NoError
6818     } ErrorFound = NoError;
6819     SourceLocation ErrorLoc, NoteLoc;
6820     SourceRange ErrorRange, NoteRange;
6821     if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6822       // If clause is a capture:
6823       //  v = x++;
6824       //  v = x--;
6825       //  v = ++x;
6826       //  v = --x;
6827       //  v = x binop= expr;
6828       //  v = x = x binop expr;
6829       //  v = x = expr binop x;
6830       const auto *AtomicBinOp =
6831           dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6832       if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6833         V = AtomicBinOp->getLHS();
6834         Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6835         OpenMPAtomicUpdateChecker Checker(*this);
6836         if (Checker.checkStatement(
6837                 Body, diag::err_omp_atomic_capture_not_expression_statement,
6838                 diag::note_omp_atomic_update))
6839           return StmtError();
6840         E = Checker.getExpr();
6841         X = Checker.getX();
6842         UE = Checker.getUpdateExpr();
6843         IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6844         IsPostfixUpdate = Checker.isPostfixUpdate();
6845       } else if (!AtomicBody->isInstantiationDependent()) {
6846         ErrorLoc = AtomicBody->getExprLoc();
6847         ErrorRange = AtomicBody->getSourceRange();
6848         NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6849                               : AtomicBody->getExprLoc();
6850         NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6851                                 : AtomicBody->getSourceRange();
6852         ErrorFound = NotAnAssignmentOp;
6853       }
6854       if (ErrorFound != NoError) {
6855         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6856             << ErrorRange;
6857         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6858         return StmtError();
6859       }
6860       if (CurContext->isDependentContext())
6861         UE = V = E = X = nullptr;
6862     } else {
6863       // If clause is a capture:
6864       //  { v = x; x = expr; }
6865       //  { v = x; x++; }
6866       //  { v = x; x--; }
6867       //  { v = x; ++x; }
6868       //  { v = x; --x; }
6869       //  { v = x; x binop= expr; }
6870       //  { v = x; x = x binop expr; }
6871       //  { v = x; x = expr binop x; }
6872       //  { x++; v = x; }
6873       //  { x--; v = x; }
6874       //  { ++x; v = x; }
6875       //  { --x; v = x; }
6876       //  { x binop= expr; v = x; }
6877       //  { x = x binop expr; v = x; }
6878       //  { x = expr binop x; v = x; }
6879       if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6880         // Check that this is { expr1; expr2; }
6881         if (CS->size() == 2) {
6882           Stmt *First = CS->body_front();
6883           Stmt *Second = CS->body_back();
6884           if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6885             First = EWC->getSubExpr()->IgnoreParenImpCasts();
6886           if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6887             Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6888           // Need to find what subexpression is 'v' and what is 'x'.
6889           OpenMPAtomicUpdateChecker Checker(*this);
6890           bool IsUpdateExprFound = !Checker.checkStatement(Second);
6891           BinaryOperator *BinOp = nullptr;
6892           if (IsUpdateExprFound) {
6893             BinOp = dyn_cast<BinaryOperator>(First);
6894             IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6895           }
6896           if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6897             //  { v = x; x++; }
6898             //  { v = x; x--; }
6899             //  { v = x; ++x; }
6900             //  { v = x; --x; }
6901             //  { v = x; x binop= expr; }
6902             //  { v = x; x = x binop expr; }
6903             //  { v = x; x = expr binop x; }
6904             // Check that the first expression has form v = x.
6905             Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6906             llvm::FoldingSetNodeID XId, PossibleXId;
6907             Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6908             PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6909             IsUpdateExprFound = XId == PossibleXId;
6910             if (IsUpdateExprFound) {
6911               V = BinOp->getLHS();
6912               X = Checker.getX();
6913               E = Checker.getExpr();
6914               UE = Checker.getUpdateExpr();
6915               IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6916               IsPostfixUpdate = true;
6917             }
6918           }
6919           if (!IsUpdateExprFound) {
6920             IsUpdateExprFound = !Checker.checkStatement(First);
6921             BinOp = nullptr;
6922             if (IsUpdateExprFound) {
6923               BinOp = dyn_cast<BinaryOperator>(Second);
6924               IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6925             }
6926             if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6927               //  { x++; v = x; }
6928               //  { x--; v = x; }
6929               //  { ++x; v = x; }
6930               //  { --x; v = x; }
6931               //  { x binop= expr; v = x; }
6932               //  { x = x binop expr; v = x; }
6933               //  { x = expr binop x; v = x; }
6934               // Check that the second expression has form v = x.
6935               Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6936               llvm::FoldingSetNodeID XId, PossibleXId;
6937               Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6938               PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6939               IsUpdateExprFound = XId == PossibleXId;
6940               if (IsUpdateExprFound) {
6941                 V = BinOp->getLHS();
6942                 X = Checker.getX();
6943                 E = Checker.getExpr();
6944                 UE = Checker.getUpdateExpr();
6945                 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6946                 IsPostfixUpdate = false;
6947               }
6948             }
6949           }
6950           if (!IsUpdateExprFound) {
6951             //  { v = x; x = expr; }
6952             auto *FirstExpr = dyn_cast<Expr>(First);
6953             auto *SecondExpr = dyn_cast<Expr>(Second);
6954             if (!FirstExpr || !SecondExpr ||
6955                 !(FirstExpr->isInstantiationDependent() ||
6956                   SecondExpr->isInstantiationDependent())) {
6957               auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6958               if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
6959                 ErrorFound = NotAnAssignmentOp;
6960                 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6961                                                 : First->getBeginLoc();
6962                 NoteRange = ErrorRange = FirstBinOp
6963                                              ? FirstBinOp->getSourceRange()
6964                                              : SourceRange(ErrorLoc, ErrorLoc);
6965               } else {
6966                 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6967                 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6968                   ErrorFound = NotAnAssignmentOp;
6969                   NoteLoc = ErrorLoc = SecondBinOp
6970                                            ? SecondBinOp->getOperatorLoc()
6971                                            : Second->getBeginLoc();
6972                   NoteRange = ErrorRange =
6973                       SecondBinOp ? SecondBinOp->getSourceRange()
6974                                   : SourceRange(ErrorLoc, ErrorLoc);
6975                 } else {
6976                   Expr *PossibleXRHSInFirst =
6977                       FirstBinOp->getRHS()->IgnoreParenImpCasts();
6978                   Expr *PossibleXLHSInSecond =
6979                       SecondBinOp->getLHS()->IgnoreParenImpCasts();
6980                   llvm::FoldingSetNodeID X1Id, X2Id;
6981                   PossibleXRHSInFirst->Profile(X1Id, Context,
6982                                                /*Canonical=*/true);
6983                   PossibleXLHSInSecond->Profile(X2Id, Context,
6984                                                 /*Canonical=*/true);
6985                   IsUpdateExprFound = X1Id == X2Id;
6986                   if (IsUpdateExprFound) {
6987                     V = FirstBinOp->getLHS();
6988                     X = SecondBinOp->getLHS();
6989                     E = SecondBinOp->getRHS();
6990                     UE = nullptr;
6991                     IsXLHSInRHSPart = false;
6992                     IsPostfixUpdate = true;
6993                   } else {
6994                     ErrorFound = NotASpecificExpression;
6995                     ErrorLoc = FirstBinOp->getExprLoc();
6996                     ErrorRange = FirstBinOp->getSourceRange();
6997                     NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6998                     NoteRange = SecondBinOp->getRHS()->getSourceRange();
6999                   }
7000                 }
7001               }
7002             }
7003           }
7004         } else {
7005           NoteLoc = ErrorLoc = Body->getBeginLoc();
7006           NoteRange = ErrorRange =
7007               SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
7008           ErrorFound = NotTwoSubstatements;
7009         }
7010       } else {
7011         NoteLoc = ErrorLoc = Body->getBeginLoc();
7012         NoteRange = ErrorRange =
7013             SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
7014         ErrorFound = NotACompoundStatement;
7015       }
7016       if (ErrorFound != NoError) {
7017         Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7018             << ErrorRange;
7019         Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7020         return StmtError();
7021       }
7022       if (CurContext->isDependentContext())
7023         UE = V = E = X = nullptr;
7024     }
7025   }
7026 
7027   setFunctionHasBranchProtectedScope();
7028 
7029   return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7030                                     X, V, E, UE, IsXLHSInRHSPart,
7031                                     IsPostfixUpdate);
7032 }
7033 
7034 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7035                                             Stmt *AStmt,
7036                                             SourceLocation StartLoc,
7037                                             SourceLocation EndLoc) {
7038   if (!AStmt)
7039     return StmtError();
7040 
7041   auto *CS = cast<CapturedStmt>(AStmt);
7042   // 1.2.2 OpenMP Language Terminology
7043   // Structured block - An executable statement with a single entry at the
7044   // top and a single exit at the bottom.
7045   // The point of exit cannot be a branch out of the structured block.
7046   // longjmp() and throw() must not violate the entry/exit criteria.
7047   CS->getCapturedDecl()->setNothrow();
7048   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7049        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7050     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7051     // 1.2.2 OpenMP Language Terminology
7052     // Structured block - An executable statement with a single entry at the
7053     // top and a single exit at the bottom.
7054     // The point of exit cannot be a branch out of the structured block.
7055     // longjmp() and throw() must not violate the entry/exit criteria.
7056     CS->getCapturedDecl()->setNothrow();
7057   }
7058 
7059   // OpenMP [2.16, Nesting of Regions]
7060   // If specified, a teams construct must be contained within a target
7061   // construct. That target construct must contain no statements or directives
7062   // outside of the teams construct.
7063   if (DSAStack->hasInnerTeamsRegion()) {
7064     const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
7065     bool OMPTeamsFound = true;
7066     if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
7067       auto I = CS->body_begin();
7068       while (I != CS->body_end()) {
7069         const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
7070         if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7071             OMPTeamsFound) {
7072 
7073           OMPTeamsFound = false;
7074           break;
7075         }
7076         ++I;
7077       }
7078       assert(I != CS->body_end() && "Not found statement");
7079       S = *I;
7080     } else {
7081       const auto *OED = dyn_cast<OMPExecutableDirective>(S);
7082       OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
7083     }
7084     if (!OMPTeamsFound) {
7085       Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7086       Diag(DSAStack->getInnerTeamsRegionLoc(),
7087            diag::note_omp_nested_teams_construct_here);
7088       Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
7089           << isa<OMPExecutableDirective>(S);
7090       return StmtError();
7091     }
7092   }
7093 
7094   setFunctionHasBranchProtectedScope();
7095 
7096   return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7097 }
7098 
7099 StmtResult
7100 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7101                                          Stmt *AStmt, SourceLocation StartLoc,
7102                                          SourceLocation EndLoc) {
7103   if (!AStmt)
7104     return StmtError();
7105 
7106   auto *CS = cast<CapturedStmt>(AStmt);
7107   // 1.2.2 OpenMP Language Terminology
7108   // Structured block - An executable statement with a single entry at the
7109   // top and a single exit at the bottom.
7110   // The point of exit cannot be a branch out of the structured block.
7111   // longjmp() and throw() must not violate the entry/exit criteria.
7112   CS->getCapturedDecl()->setNothrow();
7113   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7114        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7115     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7116     // 1.2.2 OpenMP Language Terminology
7117     // Structured block - An executable statement with a single entry at the
7118     // top and a single exit at the bottom.
7119     // The point of exit cannot be a branch out of the structured block.
7120     // longjmp() and throw() must not violate the entry/exit criteria.
7121     CS->getCapturedDecl()->setNothrow();
7122   }
7123 
7124   setFunctionHasBranchProtectedScope();
7125 
7126   return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7127                                             AStmt);
7128 }
7129 
7130 StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7131     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7132     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7133   if (!AStmt)
7134     return StmtError();
7135 
7136   auto *CS = cast<CapturedStmt>(AStmt);
7137   // 1.2.2 OpenMP Language Terminology
7138   // Structured block - An executable statement with a single entry at the
7139   // top and a single exit at the bottom.
7140   // The point of exit cannot be a branch out of the structured block.
7141   // longjmp() and throw() must not violate the entry/exit criteria.
7142   CS->getCapturedDecl()->setNothrow();
7143   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7144        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7145     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7146     // 1.2.2 OpenMP Language Terminology
7147     // Structured block - An executable statement with a single entry at the
7148     // top and a single exit at the bottom.
7149     // The point of exit cannot be a branch out of the structured block.
7150     // longjmp() and throw() must not violate the entry/exit criteria.
7151     CS->getCapturedDecl()->setNothrow();
7152   }
7153 
7154   OMPLoopDirective::HelperExprs B;
7155   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7156   // define the nested loops number.
7157   unsigned NestedLoopCount =
7158       checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
7159                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7160                       VarsWithImplicitDSA, B);
7161   if (NestedLoopCount == 0)
7162     return StmtError();
7163 
7164   assert((CurContext->isDependentContext() || B.builtAll()) &&
7165          "omp target parallel for loop exprs were not built");
7166 
7167   if (!CurContext->isDependentContext()) {
7168     // Finalize the clauses that need pre-built expressions for CodeGen.
7169     for (OMPClause *C : Clauses) {
7170       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7171         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7172                                      B.NumIterations, *this, CurScope,
7173                                      DSAStack))
7174           return StmtError();
7175     }
7176   }
7177 
7178   setFunctionHasBranchProtectedScope();
7179   return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7180                                                NestedLoopCount, Clauses, AStmt,
7181                                                B, DSAStack->isCancelRegion());
7182 }
7183 
7184 /// Check for existence of a map clause in the list of clauses.
7185 static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7186                        const OpenMPClauseKind K) {
7187   return llvm::any_of(
7188       Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7189 }
7190 
7191 template <typename... Params>
7192 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7193                        const Params... ClauseTypes) {
7194   return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
7195 }
7196 
7197 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7198                                                 Stmt *AStmt,
7199                                                 SourceLocation StartLoc,
7200                                                 SourceLocation EndLoc) {
7201   if (!AStmt)
7202     return StmtError();
7203 
7204   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7205 
7206   // OpenMP [2.10.1, Restrictions, p. 97]
7207   // At least one map clause must appear on the directive.
7208   if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7209     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7210         << "'map' or 'use_device_ptr'"
7211         << getOpenMPDirectiveName(OMPD_target_data);
7212     return StmtError();
7213   }
7214 
7215   setFunctionHasBranchProtectedScope();
7216 
7217   return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7218                                         AStmt);
7219 }
7220 
7221 StmtResult
7222 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7223                                           SourceLocation StartLoc,
7224                                           SourceLocation EndLoc, Stmt *AStmt) {
7225   if (!AStmt)
7226     return StmtError();
7227 
7228   auto *CS = cast<CapturedStmt>(AStmt);
7229   // 1.2.2 OpenMP Language Terminology
7230   // Structured block - An executable statement with a single entry at the
7231   // top and a single exit at the bottom.
7232   // The point of exit cannot be a branch out of the structured block.
7233   // longjmp() and throw() must not violate the entry/exit criteria.
7234   CS->getCapturedDecl()->setNothrow();
7235   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7236        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7237     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7238     // 1.2.2 OpenMP Language Terminology
7239     // Structured block - An executable statement with a single entry at the
7240     // top and a single exit at the bottom.
7241     // The point of exit cannot be a branch out of the structured block.
7242     // longjmp() and throw() must not violate the entry/exit criteria.
7243     CS->getCapturedDecl()->setNothrow();
7244   }
7245 
7246   // OpenMP [2.10.2, Restrictions, p. 99]
7247   // At least one map clause must appear on the directive.
7248   if (!hasClauses(Clauses, OMPC_map)) {
7249     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7250         << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
7251     return StmtError();
7252   }
7253 
7254   return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7255                                              AStmt);
7256 }
7257 
7258 StmtResult
7259 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7260                                          SourceLocation StartLoc,
7261                                          SourceLocation EndLoc, Stmt *AStmt) {
7262   if (!AStmt)
7263     return StmtError();
7264 
7265   auto *CS = cast<CapturedStmt>(AStmt);
7266   // 1.2.2 OpenMP Language Terminology
7267   // Structured block - An executable statement with a single entry at the
7268   // top and a single exit at the bottom.
7269   // The point of exit cannot be a branch out of the structured block.
7270   // longjmp() and throw() must not violate the entry/exit criteria.
7271   CS->getCapturedDecl()->setNothrow();
7272   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7273        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7274     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7275     // 1.2.2 OpenMP Language Terminology
7276     // Structured block - An executable statement with a single entry at the
7277     // top and a single exit at the bottom.
7278     // The point of exit cannot be a branch out of the structured block.
7279     // longjmp() and throw() must not violate the entry/exit criteria.
7280     CS->getCapturedDecl()->setNothrow();
7281   }
7282 
7283   // OpenMP [2.10.3, Restrictions, p. 102]
7284   // At least one map clause must appear on the directive.
7285   if (!hasClauses(Clauses, OMPC_map)) {
7286     Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7287         << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
7288     return StmtError();
7289   }
7290 
7291   return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7292                                             AStmt);
7293 }
7294 
7295 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7296                                                   SourceLocation StartLoc,
7297                                                   SourceLocation EndLoc,
7298                                                   Stmt *AStmt) {
7299   if (!AStmt)
7300     return StmtError();
7301 
7302   auto *CS = cast<CapturedStmt>(AStmt);
7303   // 1.2.2 OpenMP Language Terminology
7304   // Structured block - An executable statement with a single entry at the
7305   // top and a single exit at the bottom.
7306   // The point of exit cannot be a branch out of the structured block.
7307   // longjmp() and throw() must not violate the entry/exit criteria.
7308   CS->getCapturedDecl()->setNothrow();
7309   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7310        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7311     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7312     // 1.2.2 OpenMP Language Terminology
7313     // Structured block - An executable statement with a single entry at the
7314     // top and a single exit at the bottom.
7315     // The point of exit cannot be a branch out of the structured block.
7316     // longjmp() and throw() must not violate the entry/exit criteria.
7317     CS->getCapturedDecl()->setNothrow();
7318   }
7319 
7320   if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
7321     Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7322     return StmtError();
7323   }
7324   return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7325                                           AStmt);
7326 }
7327 
7328 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7329                                            Stmt *AStmt, SourceLocation StartLoc,
7330                                            SourceLocation EndLoc) {
7331   if (!AStmt)
7332     return StmtError();
7333 
7334   auto *CS = cast<CapturedStmt>(AStmt);
7335   // 1.2.2 OpenMP Language Terminology
7336   // Structured block - An executable statement with a single entry at the
7337   // top and a single exit at the bottom.
7338   // The point of exit cannot be a branch out of the structured block.
7339   // longjmp() and throw() must not violate the entry/exit criteria.
7340   CS->getCapturedDecl()->setNothrow();
7341 
7342   setFunctionHasBranchProtectedScope();
7343 
7344   DSAStack->setParentTeamsRegionLoc(StartLoc);
7345 
7346   return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7347 }
7348 
7349 StmtResult
7350 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7351                                             SourceLocation EndLoc,
7352                                             OpenMPDirectiveKind CancelRegion) {
7353   if (DSAStack->isParentNowaitRegion()) {
7354     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7355     return StmtError();
7356   }
7357   if (DSAStack->isParentOrderedRegion()) {
7358     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7359     return StmtError();
7360   }
7361   return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7362                                                CancelRegion);
7363 }
7364 
7365 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7366                                             SourceLocation StartLoc,
7367                                             SourceLocation EndLoc,
7368                                             OpenMPDirectiveKind CancelRegion) {
7369   if (DSAStack->isParentNowaitRegion()) {
7370     Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7371     return StmtError();
7372   }
7373   if (DSAStack->isParentOrderedRegion()) {
7374     Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7375     return StmtError();
7376   }
7377   DSAStack->setParentCancelRegion(/*Cancel=*/true);
7378   return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7379                                     CancelRegion);
7380 }
7381 
7382 static bool checkGrainsizeNumTasksClauses(Sema &S,
7383                                           ArrayRef<OMPClause *> Clauses) {
7384   const OMPClause *PrevClause = nullptr;
7385   bool ErrorFound = false;
7386   for (const OMPClause *C : Clauses) {
7387     if (C->getClauseKind() == OMPC_grainsize ||
7388         C->getClauseKind() == OMPC_num_tasks) {
7389       if (!PrevClause)
7390         PrevClause = C;
7391       else if (PrevClause->getClauseKind() != C->getClauseKind()) {
7392         S.Diag(C->getBeginLoc(),
7393                diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7394             << getOpenMPClauseName(C->getClauseKind())
7395             << getOpenMPClauseName(PrevClause->getClauseKind());
7396         S.Diag(PrevClause->getBeginLoc(),
7397                diag::note_omp_previous_grainsize_num_tasks)
7398             << getOpenMPClauseName(PrevClause->getClauseKind());
7399         ErrorFound = true;
7400       }
7401     }
7402   }
7403   return ErrorFound;
7404 }
7405 
7406 static bool checkReductionClauseWithNogroup(Sema &S,
7407                                             ArrayRef<OMPClause *> Clauses) {
7408   const OMPClause *ReductionClause = nullptr;
7409   const OMPClause *NogroupClause = nullptr;
7410   for (const OMPClause *C : Clauses) {
7411     if (C->getClauseKind() == OMPC_reduction) {
7412       ReductionClause = C;
7413       if (NogroupClause)
7414         break;
7415       continue;
7416     }
7417     if (C->getClauseKind() == OMPC_nogroup) {
7418       NogroupClause = C;
7419       if (ReductionClause)
7420         break;
7421       continue;
7422     }
7423   }
7424   if (ReductionClause && NogroupClause) {
7425     S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7426         << SourceRange(NogroupClause->getBeginLoc(),
7427                        NogroupClause->getEndLoc());
7428     return true;
7429   }
7430   return false;
7431 }
7432 
7433 StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7434     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7435     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7436   if (!AStmt)
7437     return StmtError();
7438 
7439   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7440   OMPLoopDirective::HelperExprs B;
7441   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7442   // define the nested loops number.
7443   unsigned NestedLoopCount =
7444       checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
7445                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7446                       VarsWithImplicitDSA, B);
7447   if (NestedLoopCount == 0)
7448     return StmtError();
7449 
7450   assert((CurContext->isDependentContext() || B.builtAll()) &&
7451          "omp for loop exprs were not built");
7452 
7453   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7454   // The grainsize clause and num_tasks clause are mutually exclusive and may
7455   // not appear on the same taskloop directive.
7456   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7457     return StmtError();
7458   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7459   // If a reduction clause is present on the taskloop directive, the nogroup
7460   // clause must not be specified.
7461   if (checkReductionClauseWithNogroup(*this, Clauses))
7462     return StmtError();
7463 
7464   setFunctionHasBranchProtectedScope();
7465   return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7466                                       NestedLoopCount, Clauses, AStmt, B);
7467 }
7468 
7469 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7470     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7471     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7472   if (!AStmt)
7473     return StmtError();
7474 
7475   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7476   OMPLoopDirective::HelperExprs B;
7477   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7478   // define the nested loops number.
7479   unsigned NestedLoopCount =
7480       checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
7481                       /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7482                       VarsWithImplicitDSA, B);
7483   if (NestedLoopCount == 0)
7484     return StmtError();
7485 
7486   assert((CurContext->isDependentContext() || B.builtAll()) &&
7487          "omp for loop exprs were not built");
7488 
7489   if (!CurContext->isDependentContext()) {
7490     // Finalize the clauses that need pre-built expressions for CodeGen.
7491     for (OMPClause *C : Clauses) {
7492       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7493         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7494                                      B.NumIterations, *this, CurScope,
7495                                      DSAStack))
7496           return StmtError();
7497     }
7498   }
7499 
7500   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7501   // The grainsize clause and num_tasks clause are mutually exclusive and may
7502   // not appear on the same taskloop directive.
7503   if (checkGrainsizeNumTasksClauses(*this, Clauses))
7504     return StmtError();
7505   // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7506   // If a reduction clause is present on the taskloop directive, the nogroup
7507   // clause must not be specified.
7508   if (checkReductionClauseWithNogroup(*this, Clauses))
7509     return StmtError();
7510   if (checkSimdlenSafelenSpecified(*this, Clauses))
7511     return StmtError();
7512 
7513   setFunctionHasBranchProtectedScope();
7514   return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7515                                           NestedLoopCount, Clauses, AStmt, B);
7516 }
7517 
7518 StmtResult Sema::ActOnOpenMPDistributeDirective(
7519     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7520     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7521   if (!AStmt)
7522     return StmtError();
7523 
7524   assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7525   OMPLoopDirective::HelperExprs B;
7526   // In presence of clause 'collapse' with number of loops, it will
7527   // define the nested loops number.
7528   unsigned NestedLoopCount =
7529       checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
7530                       nullptr /*ordered not a clause on distribute*/, AStmt,
7531                       *this, *DSAStack, VarsWithImplicitDSA, B);
7532   if (NestedLoopCount == 0)
7533     return StmtError();
7534 
7535   assert((CurContext->isDependentContext() || B.builtAll()) &&
7536          "omp for loop exprs were not built");
7537 
7538   setFunctionHasBranchProtectedScope();
7539   return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7540                                         NestedLoopCount, Clauses, AStmt, B);
7541 }
7542 
7543 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7544     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7545     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7546   if (!AStmt)
7547     return StmtError();
7548 
7549   auto *CS = cast<CapturedStmt>(AStmt);
7550   // 1.2.2 OpenMP Language Terminology
7551   // Structured block - An executable statement with a single entry at the
7552   // top and a single exit at the bottom.
7553   // The point of exit cannot be a branch out of the structured block.
7554   // longjmp() and throw() must not violate the entry/exit criteria.
7555   CS->getCapturedDecl()->setNothrow();
7556   for (int ThisCaptureLevel =
7557            getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7558        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7559     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7560     // 1.2.2 OpenMP Language Terminology
7561     // Structured block - An executable statement with a single entry at the
7562     // top and a single exit at the bottom.
7563     // The point of exit cannot be a branch out of the structured block.
7564     // longjmp() and throw() must not violate the entry/exit criteria.
7565     CS->getCapturedDecl()->setNothrow();
7566   }
7567 
7568   OMPLoopDirective::HelperExprs B;
7569   // In presence of clause 'collapse' with number of loops, it will
7570   // define the nested loops number.
7571   unsigned NestedLoopCount = checkOpenMPLoop(
7572       OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7573       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7574       VarsWithImplicitDSA, B);
7575   if (NestedLoopCount == 0)
7576     return StmtError();
7577 
7578   assert((CurContext->isDependentContext() || B.builtAll()) &&
7579          "omp for loop exprs were not built");
7580 
7581   setFunctionHasBranchProtectedScope();
7582   return OMPDistributeParallelForDirective::Create(
7583       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7584       DSAStack->isCancelRegion());
7585 }
7586 
7587 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7588     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7589     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7590   if (!AStmt)
7591     return StmtError();
7592 
7593   auto *CS = cast<CapturedStmt>(AStmt);
7594   // 1.2.2 OpenMP Language Terminology
7595   // Structured block - An executable statement with a single entry at the
7596   // top and a single exit at the bottom.
7597   // The point of exit cannot be a branch out of the structured block.
7598   // longjmp() and throw() must not violate the entry/exit criteria.
7599   CS->getCapturedDecl()->setNothrow();
7600   for (int ThisCaptureLevel =
7601            getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7602        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7603     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7604     // 1.2.2 OpenMP Language Terminology
7605     // Structured block - An executable statement with a single entry at the
7606     // top and a single exit at the bottom.
7607     // The point of exit cannot be a branch out of the structured block.
7608     // longjmp() and throw() must not violate the entry/exit criteria.
7609     CS->getCapturedDecl()->setNothrow();
7610   }
7611 
7612   OMPLoopDirective::HelperExprs B;
7613   // In presence of clause 'collapse' with number of loops, it will
7614   // define the nested loops number.
7615   unsigned NestedLoopCount = checkOpenMPLoop(
7616       OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7617       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7618       VarsWithImplicitDSA, B);
7619   if (NestedLoopCount == 0)
7620     return StmtError();
7621 
7622   assert((CurContext->isDependentContext() || B.builtAll()) &&
7623          "omp for loop exprs were not built");
7624 
7625   if (!CurContext->isDependentContext()) {
7626     // Finalize the clauses that need pre-built expressions for CodeGen.
7627     for (OMPClause *C : Clauses) {
7628       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7629         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7630                                      B.NumIterations, *this, CurScope,
7631                                      DSAStack))
7632           return StmtError();
7633     }
7634   }
7635 
7636   if (checkSimdlenSafelenSpecified(*this, Clauses))
7637     return StmtError();
7638 
7639   setFunctionHasBranchProtectedScope();
7640   return OMPDistributeParallelForSimdDirective::Create(
7641       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7642 }
7643 
7644 StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7645     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7646     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7647   if (!AStmt)
7648     return StmtError();
7649 
7650   auto *CS = cast<CapturedStmt>(AStmt);
7651   // 1.2.2 OpenMP Language Terminology
7652   // Structured block - An executable statement with a single entry at the
7653   // top and a single exit at the bottom.
7654   // The point of exit cannot be a branch out of the structured block.
7655   // longjmp() and throw() must not violate the entry/exit criteria.
7656   CS->getCapturedDecl()->setNothrow();
7657   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7658        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7659     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7660     // 1.2.2 OpenMP Language Terminology
7661     // Structured block - An executable statement with a single entry at the
7662     // top and a single exit at the bottom.
7663     // The point of exit cannot be a branch out of the structured block.
7664     // longjmp() and throw() must not violate the entry/exit criteria.
7665     CS->getCapturedDecl()->setNothrow();
7666   }
7667 
7668   OMPLoopDirective::HelperExprs B;
7669   // In presence of clause 'collapse' with number of loops, it will
7670   // define the nested loops number.
7671   unsigned NestedLoopCount =
7672       checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
7673                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7674                       *DSAStack, VarsWithImplicitDSA, B);
7675   if (NestedLoopCount == 0)
7676     return StmtError();
7677 
7678   assert((CurContext->isDependentContext() || B.builtAll()) &&
7679          "omp for loop exprs were not built");
7680 
7681   if (!CurContext->isDependentContext()) {
7682     // Finalize the clauses that need pre-built expressions for CodeGen.
7683     for (OMPClause *C : Clauses) {
7684       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7685         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7686                                      B.NumIterations, *this, CurScope,
7687                                      DSAStack))
7688           return StmtError();
7689     }
7690   }
7691 
7692   if (checkSimdlenSafelenSpecified(*this, Clauses))
7693     return StmtError();
7694 
7695   setFunctionHasBranchProtectedScope();
7696   return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7697                                             NestedLoopCount, Clauses, AStmt, B);
7698 }
7699 
7700 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7701     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7702     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7703   if (!AStmt)
7704     return StmtError();
7705 
7706   auto *CS = cast<CapturedStmt>(AStmt);
7707   // 1.2.2 OpenMP Language Terminology
7708   // Structured block - An executable statement with a single entry at the
7709   // top and a single exit at the bottom.
7710   // The point of exit cannot be a branch out of the structured block.
7711   // longjmp() and throw() must not violate the entry/exit criteria.
7712   CS->getCapturedDecl()->setNothrow();
7713   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7714        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7715     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7716     // 1.2.2 OpenMP Language Terminology
7717     // Structured block - An executable statement with a single entry at the
7718     // top and a single exit at the bottom.
7719     // The point of exit cannot be a branch out of the structured block.
7720     // longjmp() and throw() must not violate the entry/exit criteria.
7721     CS->getCapturedDecl()->setNothrow();
7722   }
7723 
7724   OMPLoopDirective::HelperExprs B;
7725   // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7726   // define the nested loops number.
7727   unsigned NestedLoopCount = checkOpenMPLoop(
7728       OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
7729       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7730       VarsWithImplicitDSA, B);
7731   if (NestedLoopCount == 0)
7732     return StmtError();
7733 
7734   assert((CurContext->isDependentContext() || B.builtAll()) &&
7735          "omp target parallel for simd loop exprs were not built");
7736 
7737   if (!CurContext->isDependentContext()) {
7738     // Finalize the clauses that need pre-built expressions for CodeGen.
7739     for (OMPClause *C : Clauses) {
7740       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7741         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7742                                      B.NumIterations, *this, CurScope,
7743                                      DSAStack))
7744           return StmtError();
7745     }
7746   }
7747   if (checkSimdlenSafelenSpecified(*this, Clauses))
7748     return StmtError();
7749 
7750   setFunctionHasBranchProtectedScope();
7751   return OMPTargetParallelForSimdDirective::Create(
7752       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7753 }
7754 
7755 StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7756     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7757     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7758   if (!AStmt)
7759     return StmtError();
7760 
7761   auto *CS = cast<CapturedStmt>(AStmt);
7762   // 1.2.2 OpenMP Language Terminology
7763   // Structured block - An executable statement with a single entry at the
7764   // top and a single exit at the bottom.
7765   // The point of exit cannot be a branch out of the structured block.
7766   // longjmp() and throw() must not violate the entry/exit criteria.
7767   CS->getCapturedDecl()->setNothrow();
7768   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7769        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7770     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7771     // 1.2.2 OpenMP Language Terminology
7772     // Structured block - An executable statement with a single entry at the
7773     // top and a single exit at the bottom.
7774     // The point of exit cannot be a branch out of the structured block.
7775     // longjmp() and throw() must not violate the entry/exit criteria.
7776     CS->getCapturedDecl()->setNothrow();
7777   }
7778 
7779   OMPLoopDirective::HelperExprs B;
7780   // In presence of clause 'collapse' with number of loops, it will define the
7781   // nested loops number.
7782   unsigned NestedLoopCount =
7783       checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
7784                       getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
7785                       VarsWithImplicitDSA, B);
7786   if (NestedLoopCount == 0)
7787     return StmtError();
7788 
7789   assert((CurContext->isDependentContext() || B.builtAll()) &&
7790          "omp target simd loop exprs were not built");
7791 
7792   if (!CurContext->isDependentContext()) {
7793     // Finalize the clauses that need pre-built expressions for CodeGen.
7794     for (OMPClause *C : Clauses) {
7795       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7796         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7797                                      B.NumIterations, *this, CurScope,
7798                                      DSAStack))
7799           return StmtError();
7800     }
7801   }
7802 
7803   if (checkSimdlenSafelenSpecified(*this, Clauses))
7804     return StmtError();
7805 
7806   setFunctionHasBranchProtectedScope();
7807   return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7808                                         NestedLoopCount, Clauses, AStmt, B);
7809 }
7810 
7811 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7812     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7813     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7814   if (!AStmt)
7815     return StmtError();
7816 
7817   auto *CS = cast<CapturedStmt>(AStmt);
7818   // 1.2.2 OpenMP Language Terminology
7819   // Structured block - An executable statement with a single entry at the
7820   // top and a single exit at the bottom.
7821   // The point of exit cannot be a branch out of the structured block.
7822   // longjmp() and throw() must not violate the entry/exit criteria.
7823   CS->getCapturedDecl()->setNothrow();
7824   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7825        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7826     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7827     // 1.2.2 OpenMP Language Terminology
7828     // Structured block - An executable statement with a single entry at the
7829     // top and a single exit at the bottom.
7830     // The point of exit cannot be a branch out of the structured block.
7831     // longjmp() and throw() must not violate the entry/exit criteria.
7832     CS->getCapturedDecl()->setNothrow();
7833   }
7834 
7835   OMPLoopDirective::HelperExprs B;
7836   // In presence of clause 'collapse' with number of loops, it will
7837   // define the nested loops number.
7838   unsigned NestedLoopCount =
7839       checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
7840                       nullptr /*ordered not a clause on distribute*/, CS, *this,
7841                       *DSAStack, VarsWithImplicitDSA, B);
7842   if (NestedLoopCount == 0)
7843     return StmtError();
7844 
7845   assert((CurContext->isDependentContext() || B.builtAll()) &&
7846          "omp teams distribute loop exprs were not built");
7847 
7848   setFunctionHasBranchProtectedScope();
7849 
7850   DSAStack->setParentTeamsRegionLoc(StartLoc);
7851 
7852   return OMPTeamsDistributeDirective::Create(
7853       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7854 }
7855 
7856 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7857     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7858     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7859   if (!AStmt)
7860     return StmtError();
7861 
7862   auto *CS = cast<CapturedStmt>(AStmt);
7863   // 1.2.2 OpenMP Language Terminology
7864   // Structured block - An executable statement with a single entry at the
7865   // top and a single exit at the bottom.
7866   // The point of exit cannot be a branch out of the structured block.
7867   // longjmp() and throw() must not violate the entry/exit criteria.
7868   CS->getCapturedDecl()->setNothrow();
7869   for (int ThisCaptureLevel =
7870            getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7871        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7872     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7873     // 1.2.2 OpenMP Language Terminology
7874     // Structured block - An executable statement with a single entry at the
7875     // top and a single exit at the bottom.
7876     // The point of exit cannot be a branch out of the structured block.
7877     // longjmp() and throw() must not violate the entry/exit criteria.
7878     CS->getCapturedDecl()->setNothrow();
7879   }
7880 
7881 
7882   OMPLoopDirective::HelperExprs B;
7883   // In presence of clause 'collapse' with number of loops, it will
7884   // define the nested loops number.
7885   unsigned NestedLoopCount = checkOpenMPLoop(
7886       OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
7887       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7888       VarsWithImplicitDSA, B);
7889 
7890   if (NestedLoopCount == 0)
7891     return StmtError();
7892 
7893   assert((CurContext->isDependentContext() || B.builtAll()) &&
7894          "omp teams distribute simd loop exprs were not built");
7895 
7896   if (!CurContext->isDependentContext()) {
7897     // Finalize the clauses that need pre-built expressions for CodeGen.
7898     for (OMPClause *C : Clauses) {
7899       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7900         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7901                                      B.NumIterations, *this, CurScope,
7902                                      DSAStack))
7903           return StmtError();
7904     }
7905   }
7906 
7907   if (checkSimdlenSafelenSpecified(*this, Clauses))
7908     return StmtError();
7909 
7910   setFunctionHasBranchProtectedScope();
7911 
7912   DSAStack->setParentTeamsRegionLoc(StartLoc);
7913 
7914   return OMPTeamsDistributeSimdDirective::Create(
7915       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7916 }
7917 
7918 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7919     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7920     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7921   if (!AStmt)
7922     return StmtError();
7923 
7924   auto *CS = cast<CapturedStmt>(AStmt);
7925   // 1.2.2 OpenMP Language Terminology
7926   // Structured block - An executable statement with a single entry at the
7927   // top and a single exit at the bottom.
7928   // The point of exit cannot be a branch out of the structured block.
7929   // longjmp() and throw() must not violate the entry/exit criteria.
7930   CS->getCapturedDecl()->setNothrow();
7931 
7932   for (int ThisCaptureLevel =
7933            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7934        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7935     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7936     // 1.2.2 OpenMP Language Terminology
7937     // Structured block - An executable statement with a single entry at the
7938     // top and a single exit at the bottom.
7939     // The point of exit cannot be a branch out of the structured block.
7940     // longjmp() and throw() must not violate the entry/exit criteria.
7941     CS->getCapturedDecl()->setNothrow();
7942   }
7943 
7944   OMPLoopDirective::HelperExprs B;
7945   // In presence of clause 'collapse' with number of loops, it will
7946   // define the nested loops number.
7947   unsigned NestedLoopCount = checkOpenMPLoop(
7948       OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
7949       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
7950       VarsWithImplicitDSA, B);
7951 
7952   if (NestedLoopCount == 0)
7953     return StmtError();
7954 
7955   assert((CurContext->isDependentContext() || B.builtAll()) &&
7956          "omp for loop exprs were not built");
7957 
7958   if (!CurContext->isDependentContext()) {
7959     // Finalize the clauses that need pre-built expressions for CodeGen.
7960     for (OMPClause *C : Clauses) {
7961       if (auto *LC = dyn_cast<OMPLinearClause>(C))
7962         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7963                                      B.NumIterations, *this, CurScope,
7964                                      DSAStack))
7965           return StmtError();
7966     }
7967   }
7968 
7969   if (checkSimdlenSafelenSpecified(*this, Clauses))
7970     return StmtError();
7971 
7972   setFunctionHasBranchProtectedScope();
7973 
7974   DSAStack->setParentTeamsRegionLoc(StartLoc);
7975 
7976   return OMPTeamsDistributeParallelForSimdDirective::Create(
7977       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7978 }
7979 
7980 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7981     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7982     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
7983   if (!AStmt)
7984     return StmtError();
7985 
7986   auto *CS = cast<CapturedStmt>(AStmt);
7987   // 1.2.2 OpenMP Language Terminology
7988   // Structured block - An executable statement with a single entry at the
7989   // top and a single exit at the bottom.
7990   // The point of exit cannot be a branch out of the structured block.
7991   // longjmp() and throw() must not violate the entry/exit criteria.
7992   CS->getCapturedDecl()->setNothrow();
7993 
7994   for (int ThisCaptureLevel =
7995            getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7996        ThisCaptureLevel > 1; --ThisCaptureLevel) {
7997     CS = cast<CapturedStmt>(CS->getCapturedStmt());
7998     // 1.2.2 OpenMP Language Terminology
7999     // Structured block - An executable statement with a single entry at the
8000     // top and a single exit at the bottom.
8001     // The point of exit cannot be a branch out of the structured block.
8002     // longjmp() and throw() must not violate the entry/exit criteria.
8003     CS->getCapturedDecl()->setNothrow();
8004   }
8005 
8006   OMPLoopDirective::HelperExprs B;
8007   // In presence of clause 'collapse' with number of loops, it will
8008   // define the nested loops number.
8009   unsigned NestedLoopCount = checkOpenMPLoop(
8010       OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8011       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8012       VarsWithImplicitDSA, B);
8013 
8014   if (NestedLoopCount == 0)
8015     return StmtError();
8016 
8017   assert((CurContext->isDependentContext() || B.builtAll()) &&
8018          "omp for loop exprs were not built");
8019 
8020   setFunctionHasBranchProtectedScope();
8021 
8022   DSAStack->setParentTeamsRegionLoc(StartLoc);
8023 
8024   return OMPTeamsDistributeParallelForDirective::Create(
8025       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8026       DSAStack->isCancelRegion());
8027 }
8028 
8029 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8030                                                  Stmt *AStmt,
8031                                                  SourceLocation StartLoc,
8032                                                  SourceLocation EndLoc) {
8033   if (!AStmt)
8034     return StmtError();
8035 
8036   auto *CS = cast<CapturedStmt>(AStmt);
8037   // 1.2.2 OpenMP Language Terminology
8038   // Structured block - An executable statement with a single entry at the
8039   // top and a single exit at the bottom.
8040   // The point of exit cannot be a branch out of the structured block.
8041   // longjmp() and throw() must not violate the entry/exit criteria.
8042   CS->getCapturedDecl()->setNothrow();
8043 
8044   for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8045        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8046     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8047     // 1.2.2 OpenMP Language Terminology
8048     // Structured block - An executable statement with a single entry at the
8049     // top and a single exit at the bottom.
8050     // The point of exit cannot be a branch out of the structured block.
8051     // longjmp() and throw() must not violate the entry/exit criteria.
8052     CS->getCapturedDecl()->setNothrow();
8053   }
8054   setFunctionHasBranchProtectedScope();
8055 
8056   return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8057                                          AStmt);
8058 }
8059 
8060 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8061     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8062     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8063   if (!AStmt)
8064     return StmtError();
8065 
8066   auto *CS = cast<CapturedStmt>(AStmt);
8067   // 1.2.2 OpenMP Language Terminology
8068   // Structured block - An executable statement with a single entry at the
8069   // top and a single exit at the bottom.
8070   // The point of exit cannot be a branch out of the structured block.
8071   // longjmp() and throw() must not violate the entry/exit criteria.
8072   CS->getCapturedDecl()->setNothrow();
8073   for (int ThisCaptureLevel =
8074            getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8075        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8076     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8077     // 1.2.2 OpenMP Language Terminology
8078     // Structured block - An executable statement with a single entry at the
8079     // top and a single exit at the bottom.
8080     // The point of exit cannot be a branch out of the structured block.
8081     // longjmp() and throw() must not violate the entry/exit criteria.
8082     CS->getCapturedDecl()->setNothrow();
8083   }
8084 
8085   OMPLoopDirective::HelperExprs B;
8086   // In presence of clause 'collapse' with number of loops, it will
8087   // define the nested loops number.
8088   unsigned NestedLoopCount = checkOpenMPLoop(
8089       OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8090       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8091       VarsWithImplicitDSA, B);
8092   if (NestedLoopCount == 0)
8093     return StmtError();
8094 
8095   assert((CurContext->isDependentContext() || B.builtAll()) &&
8096          "omp target teams distribute loop exprs were not built");
8097 
8098   setFunctionHasBranchProtectedScope();
8099   return OMPTargetTeamsDistributeDirective::Create(
8100       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8101 }
8102 
8103 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8104     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8105     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8106   if (!AStmt)
8107     return StmtError();
8108 
8109   auto *CS = cast<CapturedStmt>(AStmt);
8110   // 1.2.2 OpenMP Language Terminology
8111   // Structured block - An executable statement with a single entry at the
8112   // top and a single exit at the bottom.
8113   // The point of exit cannot be a branch out of the structured block.
8114   // longjmp() and throw() must not violate the entry/exit criteria.
8115   CS->getCapturedDecl()->setNothrow();
8116   for (int ThisCaptureLevel =
8117            getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8118        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8119     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8120     // 1.2.2 OpenMP Language Terminology
8121     // Structured block - An executable statement with a single entry at the
8122     // top and a single exit at the bottom.
8123     // The point of exit cannot be a branch out of the structured block.
8124     // longjmp() and throw() must not violate the entry/exit criteria.
8125     CS->getCapturedDecl()->setNothrow();
8126   }
8127 
8128   OMPLoopDirective::HelperExprs B;
8129   // In presence of clause 'collapse' with number of loops, it will
8130   // define the nested loops number.
8131   unsigned NestedLoopCount = checkOpenMPLoop(
8132       OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8133       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8134       VarsWithImplicitDSA, B);
8135   if (NestedLoopCount == 0)
8136     return StmtError();
8137 
8138   assert((CurContext->isDependentContext() || B.builtAll()) &&
8139          "omp target teams distribute parallel for loop exprs were not built");
8140 
8141   if (!CurContext->isDependentContext()) {
8142     // Finalize the clauses that need pre-built expressions for CodeGen.
8143     for (OMPClause *C : Clauses) {
8144       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8145         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8146                                      B.NumIterations, *this, CurScope,
8147                                      DSAStack))
8148           return StmtError();
8149     }
8150   }
8151 
8152   setFunctionHasBranchProtectedScope();
8153   return OMPTargetTeamsDistributeParallelForDirective::Create(
8154       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8155       DSAStack->isCancelRegion());
8156 }
8157 
8158 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8159     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8160     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8161   if (!AStmt)
8162     return StmtError();
8163 
8164   auto *CS = cast<CapturedStmt>(AStmt);
8165   // 1.2.2 OpenMP Language Terminology
8166   // Structured block - An executable statement with a single entry at the
8167   // top and a single exit at the bottom.
8168   // The point of exit cannot be a branch out of the structured block.
8169   // longjmp() and throw() must not violate the entry/exit criteria.
8170   CS->getCapturedDecl()->setNothrow();
8171   for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8172            OMPD_target_teams_distribute_parallel_for_simd);
8173        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8174     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8175     // 1.2.2 OpenMP Language Terminology
8176     // Structured block - An executable statement with a single entry at the
8177     // top and a single exit at the bottom.
8178     // The point of exit cannot be a branch out of the structured block.
8179     // longjmp() and throw() must not violate the entry/exit criteria.
8180     CS->getCapturedDecl()->setNothrow();
8181   }
8182 
8183   OMPLoopDirective::HelperExprs B;
8184   // In presence of clause 'collapse' with number of loops, it will
8185   // define the nested loops number.
8186   unsigned NestedLoopCount =
8187       checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
8188                       getCollapseNumberExpr(Clauses),
8189                       nullptr /*ordered not a clause on distribute*/, CS, *this,
8190                       *DSAStack, VarsWithImplicitDSA, B);
8191   if (NestedLoopCount == 0)
8192     return StmtError();
8193 
8194   assert((CurContext->isDependentContext() || B.builtAll()) &&
8195          "omp target teams distribute parallel for simd loop exprs were not "
8196          "built");
8197 
8198   if (!CurContext->isDependentContext()) {
8199     // Finalize the clauses that need pre-built expressions for CodeGen.
8200     for (OMPClause *C : Clauses) {
8201       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8202         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8203                                      B.NumIterations, *this, CurScope,
8204                                      DSAStack))
8205           return StmtError();
8206     }
8207   }
8208 
8209   if (checkSimdlenSafelenSpecified(*this, Clauses))
8210     return StmtError();
8211 
8212   setFunctionHasBranchProtectedScope();
8213   return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8214       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8215 }
8216 
8217 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8218     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8219     SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
8220   if (!AStmt)
8221     return StmtError();
8222 
8223   auto *CS = cast<CapturedStmt>(AStmt);
8224   // 1.2.2 OpenMP Language Terminology
8225   // Structured block - An executable statement with a single entry at the
8226   // top and a single exit at the bottom.
8227   // The point of exit cannot be a branch out of the structured block.
8228   // longjmp() and throw() must not violate the entry/exit criteria.
8229   CS->getCapturedDecl()->setNothrow();
8230   for (int ThisCaptureLevel =
8231            getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8232        ThisCaptureLevel > 1; --ThisCaptureLevel) {
8233     CS = cast<CapturedStmt>(CS->getCapturedStmt());
8234     // 1.2.2 OpenMP Language Terminology
8235     // Structured block - An executable statement with a single entry at the
8236     // top and a single exit at the bottom.
8237     // The point of exit cannot be a branch out of the structured block.
8238     // longjmp() and throw() must not violate the entry/exit criteria.
8239     CS->getCapturedDecl()->setNothrow();
8240   }
8241 
8242   OMPLoopDirective::HelperExprs B;
8243   // In presence of clause 'collapse' with number of loops, it will
8244   // define the nested loops number.
8245   unsigned NestedLoopCount = checkOpenMPLoop(
8246       OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
8247       nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
8248       VarsWithImplicitDSA, B);
8249   if (NestedLoopCount == 0)
8250     return StmtError();
8251 
8252   assert((CurContext->isDependentContext() || B.builtAll()) &&
8253          "omp target teams distribute simd loop exprs were not built");
8254 
8255   if (!CurContext->isDependentContext()) {
8256     // Finalize the clauses that need pre-built expressions for CodeGen.
8257     for (OMPClause *C : Clauses) {
8258       if (auto *LC = dyn_cast<OMPLinearClause>(C))
8259         if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8260                                      B.NumIterations, *this, CurScope,
8261                                      DSAStack))
8262           return StmtError();
8263     }
8264   }
8265 
8266   if (checkSimdlenSafelenSpecified(*this, Clauses))
8267     return StmtError();
8268 
8269   setFunctionHasBranchProtectedScope();
8270   return OMPTargetTeamsDistributeSimdDirective::Create(
8271       Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8272 }
8273 
8274 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
8275                                              SourceLocation StartLoc,
8276                                              SourceLocation LParenLoc,
8277                                              SourceLocation EndLoc) {
8278   OMPClause *Res = nullptr;
8279   switch (Kind) {
8280   case OMPC_final:
8281     Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8282     break;
8283   case OMPC_num_threads:
8284     Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8285     break;
8286   case OMPC_safelen:
8287     Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8288     break;
8289   case OMPC_simdlen:
8290     Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8291     break;
8292   case OMPC_collapse:
8293     Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8294     break;
8295   case OMPC_ordered:
8296     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8297     break;
8298   case OMPC_device:
8299     Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8300     break;
8301   case OMPC_num_teams:
8302     Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8303     break;
8304   case OMPC_thread_limit:
8305     Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8306     break;
8307   case OMPC_priority:
8308     Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8309     break;
8310   case OMPC_grainsize:
8311     Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8312     break;
8313   case OMPC_num_tasks:
8314     Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8315     break;
8316   case OMPC_hint:
8317     Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8318     break;
8319   case OMPC_if:
8320   case OMPC_default:
8321   case OMPC_proc_bind:
8322   case OMPC_schedule:
8323   case OMPC_private:
8324   case OMPC_firstprivate:
8325   case OMPC_lastprivate:
8326   case OMPC_shared:
8327   case OMPC_reduction:
8328   case OMPC_task_reduction:
8329   case OMPC_in_reduction:
8330   case OMPC_linear:
8331   case OMPC_aligned:
8332   case OMPC_copyin:
8333   case OMPC_copyprivate:
8334   case OMPC_nowait:
8335   case OMPC_untied:
8336   case OMPC_mergeable:
8337   case OMPC_threadprivate:
8338   case OMPC_flush:
8339   case OMPC_read:
8340   case OMPC_write:
8341   case OMPC_update:
8342   case OMPC_capture:
8343   case OMPC_seq_cst:
8344   case OMPC_depend:
8345   case OMPC_threads:
8346   case OMPC_simd:
8347   case OMPC_map:
8348   case OMPC_nogroup:
8349   case OMPC_dist_schedule:
8350   case OMPC_defaultmap:
8351   case OMPC_unknown:
8352   case OMPC_uniform:
8353   case OMPC_to:
8354   case OMPC_from:
8355   case OMPC_use_device_ptr:
8356   case OMPC_is_device_ptr:
8357   case OMPC_unified_address:
8358   case OMPC_unified_shared_memory:
8359   case OMPC_reverse_offload:
8360   case OMPC_dynamic_allocators:
8361   case OMPC_atomic_default_mem_order:
8362     llvm_unreachable("Clause is not allowed.");
8363   }
8364   return Res;
8365 }
8366 
8367 // An OpenMP directive such as 'target parallel' has two captured regions:
8368 // for the 'target' and 'parallel' respectively.  This function returns
8369 // the region in which to capture expressions associated with a clause.
8370 // A return value of OMPD_unknown signifies that the expression should not
8371 // be captured.
8372 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8373     OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8374     OpenMPDirectiveKind NameModifier = OMPD_unknown) {
8375   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8376   switch (CKind) {
8377   case OMPC_if:
8378     switch (DKind) {
8379     case OMPD_target_parallel:
8380     case OMPD_target_parallel_for:
8381     case OMPD_target_parallel_for_simd:
8382       // If this clause applies to the nested 'parallel' region, capture within
8383       // the 'target' region, otherwise do not capture.
8384       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8385         CaptureRegion = OMPD_target;
8386       break;
8387     case OMPD_target_teams_distribute_parallel_for:
8388     case OMPD_target_teams_distribute_parallel_for_simd:
8389       // If this clause applies to the nested 'parallel' region, capture within
8390       // the 'teams' region, otherwise do not capture.
8391       if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8392         CaptureRegion = OMPD_teams;
8393       break;
8394     case OMPD_teams_distribute_parallel_for:
8395     case OMPD_teams_distribute_parallel_for_simd:
8396       CaptureRegion = OMPD_teams;
8397       break;
8398     case OMPD_target_update:
8399     case OMPD_target_enter_data:
8400     case OMPD_target_exit_data:
8401       CaptureRegion = OMPD_task;
8402       break;
8403     case OMPD_cancel:
8404     case OMPD_parallel:
8405     case OMPD_parallel_sections:
8406     case OMPD_parallel_for:
8407     case OMPD_parallel_for_simd:
8408     case OMPD_target:
8409     case OMPD_target_simd:
8410     case OMPD_target_teams:
8411     case OMPD_target_teams_distribute:
8412     case OMPD_target_teams_distribute_simd:
8413     case OMPD_distribute_parallel_for:
8414     case OMPD_distribute_parallel_for_simd:
8415     case OMPD_task:
8416     case OMPD_taskloop:
8417     case OMPD_taskloop_simd:
8418     case OMPD_target_data:
8419       // Do not capture if-clause expressions.
8420       break;
8421     case OMPD_threadprivate:
8422     case OMPD_taskyield:
8423     case OMPD_barrier:
8424     case OMPD_taskwait:
8425     case OMPD_cancellation_point:
8426     case OMPD_flush:
8427     case OMPD_declare_reduction:
8428     case OMPD_declare_mapper:
8429     case OMPD_declare_simd:
8430     case OMPD_declare_target:
8431     case OMPD_end_declare_target:
8432     case OMPD_teams:
8433     case OMPD_simd:
8434     case OMPD_for:
8435     case OMPD_for_simd:
8436     case OMPD_sections:
8437     case OMPD_section:
8438     case OMPD_single:
8439     case OMPD_master:
8440     case OMPD_critical:
8441     case OMPD_taskgroup:
8442     case OMPD_distribute:
8443     case OMPD_ordered:
8444     case OMPD_atomic:
8445     case OMPD_distribute_simd:
8446     case OMPD_teams_distribute:
8447     case OMPD_teams_distribute_simd:
8448     case OMPD_requires:
8449       llvm_unreachable("Unexpected OpenMP directive with if-clause");
8450     case OMPD_unknown:
8451       llvm_unreachable("Unknown OpenMP directive");
8452     }
8453     break;
8454   case OMPC_num_threads:
8455     switch (DKind) {
8456     case OMPD_target_parallel:
8457     case OMPD_target_parallel_for:
8458     case OMPD_target_parallel_for_simd:
8459       CaptureRegion = OMPD_target;
8460       break;
8461     case OMPD_teams_distribute_parallel_for:
8462     case OMPD_teams_distribute_parallel_for_simd:
8463     case OMPD_target_teams_distribute_parallel_for:
8464     case OMPD_target_teams_distribute_parallel_for_simd:
8465       CaptureRegion = OMPD_teams;
8466       break;
8467     case OMPD_parallel:
8468     case OMPD_parallel_sections:
8469     case OMPD_parallel_for:
8470     case OMPD_parallel_for_simd:
8471     case OMPD_distribute_parallel_for:
8472     case OMPD_distribute_parallel_for_simd:
8473       // Do not capture num_threads-clause expressions.
8474       break;
8475     case OMPD_target_data:
8476     case OMPD_target_enter_data:
8477     case OMPD_target_exit_data:
8478     case OMPD_target_update:
8479     case OMPD_target:
8480     case OMPD_target_simd:
8481     case OMPD_target_teams:
8482     case OMPD_target_teams_distribute:
8483     case OMPD_target_teams_distribute_simd:
8484     case OMPD_cancel:
8485     case OMPD_task:
8486     case OMPD_taskloop:
8487     case OMPD_taskloop_simd:
8488     case OMPD_threadprivate:
8489     case OMPD_taskyield:
8490     case OMPD_barrier:
8491     case OMPD_taskwait:
8492     case OMPD_cancellation_point:
8493     case OMPD_flush:
8494     case OMPD_declare_reduction:
8495     case OMPD_declare_mapper:
8496     case OMPD_declare_simd:
8497     case OMPD_declare_target:
8498     case OMPD_end_declare_target:
8499     case OMPD_teams:
8500     case OMPD_simd:
8501     case OMPD_for:
8502     case OMPD_for_simd:
8503     case OMPD_sections:
8504     case OMPD_section:
8505     case OMPD_single:
8506     case OMPD_master:
8507     case OMPD_critical:
8508     case OMPD_taskgroup:
8509     case OMPD_distribute:
8510     case OMPD_ordered:
8511     case OMPD_atomic:
8512     case OMPD_distribute_simd:
8513     case OMPD_teams_distribute:
8514     case OMPD_teams_distribute_simd:
8515     case OMPD_requires:
8516       llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8517     case OMPD_unknown:
8518       llvm_unreachable("Unknown OpenMP directive");
8519     }
8520     break;
8521   case OMPC_num_teams:
8522     switch (DKind) {
8523     case OMPD_target_teams:
8524     case OMPD_target_teams_distribute:
8525     case OMPD_target_teams_distribute_simd:
8526     case OMPD_target_teams_distribute_parallel_for:
8527     case OMPD_target_teams_distribute_parallel_for_simd:
8528       CaptureRegion = OMPD_target;
8529       break;
8530     case OMPD_teams_distribute_parallel_for:
8531     case OMPD_teams_distribute_parallel_for_simd:
8532     case OMPD_teams:
8533     case OMPD_teams_distribute:
8534     case OMPD_teams_distribute_simd:
8535       // Do not capture num_teams-clause expressions.
8536       break;
8537     case OMPD_distribute_parallel_for:
8538     case OMPD_distribute_parallel_for_simd:
8539     case OMPD_task:
8540     case OMPD_taskloop:
8541     case OMPD_taskloop_simd:
8542     case OMPD_target_data:
8543     case OMPD_target_enter_data:
8544     case OMPD_target_exit_data:
8545     case OMPD_target_update:
8546     case OMPD_cancel:
8547     case OMPD_parallel:
8548     case OMPD_parallel_sections:
8549     case OMPD_parallel_for:
8550     case OMPD_parallel_for_simd:
8551     case OMPD_target:
8552     case OMPD_target_simd:
8553     case OMPD_target_parallel:
8554     case OMPD_target_parallel_for:
8555     case OMPD_target_parallel_for_simd:
8556     case OMPD_threadprivate:
8557     case OMPD_taskyield:
8558     case OMPD_barrier:
8559     case OMPD_taskwait:
8560     case OMPD_cancellation_point:
8561     case OMPD_flush:
8562     case OMPD_declare_reduction:
8563     case OMPD_declare_mapper:
8564     case OMPD_declare_simd:
8565     case OMPD_declare_target:
8566     case OMPD_end_declare_target:
8567     case OMPD_simd:
8568     case OMPD_for:
8569     case OMPD_for_simd:
8570     case OMPD_sections:
8571     case OMPD_section:
8572     case OMPD_single:
8573     case OMPD_master:
8574     case OMPD_critical:
8575     case OMPD_taskgroup:
8576     case OMPD_distribute:
8577     case OMPD_ordered:
8578     case OMPD_atomic:
8579     case OMPD_distribute_simd:
8580     case OMPD_requires:
8581       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8582     case OMPD_unknown:
8583       llvm_unreachable("Unknown OpenMP directive");
8584     }
8585     break;
8586   case OMPC_thread_limit:
8587     switch (DKind) {
8588     case OMPD_target_teams:
8589     case OMPD_target_teams_distribute:
8590     case OMPD_target_teams_distribute_simd:
8591     case OMPD_target_teams_distribute_parallel_for:
8592     case OMPD_target_teams_distribute_parallel_for_simd:
8593       CaptureRegion = OMPD_target;
8594       break;
8595     case OMPD_teams_distribute_parallel_for:
8596     case OMPD_teams_distribute_parallel_for_simd:
8597     case OMPD_teams:
8598     case OMPD_teams_distribute:
8599     case OMPD_teams_distribute_simd:
8600       // Do not capture thread_limit-clause expressions.
8601       break;
8602     case OMPD_distribute_parallel_for:
8603     case OMPD_distribute_parallel_for_simd:
8604     case OMPD_task:
8605     case OMPD_taskloop:
8606     case OMPD_taskloop_simd:
8607     case OMPD_target_data:
8608     case OMPD_target_enter_data:
8609     case OMPD_target_exit_data:
8610     case OMPD_target_update:
8611     case OMPD_cancel:
8612     case OMPD_parallel:
8613     case OMPD_parallel_sections:
8614     case OMPD_parallel_for:
8615     case OMPD_parallel_for_simd:
8616     case OMPD_target:
8617     case OMPD_target_simd:
8618     case OMPD_target_parallel:
8619     case OMPD_target_parallel_for:
8620     case OMPD_target_parallel_for_simd:
8621     case OMPD_threadprivate:
8622     case OMPD_taskyield:
8623     case OMPD_barrier:
8624     case OMPD_taskwait:
8625     case OMPD_cancellation_point:
8626     case OMPD_flush:
8627     case OMPD_declare_reduction:
8628     case OMPD_declare_mapper:
8629     case OMPD_declare_simd:
8630     case OMPD_declare_target:
8631     case OMPD_end_declare_target:
8632     case OMPD_simd:
8633     case OMPD_for:
8634     case OMPD_for_simd:
8635     case OMPD_sections:
8636     case OMPD_section:
8637     case OMPD_single:
8638     case OMPD_master:
8639     case OMPD_critical:
8640     case OMPD_taskgroup:
8641     case OMPD_distribute:
8642     case OMPD_ordered:
8643     case OMPD_atomic:
8644     case OMPD_distribute_simd:
8645     case OMPD_requires:
8646       llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8647     case OMPD_unknown:
8648       llvm_unreachable("Unknown OpenMP directive");
8649     }
8650     break;
8651   case OMPC_schedule:
8652     switch (DKind) {
8653     case OMPD_parallel_for:
8654     case OMPD_parallel_for_simd:
8655     case OMPD_distribute_parallel_for:
8656     case OMPD_distribute_parallel_for_simd:
8657     case OMPD_teams_distribute_parallel_for:
8658     case OMPD_teams_distribute_parallel_for_simd:
8659     case OMPD_target_parallel_for:
8660     case OMPD_target_parallel_for_simd:
8661     case OMPD_target_teams_distribute_parallel_for:
8662     case OMPD_target_teams_distribute_parallel_for_simd:
8663       CaptureRegion = OMPD_parallel;
8664       break;
8665     case OMPD_for:
8666     case OMPD_for_simd:
8667       // Do not capture schedule-clause expressions.
8668       break;
8669     case OMPD_task:
8670     case OMPD_taskloop:
8671     case OMPD_taskloop_simd:
8672     case OMPD_target_data:
8673     case OMPD_target_enter_data:
8674     case OMPD_target_exit_data:
8675     case OMPD_target_update:
8676     case OMPD_teams:
8677     case OMPD_teams_distribute:
8678     case OMPD_teams_distribute_simd:
8679     case OMPD_target_teams_distribute:
8680     case OMPD_target_teams_distribute_simd:
8681     case OMPD_target:
8682     case OMPD_target_simd:
8683     case OMPD_target_parallel:
8684     case OMPD_cancel:
8685     case OMPD_parallel:
8686     case OMPD_parallel_sections:
8687     case OMPD_threadprivate:
8688     case OMPD_taskyield:
8689     case OMPD_barrier:
8690     case OMPD_taskwait:
8691     case OMPD_cancellation_point:
8692     case OMPD_flush:
8693     case OMPD_declare_reduction:
8694     case OMPD_declare_mapper:
8695     case OMPD_declare_simd:
8696     case OMPD_declare_target:
8697     case OMPD_end_declare_target:
8698     case OMPD_simd:
8699     case OMPD_sections:
8700     case OMPD_section:
8701     case OMPD_single:
8702     case OMPD_master:
8703     case OMPD_critical:
8704     case OMPD_taskgroup:
8705     case OMPD_distribute:
8706     case OMPD_ordered:
8707     case OMPD_atomic:
8708     case OMPD_distribute_simd:
8709     case OMPD_target_teams:
8710     case OMPD_requires:
8711       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8712     case OMPD_unknown:
8713       llvm_unreachable("Unknown OpenMP directive");
8714     }
8715     break;
8716   case OMPC_dist_schedule:
8717     switch (DKind) {
8718     case OMPD_teams_distribute_parallel_for:
8719     case OMPD_teams_distribute_parallel_for_simd:
8720     case OMPD_teams_distribute:
8721     case OMPD_teams_distribute_simd:
8722     case OMPD_target_teams_distribute_parallel_for:
8723     case OMPD_target_teams_distribute_parallel_for_simd:
8724     case OMPD_target_teams_distribute:
8725     case OMPD_target_teams_distribute_simd:
8726       CaptureRegion = OMPD_teams;
8727       break;
8728     case OMPD_distribute_parallel_for:
8729     case OMPD_distribute_parallel_for_simd:
8730     case OMPD_distribute:
8731     case OMPD_distribute_simd:
8732       // Do not capture thread_limit-clause expressions.
8733       break;
8734     case OMPD_parallel_for:
8735     case OMPD_parallel_for_simd:
8736     case OMPD_target_parallel_for_simd:
8737     case OMPD_target_parallel_for:
8738     case OMPD_task:
8739     case OMPD_taskloop:
8740     case OMPD_taskloop_simd:
8741     case OMPD_target_data:
8742     case OMPD_target_enter_data:
8743     case OMPD_target_exit_data:
8744     case OMPD_target_update:
8745     case OMPD_teams:
8746     case OMPD_target:
8747     case OMPD_target_simd:
8748     case OMPD_target_parallel:
8749     case OMPD_cancel:
8750     case OMPD_parallel:
8751     case OMPD_parallel_sections:
8752     case OMPD_threadprivate:
8753     case OMPD_taskyield:
8754     case OMPD_barrier:
8755     case OMPD_taskwait:
8756     case OMPD_cancellation_point:
8757     case OMPD_flush:
8758     case OMPD_declare_reduction:
8759     case OMPD_declare_mapper:
8760     case OMPD_declare_simd:
8761     case OMPD_declare_target:
8762     case OMPD_end_declare_target:
8763     case OMPD_simd:
8764     case OMPD_for:
8765     case OMPD_for_simd:
8766     case OMPD_sections:
8767     case OMPD_section:
8768     case OMPD_single:
8769     case OMPD_master:
8770     case OMPD_critical:
8771     case OMPD_taskgroup:
8772     case OMPD_ordered:
8773     case OMPD_atomic:
8774     case OMPD_target_teams:
8775     case OMPD_requires:
8776       llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8777     case OMPD_unknown:
8778       llvm_unreachable("Unknown OpenMP directive");
8779     }
8780     break;
8781   case OMPC_device:
8782     switch (DKind) {
8783     case OMPD_target_update:
8784     case OMPD_target_enter_data:
8785     case OMPD_target_exit_data:
8786     case OMPD_target:
8787     case OMPD_target_simd:
8788     case OMPD_target_teams:
8789     case OMPD_target_parallel:
8790     case OMPD_target_teams_distribute:
8791     case OMPD_target_teams_distribute_simd:
8792     case OMPD_target_parallel_for:
8793     case OMPD_target_parallel_for_simd:
8794     case OMPD_target_teams_distribute_parallel_for:
8795     case OMPD_target_teams_distribute_parallel_for_simd:
8796       CaptureRegion = OMPD_task;
8797       break;
8798     case OMPD_target_data:
8799       // Do not capture device-clause expressions.
8800       break;
8801     case OMPD_teams_distribute_parallel_for:
8802     case OMPD_teams_distribute_parallel_for_simd:
8803     case OMPD_teams:
8804     case OMPD_teams_distribute:
8805     case OMPD_teams_distribute_simd:
8806     case OMPD_distribute_parallel_for:
8807     case OMPD_distribute_parallel_for_simd:
8808     case OMPD_task:
8809     case OMPD_taskloop:
8810     case OMPD_taskloop_simd:
8811     case OMPD_cancel:
8812     case OMPD_parallel:
8813     case OMPD_parallel_sections:
8814     case OMPD_parallel_for:
8815     case OMPD_parallel_for_simd:
8816     case OMPD_threadprivate:
8817     case OMPD_taskyield:
8818     case OMPD_barrier:
8819     case OMPD_taskwait:
8820     case OMPD_cancellation_point:
8821     case OMPD_flush:
8822     case OMPD_declare_reduction:
8823     case OMPD_declare_mapper:
8824     case OMPD_declare_simd:
8825     case OMPD_declare_target:
8826     case OMPD_end_declare_target:
8827     case OMPD_simd:
8828     case OMPD_for:
8829     case OMPD_for_simd:
8830     case OMPD_sections:
8831     case OMPD_section:
8832     case OMPD_single:
8833     case OMPD_master:
8834     case OMPD_critical:
8835     case OMPD_taskgroup:
8836     case OMPD_distribute:
8837     case OMPD_ordered:
8838     case OMPD_atomic:
8839     case OMPD_distribute_simd:
8840     case OMPD_requires:
8841       llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8842     case OMPD_unknown:
8843       llvm_unreachable("Unknown OpenMP directive");
8844     }
8845     break;
8846   case OMPC_firstprivate:
8847   case OMPC_lastprivate:
8848   case OMPC_reduction:
8849   case OMPC_task_reduction:
8850   case OMPC_in_reduction:
8851   case OMPC_linear:
8852   case OMPC_default:
8853   case OMPC_proc_bind:
8854   case OMPC_final:
8855   case OMPC_safelen:
8856   case OMPC_simdlen:
8857   case OMPC_collapse:
8858   case OMPC_private:
8859   case OMPC_shared:
8860   case OMPC_aligned:
8861   case OMPC_copyin:
8862   case OMPC_copyprivate:
8863   case OMPC_ordered:
8864   case OMPC_nowait:
8865   case OMPC_untied:
8866   case OMPC_mergeable:
8867   case OMPC_threadprivate:
8868   case OMPC_flush:
8869   case OMPC_read:
8870   case OMPC_write:
8871   case OMPC_update:
8872   case OMPC_capture:
8873   case OMPC_seq_cst:
8874   case OMPC_depend:
8875   case OMPC_threads:
8876   case OMPC_simd:
8877   case OMPC_map:
8878   case OMPC_priority:
8879   case OMPC_grainsize:
8880   case OMPC_nogroup:
8881   case OMPC_num_tasks:
8882   case OMPC_hint:
8883   case OMPC_defaultmap:
8884   case OMPC_unknown:
8885   case OMPC_uniform:
8886   case OMPC_to:
8887   case OMPC_from:
8888   case OMPC_use_device_ptr:
8889   case OMPC_is_device_ptr:
8890   case OMPC_unified_address:
8891   case OMPC_unified_shared_memory:
8892   case OMPC_reverse_offload:
8893   case OMPC_dynamic_allocators:
8894   case OMPC_atomic_default_mem_order:
8895     llvm_unreachable("Unexpected OpenMP clause.");
8896   }
8897   return CaptureRegion;
8898 }
8899 
8900 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8901                                      Expr *Condition, SourceLocation StartLoc,
8902                                      SourceLocation LParenLoc,
8903                                      SourceLocation NameModifierLoc,
8904                                      SourceLocation ColonLoc,
8905                                      SourceLocation EndLoc) {
8906   Expr *ValExpr = Condition;
8907   Stmt *HelperValStmt = nullptr;
8908   OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
8909   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8910       !Condition->isInstantiationDependent() &&
8911       !Condition->containsUnexpandedParameterPack()) {
8912     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8913     if (Val.isInvalid())
8914       return nullptr;
8915 
8916     ValExpr = Val.get();
8917 
8918     OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8919     CaptureRegion =
8920         getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
8921     if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
8922       ValExpr = MakeFullExpr(ValExpr).get();
8923       llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
8924       ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8925       HelperValStmt = buildPreInits(Context, Captures);
8926     }
8927   }
8928 
8929   return new (Context)
8930       OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8931                   LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
8932 }
8933 
8934 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8935                                         SourceLocation StartLoc,
8936                                         SourceLocation LParenLoc,
8937                                         SourceLocation EndLoc) {
8938   Expr *ValExpr = Condition;
8939   if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8940       !Condition->isInstantiationDependent() &&
8941       !Condition->containsUnexpandedParameterPack()) {
8942     ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
8943     if (Val.isInvalid())
8944       return nullptr;
8945 
8946     ValExpr = MakeFullExpr(Val.get()).get();
8947   }
8948 
8949   return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8950 }
8951 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8952                                                         Expr *Op) {
8953   if (!Op)
8954     return ExprError();
8955 
8956   class IntConvertDiagnoser : public ICEConvertDiagnoser {
8957   public:
8958     IntConvertDiagnoser()
8959         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
8960     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8961                                          QualType T) override {
8962       return S.Diag(Loc, diag::err_omp_not_integral) << T;
8963     }
8964     SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8965                                              QualType T) override {
8966       return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8967     }
8968     SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8969                                                QualType T,
8970                                                QualType ConvTy) override {
8971       return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8972     }
8973     SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8974                                            QualType ConvTy) override {
8975       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8976              << ConvTy->isEnumeralType() << ConvTy;
8977     }
8978     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8979                                             QualType T) override {
8980       return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8981     }
8982     SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8983                                         QualType ConvTy) override {
8984       return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
8985              << ConvTy->isEnumeralType() << ConvTy;
8986     }
8987     SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8988                                              QualType) override {
8989       llvm_unreachable("conversion functions are permitted");
8990     }
8991   } ConvertDiagnoser;
8992   return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8993 }
8994 
8995 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
8996                                       OpenMPClauseKind CKind,
8997                                       bool StrictlyPositive) {
8998   if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8999       !ValExpr->isInstantiationDependent()) {
9000     SourceLocation Loc = ValExpr->getExprLoc();
9001     ExprResult Value =
9002         SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9003     if (Value.isInvalid())
9004       return false;
9005 
9006     ValExpr = Value.get();
9007     // The expression must evaluate to a non-negative integer value.
9008     llvm::APSInt Result;
9009     if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
9010         Result.isSigned() &&
9011         !((!StrictlyPositive && Result.isNonNegative()) ||
9012           (StrictlyPositive && Result.isStrictlyPositive()))) {
9013       SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
9014           << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9015           << ValExpr->getSourceRange();
9016       return false;
9017     }
9018   }
9019   return true;
9020 }
9021 
9022 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9023                                              SourceLocation StartLoc,
9024                                              SourceLocation LParenLoc,
9025                                              SourceLocation EndLoc) {
9026   Expr *ValExpr = NumThreads;
9027   Stmt *HelperValStmt = nullptr;
9028 
9029   // OpenMP [2.5, Restrictions]
9030   //  The num_threads expression must evaluate to a positive integer value.
9031   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
9032                                  /*StrictlyPositive=*/true))
9033     return nullptr;
9034 
9035   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9036   OpenMPDirectiveKind CaptureRegion =
9037       getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9038   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
9039     ValExpr = MakeFullExpr(ValExpr).get();
9040     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9041     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9042     HelperValStmt = buildPreInits(Context, Captures);
9043   }
9044 
9045   return new (Context) OMPNumThreadsClause(
9046       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
9047 }
9048 
9049 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
9050                                                        OpenMPClauseKind CKind,
9051                                                        bool StrictlyPositive) {
9052   if (!E)
9053     return ExprError();
9054   if (E->isValueDependent() || E->isTypeDependent() ||
9055       E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
9056     return E;
9057   llvm::APSInt Result;
9058   ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9059   if (ICE.isInvalid())
9060     return ExprError();
9061   if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9062       (!StrictlyPositive && !Result.isNonNegative())) {
9063     Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
9064         << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9065         << E->getSourceRange();
9066     return ExprError();
9067   }
9068   if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9069     Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9070         << E->getSourceRange();
9071     return ExprError();
9072   }
9073   if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9074     DSAStack->setAssociatedLoops(Result.getExtValue());
9075   else if (CKind == OMPC_ordered)
9076     DSAStack->setAssociatedLoops(Result.getExtValue());
9077   return ICE;
9078 }
9079 
9080 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9081                                           SourceLocation LParenLoc,
9082                                           SourceLocation EndLoc) {
9083   // OpenMP [2.8.1, simd construct, Description]
9084   // The parameter of the safelen clause must be a constant
9085   // positive integer expression.
9086   ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9087   if (Safelen.isInvalid())
9088     return nullptr;
9089   return new (Context)
9090       OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
9091 }
9092 
9093 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9094                                           SourceLocation LParenLoc,
9095                                           SourceLocation EndLoc) {
9096   // OpenMP [2.8.1, simd construct, Description]
9097   // The parameter of the simdlen clause must be a constant
9098   // positive integer expression.
9099   ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9100   if (Simdlen.isInvalid())
9101     return nullptr;
9102   return new (Context)
9103       OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9104 }
9105 
9106 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9107                                            SourceLocation StartLoc,
9108                                            SourceLocation LParenLoc,
9109                                            SourceLocation EndLoc) {
9110   // OpenMP [2.7.1, loop construct, Description]
9111   // OpenMP [2.8.1, simd construct, Description]
9112   // OpenMP [2.9.6, distribute construct, Description]
9113   // The parameter of the collapse clause must be a constant
9114   // positive integer expression.
9115   ExprResult NumForLoopsResult =
9116       VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9117   if (NumForLoopsResult.isInvalid())
9118     return nullptr;
9119   return new (Context)
9120       OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
9121 }
9122 
9123 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9124                                           SourceLocation EndLoc,
9125                                           SourceLocation LParenLoc,
9126                                           Expr *NumForLoops) {
9127   // OpenMP [2.7.1, loop construct, Description]
9128   // OpenMP [2.8.1, simd construct, Description]
9129   // OpenMP [2.9.6, distribute construct, Description]
9130   // The parameter of the ordered clause must be a constant
9131   // positive integer expression if any.
9132   if (NumForLoops && LParenLoc.isValid()) {
9133     ExprResult NumForLoopsResult =
9134         VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9135     if (NumForLoopsResult.isInvalid())
9136       return nullptr;
9137     NumForLoops = NumForLoopsResult.get();
9138   } else {
9139     NumForLoops = nullptr;
9140   }
9141   auto *Clause = OMPOrderedClause::Create(
9142       Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9143       StartLoc, LParenLoc, EndLoc);
9144   DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9145   return Clause;
9146 }
9147 
9148 OMPClause *Sema::ActOnOpenMPSimpleClause(
9149     OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9150     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9151   OMPClause *Res = nullptr;
9152   switch (Kind) {
9153   case OMPC_default:
9154     Res =
9155         ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9156                                  ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9157     break;
9158   case OMPC_proc_bind:
9159     Res = ActOnOpenMPProcBindClause(
9160         static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9161         LParenLoc, EndLoc);
9162     break;
9163   case OMPC_atomic_default_mem_order:
9164     Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9165         static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9166         ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9167     break;
9168   case OMPC_if:
9169   case OMPC_final:
9170   case OMPC_num_threads:
9171   case OMPC_safelen:
9172   case OMPC_simdlen:
9173   case OMPC_collapse:
9174   case OMPC_schedule:
9175   case OMPC_private:
9176   case OMPC_firstprivate:
9177   case OMPC_lastprivate:
9178   case OMPC_shared:
9179   case OMPC_reduction:
9180   case OMPC_task_reduction:
9181   case OMPC_in_reduction:
9182   case OMPC_linear:
9183   case OMPC_aligned:
9184   case OMPC_copyin:
9185   case OMPC_copyprivate:
9186   case OMPC_ordered:
9187   case OMPC_nowait:
9188   case OMPC_untied:
9189   case OMPC_mergeable:
9190   case OMPC_threadprivate:
9191   case OMPC_flush:
9192   case OMPC_read:
9193   case OMPC_write:
9194   case OMPC_update:
9195   case OMPC_capture:
9196   case OMPC_seq_cst:
9197   case OMPC_depend:
9198   case OMPC_device:
9199   case OMPC_threads:
9200   case OMPC_simd:
9201   case OMPC_map:
9202   case OMPC_num_teams:
9203   case OMPC_thread_limit:
9204   case OMPC_priority:
9205   case OMPC_grainsize:
9206   case OMPC_nogroup:
9207   case OMPC_num_tasks:
9208   case OMPC_hint:
9209   case OMPC_dist_schedule:
9210   case OMPC_defaultmap:
9211   case OMPC_unknown:
9212   case OMPC_uniform:
9213   case OMPC_to:
9214   case OMPC_from:
9215   case OMPC_use_device_ptr:
9216   case OMPC_is_device_ptr:
9217   case OMPC_unified_address:
9218   case OMPC_unified_shared_memory:
9219   case OMPC_reverse_offload:
9220   case OMPC_dynamic_allocators:
9221     llvm_unreachable("Clause is not allowed.");
9222   }
9223   return Res;
9224 }
9225 
9226 static std::string
9227 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9228                         ArrayRef<unsigned> Exclude = llvm::None) {
9229   SmallString<256> Buffer;
9230   llvm::raw_svector_ostream Out(Buffer);
9231   unsigned Bound = Last >= 2 ? Last - 2 : 0;
9232   unsigned Skipped = Exclude.size();
9233   auto S = Exclude.begin(), E = Exclude.end();
9234   for (unsigned I = First; I < Last; ++I) {
9235     if (std::find(S, E, I) != E) {
9236       --Skipped;
9237       continue;
9238     }
9239     Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9240     if (I == Bound - Skipped)
9241       Out << " or ";
9242     else if (I != Bound + 1 - Skipped)
9243       Out << ", ";
9244   }
9245   return Out.str();
9246 }
9247 
9248 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9249                                           SourceLocation KindKwLoc,
9250                                           SourceLocation StartLoc,
9251                                           SourceLocation LParenLoc,
9252                                           SourceLocation EndLoc) {
9253   if (Kind == OMPC_DEFAULT_unknown) {
9254     static_assert(OMPC_DEFAULT_unknown > 0,
9255                   "OMPC_DEFAULT_unknown not greater than 0");
9256     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9257         << getListOfPossibleValues(OMPC_default, /*First=*/0,
9258                                    /*Last=*/OMPC_DEFAULT_unknown)
9259         << getOpenMPClauseName(OMPC_default);
9260     return nullptr;
9261   }
9262   switch (Kind) {
9263   case OMPC_DEFAULT_none:
9264     DSAStack->setDefaultDSANone(KindKwLoc);
9265     break;
9266   case OMPC_DEFAULT_shared:
9267     DSAStack->setDefaultDSAShared(KindKwLoc);
9268     break;
9269   case OMPC_DEFAULT_unknown:
9270     llvm_unreachable("Clause kind is not allowed.");
9271     break;
9272   }
9273   return new (Context)
9274       OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9275 }
9276 
9277 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9278                                            SourceLocation KindKwLoc,
9279                                            SourceLocation StartLoc,
9280                                            SourceLocation LParenLoc,
9281                                            SourceLocation EndLoc) {
9282   if (Kind == OMPC_PROC_BIND_unknown) {
9283     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9284         << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9285                                    /*Last=*/OMPC_PROC_BIND_unknown)
9286         << getOpenMPClauseName(OMPC_proc_bind);
9287     return nullptr;
9288   }
9289   return new (Context)
9290       OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
9291 }
9292 
9293 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9294     OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9295     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9296   if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9297     Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9298         << getListOfPossibleValues(
9299                OMPC_atomic_default_mem_order, /*First=*/0,
9300                /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9301         << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9302     return nullptr;
9303   }
9304   return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9305                                                       LParenLoc, EndLoc);
9306 }
9307 
9308 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
9309     OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
9310     SourceLocation StartLoc, SourceLocation LParenLoc,
9311     ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
9312     SourceLocation EndLoc) {
9313   OMPClause *Res = nullptr;
9314   switch (Kind) {
9315   case OMPC_schedule:
9316     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9317     assert(Argument.size() == NumberOfElements &&
9318            ArgumentLoc.size() == NumberOfElements);
9319     Res = ActOnOpenMPScheduleClause(
9320         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9321         static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9322         static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9323         StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9324         ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
9325     break;
9326   case OMPC_if:
9327     assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9328     Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9329                               Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9330                               DelimLoc, EndLoc);
9331     break;
9332   case OMPC_dist_schedule:
9333     Res = ActOnOpenMPDistScheduleClause(
9334         static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9335         StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9336     break;
9337   case OMPC_defaultmap:
9338     enum { Modifier, DefaultmapKind };
9339     Res = ActOnOpenMPDefaultmapClause(
9340         static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9341         static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
9342         StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9343         EndLoc);
9344     break;
9345   case OMPC_final:
9346   case OMPC_num_threads:
9347   case OMPC_safelen:
9348   case OMPC_simdlen:
9349   case OMPC_collapse:
9350   case OMPC_default:
9351   case OMPC_proc_bind:
9352   case OMPC_private:
9353   case OMPC_firstprivate:
9354   case OMPC_lastprivate:
9355   case OMPC_shared:
9356   case OMPC_reduction:
9357   case OMPC_task_reduction:
9358   case OMPC_in_reduction:
9359   case OMPC_linear:
9360   case OMPC_aligned:
9361   case OMPC_copyin:
9362   case OMPC_copyprivate:
9363   case OMPC_ordered:
9364   case OMPC_nowait:
9365   case OMPC_untied:
9366   case OMPC_mergeable:
9367   case OMPC_threadprivate:
9368   case OMPC_flush:
9369   case OMPC_read:
9370   case OMPC_write:
9371   case OMPC_update:
9372   case OMPC_capture:
9373   case OMPC_seq_cst:
9374   case OMPC_depend:
9375   case OMPC_device:
9376   case OMPC_threads:
9377   case OMPC_simd:
9378   case OMPC_map:
9379   case OMPC_num_teams:
9380   case OMPC_thread_limit:
9381   case OMPC_priority:
9382   case OMPC_grainsize:
9383   case OMPC_nogroup:
9384   case OMPC_num_tasks:
9385   case OMPC_hint:
9386   case OMPC_unknown:
9387   case OMPC_uniform:
9388   case OMPC_to:
9389   case OMPC_from:
9390   case OMPC_use_device_ptr:
9391   case OMPC_is_device_ptr:
9392   case OMPC_unified_address:
9393   case OMPC_unified_shared_memory:
9394   case OMPC_reverse_offload:
9395   case OMPC_dynamic_allocators:
9396   case OMPC_atomic_default_mem_order:
9397     llvm_unreachable("Clause is not allowed.");
9398   }
9399   return Res;
9400 }
9401 
9402 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9403                                    OpenMPScheduleClauseModifier M2,
9404                                    SourceLocation M1Loc, SourceLocation M2Loc) {
9405   if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9406     SmallVector<unsigned, 2> Excluded;
9407     if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9408       Excluded.push_back(M2);
9409     if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9410       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9411     if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9412       Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9413     S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9414         << getListOfPossibleValues(OMPC_schedule,
9415                                    /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9416                                    /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9417                                    Excluded)
9418         << getOpenMPClauseName(OMPC_schedule);
9419     return true;
9420   }
9421   return false;
9422 }
9423 
9424 OMPClause *Sema::ActOnOpenMPScheduleClause(
9425     OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
9426     OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
9427     SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9428     SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9429   if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9430       checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9431     return nullptr;
9432   // OpenMP, 2.7.1, Loop Construct, Restrictions
9433   // Either the monotonic modifier or the nonmonotonic modifier can be specified
9434   // but not both.
9435   if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9436       (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9437        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9438       (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9439        M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9440     Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9441         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9442         << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9443     return nullptr;
9444   }
9445   if (Kind == OMPC_SCHEDULE_unknown) {
9446     std::string Values;
9447     if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9448       unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9449       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9450                                        /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9451                                        Exclude);
9452     } else {
9453       Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9454                                        /*Last=*/OMPC_SCHEDULE_unknown);
9455     }
9456     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9457         << Values << getOpenMPClauseName(OMPC_schedule);
9458     return nullptr;
9459   }
9460   // OpenMP, 2.7.1, Loop Construct, Restrictions
9461   // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9462   // schedule(guided).
9463   if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9464        M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9465       Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9466     Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9467          diag::err_omp_schedule_nonmonotonic_static);
9468     return nullptr;
9469   }
9470   Expr *ValExpr = ChunkSize;
9471   Stmt *HelperValStmt = nullptr;
9472   if (ChunkSize) {
9473     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9474         !ChunkSize->isInstantiationDependent() &&
9475         !ChunkSize->containsUnexpandedParameterPack()) {
9476       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
9477       ExprResult Val =
9478           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9479       if (Val.isInvalid())
9480         return nullptr;
9481 
9482       ValExpr = Val.get();
9483 
9484       // OpenMP [2.7.1, Restrictions]
9485       //  chunk_size must be a loop invariant integer expression with a positive
9486       //  value.
9487       llvm::APSInt Result;
9488       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9489         if (Result.isSigned() && !Result.isStrictlyPositive()) {
9490           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
9491               << "schedule" << 1 << ChunkSize->getSourceRange();
9492           return nullptr;
9493         }
9494       } else if (getOpenMPCaptureRegionForClause(
9495                      DSAStack->getCurrentDirective(), OMPC_schedule) !=
9496                      OMPD_unknown &&
9497                  !CurContext->isDependentContext()) {
9498         ValExpr = MakeFullExpr(ValExpr).get();
9499         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
9500         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9501         HelperValStmt = buildPreInits(Context, Captures);
9502       }
9503     }
9504   }
9505 
9506   return new (Context)
9507       OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
9508                         ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
9509 }
9510 
9511 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9512                                    SourceLocation StartLoc,
9513                                    SourceLocation EndLoc) {
9514   OMPClause *Res = nullptr;
9515   switch (Kind) {
9516   case OMPC_ordered:
9517     Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9518     break;
9519   case OMPC_nowait:
9520     Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9521     break;
9522   case OMPC_untied:
9523     Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9524     break;
9525   case OMPC_mergeable:
9526     Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9527     break;
9528   case OMPC_read:
9529     Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9530     break;
9531   case OMPC_write:
9532     Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9533     break;
9534   case OMPC_update:
9535     Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9536     break;
9537   case OMPC_capture:
9538     Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9539     break;
9540   case OMPC_seq_cst:
9541     Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9542     break;
9543   case OMPC_threads:
9544     Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9545     break;
9546   case OMPC_simd:
9547     Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9548     break;
9549   case OMPC_nogroup:
9550     Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9551     break;
9552   case OMPC_unified_address:
9553     Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9554     break;
9555   case OMPC_unified_shared_memory:
9556     Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9557     break;
9558   case OMPC_reverse_offload:
9559     Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9560     break;
9561   case OMPC_dynamic_allocators:
9562     Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9563     break;
9564   case OMPC_if:
9565   case OMPC_final:
9566   case OMPC_num_threads:
9567   case OMPC_safelen:
9568   case OMPC_simdlen:
9569   case OMPC_collapse:
9570   case OMPC_schedule:
9571   case OMPC_private:
9572   case OMPC_firstprivate:
9573   case OMPC_lastprivate:
9574   case OMPC_shared:
9575   case OMPC_reduction:
9576   case OMPC_task_reduction:
9577   case OMPC_in_reduction:
9578   case OMPC_linear:
9579   case OMPC_aligned:
9580   case OMPC_copyin:
9581   case OMPC_copyprivate:
9582   case OMPC_default:
9583   case OMPC_proc_bind:
9584   case OMPC_threadprivate:
9585   case OMPC_flush:
9586   case OMPC_depend:
9587   case OMPC_device:
9588   case OMPC_map:
9589   case OMPC_num_teams:
9590   case OMPC_thread_limit:
9591   case OMPC_priority:
9592   case OMPC_grainsize:
9593   case OMPC_num_tasks:
9594   case OMPC_hint:
9595   case OMPC_dist_schedule:
9596   case OMPC_defaultmap:
9597   case OMPC_unknown:
9598   case OMPC_uniform:
9599   case OMPC_to:
9600   case OMPC_from:
9601   case OMPC_use_device_ptr:
9602   case OMPC_is_device_ptr:
9603   case OMPC_atomic_default_mem_order:
9604     llvm_unreachable("Clause is not allowed.");
9605   }
9606   return Res;
9607 }
9608 
9609 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9610                                          SourceLocation EndLoc) {
9611   DSAStack->setNowaitRegion();
9612   return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9613 }
9614 
9615 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9616                                          SourceLocation EndLoc) {
9617   return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9618 }
9619 
9620 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9621                                             SourceLocation EndLoc) {
9622   return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9623 }
9624 
9625 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9626                                        SourceLocation EndLoc) {
9627   return new (Context) OMPReadClause(StartLoc, EndLoc);
9628 }
9629 
9630 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9631                                         SourceLocation EndLoc) {
9632   return new (Context) OMPWriteClause(StartLoc, EndLoc);
9633 }
9634 
9635 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9636                                          SourceLocation EndLoc) {
9637   return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9638 }
9639 
9640 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9641                                           SourceLocation EndLoc) {
9642   return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9643 }
9644 
9645 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9646                                          SourceLocation EndLoc) {
9647   return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9648 }
9649 
9650 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9651                                           SourceLocation EndLoc) {
9652   return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9653 }
9654 
9655 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9656                                        SourceLocation EndLoc) {
9657   return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9658 }
9659 
9660 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9661                                           SourceLocation EndLoc) {
9662   return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9663 }
9664 
9665 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9666                                                  SourceLocation EndLoc) {
9667   return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
9668 }
9669 
9670 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9671                                                       SourceLocation EndLoc) {
9672   return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9673 }
9674 
9675 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9676                                                  SourceLocation EndLoc) {
9677   return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
9678 }
9679 
9680 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9681                                                     SourceLocation EndLoc) {
9682   return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
9683 }
9684 
9685 OMPClause *Sema::ActOnOpenMPVarListClause(
9686     OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9687     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9688     SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
9689     const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
9690     OpenMPLinearClauseKind LinKind,
9691     ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
9692     ArrayRef<SourceLocation> MapTypeModifiersLoc,
9693     OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9694     SourceLocation DepLinMapLoc) {
9695   OMPClause *Res = nullptr;
9696   switch (Kind) {
9697   case OMPC_private:
9698     Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9699     break;
9700   case OMPC_firstprivate:
9701     Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9702     break;
9703   case OMPC_lastprivate:
9704     Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9705     break;
9706   case OMPC_shared:
9707     Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9708     break;
9709   case OMPC_reduction:
9710     Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9711                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9712     break;
9713   case OMPC_task_reduction:
9714     Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9715                                          EndLoc, ReductionIdScopeSpec,
9716                                          ReductionId);
9717     break;
9718   case OMPC_in_reduction:
9719     Res =
9720         ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9721                                      EndLoc, ReductionIdScopeSpec, ReductionId);
9722     break;
9723   case OMPC_linear:
9724     Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
9725                                   LinKind, DepLinMapLoc, ColonLoc, EndLoc);
9726     break;
9727   case OMPC_aligned:
9728     Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9729                                    ColonLoc, EndLoc);
9730     break;
9731   case OMPC_copyin:
9732     Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9733     break;
9734   case OMPC_copyprivate:
9735     Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9736     break;
9737   case OMPC_flush:
9738     Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9739     break;
9740   case OMPC_depend:
9741     Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
9742                                   StartLoc, LParenLoc, EndLoc);
9743     break;
9744   case OMPC_map:
9745     Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc, MapType,
9746                                IsMapTypeImplicit, DepLinMapLoc, ColonLoc,
9747                                VarList, StartLoc, LParenLoc, EndLoc);
9748     break;
9749   case OMPC_to:
9750     Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9751     break;
9752   case OMPC_from:
9753     Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9754     break;
9755   case OMPC_use_device_ptr:
9756     Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9757     break;
9758   case OMPC_is_device_ptr:
9759     Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9760     break;
9761   case OMPC_if:
9762   case OMPC_final:
9763   case OMPC_num_threads:
9764   case OMPC_safelen:
9765   case OMPC_simdlen:
9766   case OMPC_collapse:
9767   case OMPC_default:
9768   case OMPC_proc_bind:
9769   case OMPC_schedule:
9770   case OMPC_ordered:
9771   case OMPC_nowait:
9772   case OMPC_untied:
9773   case OMPC_mergeable:
9774   case OMPC_threadprivate:
9775   case OMPC_read:
9776   case OMPC_write:
9777   case OMPC_update:
9778   case OMPC_capture:
9779   case OMPC_seq_cst:
9780   case OMPC_device:
9781   case OMPC_threads:
9782   case OMPC_simd:
9783   case OMPC_num_teams:
9784   case OMPC_thread_limit:
9785   case OMPC_priority:
9786   case OMPC_grainsize:
9787   case OMPC_nogroup:
9788   case OMPC_num_tasks:
9789   case OMPC_hint:
9790   case OMPC_dist_schedule:
9791   case OMPC_defaultmap:
9792   case OMPC_unknown:
9793   case OMPC_uniform:
9794   case OMPC_unified_address:
9795   case OMPC_unified_shared_memory:
9796   case OMPC_reverse_offload:
9797   case OMPC_dynamic_allocators:
9798   case OMPC_atomic_default_mem_order:
9799     llvm_unreachable("Clause is not allowed.");
9800   }
9801   return Res;
9802 }
9803 
9804 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
9805                                        ExprObjectKind OK, SourceLocation Loc) {
9806   ExprResult Res = BuildDeclRefExpr(
9807       Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9808   if (!Res.isUsable())
9809     return ExprError();
9810   if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9811     Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9812     if (!Res.isUsable())
9813       return ExprError();
9814   }
9815   if (VK != VK_LValue && Res.get()->isGLValue()) {
9816     Res = DefaultLvalueConversion(Res.get());
9817     if (!Res.isUsable())
9818       return ExprError();
9819   }
9820   return Res;
9821 }
9822 
9823 static std::pair<ValueDecl *, bool>
9824 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9825                SourceRange &ERange, bool AllowArraySection = false) {
9826   if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9827       RefExpr->containsUnexpandedParameterPack())
9828     return std::make_pair(nullptr, true);
9829 
9830   // OpenMP [3.1, C/C++]
9831   //  A list item is a variable name.
9832   // OpenMP  [2.9.3.3, Restrictions, p.1]
9833   //  A variable that is part of another variable (as an array or
9834   //  structure element) cannot appear in a private clause.
9835   RefExpr = RefExpr->IgnoreParens();
9836   enum {
9837     NoArrayExpr = -1,
9838     ArraySubscript = 0,
9839     OMPArraySection = 1
9840   } IsArrayExpr = NoArrayExpr;
9841   if (AllowArraySection) {
9842     if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9843       Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
9844       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9845         Base = TempASE->getBase()->IgnoreParenImpCasts();
9846       RefExpr = Base;
9847       IsArrayExpr = ArraySubscript;
9848     } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9849       Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
9850       while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9851         Base = TempOASE->getBase()->IgnoreParenImpCasts();
9852       while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9853         Base = TempASE->getBase()->IgnoreParenImpCasts();
9854       RefExpr = Base;
9855       IsArrayExpr = OMPArraySection;
9856     }
9857   }
9858   ELoc = RefExpr->getExprLoc();
9859   ERange = RefExpr->getSourceRange();
9860   RefExpr = RefExpr->IgnoreParenImpCasts();
9861   auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9862   auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9863   if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9864       (S.getCurrentThisType().isNull() || !ME ||
9865        !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9866        !isa<FieldDecl>(ME->getMemberDecl()))) {
9867     if (IsArrayExpr != NoArrayExpr) {
9868       S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9869                                                          << ERange;
9870     } else {
9871       S.Diag(ELoc,
9872              AllowArraySection
9873                  ? diag::err_omp_expected_var_name_member_expr_or_array_item
9874                  : diag::err_omp_expected_var_name_member_expr)
9875           << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9876     }
9877     return std::make_pair(nullptr, false);
9878   }
9879   return std::make_pair(
9880       getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
9881 }
9882 
9883 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9884                                           SourceLocation StartLoc,
9885                                           SourceLocation LParenLoc,
9886                                           SourceLocation EndLoc) {
9887   SmallVector<Expr *, 8> Vars;
9888   SmallVector<Expr *, 8> PrivateCopies;
9889   for (Expr *RefExpr : VarList) {
9890     assert(RefExpr && "NULL expr in OpenMP private clause.");
9891     SourceLocation ELoc;
9892     SourceRange ERange;
9893     Expr *SimpleRefExpr = RefExpr;
9894     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
9895     if (Res.second) {
9896       // It will be analyzed later.
9897       Vars.push_back(RefExpr);
9898       PrivateCopies.push_back(nullptr);
9899     }
9900     ValueDecl *D = Res.first;
9901     if (!D)
9902       continue;
9903 
9904     QualType Type = D->getType();
9905     auto *VD = dyn_cast<VarDecl>(D);
9906 
9907     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9908     //  A variable that appears in a private clause must not have an incomplete
9909     //  type or a reference type.
9910     if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
9911       continue;
9912     Type = Type.getNonReferenceType();
9913 
9914     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
9915     // A variable that is privatized must not have a const-qualified type
9916     // unless it is of class type with a mutable member. This restriction does
9917     // not apply to the firstprivate clause.
9918     //
9919     // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
9920     // A variable that appears in a private clause must not have a
9921     // const-qualified type unless it is of class type with a mutable member.
9922     if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
9923       continue;
9924 
9925     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9926     // in a Construct]
9927     //  Variables with the predetermined data-sharing attributes may not be
9928     //  listed in data-sharing attributes clauses, except for the cases
9929     //  listed below. For these exceptions only, listing a predetermined
9930     //  variable in a data-sharing attribute clause is allowed and overrides
9931     //  the variable's predetermined data-sharing attributes.
9932     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
9933     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
9934       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9935                                           << getOpenMPClauseName(OMPC_private);
9936       reportOriginalDsa(*this, DSAStack, D, DVar);
9937       continue;
9938     }
9939 
9940     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
9941     // Variably modified types are not supported for tasks.
9942     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
9943         isOpenMPTaskingDirective(CurrDir)) {
9944       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9945           << getOpenMPClauseName(OMPC_private) << Type
9946           << getOpenMPDirectiveName(CurrDir);
9947       bool IsDecl =
9948           !VD ||
9949           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
9950       Diag(D->getLocation(),
9951            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
9952           << D;
9953       continue;
9954     }
9955 
9956     // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9957     // A list item cannot appear in both a map clause and a data-sharing
9958     // attribute clause on the same construct
9959     if (isOpenMPTargetExecutionDirective(CurrDir)) {
9960       OpenMPClauseKind ConflictKind;
9961       if (DSAStack->checkMappableExprComponentListsForDecl(
9962               VD, /*CurrentRegionOnly=*/true,
9963               [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9964                   OpenMPClauseKind WhereFoundClauseKind) -> bool {
9965                 ConflictKind = WhereFoundClauseKind;
9966                 return true;
9967               })) {
9968         Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
9969             << getOpenMPClauseName(OMPC_private)
9970             << getOpenMPClauseName(ConflictKind)
9971             << getOpenMPDirectiveName(CurrDir);
9972         reportOriginalDsa(*this, DSAStack, D, DVar);
9973         continue;
9974       }
9975     }
9976 
9977     // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9978     //  A variable of class type (or array thereof) that appears in a private
9979     //  clause requires an accessible, unambiguous default constructor for the
9980     //  class type.
9981     // Generate helper private variable and initialize it with the default
9982     // value. The address of the original variable is replaced by the address of
9983     // the new private variable in CodeGen. This new variable is not added to
9984     // IdResolver, so the code in the OpenMP region uses original variable for
9985     // proper diagnostics.
9986     Type = Type.getUnqualifiedType();
9987     VarDecl *VDPrivate =
9988         buildVarDecl(*this, ELoc, Type, D->getName(),
9989                      D->hasAttrs() ? &D->getAttrs() : nullptr,
9990                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
9991     ActOnUninitializedDecl(VDPrivate);
9992     if (VDPrivate->isInvalidDecl())
9993       continue;
9994     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
9995         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
9996 
9997     DeclRefExpr *Ref = nullptr;
9998     if (!VD && !CurContext->isDependentContext())
9999       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10000     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
10001     Vars.push_back((VD || CurContext->isDependentContext())
10002                        ? RefExpr->IgnoreParens()
10003                        : Ref);
10004     PrivateCopies.push_back(VDPrivateRefExpr);
10005   }
10006 
10007   if (Vars.empty())
10008     return nullptr;
10009 
10010   return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10011                                   PrivateCopies);
10012 }
10013 
10014 namespace {
10015 class DiagsUninitializedSeveretyRAII {
10016 private:
10017   DiagnosticsEngine &Diags;
10018   SourceLocation SavedLoc;
10019   bool IsIgnored = false;
10020 
10021 public:
10022   DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10023                                  bool IsIgnored)
10024       : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10025     if (!IsIgnored) {
10026       Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10027                         /*Map*/ diag::Severity::Ignored, Loc);
10028     }
10029   }
10030   ~DiagsUninitializedSeveretyRAII() {
10031     if (!IsIgnored)
10032       Diags.popMappings(SavedLoc);
10033   }
10034 };
10035 }
10036 
10037 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10038                                                SourceLocation StartLoc,
10039                                                SourceLocation LParenLoc,
10040                                                SourceLocation EndLoc) {
10041   SmallVector<Expr *, 8> Vars;
10042   SmallVector<Expr *, 8> PrivateCopies;
10043   SmallVector<Expr *, 8> Inits;
10044   SmallVector<Decl *, 4> ExprCaptures;
10045   bool IsImplicitClause =
10046       StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
10047   SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
10048 
10049   for (Expr *RefExpr : VarList) {
10050     assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
10051     SourceLocation ELoc;
10052     SourceRange ERange;
10053     Expr *SimpleRefExpr = RefExpr;
10054     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10055     if (Res.second) {
10056       // It will be analyzed later.
10057       Vars.push_back(RefExpr);
10058       PrivateCopies.push_back(nullptr);
10059       Inits.push_back(nullptr);
10060     }
10061     ValueDecl *D = Res.first;
10062     if (!D)
10063       continue;
10064 
10065     ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
10066     QualType Type = D->getType();
10067     auto *VD = dyn_cast<VarDecl>(D);
10068 
10069     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10070     //  A variable that appears in a private clause must not have an incomplete
10071     //  type or a reference type.
10072     if (RequireCompleteType(ELoc, Type,
10073                             diag::err_omp_firstprivate_incomplete_type))
10074       continue;
10075     Type = Type.getNonReferenceType();
10076 
10077     // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10078     //  A variable of class type (or array thereof) that appears in a private
10079     //  clause requires an accessible, unambiguous copy constructor for the
10080     //  class type.
10081     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
10082 
10083     // If an implicit firstprivate variable found it was checked already.
10084     DSAStackTy::DSAVarData TopDVar;
10085     if (!IsImplicitClause) {
10086       DSAStackTy::DSAVarData DVar =
10087           DSAStack->getTopDSA(D, /*FromParent=*/false);
10088       TopDVar = DVar;
10089       OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10090       bool IsConstant = ElemType.isConstant(Context);
10091       // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10092       //  A list item that specifies a given variable may not appear in more
10093       // than one clause on the same directive, except that a variable may be
10094       //  specified in both firstprivate and lastprivate clauses.
10095       // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10096       // A list item may appear in a firstprivate or lastprivate clause but not
10097       // both.
10098       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
10099           (isOpenMPDistributeDirective(CurrDir) ||
10100            DVar.CKind != OMPC_lastprivate) &&
10101           DVar.RefExpr) {
10102         Diag(ELoc, diag::err_omp_wrong_dsa)
10103             << getOpenMPClauseName(DVar.CKind)
10104             << getOpenMPClauseName(OMPC_firstprivate);
10105         reportOriginalDsa(*this, DSAStack, D, DVar);
10106         continue;
10107       }
10108 
10109       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10110       // in a Construct]
10111       //  Variables with the predetermined data-sharing attributes may not be
10112       //  listed in data-sharing attributes clauses, except for the cases
10113       //  listed below. For these exceptions only, listing a predetermined
10114       //  variable in a data-sharing attribute clause is allowed and overrides
10115       //  the variable's predetermined data-sharing attributes.
10116       // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10117       // in a Construct, C/C++, p.2]
10118       //  Variables with const-qualified type having no mutable member may be
10119       //  listed in a firstprivate clause, even if they are static data members.
10120       if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
10121           DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10122         Diag(ELoc, diag::err_omp_wrong_dsa)
10123             << getOpenMPClauseName(DVar.CKind)
10124             << getOpenMPClauseName(OMPC_firstprivate);
10125         reportOriginalDsa(*this, DSAStack, D, DVar);
10126         continue;
10127       }
10128 
10129       // OpenMP [2.9.3.4, Restrictions, p.2]
10130       //  A list item that is private within a parallel region must not appear
10131       //  in a firstprivate clause on a worksharing construct if any of the
10132       //  worksharing regions arising from the worksharing construct ever bind
10133       //  to any of the parallel regions arising from the parallel construct.
10134       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10135       // A list item that is private within a teams region must not appear in a
10136       // firstprivate clause on a distribute construct if any of the distribute
10137       // regions arising from the distribute construct ever bind to any of the
10138       // teams regions arising from the teams construct.
10139       // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10140       // A list item that appears in a reduction clause of a teams construct
10141       // must not appear in a firstprivate clause on a distribute construct if
10142       // any of the distribute regions arising from the distribute construct
10143       // ever bind to any of the teams regions arising from the teams construct.
10144       if ((isOpenMPWorksharingDirective(CurrDir) ||
10145            isOpenMPDistributeDirective(CurrDir)) &&
10146           !isOpenMPParallelDirective(CurrDir) &&
10147           !isOpenMPTeamsDirective(CurrDir)) {
10148         DVar = DSAStack->getImplicitDSA(D, true);
10149         if (DVar.CKind != OMPC_shared &&
10150             (isOpenMPParallelDirective(DVar.DKind) ||
10151              isOpenMPTeamsDirective(DVar.DKind) ||
10152              DVar.DKind == OMPD_unknown)) {
10153           Diag(ELoc, diag::err_omp_required_access)
10154               << getOpenMPClauseName(OMPC_firstprivate)
10155               << getOpenMPClauseName(OMPC_shared);
10156           reportOriginalDsa(*this, DSAStack, D, DVar);
10157           continue;
10158         }
10159       }
10160       // OpenMP [2.9.3.4, Restrictions, p.3]
10161       //  A list item that appears in a reduction clause of a parallel construct
10162       //  must not appear in a firstprivate clause on a worksharing or task
10163       //  construct if any of the worksharing or task regions arising from the
10164       //  worksharing or task construct ever bind to any of the parallel regions
10165       //  arising from the parallel construct.
10166       // OpenMP [2.9.3.4, Restrictions, p.4]
10167       //  A list item that appears in a reduction clause in worksharing
10168       //  construct must not appear in a firstprivate clause in a task construct
10169       //  encountered during execution of any of the worksharing regions arising
10170       //  from the worksharing construct.
10171       if (isOpenMPTaskingDirective(CurrDir)) {
10172         DVar = DSAStack->hasInnermostDSA(
10173             D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10174             [](OpenMPDirectiveKind K) {
10175               return isOpenMPParallelDirective(K) ||
10176                      isOpenMPWorksharingDirective(K) ||
10177                      isOpenMPTeamsDirective(K);
10178             },
10179             /*FromParent=*/true);
10180         if (DVar.CKind == OMPC_reduction &&
10181             (isOpenMPParallelDirective(DVar.DKind) ||
10182              isOpenMPWorksharingDirective(DVar.DKind) ||
10183              isOpenMPTeamsDirective(DVar.DKind))) {
10184           Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10185               << getOpenMPDirectiveName(DVar.DKind);
10186           reportOriginalDsa(*this, DSAStack, D, DVar);
10187           continue;
10188         }
10189       }
10190 
10191       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10192       // A list item cannot appear in both a map clause and a data-sharing
10193       // attribute clause on the same construct
10194       if (isOpenMPTargetExecutionDirective(CurrDir)) {
10195         OpenMPClauseKind ConflictKind;
10196         if (DSAStack->checkMappableExprComponentListsForDecl(
10197                 VD, /*CurrentRegionOnly=*/true,
10198                 [&ConflictKind](
10199                     OMPClauseMappableExprCommon::MappableExprComponentListRef,
10200                     OpenMPClauseKind WhereFoundClauseKind) {
10201                   ConflictKind = WhereFoundClauseKind;
10202                   return true;
10203                 })) {
10204           Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
10205               << getOpenMPClauseName(OMPC_firstprivate)
10206               << getOpenMPClauseName(ConflictKind)
10207               << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10208           reportOriginalDsa(*this, DSAStack, D, DVar);
10209           continue;
10210         }
10211       }
10212     }
10213 
10214     // Variably modified types are not supported for tasks.
10215     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
10216         isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
10217       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10218           << getOpenMPClauseName(OMPC_firstprivate) << Type
10219           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10220       bool IsDecl =
10221           !VD ||
10222           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10223       Diag(D->getLocation(),
10224            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10225           << D;
10226       continue;
10227     }
10228 
10229     Type = Type.getUnqualifiedType();
10230     VarDecl *VDPrivate =
10231         buildVarDecl(*this, ELoc, Type, D->getName(),
10232                      D->hasAttrs() ? &D->getAttrs() : nullptr,
10233                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
10234     // Generate helper private variable and initialize it with the value of the
10235     // original variable. The address of the original variable is replaced by
10236     // the address of the new private variable in the CodeGen. This new variable
10237     // is not added to IdResolver, so the code in the OpenMP region uses
10238     // original variable for proper diagnostics and variable capturing.
10239     Expr *VDInitRefExpr = nullptr;
10240     // For arrays generate initializer for single element and replace it by the
10241     // original array element in CodeGen.
10242     if (Type->isArrayType()) {
10243       VarDecl *VDInit =
10244           buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
10245       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
10246       Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
10247       ElemType = ElemType.getUnqualifiedType();
10248       VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10249                                          ".firstprivate.temp");
10250       InitializedEntity Entity =
10251           InitializedEntity::InitializeVariable(VDInitTemp);
10252       InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10253 
10254       InitializationSequence InitSeq(*this, Entity, Kind, Init);
10255       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10256       if (Result.isInvalid())
10257         VDPrivate->setInvalidDecl();
10258       else
10259         VDPrivate->setInit(Result.getAs<Expr>());
10260       // Remove temp variable declaration.
10261       Context.Deallocate(VDInitTemp);
10262     } else {
10263       VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10264                                      ".firstprivate.temp");
10265       VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10266                                        RefExpr->getExprLoc());
10267       AddInitializerToDecl(VDPrivate,
10268                            DefaultLvalueConversion(VDInitRefExpr).get(),
10269                            /*DirectInit=*/false);
10270     }
10271     if (VDPrivate->isInvalidDecl()) {
10272       if (IsImplicitClause) {
10273         Diag(RefExpr->getExprLoc(),
10274              diag::note_omp_task_predetermined_firstprivate_here);
10275       }
10276       continue;
10277     }
10278     CurContext->addDecl(VDPrivate);
10279     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
10280         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10281         RefExpr->getExprLoc());
10282     DeclRefExpr *Ref = nullptr;
10283     if (!VD && !CurContext->isDependentContext()) {
10284       if (TopDVar.CKind == OMPC_lastprivate) {
10285         Ref = TopDVar.PrivateCopy;
10286       } else {
10287         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10288         if (!isOpenMPCapturedDecl(D))
10289           ExprCaptures.push_back(Ref->getDecl());
10290       }
10291     }
10292     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
10293     Vars.push_back((VD || CurContext->isDependentContext())
10294                        ? RefExpr->IgnoreParens()
10295                        : Ref);
10296     PrivateCopies.push_back(VDPrivateRefExpr);
10297     Inits.push_back(VDInitRefExpr);
10298   }
10299 
10300   if (Vars.empty())
10301     return nullptr;
10302 
10303   return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10304                                        Vars, PrivateCopies, Inits,
10305                                        buildPreInits(Context, ExprCaptures));
10306 }
10307 
10308 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10309                                               SourceLocation StartLoc,
10310                                               SourceLocation LParenLoc,
10311                                               SourceLocation EndLoc) {
10312   SmallVector<Expr *, 8> Vars;
10313   SmallVector<Expr *, 8> SrcExprs;
10314   SmallVector<Expr *, 8> DstExprs;
10315   SmallVector<Expr *, 8> AssignmentOps;
10316   SmallVector<Decl *, 4> ExprCaptures;
10317   SmallVector<Expr *, 4> ExprPostUpdates;
10318   for (Expr *RefExpr : VarList) {
10319     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10320     SourceLocation ELoc;
10321     SourceRange ERange;
10322     Expr *SimpleRefExpr = RefExpr;
10323     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10324     if (Res.second) {
10325       // It will be analyzed later.
10326       Vars.push_back(RefExpr);
10327       SrcExprs.push_back(nullptr);
10328       DstExprs.push_back(nullptr);
10329       AssignmentOps.push_back(nullptr);
10330     }
10331     ValueDecl *D = Res.first;
10332     if (!D)
10333       continue;
10334 
10335     QualType Type = D->getType();
10336     auto *VD = dyn_cast<VarDecl>(D);
10337 
10338     // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10339     //  A variable that appears in a lastprivate clause must not have an
10340     //  incomplete type or a reference type.
10341     if (RequireCompleteType(ELoc, Type,
10342                             diag::err_omp_lastprivate_incomplete_type))
10343       continue;
10344     Type = Type.getNonReferenceType();
10345 
10346     // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10347     // A variable that is privatized must not have a const-qualified type
10348     // unless it is of class type with a mutable member. This restriction does
10349     // not apply to the firstprivate clause.
10350     //
10351     // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10352     // A variable that appears in a lastprivate clause must not have a
10353     // const-qualified type unless it is of class type with a mutable member.
10354     if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
10355       continue;
10356 
10357     OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
10358     // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10359     // in a Construct]
10360     //  Variables with the predetermined data-sharing attributes may not be
10361     //  listed in data-sharing attributes clauses, except for the cases
10362     //  listed below.
10363     // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10364     // A list item may appear in a firstprivate or lastprivate clause but not
10365     // both.
10366     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10367     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
10368         (isOpenMPDistributeDirective(CurrDir) ||
10369          DVar.CKind != OMPC_firstprivate) &&
10370         (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10371       Diag(ELoc, diag::err_omp_wrong_dsa)
10372           << getOpenMPClauseName(DVar.CKind)
10373           << getOpenMPClauseName(OMPC_lastprivate);
10374       reportOriginalDsa(*this, DSAStack, D, DVar);
10375       continue;
10376     }
10377 
10378     // OpenMP [2.14.3.5, Restrictions, p.2]
10379     // A list item that is private within a parallel region, or that appears in
10380     // the reduction clause of a parallel construct, must not appear in a
10381     // lastprivate clause on a worksharing construct if any of the corresponding
10382     // worksharing regions ever binds to any of the corresponding parallel
10383     // regions.
10384     DSAStackTy::DSAVarData TopDVar = DVar;
10385     if (isOpenMPWorksharingDirective(CurrDir) &&
10386         !isOpenMPParallelDirective(CurrDir) &&
10387         !isOpenMPTeamsDirective(CurrDir)) {
10388       DVar = DSAStack->getImplicitDSA(D, true);
10389       if (DVar.CKind != OMPC_shared) {
10390         Diag(ELoc, diag::err_omp_required_access)
10391             << getOpenMPClauseName(OMPC_lastprivate)
10392             << getOpenMPClauseName(OMPC_shared);
10393         reportOriginalDsa(*this, DSAStack, D, DVar);
10394         continue;
10395       }
10396     }
10397 
10398     // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
10399     //  A variable of class type (or array thereof) that appears in a
10400     //  lastprivate clause requires an accessible, unambiguous default
10401     //  constructor for the class type, unless the list item is also specified
10402     //  in a firstprivate clause.
10403     //  A variable of class type (or array thereof) that appears in a
10404     //  lastprivate clause requires an accessible, unambiguous copy assignment
10405     //  operator for the class type.
10406     Type = Context.getBaseElementType(Type).getNonReferenceType();
10407     VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10408                                   Type.getUnqualifiedType(), ".lastprivate.src",
10409                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
10410     DeclRefExpr *PseudoSrcExpr =
10411         buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
10412     VarDecl *DstVD =
10413         buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
10414                      D->hasAttrs() ? &D->getAttrs() : nullptr);
10415     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
10416     // For arrays generate assignment operation for single element and replace
10417     // it by the original array element in CodeGen.
10418     ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10419                                          PseudoDstExpr, PseudoSrcExpr);
10420     if (AssignmentOp.isInvalid())
10421       continue;
10422     AssignmentOp =
10423         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
10424     if (AssignmentOp.isInvalid())
10425       continue;
10426 
10427     DeclRefExpr *Ref = nullptr;
10428     if (!VD && !CurContext->isDependentContext()) {
10429       if (TopDVar.CKind == OMPC_firstprivate) {
10430         Ref = TopDVar.PrivateCopy;
10431       } else {
10432         Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10433         if (!isOpenMPCapturedDecl(D))
10434           ExprCaptures.push_back(Ref->getDecl());
10435       }
10436       if (TopDVar.CKind == OMPC_firstprivate ||
10437           (!isOpenMPCapturedDecl(D) &&
10438            Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
10439         ExprResult RefRes = DefaultLvalueConversion(Ref);
10440         if (!RefRes.isUsable())
10441           continue;
10442         ExprResult PostUpdateRes =
10443             BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10444                        RefRes.get());
10445         if (!PostUpdateRes.isUsable())
10446           continue;
10447         ExprPostUpdates.push_back(
10448             IgnoredValueConversions(PostUpdateRes.get()).get());
10449       }
10450     }
10451     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
10452     Vars.push_back((VD || CurContext->isDependentContext())
10453                        ? RefExpr->IgnoreParens()
10454                        : Ref);
10455     SrcExprs.push_back(PseudoSrcExpr);
10456     DstExprs.push_back(PseudoDstExpr);
10457     AssignmentOps.push_back(AssignmentOp.get());
10458   }
10459 
10460   if (Vars.empty())
10461     return nullptr;
10462 
10463   return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
10464                                       Vars, SrcExprs, DstExprs, AssignmentOps,
10465                                       buildPreInits(Context, ExprCaptures),
10466                                       buildPostUpdate(*this, ExprPostUpdates));
10467 }
10468 
10469 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10470                                          SourceLocation StartLoc,
10471                                          SourceLocation LParenLoc,
10472                                          SourceLocation EndLoc) {
10473   SmallVector<Expr *, 8> Vars;
10474   for (Expr *RefExpr : VarList) {
10475     assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
10476     SourceLocation ELoc;
10477     SourceRange ERange;
10478     Expr *SimpleRefExpr = RefExpr;
10479     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
10480     if (Res.second) {
10481       // It will be analyzed later.
10482       Vars.push_back(RefExpr);
10483     }
10484     ValueDecl *D = Res.first;
10485     if (!D)
10486       continue;
10487 
10488     auto *VD = dyn_cast<VarDecl>(D);
10489     // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10490     // in a Construct]
10491     //  Variables with the predetermined data-sharing attributes may not be
10492     //  listed in data-sharing attributes clauses, except for the cases
10493     //  listed below. For these exceptions only, listing a predetermined
10494     //  variable in a data-sharing attribute clause is allowed and overrides
10495     //  the variable's predetermined data-sharing attributes.
10496     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
10497     if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10498         DVar.RefExpr) {
10499       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10500                                           << getOpenMPClauseName(OMPC_shared);
10501       reportOriginalDsa(*this, DSAStack, D, DVar);
10502       continue;
10503     }
10504 
10505     DeclRefExpr *Ref = nullptr;
10506     if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
10507       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
10508     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
10509     Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10510                        ? RefExpr->IgnoreParens()
10511                        : Ref);
10512   }
10513 
10514   if (Vars.empty())
10515     return nullptr;
10516 
10517   return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10518 }
10519 
10520 namespace {
10521 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10522   DSAStackTy *Stack;
10523 
10524 public:
10525   bool VisitDeclRefExpr(DeclRefExpr *E) {
10526     if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10527       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
10528       if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10529         return false;
10530       if (DVar.CKind != OMPC_unknown)
10531         return true;
10532       DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
10533           VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
10534           /*FromParent=*/true);
10535       return DVarPrivate.CKind != OMPC_unknown;
10536     }
10537     return false;
10538   }
10539   bool VisitStmt(Stmt *S) {
10540     for (Stmt *Child : S->children()) {
10541       if (Child && Visit(Child))
10542         return true;
10543     }
10544     return false;
10545   }
10546   explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
10547 };
10548 } // namespace
10549 
10550 namespace {
10551 // Transform MemberExpression for specified FieldDecl of current class to
10552 // DeclRefExpr to specified OMPCapturedExprDecl.
10553 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10554   typedef TreeTransform<TransformExprToCaptures> BaseTransform;
10555   ValueDecl *Field = nullptr;
10556   DeclRefExpr *CapturedExpr = nullptr;
10557 
10558 public:
10559   TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10560       : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10561 
10562   ExprResult TransformMemberExpr(MemberExpr *E) {
10563     if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10564         E->getMemberDecl() == Field) {
10565       CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
10566       return CapturedExpr;
10567     }
10568     return BaseTransform::TransformMemberExpr(E);
10569   }
10570   DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10571 };
10572 } // namespace
10573 
10574 template <typename T, typename U>
10575 static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
10576                             const llvm::function_ref<T(ValueDecl *)> Gen) {
10577   for (U &Set : Lookups) {
10578     for (auto *D : Set) {
10579       if (T Res = Gen(cast<ValueDecl>(D)))
10580         return Res;
10581     }
10582   }
10583   return T();
10584 }
10585 
10586 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10587   assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10588 
10589   for (auto RD : D->redecls()) {
10590     // Don't bother with extra checks if we already know this one isn't visible.
10591     if (RD == D)
10592       continue;
10593 
10594     auto ND = cast<NamedDecl>(RD);
10595     if (LookupResult::isVisible(SemaRef, ND))
10596       return ND;
10597   }
10598 
10599   return nullptr;
10600 }
10601 
10602 static void
10603 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &ReductionId,
10604                         SourceLocation Loc, QualType Ty,
10605                         SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10606   // Find all of the associated namespaces and classes based on the
10607   // arguments we have.
10608   Sema::AssociatedNamespaceSet AssociatedNamespaces;
10609   Sema::AssociatedClassSet AssociatedClasses;
10610   OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10611   SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10612                                              AssociatedClasses);
10613 
10614   // C++ [basic.lookup.argdep]p3:
10615   //   Let X be the lookup set produced by unqualified lookup (3.4.1)
10616   //   and let Y be the lookup set produced by argument dependent
10617   //   lookup (defined as follows). If X contains [...] then Y is
10618   //   empty. Otherwise Y is the set of declarations found in the
10619   //   namespaces associated with the argument types as described
10620   //   below. The set of declarations found by the lookup of the name
10621   //   is the union of X and Y.
10622   //
10623   // Here, we compute Y and add its members to the overloaded
10624   // candidate set.
10625   for (auto *NS : AssociatedNamespaces) {
10626     //   When considering an associated namespace, the lookup is the
10627     //   same as the lookup performed when the associated namespace is
10628     //   used as a qualifier (3.4.3.2) except that:
10629     //
10630     //     -- Any using-directives in the associated namespace are
10631     //        ignored.
10632     //
10633     //     -- Any namespace-scope friend functions declared in
10634     //        associated classes are visible within their respective
10635     //        namespaces even if they are not visible during an ordinary
10636     //        lookup (11.4).
10637     DeclContext::lookup_result R = NS->lookup(ReductionId.getName());
10638     for (auto *D : R) {
10639       auto *Underlying = D;
10640       if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10641         Underlying = USD->getTargetDecl();
10642 
10643       if (!isa<OMPDeclareReductionDecl>(Underlying))
10644         continue;
10645 
10646       if (!SemaRef.isVisible(D)) {
10647         D = findAcceptableDecl(SemaRef, D);
10648         if (!D)
10649           continue;
10650         if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10651           Underlying = USD->getTargetDecl();
10652       }
10653       Lookups.emplace_back();
10654       Lookups.back().addDecl(Underlying);
10655     }
10656   }
10657 }
10658 
10659 static ExprResult
10660 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
10661                          Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
10662                          const DeclarationNameInfo &ReductionId, QualType Ty,
10663                          CXXCastPath &BasePath, Expr *UnresolvedReduction) {
10664   if (ReductionIdScopeSpec.isInvalid())
10665     return ExprError();
10666   SmallVector<UnresolvedSet<8>, 4> Lookups;
10667   if (S) {
10668     LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10669     Lookup.suppressDiagnostics();
10670     while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
10671       NamedDecl *D = Lookup.getRepresentativeDecl();
10672       do {
10673         S = S->getParent();
10674       } while (S && !S->isDeclScope(D));
10675       if (S)
10676         S = S->getParent();
10677       Lookups.emplace_back();
10678       Lookups.back().append(Lookup.begin(), Lookup.end());
10679       Lookup.clear();
10680     }
10681   } else if (auto *ULE =
10682                  cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
10683     Lookups.push_back(UnresolvedSet<8>());
10684     Decl *PrevD = nullptr;
10685     for (NamedDecl *D : ULE->decls()) {
10686       if (D == PrevD)
10687         Lookups.push_back(UnresolvedSet<8>());
10688       else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10689         Lookups.back().addDecl(DRD);
10690       PrevD = D;
10691     }
10692   }
10693   if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10694       Ty->isInstantiationDependentType() ||
10695       Ty->containsUnexpandedParameterPack() ||
10696       filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
10697         return !D->isInvalidDecl() &&
10698                (D->getType()->isDependentType() ||
10699                 D->getType()->isInstantiationDependentType() ||
10700                 D->getType()->containsUnexpandedParameterPack());
10701       })) {
10702     UnresolvedSet<8> ResSet;
10703     for (const UnresolvedSet<8> &Set : Lookups) {
10704       if (Set.empty())
10705         continue;
10706       ResSet.append(Set.begin(), Set.end());
10707       // The last item marks the end of all declarations at the specified scope.
10708       ResSet.addDecl(Set[Set.size() - 1]);
10709     }
10710     return UnresolvedLookupExpr::Create(
10711         SemaRef.Context, /*NamingClass=*/nullptr,
10712         ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10713         /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10714   }
10715   // Lookup inside the classes.
10716   // C++ [over.match.oper]p3:
10717   //   For a unary operator @ with an operand of a type whose
10718   //   cv-unqualified version is T1, and for a binary operator @ with
10719   //   a left operand of a type whose cv-unqualified version is T1 and
10720   //   a right operand of a type whose cv-unqualified version is T2,
10721   //   three sets of candidate functions, designated member
10722   //   candidates, non-member candidates and built-in candidates, are
10723   //   constructed as follows:
10724   //     -- If T1 is a complete class type or a class currently being
10725   //        defined, the set of member candidates is the result of the
10726   //        qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
10727   //        the set of member candidates is empty.
10728   LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10729   Lookup.suppressDiagnostics();
10730   if (const auto *TyRec = Ty->getAs<RecordType>()) {
10731     // Complete the type if it can be completed.
10732     // If the type is neither complete nor being defined, bail out now.
10733     if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
10734         TyRec->getDecl()->getDefinition()) {
10735       Lookup.clear();
10736       SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
10737       if (Lookup.empty()) {
10738         Lookups.emplace_back();
10739         Lookups.back().append(Lookup.begin(), Lookup.end());
10740       }
10741     }
10742   }
10743   // Perform ADL.
10744   argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
10745   if (auto *VD = filterLookupForUDR<ValueDecl *>(
10746           Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10747             if (!D->isInvalidDecl() &&
10748                 SemaRef.Context.hasSameType(D->getType(), Ty))
10749               return D;
10750             return nullptr;
10751           }))
10752     return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
10753                                     VK_LValue, Loc);
10754   if (auto *VD = filterLookupForUDR<ValueDecl *>(
10755           Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10756             if (!D->isInvalidDecl() &&
10757                 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10758                 !Ty.isMoreQualifiedThan(D->getType()))
10759               return D;
10760             return nullptr;
10761           })) {
10762     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10763                        /*DetectVirtual=*/false);
10764     if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10765       if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10766               VD->getType().getUnqualifiedType()))) {
10767         if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10768                                          /*DiagID=*/0) !=
10769             Sema::AR_inaccessible) {
10770           SemaRef.BuildBasePathArray(Paths, BasePath);
10771           return SemaRef.BuildDeclRefExpr(
10772               VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
10773         }
10774       }
10775     }
10776   }
10777   if (ReductionIdScopeSpec.isSet()) {
10778     SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10779     return ExprError();
10780   }
10781   return ExprEmpty();
10782 }
10783 
10784 namespace {
10785 /// Data for the reduction-based clauses.
10786 struct ReductionData {
10787   /// List of original reduction items.
10788   SmallVector<Expr *, 8> Vars;
10789   /// List of private copies of the reduction items.
10790   SmallVector<Expr *, 8> Privates;
10791   /// LHS expressions for the reduction_op expressions.
10792   SmallVector<Expr *, 8> LHSs;
10793   /// RHS expressions for the reduction_op expressions.
10794   SmallVector<Expr *, 8> RHSs;
10795   /// Reduction operation expression.
10796   SmallVector<Expr *, 8> ReductionOps;
10797   /// Taskgroup descriptors for the corresponding reduction items in
10798   /// in_reduction clauses.
10799   SmallVector<Expr *, 8> TaskgroupDescriptors;
10800   /// List of captures for clause.
10801   SmallVector<Decl *, 4> ExprCaptures;
10802   /// List of postupdate expressions.
10803   SmallVector<Expr *, 4> ExprPostUpdates;
10804   ReductionData() = delete;
10805   /// Reserves required memory for the reduction data.
10806   ReductionData(unsigned Size) {
10807     Vars.reserve(Size);
10808     Privates.reserve(Size);
10809     LHSs.reserve(Size);
10810     RHSs.reserve(Size);
10811     ReductionOps.reserve(Size);
10812     TaskgroupDescriptors.reserve(Size);
10813     ExprCaptures.reserve(Size);
10814     ExprPostUpdates.reserve(Size);
10815   }
10816   /// Stores reduction item and reduction operation only (required for dependent
10817   /// reduction item).
10818   void push(Expr *Item, Expr *ReductionOp) {
10819     Vars.emplace_back(Item);
10820     Privates.emplace_back(nullptr);
10821     LHSs.emplace_back(nullptr);
10822     RHSs.emplace_back(nullptr);
10823     ReductionOps.emplace_back(ReductionOp);
10824     TaskgroupDescriptors.emplace_back(nullptr);
10825   }
10826   /// Stores reduction data.
10827   void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10828             Expr *TaskgroupDescriptor) {
10829     Vars.emplace_back(Item);
10830     Privates.emplace_back(Private);
10831     LHSs.emplace_back(LHS);
10832     RHSs.emplace_back(RHS);
10833     ReductionOps.emplace_back(ReductionOp);
10834     TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
10835   }
10836 };
10837 } // namespace
10838 
10839 static bool checkOMPArraySectionConstantForReduction(
10840     ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10841     SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10842   const Expr *Length = OASE->getLength();
10843   if (Length == nullptr) {
10844     // For array sections of the form [1:] or [:], we would need to analyze
10845     // the lower bound...
10846     if (OASE->getColonLoc().isValid())
10847       return false;
10848 
10849     // This is an array subscript which has implicit length 1!
10850     SingleElement = true;
10851     ArraySizes.push_back(llvm::APSInt::get(1));
10852   } else {
10853     Expr::EvalResult Result;
10854     if (!Length->EvaluateAsInt(Result, Context))
10855       return false;
10856 
10857     llvm::APSInt ConstantLengthValue = Result.Val.getInt();
10858     SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10859     ArraySizes.push_back(ConstantLengthValue);
10860   }
10861 
10862   // Get the base of this array section and walk up from there.
10863   const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10864 
10865   // We require length = 1 for all array sections except the right-most to
10866   // guarantee that the memory region is contiguous and has no holes in it.
10867   while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10868     Length = TempOASE->getLength();
10869     if (Length == nullptr) {
10870       // For array sections of the form [1:] or [:], we would need to analyze
10871       // the lower bound...
10872       if (OASE->getColonLoc().isValid())
10873         return false;
10874 
10875       // This is an array subscript which has implicit length 1!
10876       ArraySizes.push_back(llvm::APSInt::get(1));
10877     } else {
10878       Expr::EvalResult Result;
10879       if (!Length->EvaluateAsInt(Result, Context))
10880         return false;
10881 
10882       llvm::APSInt ConstantLengthValue = Result.Val.getInt();
10883       if (ConstantLengthValue.getSExtValue() != 1)
10884         return false;
10885 
10886       ArraySizes.push_back(ConstantLengthValue);
10887     }
10888     Base = TempOASE->getBase()->IgnoreParenImpCasts();
10889   }
10890 
10891   // If we have a single element, we don't need to add the implicit lengths.
10892   if (!SingleElement) {
10893     while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10894       // Has implicit length 1!
10895       ArraySizes.push_back(llvm::APSInt::get(1));
10896       Base = TempASE->getBase()->IgnoreParenImpCasts();
10897     }
10898   }
10899 
10900   // This array section can be privatized as a single value or as a constant
10901   // sized array.
10902   return true;
10903 }
10904 
10905 static bool actOnOMPReductionKindClause(
10906     Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10907     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10908     SourceLocation ColonLoc, SourceLocation EndLoc,
10909     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10910     ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
10911   DeclarationName DN = ReductionId.getName();
10912   OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
10913   BinaryOperatorKind BOK = BO_Comma;
10914 
10915   ASTContext &Context = S.Context;
10916   // OpenMP [2.14.3.6, reduction clause]
10917   // C
10918   // reduction-identifier is either an identifier or one of the following
10919   // operators: +, -, *,  &, |, ^, && and ||
10920   // C++
10921   // reduction-identifier is either an id-expression or one of the following
10922   // operators: +, -, *, &, |, ^, && and ||
10923   switch (OOK) {
10924   case OO_Plus:
10925   case OO_Minus:
10926     BOK = BO_Add;
10927     break;
10928   case OO_Star:
10929     BOK = BO_Mul;
10930     break;
10931   case OO_Amp:
10932     BOK = BO_And;
10933     break;
10934   case OO_Pipe:
10935     BOK = BO_Or;
10936     break;
10937   case OO_Caret:
10938     BOK = BO_Xor;
10939     break;
10940   case OO_AmpAmp:
10941     BOK = BO_LAnd;
10942     break;
10943   case OO_PipePipe:
10944     BOK = BO_LOr;
10945     break;
10946   case OO_New:
10947   case OO_Delete:
10948   case OO_Array_New:
10949   case OO_Array_Delete:
10950   case OO_Slash:
10951   case OO_Percent:
10952   case OO_Tilde:
10953   case OO_Exclaim:
10954   case OO_Equal:
10955   case OO_Less:
10956   case OO_Greater:
10957   case OO_LessEqual:
10958   case OO_GreaterEqual:
10959   case OO_PlusEqual:
10960   case OO_MinusEqual:
10961   case OO_StarEqual:
10962   case OO_SlashEqual:
10963   case OO_PercentEqual:
10964   case OO_CaretEqual:
10965   case OO_AmpEqual:
10966   case OO_PipeEqual:
10967   case OO_LessLess:
10968   case OO_GreaterGreater:
10969   case OO_LessLessEqual:
10970   case OO_GreaterGreaterEqual:
10971   case OO_EqualEqual:
10972   case OO_ExclaimEqual:
10973   case OO_Spaceship:
10974   case OO_PlusPlus:
10975   case OO_MinusMinus:
10976   case OO_Comma:
10977   case OO_ArrowStar:
10978   case OO_Arrow:
10979   case OO_Call:
10980   case OO_Subscript:
10981   case OO_Conditional:
10982   case OO_Coawait:
10983   case NUM_OVERLOADED_OPERATORS:
10984     llvm_unreachable("Unexpected reduction identifier");
10985   case OO_None:
10986     if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
10987       if (II->isStr("max"))
10988         BOK = BO_GT;
10989       else if (II->isStr("min"))
10990         BOK = BO_LT;
10991     }
10992     break;
10993   }
10994   SourceRange ReductionIdRange;
10995   if (ReductionIdScopeSpec.isValid())
10996     ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
10997   else
10998     ReductionIdRange.setBegin(ReductionId.getBeginLoc());
10999   ReductionIdRange.setEnd(ReductionId.getEndLoc());
11000 
11001   auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11002   bool FirstIter = true;
11003   for (Expr *RefExpr : VarList) {
11004     assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
11005     // OpenMP [2.1, C/C++]
11006     //  A list item is a variable or array section, subject to the restrictions
11007     //  specified in Section 2.4 on page 42 and in each of the sections
11008     // describing clauses and directives for which a list appears.
11009     // OpenMP  [2.14.3.3, Restrictions, p.1]
11010     //  A variable that is part of another variable (as an array or
11011     //  structure element) cannot appear in a private clause.
11012     if (!FirstIter && IR != ER)
11013       ++IR;
11014     FirstIter = false;
11015     SourceLocation ELoc;
11016     SourceRange ERange;
11017     Expr *SimpleRefExpr = RefExpr;
11018     auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
11019                               /*AllowArraySection=*/true);
11020     if (Res.second) {
11021       // Try to find 'declare reduction' corresponding construct before using
11022       // builtin/overloaded operators.
11023       QualType Type = Context.DependentTy;
11024       CXXCastPath BasePath;
11025       ExprResult DeclareReductionRef = buildDeclareReductionRef(
11026           S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
11027           ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11028       Expr *ReductionOp = nullptr;
11029       if (S.CurContext->isDependentContext() &&
11030           (DeclareReductionRef.isUnset() ||
11031            isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
11032         ReductionOp = DeclareReductionRef.get();
11033       // It will be analyzed later.
11034       RD.push(RefExpr, ReductionOp);
11035     }
11036     ValueDecl *D = Res.first;
11037     if (!D)
11038       continue;
11039 
11040     Expr *TaskgroupDescriptor = nullptr;
11041     QualType Type;
11042     auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11043     auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
11044     if (ASE) {
11045       Type = ASE->getType().getNonReferenceType();
11046     } else if (OASE) {
11047       QualType BaseType =
11048           OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11049       if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
11050         Type = ATy->getElementType();
11051       else
11052         Type = BaseType->getPointeeType();
11053       Type = Type.getNonReferenceType();
11054     } else {
11055       Type = Context.getBaseElementType(D->getType().getNonReferenceType());
11056     }
11057     auto *VD = dyn_cast<VarDecl>(D);
11058 
11059     // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11060     //  A variable that appears in a private clause must not have an incomplete
11061     //  type or a reference type.
11062     if (S.RequireCompleteType(ELoc, D->getType(),
11063                               diag::err_omp_reduction_incomplete_type))
11064       continue;
11065     // OpenMP [2.14.3.6, reduction clause, Restrictions]
11066     // A list item that appears in a reduction clause must not be
11067     // const-qualified.
11068     if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11069                                   /*AcceptIfMutable*/ false, ASE || OASE))
11070       continue;
11071 
11072     OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
11073     // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11074     //  If a list-item is a reference type then it must bind to the same object
11075     //  for all threads of the team.
11076     if (!ASE && !OASE) {
11077       if (VD) {
11078         VarDecl *VDDef = VD->getDefinition();
11079         if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11080           DSARefChecker Check(Stack);
11081           if (Check.Visit(VDDef->getInit())) {
11082             S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11083                 << getOpenMPClauseName(ClauseKind) << ERange;
11084             S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11085             continue;
11086           }
11087         }
11088       }
11089 
11090       // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11091       // in a Construct]
11092       //  Variables with the predetermined data-sharing attributes may not be
11093       //  listed in data-sharing attributes clauses, except for the cases
11094       //  listed below. For these exceptions only, listing a predetermined
11095       //  variable in a data-sharing attribute clause is allowed and overrides
11096       //  the variable's predetermined data-sharing attributes.
11097       // OpenMP [2.14.3.6, Restrictions, p.3]
11098       //  Any number of reduction clauses can be specified on the directive,
11099       //  but a list item can appear only once in the reduction clauses for that
11100       //  directive.
11101       DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11102       if (DVar.CKind == OMPC_reduction) {
11103         S.Diag(ELoc, diag::err_omp_once_referenced)
11104             << getOpenMPClauseName(ClauseKind);
11105         if (DVar.RefExpr)
11106           S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11107         continue;
11108       }
11109       if (DVar.CKind != OMPC_unknown) {
11110         S.Diag(ELoc, diag::err_omp_wrong_dsa)
11111             << getOpenMPClauseName(DVar.CKind)
11112             << getOpenMPClauseName(OMPC_reduction);
11113         reportOriginalDsa(S, Stack, D, DVar);
11114         continue;
11115       }
11116 
11117       // OpenMP [2.14.3.6, Restrictions, p.1]
11118       //  A list item that appears in a reduction clause of a worksharing
11119       //  construct must be shared in the parallel regions to which any of the
11120       //  worksharing regions arising from the worksharing construct bind.
11121       if (isOpenMPWorksharingDirective(CurrDir) &&
11122           !isOpenMPParallelDirective(CurrDir) &&
11123           !isOpenMPTeamsDirective(CurrDir)) {
11124         DVar = Stack->getImplicitDSA(D, true);
11125         if (DVar.CKind != OMPC_shared) {
11126           S.Diag(ELoc, diag::err_omp_required_access)
11127               << getOpenMPClauseName(OMPC_reduction)
11128               << getOpenMPClauseName(OMPC_shared);
11129           reportOriginalDsa(S, Stack, D, DVar);
11130           continue;
11131         }
11132       }
11133     }
11134 
11135     // Try to find 'declare reduction' corresponding construct before using
11136     // builtin/overloaded operators.
11137     CXXCastPath BasePath;
11138     ExprResult DeclareReductionRef = buildDeclareReductionRef(
11139         S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
11140         ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11141     if (DeclareReductionRef.isInvalid())
11142       continue;
11143     if (S.CurContext->isDependentContext() &&
11144         (DeclareReductionRef.isUnset() ||
11145          isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
11146       RD.push(RefExpr, DeclareReductionRef.get());
11147       continue;
11148     }
11149     if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11150       // Not allowed reduction identifier is found.
11151       S.Diag(ReductionId.getBeginLoc(),
11152              diag::err_omp_unknown_reduction_identifier)
11153           << Type << ReductionIdRange;
11154       continue;
11155     }
11156 
11157     // OpenMP [2.14.3.6, reduction clause, Restrictions]
11158     // The type of a list item that appears in a reduction clause must be valid
11159     // for the reduction-identifier. For a max or min reduction in C, the type
11160     // of the list item must be an allowed arithmetic data type: char, int,
11161     // float, double, or _Bool, possibly modified with long, short, signed, or
11162     // unsigned. For a max or min reduction in C++, the type of the list item
11163     // must be an allowed arithmetic data type: char, wchar_t, int, float,
11164     // double, or bool, possibly modified with long, short, signed, or unsigned.
11165     if (DeclareReductionRef.isUnset()) {
11166       if ((BOK == BO_GT || BOK == BO_LT) &&
11167           !(Type->isScalarType() ||
11168             (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11169         S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
11170             << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
11171         if (!ASE && !OASE) {
11172           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11173                                    VarDecl::DeclarationOnly;
11174           S.Diag(D->getLocation(),
11175                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11176               << D;
11177         }
11178         continue;
11179       }
11180       if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
11181           !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
11182         S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11183             << getOpenMPClauseName(ClauseKind);
11184         if (!ASE && !OASE) {
11185           bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11186                                    VarDecl::DeclarationOnly;
11187           S.Diag(D->getLocation(),
11188                  IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11189               << D;
11190         }
11191         continue;
11192       }
11193     }
11194 
11195     Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
11196     VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11197                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
11198     VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11199                                   D->hasAttrs() ? &D->getAttrs() : nullptr);
11200     QualType PrivateTy = Type;
11201 
11202     // Try if we can determine constant lengths for all array sections and avoid
11203     // the VLA.
11204     bool ConstantLengthOASE = false;
11205     if (OASE) {
11206       bool SingleElement;
11207       llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
11208       ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
11209           Context, OASE, SingleElement, ArraySizes);
11210 
11211       // If we don't have a single element, we must emit a constant array type.
11212       if (ConstantLengthOASE && !SingleElement) {
11213         for (llvm::APSInt &Size : ArraySizes)
11214           PrivateTy = Context.getConstantArrayType(
11215               PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
11216       }
11217     }
11218 
11219     if ((OASE && !ConstantLengthOASE) ||
11220         (!OASE && !ASE &&
11221          D->getType().getNonReferenceType()->isVariablyModifiedType())) {
11222       if (!Context.getTargetInfo().isVLASupported() &&
11223           S.shouldDiagnoseTargetSupportFromOpenMP()) {
11224         S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11225         S.Diag(ELoc, diag::note_vla_unsupported);
11226         continue;
11227       }
11228       // For arrays/array sections only:
11229       // Create pseudo array type for private copy. The size for this array will
11230       // be generated during codegen.
11231       // For array subscripts or single variables Private Ty is the same as Type
11232       // (type of the variable or single array element).
11233       PrivateTy = Context.getVariableArrayType(
11234           Type,
11235           new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
11236           ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
11237     } else if (!ASE && !OASE &&
11238                Context.getAsArrayType(D->getType().getNonReferenceType())) {
11239       PrivateTy = D->getType().getNonReferenceType();
11240     }
11241     // Private copy.
11242     VarDecl *PrivateVD =
11243         buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11244                      D->hasAttrs() ? &D->getAttrs() : nullptr,
11245                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
11246     // Add initializer for private variable.
11247     Expr *Init = nullptr;
11248     DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11249     DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
11250     if (DeclareReductionRef.isUsable()) {
11251       auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11252       auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11253       if (DRD->getInitializer()) {
11254         Init = DRDRef;
11255         RHSVD->setInit(DRDRef);
11256         RHSVD->setInitStyle(VarDecl::CallInit);
11257       }
11258     } else {
11259       switch (BOK) {
11260       case BO_Add:
11261       case BO_Xor:
11262       case BO_Or:
11263       case BO_LOr:
11264         // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11265         if (Type->isScalarType() || Type->isAnyComplexType())
11266           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
11267         break;
11268       case BO_Mul:
11269       case BO_LAnd:
11270         if (Type->isScalarType() || Type->isAnyComplexType()) {
11271           // '*' and '&&' reduction ops - initializer is '1'.
11272           Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
11273         }
11274         break;
11275       case BO_And: {
11276         // '&' reduction op - initializer is '~0'.
11277         QualType OrigType = Type;
11278         if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11279           Type = ComplexTy->getElementType();
11280         if (Type->isRealFloatingType()) {
11281           llvm::APFloat InitValue =
11282               llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11283                                              /*isIEEE=*/true);
11284           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11285                                          Type, ELoc);
11286         } else if (Type->isScalarType()) {
11287           uint64_t Size = Context.getTypeSize(Type);
11288           QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11289           llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11290           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11291         }
11292         if (Init && OrigType->isAnyComplexType()) {
11293           // Init = 0xFFFF + 0xFFFFi;
11294           auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
11295           Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
11296         }
11297         Type = OrigType;
11298         break;
11299       }
11300       case BO_LT:
11301       case BO_GT: {
11302         // 'min' reduction op - initializer is 'Largest representable number in
11303         // the reduction list item type'.
11304         // 'max' reduction op - initializer is 'Least representable number in
11305         // the reduction list item type'.
11306         if (Type->isIntegerType() || Type->isPointerType()) {
11307           bool IsSigned = Type->hasSignedIntegerRepresentation();
11308           uint64_t Size = Context.getTypeSize(Type);
11309           QualType IntTy =
11310               Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11311           llvm::APInt InitValue =
11312               (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11313                                         : llvm::APInt::getMinValue(Size)
11314                              : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11315                                         : llvm::APInt::getMaxValue(Size);
11316           Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11317           if (Type->isPointerType()) {
11318             // Cast to pointer type.
11319             ExprResult CastExpr = S.BuildCStyleCastExpr(
11320                 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
11321             if (CastExpr.isInvalid())
11322               continue;
11323             Init = CastExpr.get();
11324           }
11325         } else if (Type->isRealFloatingType()) {
11326           llvm::APFloat InitValue = llvm::APFloat::getLargest(
11327               Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11328           Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11329                                          Type, ELoc);
11330         }
11331         break;
11332       }
11333       case BO_PtrMemD:
11334       case BO_PtrMemI:
11335       case BO_MulAssign:
11336       case BO_Div:
11337       case BO_Rem:
11338       case BO_Sub:
11339       case BO_Shl:
11340       case BO_Shr:
11341       case BO_LE:
11342       case BO_GE:
11343       case BO_EQ:
11344       case BO_NE:
11345       case BO_Cmp:
11346       case BO_AndAssign:
11347       case BO_XorAssign:
11348       case BO_OrAssign:
11349       case BO_Assign:
11350       case BO_AddAssign:
11351       case BO_SubAssign:
11352       case BO_DivAssign:
11353       case BO_RemAssign:
11354       case BO_ShlAssign:
11355       case BO_ShrAssign:
11356       case BO_Comma:
11357         llvm_unreachable("Unexpected reduction operation");
11358       }
11359     }
11360     if (Init && DeclareReductionRef.isUnset())
11361       S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11362     else if (!Init)
11363       S.ActOnUninitializedDecl(RHSVD);
11364     if (RHSVD->isInvalidDecl())
11365       continue;
11366     if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
11367       S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11368           << Type << ReductionIdRange;
11369       bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11370                                VarDecl::DeclarationOnly;
11371       S.Diag(D->getLocation(),
11372              IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11373           << D;
11374       continue;
11375     }
11376     // Store initializer for single element in private copy. Will be used during
11377     // codegen.
11378     PrivateVD->setInit(RHSVD->getInit());
11379     PrivateVD->setInitStyle(RHSVD->getInitStyle());
11380     DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
11381     ExprResult ReductionOp;
11382     if (DeclareReductionRef.isUsable()) {
11383       QualType RedTy = DeclareReductionRef.get()->getType();
11384       QualType PtrRedTy = Context.getPointerType(RedTy);
11385       ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11386       ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
11387       if (!BasePath.empty()) {
11388         LHS = S.DefaultLvalueConversion(LHS.get());
11389         RHS = S.DefaultLvalueConversion(RHS.get());
11390         LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11391                                        CK_UncheckedDerivedToBase, LHS.get(),
11392                                        &BasePath, LHS.get()->getValueKind());
11393         RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11394                                        CK_UncheckedDerivedToBase, RHS.get(),
11395                                        &BasePath, RHS.get()->getValueKind());
11396       }
11397       FunctionProtoType::ExtProtoInfo EPI;
11398       QualType Params[] = {PtrRedTy, PtrRedTy};
11399       QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11400       auto *OVE = new (Context) OpaqueValueExpr(
11401           ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
11402           S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
11403       Expr *Args[] = {LHS.get(), RHS.get()};
11404       ReductionOp =
11405           CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
11406     } else {
11407       ReductionOp = S.BuildBinOp(
11408           Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
11409       if (ReductionOp.isUsable()) {
11410         if (BOK != BO_LT && BOK != BO_GT) {
11411           ReductionOp =
11412               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11413                            BO_Assign, LHSDRE, ReductionOp.get());
11414         } else {
11415           auto *ConditionalOp = new (Context)
11416               ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11417                                   Type, VK_LValue, OK_Ordinary);
11418           ReductionOp =
11419               S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
11420                            BO_Assign, LHSDRE, ConditionalOp);
11421         }
11422         if (ReductionOp.isUsable())
11423           ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11424                                               /*DiscardedValue*/ false);
11425       }
11426       if (!ReductionOp.isUsable())
11427         continue;
11428     }
11429 
11430     // OpenMP [2.15.4.6, Restrictions, p.2]
11431     // A list item that appears in an in_reduction clause of a task construct
11432     // must appear in a task_reduction clause of a construct associated with a
11433     // taskgroup region that includes the participating task in its taskgroup
11434     // set. The construct associated with the innermost region that meets this
11435     // condition must specify the same reduction-identifier as the in_reduction
11436     // clause.
11437     if (ClauseKind == OMPC_in_reduction) {
11438       SourceRange ParentSR;
11439       BinaryOperatorKind ParentBOK;
11440       const Expr *ParentReductionOp;
11441       Expr *ParentBOKTD, *ParentReductionOpTD;
11442       DSAStackTy::DSAVarData ParentBOKDSA =
11443           Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11444                                                   ParentBOKTD);
11445       DSAStackTy::DSAVarData ParentReductionOpDSA =
11446           Stack->getTopMostTaskgroupReductionData(
11447               D, ParentSR, ParentReductionOp, ParentReductionOpTD);
11448       bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11449       bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11450       if (!IsParentBOK && !IsParentReductionOp) {
11451         S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11452         continue;
11453       }
11454       if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11455           (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11456           IsParentReductionOp) {
11457         bool EmitError = true;
11458         if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11459           llvm::FoldingSetNodeID RedId, ParentRedId;
11460           ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11461           DeclareReductionRef.get()->Profile(RedId, Context,
11462                                              /*Canonical=*/true);
11463           EmitError = RedId != ParentRedId;
11464         }
11465         if (EmitError) {
11466           S.Diag(ReductionId.getBeginLoc(),
11467                  diag::err_omp_reduction_identifier_mismatch)
11468               << ReductionIdRange << RefExpr->getSourceRange();
11469           S.Diag(ParentSR.getBegin(),
11470                  diag::note_omp_previous_reduction_identifier)
11471               << ParentSR
11472               << (IsParentBOK ? ParentBOKDSA.RefExpr
11473                               : ParentReductionOpDSA.RefExpr)
11474                      ->getSourceRange();
11475           continue;
11476         }
11477       }
11478       TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11479       assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
11480     }
11481 
11482     DeclRefExpr *Ref = nullptr;
11483     Expr *VarsExpr = RefExpr->IgnoreParens();
11484     if (!VD && !S.CurContext->isDependentContext()) {
11485       if (ASE || OASE) {
11486         TransformExprToCaptures RebuildToCapture(S, D);
11487         VarsExpr =
11488             RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11489         Ref = RebuildToCapture.getCapturedExpr();
11490       } else {
11491         VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
11492       }
11493       if (!S.isOpenMPCapturedDecl(D)) {
11494         RD.ExprCaptures.emplace_back(Ref->getDecl());
11495         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11496           ExprResult RefRes = S.DefaultLvalueConversion(Ref);
11497           if (!RefRes.isUsable())
11498             continue;
11499           ExprResult PostUpdateRes =
11500               S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11501                            RefRes.get());
11502           if (!PostUpdateRes.isUsable())
11503             continue;
11504           if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11505               Stack->getCurrentDirective() == OMPD_taskgroup) {
11506             S.Diag(RefExpr->getExprLoc(),
11507                    diag::err_omp_reduction_non_addressable_expression)
11508                 << RefExpr->getSourceRange();
11509             continue;
11510           }
11511           RD.ExprPostUpdates.emplace_back(
11512               S.IgnoredValueConversions(PostUpdateRes.get()).get());
11513         }
11514       }
11515     }
11516     // All reduction items are still marked as reduction (to do not increase
11517     // code base size).
11518     Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
11519     if (CurrDir == OMPD_taskgroup) {
11520       if (DeclareReductionRef.isUsable())
11521         Stack->addTaskgroupReductionData(D, ReductionIdRange,
11522                                          DeclareReductionRef.get());
11523       else
11524         Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
11525     }
11526     RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11527             TaskgroupDescriptor);
11528   }
11529   return RD.Vars.empty();
11530 }
11531 
11532 OMPClause *Sema::ActOnOpenMPReductionClause(
11533     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11534     SourceLocation ColonLoc, SourceLocation EndLoc,
11535     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11536     ArrayRef<Expr *> UnresolvedReductions) {
11537   ReductionData RD(VarList.size());
11538   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
11539                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11540                                   ReductionIdScopeSpec, ReductionId,
11541                                   UnresolvedReductions, RD))
11542     return nullptr;
11543 
11544   return OMPReductionClause::Create(
11545       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11546       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11547       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11548       buildPreInits(Context, RD.ExprCaptures),
11549       buildPostUpdate(*this, RD.ExprPostUpdates));
11550 }
11551 
11552 OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11553     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11554     SourceLocation ColonLoc, SourceLocation EndLoc,
11555     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11556     ArrayRef<Expr *> UnresolvedReductions) {
11557   ReductionData RD(VarList.size());
11558   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11559                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11560                                   ReductionIdScopeSpec, ReductionId,
11561                                   UnresolvedReductions, RD))
11562     return nullptr;
11563 
11564   return OMPTaskReductionClause::Create(
11565       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11566       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11567       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11568       buildPreInits(Context, RD.ExprCaptures),
11569       buildPostUpdate(*this, RD.ExprPostUpdates));
11570 }
11571 
11572 OMPClause *Sema::ActOnOpenMPInReductionClause(
11573     ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11574     SourceLocation ColonLoc, SourceLocation EndLoc,
11575     CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11576     ArrayRef<Expr *> UnresolvedReductions) {
11577   ReductionData RD(VarList.size());
11578   if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
11579                                   StartLoc, LParenLoc, ColonLoc, EndLoc,
11580                                   ReductionIdScopeSpec, ReductionId,
11581                                   UnresolvedReductions, RD))
11582     return nullptr;
11583 
11584   return OMPInReductionClause::Create(
11585       Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11586       ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11587       RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
11588       buildPreInits(Context, RD.ExprCaptures),
11589       buildPostUpdate(*this, RD.ExprPostUpdates));
11590 }
11591 
11592 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11593                                      SourceLocation LinLoc) {
11594   if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11595       LinKind == OMPC_LINEAR_unknown) {
11596     Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11597     return true;
11598   }
11599   return false;
11600 }
11601 
11602 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11603                                  OpenMPLinearClauseKind LinKind,
11604                                  QualType Type) {
11605   const auto *VD = dyn_cast_or_null<VarDecl>(D);
11606   // A variable must not have an incomplete type or a reference type.
11607   if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11608     return true;
11609   if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11610       !Type->isReferenceType()) {
11611     Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11612         << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11613     return true;
11614   }
11615   Type = Type.getNonReferenceType();
11616 
11617   // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11618   // A variable that is privatized must not have a const-qualified type
11619   // unless it is of class type with a mutable member. This restriction does
11620   // not apply to the firstprivate clause.
11621   if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
11622     return true;
11623 
11624   // A list item must be of integral or pointer type.
11625   Type = Type.getUnqualifiedType().getCanonicalType();
11626   const auto *Ty = Type.getTypePtrOrNull();
11627   if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11628               !Ty->isPointerType())) {
11629     Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
11630     if (D) {
11631       bool IsDecl =
11632           !VD ||
11633           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11634       Diag(D->getLocation(),
11635            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11636           << D;
11637     }
11638     return true;
11639   }
11640   return false;
11641 }
11642 
11643 OMPClause *Sema::ActOnOpenMPLinearClause(
11644     ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
11645     SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
11646     SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11647   SmallVector<Expr *, 8> Vars;
11648   SmallVector<Expr *, 8> Privates;
11649   SmallVector<Expr *, 8> Inits;
11650   SmallVector<Decl *, 4> ExprCaptures;
11651   SmallVector<Expr *, 4> ExprPostUpdates;
11652   if (CheckOpenMPLinearModifier(LinKind, LinLoc))
11653     LinKind = OMPC_LINEAR_val;
11654   for (Expr *RefExpr : VarList) {
11655     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11656     SourceLocation ELoc;
11657     SourceRange ERange;
11658     Expr *SimpleRefExpr = RefExpr;
11659     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11660     if (Res.second) {
11661       // It will be analyzed later.
11662       Vars.push_back(RefExpr);
11663       Privates.push_back(nullptr);
11664       Inits.push_back(nullptr);
11665     }
11666     ValueDecl *D = Res.first;
11667     if (!D)
11668       continue;
11669 
11670     QualType Type = D->getType();
11671     auto *VD = dyn_cast<VarDecl>(D);
11672 
11673     // OpenMP [2.14.3.7, linear clause]
11674     //  A list-item cannot appear in more than one linear clause.
11675     //  A list-item that appears in a linear clause cannot appear in any
11676     //  other data-sharing attribute clause.
11677     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
11678     if (DVar.RefExpr) {
11679       Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11680                                           << getOpenMPClauseName(OMPC_linear);
11681       reportOriginalDsa(*this, DSAStack, D, DVar);
11682       continue;
11683     }
11684 
11685     if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
11686       continue;
11687     Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11688 
11689     // Build private copy of original var.
11690     VarDecl *Private =
11691         buildVarDecl(*this, ELoc, Type, D->getName(),
11692                      D->hasAttrs() ? &D->getAttrs() : nullptr,
11693                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
11694     DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
11695     // Build var to save initial value.
11696     VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
11697     Expr *InitExpr;
11698     DeclRefExpr *Ref = nullptr;
11699     if (!VD && !CurContext->isDependentContext()) {
11700       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
11701       if (!isOpenMPCapturedDecl(D)) {
11702         ExprCaptures.push_back(Ref->getDecl());
11703         if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11704           ExprResult RefRes = DefaultLvalueConversion(Ref);
11705           if (!RefRes.isUsable())
11706             continue;
11707           ExprResult PostUpdateRes =
11708               BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11709                          SimpleRefExpr, RefRes.get());
11710           if (!PostUpdateRes.isUsable())
11711             continue;
11712           ExprPostUpdates.push_back(
11713               IgnoredValueConversions(PostUpdateRes.get()).get());
11714         }
11715       }
11716     }
11717     if (LinKind == OMPC_LINEAR_uval)
11718       InitExpr = VD ? VD->getInit() : SimpleRefExpr;
11719     else
11720       InitExpr = VD ? SimpleRefExpr : Ref;
11721     AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
11722                          /*DirectInit=*/false);
11723     DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
11724 
11725     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
11726     Vars.push_back((VD || CurContext->isDependentContext())
11727                        ? RefExpr->IgnoreParens()
11728                        : Ref);
11729     Privates.push_back(PrivateRef);
11730     Inits.push_back(InitRef);
11731   }
11732 
11733   if (Vars.empty())
11734     return nullptr;
11735 
11736   Expr *StepExpr = Step;
11737   Expr *CalcStepExpr = nullptr;
11738   if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11739       !Step->isInstantiationDependent() &&
11740       !Step->containsUnexpandedParameterPack()) {
11741     SourceLocation StepLoc = Step->getBeginLoc();
11742     ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
11743     if (Val.isInvalid())
11744       return nullptr;
11745     StepExpr = Val.get();
11746 
11747     // Build var to save the step value.
11748     VarDecl *SaveVar =
11749         buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
11750     ExprResult SaveRef =
11751         buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
11752     ExprResult CalcStep =
11753         BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
11754     CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
11755 
11756     // Warn about zero linear step (it would be probably better specified as
11757     // making corresponding variables 'const').
11758     llvm::APSInt Result;
11759     bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11760     if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
11761       Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11762                                                      << (Vars.size() > 1);
11763     if (!IsConstant && CalcStep.isUsable()) {
11764       // Calculate the step beforehand instead of doing this on each iteration.
11765       // (This is not used if the number of iterations may be kfold-ed).
11766       CalcStepExpr = CalcStep.get();
11767     }
11768   }
11769 
11770   return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11771                                  ColonLoc, EndLoc, Vars, Privates, Inits,
11772                                  StepExpr, CalcStepExpr,
11773                                  buildPreInits(Context, ExprCaptures),
11774                                  buildPostUpdate(*this, ExprPostUpdates));
11775 }
11776 
11777 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11778                                      Expr *NumIterations, Sema &SemaRef,
11779                                      Scope *S, DSAStackTy *Stack) {
11780   // Walk the vars and build update/final expressions for the CodeGen.
11781   SmallVector<Expr *, 8> Updates;
11782   SmallVector<Expr *, 8> Finals;
11783   Expr *Step = Clause.getStep();
11784   Expr *CalcStep = Clause.getCalcStep();
11785   // OpenMP [2.14.3.7, linear clause]
11786   // If linear-step is not specified it is assumed to be 1.
11787   if (!Step)
11788     Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
11789   else if (CalcStep)
11790     Step = cast<BinaryOperator>(CalcStep)->getLHS();
11791   bool HasErrors = false;
11792   auto CurInit = Clause.inits().begin();
11793   auto CurPrivate = Clause.privates().begin();
11794   OpenMPLinearClauseKind LinKind = Clause.getModifier();
11795   for (Expr *RefExpr : Clause.varlists()) {
11796     SourceLocation ELoc;
11797     SourceRange ERange;
11798     Expr *SimpleRefExpr = RefExpr;
11799     auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
11800     ValueDecl *D = Res.first;
11801     if (Res.second || !D) {
11802       Updates.push_back(nullptr);
11803       Finals.push_back(nullptr);
11804       HasErrors = true;
11805       continue;
11806     }
11807     auto &&Info = Stack->isLoopControlVariable(D);
11808     // OpenMP [2.15.11, distribute simd Construct]
11809     // A list item may not appear in a linear clause, unless it is the loop
11810     // iteration variable.
11811     if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11812         isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11813       SemaRef.Diag(ELoc,
11814                    diag::err_omp_linear_distribute_var_non_loop_iteration);
11815       Updates.push_back(nullptr);
11816       Finals.push_back(nullptr);
11817       HasErrors = true;
11818       continue;
11819     }
11820     Expr *InitExpr = *CurInit;
11821 
11822     // Build privatized reference to the current linear var.
11823     auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
11824     Expr *CapturedRef;
11825     if (LinKind == OMPC_LINEAR_uval)
11826       CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11827     else
11828       CapturedRef =
11829           buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11830                            DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11831                            /*RefersToCapture=*/true);
11832 
11833     // Build update: Var = InitExpr + IV * Step
11834     ExprResult Update;
11835     if (!Info.first)
11836       Update =
11837           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11838                              InitExpr, IV, Step, /* Subtract */ false);
11839     else
11840       Update = *CurPrivate;
11841     Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
11842                                          /*DiscardedValue*/ false);
11843 
11844     // Build final: Var = InitExpr + NumIterations * Step
11845     ExprResult Final;
11846     if (!Info.first)
11847       Final =
11848           buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11849                              InitExpr, NumIterations, Step, /*Subtract=*/false);
11850     else
11851       Final = *CurPrivate;
11852     Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
11853                                         /*DiscardedValue*/ false);
11854 
11855     if (!Update.isUsable() || !Final.isUsable()) {
11856       Updates.push_back(nullptr);
11857       Finals.push_back(nullptr);
11858       HasErrors = true;
11859     } else {
11860       Updates.push_back(Update.get());
11861       Finals.push_back(Final.get());
11862     }
11863     ++CurInit;
11864     ++CurPrivate;
11865   }
11866   Clause.setUpdates(Updates);
11867   Clause.setFinals(Finals);
11868   return HasErrors;
11869 }
11870 
11871 OMPClause *Sema::ActOnOpenMPAlignedClause(
11872     ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11873     SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11874   SmallVector<Expr *, 8> Vars;
11875   for (Expr *RefExpr : VarList) {
11876     assert(RefExpr && "NULL expr in OpenMP linear clause.");
11877     SourceLocation ELoc;
11878     SourceRange ERange;
11879     Expr *SimpleRefExpr = RefExpr;
11880     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
11881     if (Res.second) {
11882       // It will be analyzed later.
11883       Vars.push_back(RefExpr);
11884     }
11885     ValueDecl *D = Res.first;
11886     if (!D)
11887       continue;
11888 
11889     QualType QType = D->getType();
11890     auto *VD = dyn_cast<VarDecl>(D);
11891 
11892     // OpenMP  [2.8.1, simd construct, Restrictions]
11893     // The type of list items appearing in the aligned clause must be
11894     // array, pointer, reference to array, or reference to pointer.
11895     QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
11896     const Type *Ty = QType.getTypePtrOrNull();
11897     if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
11898       Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
11899           << QType << getLangOpts().CPlusPlus << ERange;
11900       bool IsDecl =
11901           !VD ||
11902           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11903       Diag(D->getLocation(),
11904            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11905           << D;
11906       continue;
11907     }
11908 
11909     // OpenMP  [2.8.1, simd construct, Restrictions]
11910     // A list-item cannot appear in more than one aligned clause.
11911     if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
11912       Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
11913       Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11914           << getOpenMPClauseName(OMPC_aligned);
11915       continue;
11916     }
11917 
11918     DeclRefExpr *Ref = nullptr;
11919     if (!VD && isOpenMPCapturedDecl(D))
11920       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11921     Vars.push_back(DefaultFunctionArrayConversion(
11922                        (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11923                        .get());
11924   }
11925 
11926   // OpenMP [2.8.1, simd construct, Description]
11927   // The parameter of the aligned clause, alignment, must be a constant
11928   // positive integer expression.
11929   // If no optional parameter is specified, implementation-defined default
11930   // alignments for SIMD instructions on the target platforms are assumed.
11931   if (Alignment != nullptr) {
11932     ExprResult AlignResult =
11933         VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11934     if (AlignResult.isInvalid())
11935       return nullptr;
11936     Alignment = AlignResult.get();
11937   }
11938   if (Vars.empty())
11939     return nullptr;
11940 
11941   return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11942                                   EndLoc, Vars, Alignment);
11943 }
11944 
11945 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11946                                          SourceLocation StartLoc,
11947                                          SourceLocation LParenLoc,
11948                                          SourceLocation EndLoc) {
11949   SmallVector<Expr *, 8> Vars;
11950   SmallVector<Expr *, 8> SrcExprs;
11951   SmallVector<Expr *, 8> DstExprs;
11952   SmallVector<Expr *, 8> AssignmentOps;
11953   for (Expr *RefExpr : VarList) {
11954     assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11955     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11956       // It will be analyzed later.
11957       Vars.push_back(RefExpr);
11958       SrcExprs.push_back(nullptr);
11959       DstExprs.push_back(nullptr);
11960       AssignmentOps.push_back(nullptr);
11961       continue;
11962     }
11963 
11964     SourceLocation ELoc = RefExpr->getExprLoc();
11965     // OpenMP [2.1, C/C++]
11966     //  A list item is a variable name.
11967     // OpenMP  [2.14.4.1, Restrictions, p.1]
11968     //  A list item that appears in a copyin clause must be threadprivate.
11969     auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
11970     if (!DE || !isa<VarDecl>(DE->getDecl())) {
11971       Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11972           << 0 << RefExpr->getSourceRange();
11973       continue;
11974     }
11975 
11976     Decl *D = DE->getDecl();
11977     auto *VD = cast<VarDecl>(D);
11978 
11979     QualType Type = VD->getType();
11980     if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11981       // It will be analyzed later.
11982       Vars.push_back(DE);
11983       SrcExprs.push_back(nullptr);
11984       DstExprs.push_back(nullptr);
11985       AssignmentOps.push_back(nullptr);
11986       continue;
11987     }
11988 
11989     // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11990     //  A list item that appears in a copyin clause must be threadprivate.
11991     if (!DSAStack->isThreadPrivate(VD)) {
11992       Diag(ELoc, diag::err_omp_required_access)
11993           << getOpenMPClauseName(OMPC_copyin)
11994           << getOpenMPDirectiveName(OMPD_threadprivate);
11995       continue;
11996     }
11997 
11998     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11999     //  A variable of class type (or array thereof) that appears in a
12000     //  copyin clause requires an accessible, unambiguous copy assignment
12001     //  operator for the class type.
12002     QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12003     VarDecl *SrcVD =
12004         buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
12005                      ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
12006     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
12007         *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
12008     VarDecl *DstVD =
12009         buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
12010                      VD->hasAttrs() ? &VD->getAttrs() : nullptr);
12011     DeclRefExpr *PseudoDstExpr =
12012         buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
12013     // For arrays generate assignment operation for single element and replace
12014     // it by the original array element in CodeGen.
12015     ExprResult AssignmentOp =
12016         BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12017                    PseudoSrcExpr);
12018     if (AssignmentOp.isInvalid())
12019       continue;
12020     AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
12021                                        /*DiscardedValue*/ false);
12022     if (AssignmentOp.isInvalid())
12023       continue;
12024 
12025     DSAStack->addDSA(VD, DE, OMPC_copyin);
12026     Vars.push_back(DE);
12027     SrcExprs.push_back(PseudoSrcExpr);
12028     DstExprs.push_back(PseudoDstExpr);
12029     AssignmentOps.push_back(AssignmentOp.get());
12030   }
12031 
12032   if (Vars.empty())
12033     return nullptr;
12034 
12035   return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12036                                  SrcExprs, DstExprs, AssignmentOps);
12037 }
12038 
12039 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12040                                               SourceLocation StartLoc,
12041                                               SourceLocation LParenLoc,
12042                                               SourceLocation EndLoc) {
12043   SmallVector<Expr *, 8> Vars;
12044   SmallVector<Expr *, 8> SrcExprs;
12045   SmallVector<Expr *, 8> DstExprs;
12046   SmallVector<Expr *, 8> AssignmentOps;
12047   for (Expr *RefExpr : VarList) {
12048     assert(RefExpr && "NULL expr in OpenMP linear clause.");
12049     SourceLocation ELoc;
12050     SourceRange ERange;
12051     Expr *SimpleRefExpr = RefExpr;
12052     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12053     if (Res.second) {
12054       // It will be analyzed later.
12055       Vars.push_back(RefExpr);
12056       SrcExprs.push_back(nullptr);
12057       DstExprs.push_back(nullptr);
12058       AssignmentOps.push_back(nullptr);
12059     }
12060     ValueDecl *D = Res.first;
12061     if (!D)
12062       continue;
12063 
12064     QualType Type = D->getType();
12065     auto *VD = dyn_cast<VarDecl>(D);
12066 
12067     // OpenMP [2.14.4.2, Restrictions, p.2]
12068     //  A list item that appears in a copyprivate clause may not appear in a
12069     //  private or firstprivate clause on the single construct.
12070     if (!VD || !DSAStack->isThreadPrivate(VD)) {
12071       DSAStackTy::DSAVarData DVar =
12072           DSAStack->getTopDSA(D, /*FromParent=*/false);
12073       if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12074           DVar.RefExpr) {
12075         Diag(ELoc, diag::err_omp_wrong_dsa)
12076             << getOpenMPClauseName(DVar.CKind)
12077             << getOpenMPClauseName(OMPC_copyprivate);
12078         reportOriginalDsa(*this, DSAStack, D, DVar);
12079         continue;
12080       }
12081 
12082       // OpenMP [2.11.4.2, Restrictions, p.1]
12083       //  All list items that appear in a copyprivate clause must be either
12084       //  threadprivate or private in the enclosing context.
12085       if (DVar.CKind == OMPC_unknown) {
12086         DVar = DSAStack->getImplicitDSA(D, false);
12087         if (DVar.CKind == OMPC_shared) {
12088           Diag(ELoc, diag::err_omp_required_access)
12089               << getOpenMPClauseName(OMPC_copyprivate)
12090               << "threadprivate or private in the enclosing context";
12091           reportOriginalDsa(*this, DSAStack, D, DVar);
12092           continue;
12093         }
12094       }
12095     }
12096 
12097     // Variably modified types are not supported.
12098     if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
12099       Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12100           << getOpenMPClauseName(OMPC_copyprivate) << Type
12101           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12102       bool IsDecl =
12103           !VD ||
12104           VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12105       Diag(D->getLocation(),
12106            IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12107           << D;
12108       continue;
12109     }
12110 
12111     // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12112     //  A variable of class type (or array thereof) that appears in a
12113     //  copyin clause requires an accessible, unambiguous copy assignment
12114     //  operator for the class type.
12115     Type = Context.getBaseElementType(Type.getNonReferenceType())
12116                .getUnqualifiedType();
12117     VarDecl *SrcVD =
12118         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
12119                      D->hasAttrs() ? &D->getAttrs() : nullptr);
12120     DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12121     VarDecl *DstVD =
12122         buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
12123                      D->hasAttrs() ? &D->getAttrs() : nullptr);
12124     DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12125     ExprResult AssignmentOp = BuildBinOp(
12126         DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
12127     if (AssignmentOp.isInvalid())
12128       continue;
12129     AssignmentOp =
12130         ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
12131     if (AssignmentOp.isInvalid())
12132       continue;
12133 
12134     // No need to mark vars as copyprivate, they are already threadprivate or
12135     // implicitly private.
12136     assert(VD || isOpenMPCapturedDecl(D));
12137     Vars.push_back(
12138         VD ? RefExpr->IgnoreParens()
12139            : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
12140     SrcExprs.push_back(PseudoSrcExpr);
12141     DstExprs.push_back(PseudoDstExpr);
12142     AssignmentOps.push_back(AssignmentOp.get());
12143   }
12144 
12145   if (Vars.empty())
12146     return nullptr;
12147 
12148   return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12149                                       Vars, SrcExprs, DstExprs, AssignmentOps);
12150 }
12151 
12152 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12153                                         SourceLocation StartLoc,
12154                                         SourceLocation LParenLoc,
12155                                         SourceLocation EndLoc) {
12156   if (VarList.empty())
12157     return nullptr;
12158 
12159   return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12160 }
12161 
12162 OMPClause *
12163 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12164                               SourceLocation DepLoc, SourceLocation ColonLoc,
12165                               ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12166                               SourceLocation LParenLoc, SourceLocation EndLoc) {
12167   if (DSAStack->getCurrentDirective() == OMPD_ordered &&
12168       DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
12169     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12170         << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
12171     return nullptr;
12172   }
12173   if (DSAStack->getCurrentDirective() != OMPD_ordered &&
12174       (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12175        DepKind == OMPC_DEPEND_sink)) {
12176     unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
12177     Diag(DepLoc, diag::err_omp_unexpected_clause_value)
12178         << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12179                                    /*Last=*/OMPC_DEPEND_unknown, Except)
12180         << getOpenMPClauseName(OMPC_depend);
12181     return nullptr;
12182   }
12183   SmallVector<Expr *, 8> Vars;
12184   DSAStackTy::OperatorOffsetTy OpsOffs;
12185   llvm::APSInt DepCounter(/*BitWidth=*/32);
12186   llvm::APSInt TotalDepCount(/*BitWidth=*/32);
12187   if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12188     if (const Expr *OrderedCountExpr =
12189             DSAStack->getParentOrderedRegionParam().first) {
12190       TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12191       TotalDepCount.setIsUnsigned(/*Val=*/true);
12192     }
12193   }
12194   for (Expr *RefExpr : VarList) {
12195     assert(RefExpr && "NULL expr in OpenMP shared clause.");
12196     if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12197       // It will be analyzed later.
12198       Vars.push_back(RefExpr);
12199       continue;
12200     }
12201 
12202     SourceLocation ELoc = RefExpr->getExprLoc();
12203     Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
12204     if (DepKind == OMPC_DEPEND_sink) {
12205       if (DSAStack->getParentOrderedRegionParam().first &&
12206           DepCounter >= TotalDepCount) {
12207         Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12208         continue;
12209       }
12210       ++DepCounter;
12211       // OpenMP  [2.13.9, Summary]
12212       // depend(dependence-type : vec), where dependence-type is:
12213       // 'sink' and where vec is the iteration vector, which has the form:
12214       //  x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12215       // where n is the value specified by the ordered clause in the loop
12216       // directive, xi denotes the loop iteration variable of the i-th nested
12217       // loop associated with the loop directive, and di is a constant
12218       // non-negative integer.
12219       if (CurContext->isDependentContext()) {
12220         // It will be analyzed later.
12221         Vars.push_back(RefExpr);
12222         continue;
12223       }
12224       SimpleExpr = SimpleExpr->IgnoreImplicit();
12225       OverloadedOperatorKind OOK = OO_None;
12226       SourceLocation OOLoc;
12227       Expr *LHS = SimpleExpr;
12228       Expr *RHS = nullptr;
12229       if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12230         OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12231         OOLoc = BO->getOperatorLoc();
12232         LHS = BO->getLHS()->IgnoreParenImpCasts();
12233         RHS = BO->getRHS()->IgnoreParenImpCasts();
12234       } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12235         OOK = OCE->getOperator();
12236         OOLoc = OCE->getOperatorLoc();
12237         LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12238         RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12239       } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12240         OOK = MCE->getMethodDecl()
12241                   ->getNameInfo()
12242                   .getName()
12243                   .getCXXOverloadedOperator();
12244         OOLoc = MCE->getCallee()->getExprLoc();
12245         LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12246         RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12247       }
12248       SourceLocation ELoc;
12249       SourceRange ERange;
12250       auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
12251       if (Res.second) {
12252         // It will be analyzed later.
12253         Vars.push_back(RefExpr);
12254       }
12255       ValueDecl *D = Res.first;
12256       if (!D)
12257         continue;
12258 
12259       if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12260         Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12261         continue;
12262       }
12263       if (RHS) {
12264         ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12265             RHS, OMPC_depend, /*StrictlyPositive=*/false);
12266         if (RHSRes.isInvalid())
12267           continue;
12268       }
12269       if (!CurContext->isDependentContext() &&
12270           DSAStack->getParentOrderedRegionParam().first &&
12271           DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
12272         const ValueDecl *VD =
12273             DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
12274         if (VD)
12275           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12276               << 1 << VD;
12277         else
12278           Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
12279         continue;
12280       }
12281       OpsOffs.emplace_back(RHS, OOK);
12282     } else {
12283       auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12284       if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12285           (ASE &&
12286            !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12287            !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12288         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12289             << RefExpr->getSourceRange();
12290         continue;
12291       }
12292       bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12293       getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12294       ExprResult Res =
12295           CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12296       getDiagnostics().setSuppressAllDiagnostics(Suppress);
12297       if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12298         Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12299             << RefExpr->getSourceRange();
12300         continue;
12301       }
12302     }
12303     Vars.push_back(RefExpr->IgnoreParenImpCasts());
12304   }
12305 
12306   if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12307       TotalDepCount > VarList.size() &&
12308       DSAStack->getParentOrderedRegionParam().first &&
12309       DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12310     Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12311         << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12312   }
12313   if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12314       Vars.empty())
12315     return nullptr;
12316 
12317   auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12318                                     DepKind, DepLoc, ColonLoc, Vars,
12319                                     TotalDepCount.getZExtValue());
12320   if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12321       DSAStack->isParentOrderedRegion())
12322     DSAStack->addDoacrossDependClause(C, OpsOffs);
12323   return C;
12324 }
12325 
12326 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12327                                          SourceLocation LParenLoc,
12328                                          SourceLocation EndLoc) {
12329   Expr *ValExpr = Device;
12330   Stmt *HelperValStmt = nullptr;
12331 
12332   // OpenMP [2.9.1, Restrictions]
12333   // The device expression must evaluate to a non-negative integer value.
12334   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
12335                                  /*StrictlyPositive=*/false))
12336     return nullptr;
12337 
12338   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
12339   OpenMPDirectiveKind CaptureRegion =
12340       getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12341   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
12342     ValExpr = MakeFullExpr(ValExpr).get();
12343     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
12344     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12345     HelperValStmt = buildPreInits(Context, Captures);
12346   }
12347 
12348   return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12349                                        StartLoc, LParenLoc, EndLoc);
12350 }
12351 
12352 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
12353                               DSAStackTy *Stack, QualType QTy,
12354                               bool FullCheck = true) {
12355   NamedDecl *ND;
12356   if (QTy->isIncompleteType(&ND)) {
12357     SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12358     return false;
12359   }
12360   if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12361       !QTy.isTrivialType(SemaRef.Context))
12362     SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
12363   return true;
12364 }
12365 
12366 /// Return true if it can be proven that the provided array expression
12367 /// (array section or array subscript) does NOT specify the whole size of the
12368 /// array whose base type is \a BaseQTy.
12369 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
12370                                                         const Expr *E,
12371                                                         QualType BaseQTy) {
12372   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12373 
12374   // If this is an array subscript, it refers to the whole size if the size of
12375   // the dimension is constant and equals 1. Also, an array section assumes the
12376   // format of an array subscript if no colon is used.
12377   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
12378     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12379       return ATy->getSize().getSExtValue() != 1;
12380     // Size can't be evaluated statically.
12381     return false;
12382   }
12383 
12384   assert(OASE && "Expecting array section if not an array subscript.");
12385   const Expr *LowerBound = OASE->getLowerBound();
12386   const Expr *Length = OASE->getLength();
12387 
12388   // If there is a lower bound that does not evaluates to zero, we are not
12389   // covering the whole dimension.
12390   if (LowerBound) {
12391     Expr::EvalResult Result;
12392     if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
12393       return false; // Can't get the integer value as a constant.
12394 
12395     llvm::APSInt ConstLowerBound = Result.Val.getInt();
12396     if (ConstLowerBound.getSExtValue())
12397       return true;
12398   }
12399 
12400   // If we don't have a length we covering the whole dimension.
12401   if (!Length)
12402     return false;
12403 
12404   // If the base is a pointer, we don't have a way to get the size of the
12405   // pointee.
12406   if (BaseQTy->isPointerType())
12407     return false;
12408 
12409   // We can only check if the length is the same as the size of the dimension
12410   // if we have a constant array.
12411   const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
12412   if (!CATy)
12413     return false;
12414 
12415   Expr::EvalResult Result;
12416   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
12417     return false; // Can't get the integer value as a constant.
12418 
12419   llvm::APSInt ConstLength = Result.Val.getInt();
12420   return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12421 }
12422 
12423 // Return true if it can be proven that the provided array expression (array
12424 // section or array subscript) does NOT specify a single element of the array
12425 // whose base type is \a BaseQTy.
12426 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
12427                                                         const Expr *E,
12428                                                         QualType BaseQTy) {
12429   const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
12430 
12431   // An array subscript always refer to a single element. Also, an array section
12432   // assumes the format of an array subscript if no colon is used.
12433   if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12434     return false;
12435 
12436   assert(OASE && "Expecting array section if not an array subscript.");
12437   const Expr *Length = OASE->getLength();
12438 
12439   // If we don't have a length we have to check if the array has unitary size
12440   // for this dimension. Also, we should always expect a length if the base type
12441   // is pointer.
12442   if (!Length) {
12443     if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
12444       return ATy->getSize().getSExtValue() != 1;
12445     // We cannot assume anything.
12446     return false;
12447   }
12448 
12449   // Check if the length evaluates to 1.
12450   Expr::EvalResult Result;
12451   if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
12452     return false; // Can't get the integer value as a constant.
12453 
12454   llvm::APSInt ConstLength = Result.Val.getInt();
12455   return ConstLength.getSExtValue() != 1;
12456 }
12457 
12458 // Return the expression of the base of the mappable expression or null if it
12459 // cannot be determined and do all the necessary checks to see if the expression
12460 // is valid as a standalone mappable expression. In the process, record all the
12461 // components of the expression.
12462 static const Expr *checkMapClauseExpressionBase(
12463     Sema &SemaRef, Expr *E,
12464     OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
12465     OpenMPClauseKind CKind, bool NoDiagnose) {
12466   SourceLocation ELoc = E->getExprLoc();
12467   SourceRange ERange = E->getSourceRange();
12468 
12469   // The base of elements of list in a map clause have to be either:
12470   //  - a reference to variable or field.
12471   //  - a member expression.
12472   //  - an array expression.
12473   //
12474   // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12475   // reference to 'r'.
12476   //
12477   // If we have:
12478   //
12479   // struct SS {
12480   //   Bla S;
12481   //   foo() {
12482   //     #pragma omp target map (S.Arr[:12]);
12483   //   }
12484   // }
12485   //
12486   // We want to retrieve the member expression 'this->S';
12487 
12488   const Expr *RelevantExpr = nullptr;
12489 
12490   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12491   //  If a list item is an array section, it must specify contiguous storage.
12492   //
12493   // For this restriction it is sufficient that we make sure only references
12494   // to variables or fields and array expressions, and that no array sections
12495   // exist except in the rightmost expression (unless they cover the whole
12496   // dimension of the array). E.g. these would be invalid:
12497   //
12498   //   r.ArrS[3:5].Arr[6:7]
12499   //
12500   //   r.ArrS[3:5].x
12501   //
12502   // but these would be valid:
12503   //   r.ArrS[3].Arr[6:7]
12504   //
12505   //   r.ArrS[3].x
12506 
12507   bool AllowUnitySizeArraySection = true;
12508   bool AllowWholeSizeArraySection = true;
12509 
12510   while (!RelevantExpr) {
12511     E = E->IgnoreParenImpCasts();
12512 
12513     if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12514       if (!isa<VarDecl>(CurE->getDecl()))
12515         return nullptr;
12516 
12517       RelevantExpr = CurE;
12518 
12519       // If we got a reference to a declaration, we should not expect any array
12520       // section before that.
12521       AllowUnitySizeArraySection = false;
12522       AllowWholeSizeArraySection = false;
12523 
12524       // Record the component.
12525       CurComponents.emplace_back(CurE, CurE->getDecl());
12526     } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
12527       Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
12528 
12529       if (isa<CXXThisExpr>(BaseE))
12530         // We found a base expression: this->Val.
12531         RelevantExpr = CurE;
12532       else
12533         E = BaseE;
12534 
12535       if (!isa<FieldDecl>(CurE->getMemberDecl())) {
12536         if (!NoDiagnose) {
12537           SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12538               << CurE->getSourceRange();
12539           return nullptr;
12540         }
12541         if (RelevantExpr)
12542           return nullptr;
12543         continue;
12544       }
12545 
12546       auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12547 
12548       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12549       //  A bit-field cannot appear in a map clause.
12550       //
12551       if (FD->isBitField()) {
12552         if (!NoDiagnose) {
12553           SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12554               << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12555           return nullptr;
12556         }
12557         if (RelevantExpr)
12558           return nullptr;
12559         continue;
12560       }
12561 
12562       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12563       //  If the type of a list item is a reference to a type T then the type
12564       //  will be considered to be T for all purposes of this clause.
12565       QualType CurType = BaseE->getType().getNonReferenceType();
12566 
12567       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12568       //  A list item cannot be a variable that is a member of a structure with
12569       //  a union type.
12570       //
12571       if (CurType->isUnionType()) {
12572         if (!NoDiagnose) {
12573           SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12574               << CurE->getSourceRange();
12575           return nullptr;
12576         }
12577         continue;
12578       }
12579 
12580       // If we got a member expression, we should not expect any array section
12581       // before that:
12582       //
12583       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12584       //  If a list item is an element of a structure, only the rightmost symbol
12585       //  of the variable reference can be an array section.
12586       //
12587       AllowUnitySizeArraySection = false;
12588       AllowWholeSizeArraySection = false;
12589 
12590       // Record the component.
12591       CurComponents.emplace_back(CurE, FD);
12592     } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
12593       E = CurE->getBase()->IgnoreParenImpCasts();
12594 
12595       if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
12596         if (!NoDiagnose) {
12597           SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12598               << 0 << CurE->getSourceRange();
12599           return nullptr;
12600         }
12601         continue;
12602       }
12603 
12604       // If we got an array subscript that express the whole dimension we
12605       // can have any array expressions before. If it only expressing part of
12606       // the dimension, we can only have unitary-size array expressions.
12607       if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
12608                                                       E->getType()))
12609         AllowWholeSizeArraySection = false;
12610 
12611       if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12612         Expr::EvalResult Result;
12613         if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12614           if (!Result.Val.getInt().isNullValue()) {
12615             SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12616                          diag::err_omp_invalid_map_this_expr);
12617             SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12618                          diag::note_omp_invalid_subscript_on_this_ptr_map);
12619           }
12620         }
12621         RelevantExpr = TE;
12622       }
12623 
12624       // Record the component - we don't have any declaration associated.
12625       CurComponents.emplace_back(CurE, nullptr);
12626     } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
12627       assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
12628       E = CurE->getBase()->IgnoreParenImpCasts();
12629 
12630       QualType CurType =
12631           OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12632 
12633       // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12634       //  If the type of a list item is a reference to a type T then the type
12635       //  will be considered to be T for all purposes of this clause.
12636       if (CurType->isReferenceType())
12637         CurType = CurType->getPointeeType();
12638 
12639       bool IsPointer = CurType->isAnyPointerType();
12640 
12641       if (!IsPointer && !CurType->isArrayType()) {
12642         SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12643             << 0 << CurE->getSourceRange();
12644         return nullptr;
12645       }
12646 
12647       bool NotWhole =
12648           checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
12649       bool NotUnity =
12650           checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
12651 
12652       if (AllowWholeSizeArraySection) {
12653         // Any array section is currently allowed. Allowing a whole size array
12654         // section implies allowing a unity array section as well.
12655         //
12656         // If this array section refers to the whole dimension we can still
12657         // accept other array sections before this one, except if the base is a
12658         // pointer. Otherwise, only unitary sections are accepted.
12659         if (NotWhole || IsPointer)
12660           AllowWholeSizeArraySection = false;
12661       } else if (AllowUnitySizeArraySection && NotUnity) {
12662         // A unity or whole array section is not allowed and that is not
12663         // compatible with the properties of the current array section.
12664         SemaRef.Diag(
12665             ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
12666             << CurE->getSourceRange();
12667         return nullptr;
12668       }
12669 
12670       if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12671         Expr::EvalResult ResultR;
12672         Expr::EvalResult ResultL;
12673         if (CurE->getLength()->EvaluateAsInt(ResultR,
12674                                              SemaRef.getASTContext())) {
12675           if (!ResultR.Val.getInt().isOneValue()) {
12676             SemaRef.Diag(CurE->getLength()->getExprLoc(),
12677                          diag::err_omp_invalid_map_this_expr);
12678             SemaRef.Diag(CurE->getLength()->getExprLoc(),
12679                          diag::note_omp_invalid_length_on_this_ptr_mapping);
12680           }
12681         }
12682         if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
12683                                         ResultL, SemaRef.getASTContext())) {
12684           if (!ResultL.Val.getInt().isNullValue()) {
12685             SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12686                          diag::err_omp_invalid_map_this_expr);
12687             SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12688                          diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
12689           }
12690         }
12691         RelevantExpr = TE;
12692       }
12693 
12694       // Record the component - we don't have any declaration associated.
12695       CurComponents.emplace_back(CurE, nullptr);
12696     } else {
12697       if (!NoDiagnose) {
12698         // If nothing else worked, this is not a valid map clause expression.
12699         SemaRef.Diag(
12700             ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
12701             << ERange;
12702       }
12703       return nullptr;
12704     }
12705   }
12706 
12707   return RelevantExpr;
12708 }
12709 
12710 // Return true if expression E associated with value VD has conflicts with other
12711 // map information.
12712 static bool checkMapConflicts(
12713     Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
12714     bool CurrentRegionOnly,
12715     OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
12716     OpenMPClauseKind CKind) {
12717   assert(VD && E);
12718   SourceLocation ELoc = E->getExprLoc();
12719   SourceRange ERange = E->getSourceRange();
12720 
12721   // In order to easily check the conflicts we need to match each component of
12722   // the expression under test with the components of the expressions that are
12723   // already in the stack.
12724 
12725   assert(!CurComponents.empty() && "Map clause expression with no components!");
12726   assert(CurComponents.back().getAssociatedDeclaration() == VD &&
12727          "Map clause expression with unexpected base!");
12728 
12729   // Variables to help detecting enclosing problems in data environment nests.
12730   bool IsEnclosedByDataEnvironmentExpr = false;
12731   const Expr *EnclosingExpr = nullptr;
12732 
12733   bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
12734       VD, CurrentRegionOnly,
12735       [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
12736        ERange, CKind, &EnclosingExpr,
12737        CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
12738                           StackComponents,
12739                       OpenMPClauseKind) {
12740         assert(!StackComponents.empty() &&
12741                "Map clause expression with no components!");
12742         assert(StackComponents.back().getAssociatedDeclaration() == VD &&
12743                "Map clause expression with unexpected base!");
12744         (void)VD;
12745 
12746         // The whole expression in the stack.
12747         const Expr *RE = StackComponents.front().getAssociatedExpression();
12748 
12749         // Expressions must start from the same base. Here we detect at which
12750         // point both expressions diverge from each other and see if we can
12751         // detect if the memory referred to both expressions is contiguous and
12752         // do not overlap.
12753         auto CI = CurComponents.rbegin();
12754         auto CE = CurComponents.rend();
12755         auto SI = StackComponents.rbegin();
12756         auto SE = StackComponents.rend();
12757         for (; CI != CE && SI != SE; ++CI, ++SI) {
12758 
12759           // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12760           //  At most one list item can be an array item derived from a given
12761           //  variable in map clauses of the same construct.
12762           if (CurrentRegionOnly &&
12763               (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12764                isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12765               (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12766                isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12767             SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
12768                          diag::err_omp_multiple_array_items_in_map_clause)
12769                 << CI->getAssociatedExpression()->getSourceRange();
12770             SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12771                          diag::note_used_here)
12772                 << SI->getAssociatedExpression()->getSourceRange();
12773             return true;
12774           }
12775 
12776           // Do both expressions have the same kind?
12777           if (CI->getAssociatedExpression()->getStmtClass() !=
12778               SI->getAssociatedExpression()->getStmtClass())
12779             break;
12780 
12781           // Are we dealing with different variables/fields?
12782           if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
12783             break;
12784         }
12785         // Check if the extra components of the expressions in the enclosing
12786         // data environment are redundant for the current base declaration.
12787         // If they are, the maps completely overlap, which is legal.
12788         for (; SI != SE; ++SI) {
12789           QualType Type;
12790           if (const auto *ASE =
12791                   dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
12792             Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
12793           } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
12794                          SI->getAssociatedExpression())) {
12795             const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
12796             Type =
12797                 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12798           }
12799           if (Type.isNull() || Type->isAnyPointerType() ||
12800               checkArrayExpressionDoesNotReferToWholeSize(
12801                   SemaRef, SI->getAssociatedExpression(), Type))
12802             break;
12803         }
12804 
12805         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12806         //  List items of map clauses in the same construct must not share
12807         //  original storage.
12808         //
12809         // If the expressions are exactly the same or one is a subset of the
12810         // other, it means they are sharing storage.
12811         if (CI == CE && SI == SE) {
12812           if (CurrentRegionOnly) {
12813             if (CKind == OMPC_map) {
12814               SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12815             } else {
12816               assert(CKind == OMPC_to || CKind == OMPC_from);
12817               SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12818                   << ERange;
12819             }
12820             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12821                 << RE->getSourceRange();
12822             return true;
12823           }
12824           // If we find the same expression in the enclosing data environment,
12825           // that is legal.
12826           IsEnclosedByDataEnvironmentExpr = true;
12827           return false;
12828         }
12829 
12830         QualType DerivedType =
12831             std::prev(CI)->getAssociatedDeclaration()->getType();
12832         SourceLocation DerivedLoc =
12833             std::prev(CI)->getAssociatedExpression()->getExprLoc();
12834 
12835         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12836         //  If the type of a list item is a reference to a type T then the type
12837         //  will be considered to be T for all purposes of this clause.
12838         DerivedType = DerivedType.getNonReferenceType();
12839 
12840         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12841         //  A variable for which the type is pointer and an array section
12842         //  derived from that variable must not appear as list items of map
12843         //  clauses of the same construct.
12844         //
12845         // Also, cover one of the cases in:
12846         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12847         //  If any part of the original storage of a list item has corresponding
12848         //  storage in the device data environment, all of the original storage
12849         //  must have corresponding storage in the device data environment.
12850         //
12851         if (DerivedType->isAnyPointerType()) {
12852           if (CI == CE || SI == SE) {
12853             SemaRef.Diag(
12854                 DerivedLoc,
12855                 diag::err_omp_pointer_mapped_along_with_derived_section)
12856                 << DerivedLoc;
12857             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12858                 << RE->getSourceRange();
12859             return true;
12860           }
12861           if (CI->getAssociatedExpression()->getStmtClass() !=
12862                          SI->getAssociatedExpression()->getStmtClass() ||
12863                      CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12864                          SI->getAssociatedDeclaration()->getCanonicalDecl()) {
12865             assert(CI != CE && SI != SE);
12866             SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
12867                 << DerivedLoc;
12868             SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12869                 << RE->getSourceRange();
12870             return true;
12871           }
12872         }
12873 
12874         // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12875         //  List items of map clauses in the same construct must not share
12876         //  original storage.
12877         //
12878         // An expression is a subset of the other.
12879         if (CurrentRegionOnly && (CI == CE || SI == SE)) {
12880           if (CKind == OMPC_map) {
12881             if (CI != CE || SI != SE) {
12882               // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
12883               // a pointer.
12884               auto Begin =
12885                   CI != CE ? CurComponents.begin() : StackComponents.begin();
12886               auto End = CI != CE ? CurComponents.end() : StackComponents.end();
12887               auto It = Begin;
12888               while (It != End && !It->getAssociatedDeclaration())
12889                 std::advance(It, 1);
12890               assert(It != End &&
12891                      "Expected at least one component with the declaration.");
12892               if (It != Begin && It->getAssociatedDeclaration()
12893                                      ->getType()
12894                                      .getCanonicalType()
12895                                      ->isAnyPointerType()) {
12896                 IsEnclosedByDataEnvironmentExpr = false;
12897                 EnclosingExpr = nullptr;
12898                 return false;
12899               }
12900             }
12901             SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12902           } else {
12903             assert(CKind == OMPC_to || CKind == OMPC_from);
12904             SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12905                 << ERange;
12906           }
12907           SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12908               << RE->getSourceRange();
12909           return true;
12910         }
12911 
12912         // The current expression uses the same base as other expression in the
12913         // data environment but does not contain it completely.
12914         if (!CurrentRegionOnly && SI != SE)
12915           EnclosingExpr = RE;
12916 
12917         // The current expression is a subset of the expression in the data
12918         // environment.
12919         IsEnclosedByDataEnvironmentExpr |=
12920             (!CurrentRegionOnly && CI != CE && SI == SE);
12921 
12922         return false;
12923       });
12924 
12925   if (CurrentRegionOnly)
12926     return FoundError;
12927 
12928   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12929   //  If any part of the original storage of a list item has corresponding
12930   //  storage in the device data environment, all of the original storage must
12931   //  have corresponding storage in the device data environment.
12932   // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12933   //  If a list item is an element of a structure, and a different element of
12934   //  the structure has a corresponding list item in the device data environment
12935   //  prior to a task encountering the construct associated with the map clause,
12936   //  then the list item must also have a corresponding list item in the device
12937   //  data environment prior to the task encountering the construct.
12938   //
12939   if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12940     SemaRef.Diag(ELoc,
12941                  diag::err_omp_original_storage_is_shared_and_does_not_contain)
12942         << ERange;
12943     SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12944         << EnclosingExpr->getSourceRange();
12945     return true;
12946   }
12947 
12948   return FoundError;
12949 }
12950 
12951 namespace {
12952 // Utility struct that gathers all the related lists associated with a mappable
12953 // expression.
12954 struct MappableVarListInfo {
12955   // The list of expressions.
12956   ArrayRef<Expr *> VarList;
12957   // The list of processed expressions.
12958   SmallVector<Expr *, 16> ProcessedVarList;
12959   // The mappble components for each expression.
12960   OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12961   // The base declaration of the variable.
12962   SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12963 
12964   MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12965     // We have a list of components and base declarations for each entry in the
12966     // variable list.
12967     VarComponents.reserve(VarList.size());
12968     VarBaseDeclarations.reserve(VarList.size());
12969   }
12970 };
12971 }
12972 
12973 // Check the validity of the provided variable list for the provided clause kind
12974 // \a CKind. In the check process the valid expressions, and mappable expression
12975 // components and variables are extracted and used to fill \a Vars,
12976 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12977 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12978 static void
12979 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12980                             OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12981                             SourceLocation StartLoc,
12982                             OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12983                             bool IsMapTypeImplicit = false) {
12984   // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12985   assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
12986          "Unexpected clause kind with mappable expressions!");
12987 
12988   // Keep track of the mappable components and base declarations in this clause.
12989   // Each entry in the list is going to have a list of components associated. We
12990   // record each set of the components so that we can build the clause later on.
12991   // In the end we should have the same amount of declarations and component
12992   // lists.
12993 
12994   for (Expr *RE : MVLI.VarList) {
12995     assert(RE && "Null expr in omp to/from/map clause");
12996     SourceLocation ELoc = RE->getExprLoc();
12997 
12998     const Expr *VE = RE->IgnoreParenLValueCasts();
12999 
13000     if (VE->isValueDependent() || VE->isTypeDependent() ||
13001         VE->isInstantiationDependent() ||
13002         VE->containsUnexpandedParameterPack()) {
13003       // We can only analyze this information once the missing information is
13004       // resolved.
13005       MVLI.ProcessedVarList.push_back(RE);
13006       continue;
13007     }
13008 
13009     Expr *SimpleExpr = RE->IgnoreParenCasts();
13010 
13011     if (!RE->IgnoreParenImpCasts()->isLValue()) {
13012       SemaRef.Diag(ELoc,
13013                    diag::err_omp_expected_named_var_member_or_array_expression)
13014           << RE->getSourceRange();
13015       continue;
13016     }
13017 
13018     OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13019     ValueDecl *CurDeclaration = nullptr;
13020 
13021     // Obtain the array or member expression bases if required. Also, fill the
13022     // components array with all the components identified in the process.
13023     const Expr *BE = checkMapClauseExpressionBase(
13024         SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
13025     if (!BE)
13026       continue;
13027 
13028     assert(!CurComponents.empty() &&
13029            "Invalid mappable expression information.");
13030 
13031     if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13032       // Add store "this" pointer to class in DSAStackTy for future checking
13033       DSAS->addMappedClassesQualTypes(TE->getType());
13034       // Skip restriction checking for variable or field declarations
13035       MVLI.ProcessedVarList.push_back(RE);
13036       MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13037       MVLI.VarComponents.back().append(CurComponents.begin(),
13038                                        CurComponents.end());
13039       MVLI.VarBaseDeclarations.push_back(nullptr);
13040       continue;
13041     }
13042 
13043     // For the following checks, we rely on the base declaration which is
13044     // expected to be associated with the last component. The declaration is
13045     // expected to be a variable or a field (if 'this' is being mapped).
13046     CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13047     assert(CurDeclaration && "Null decl on map clause.");
13048     assert(
13049         CurDeclaration->isCanonicalDecl() &&
13050         "Expecting components to have associated only canonical declarations.");
13051 
13052     auto *VD = dyn_cast<VarDecl>(CurDeclaration);
13053     const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
13054 
13055     assert((VD || FD) && "Only variables or fields are expected here!");
13056     (void)FD;
13057 
13058     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
13059     // threadprivate variables cannot appear in a map clause.
13060     // OpenMP 4.5 [2.10.5, target update Construct]
13061     // threadprivate variables cannot appear in a from clause.
13062     if (VD && DSAS->isThreadPrivate(VD)) {
13063       DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
13064       SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13065           << getOpenMPClauseName(CKind);
13066       reportOriginalDsa(SemaRef, DSAS, VD, DVar);
13067       continue;
13068     }
13069 
13070     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13071     //  A list item cannot appear in both a map clause and a data-sharing
13072     //  attribute clause on the same construct.
13073 
13074     // Check conflicts with other map clause expressions. We check the conflicts
13075     // with the current construct separately from the enclosing data
13076     // environment, because the restrictions are different. We only have to
13077     // check conflicts across regions for the map clauses.
13078     if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
13079                           /*CurrentRegionOnly=*/true, CurComponents, CKind))
13080       break;
13081     if (CKind == OMPC_map &&
13082         checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
13083                           /*CurrentRegionOnly=*/false, CurComponents, CKind))
13084       break;
13085 
13086     // OpenMP 4.5 [2.10.5, target update Construct]
13087     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13088     //  If the type of a list item is a reference to a type T then the type will
13089     //  be considered to be T for all purposes of this clause.
13090     auto I = llvm::find_if(
13091         CurComponents,
13092         [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13093           return MC.getAssociatedDeclaration();
13094         });
13095     assert(I != CurComponents.end() && "Null decl on map clause.");
13096     QualType Type =
13097         I->getAssociatedDeclaration()->getType().getNonReferenceType();
13098 
13099     // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13100     // A list item in a to or from clause must have a mappable type.
13101     // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13102     //  A list item must have a mappable type.
13103     if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
13104                            DSAS, Type))
13105       continue;
13106 
13107     if (CKind == OMPC_map) {
13108       // target enter data
13109       // OpenMP [2.10.2, Restrictions, p. 99]
13110       // A map-type must be specified in all map clauses and must be either
13111       // to or alloc.
13112       OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13113       if (DKind == OMPD_target_enter_data &&
13114           !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13115         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13116             << (IsMapTypeImplicit ? 1 : 0)
13117             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13118             << getOpenMPDirectiveName(DKind);
13119         continue;
13120       }
13121 
13122       // target exit_data
13123       // OpenMP [2.10.3, Restrictions, p. 102]
13124       // A map-type must be specified in all map clauses and must be either
13125       // from, release, or delete.
13126       if (DKind == OMPD_target_exit_data &&
13127           !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13128             MapType == OMPC_MAP_delete)) {
13129         SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13130             << (IsMapTypeImplicit ? 1 : 0)
13131             << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13132             << getOpenMPDirectiveName(DKind);
13133         continue;
13134       }
13135 
13136       // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13137       // A list item cannot appear in both a map clause and a data-sharing
13138       // attribute clause on the same construct
13139       if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13140         DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
13141         if (isOpenMPPrivate(DVar.CKind)) {
13142           SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13143               << getOpenMPClauseName(DVar.CKind)
13144               << getOpenMPClauseName(OMPC_map)
13145               << getOpenMPDirectiveName(DSAS->getCurrentDirective());
13146           reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
13147           continue;
13148         }
13149       }
13150     }
13151 
13152     // Save the current expression.
13153     MVLI.ProcessedVarList.push_back(RE);
13154 
13155     // Store the components in the stack so that they can be used to check
13156     // against other clauses later on.
13157     DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13158                                           /*WhereFoundClauseKind=*/OMPC_map);
13159 
13160     // Save the components and declaration to create the clause. For purposes of
13161     // the clause creation, any component list that has has base 'this' uses
13162     // null as base declaration.
13163     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13164     MVLI.VarComponents.back().append(CurComponents.begin(),
13165                                      CurComponents.end());
13166     MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13167                                                            : CurDeclaration);
13168   }
13169 }
13170 
13171 OMPClause *
13172 Sema::ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13173                            ArrayRef<SourceLocation> MapTypeModifiersLoc,
13174                            OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
13175                            SourceLocation MapLoc, SourceLocation ColonLoc,
13176                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
13177                            SourceLocation LParenLoc, SourceLocation EndLoc) {
13178   MappableVarListInfo MVLI(VarList);
13179   checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
13180                               MapType, IsMapTypeImplicit);
13181 
13182   OpenMPMapModifierKind Modifiers[] = { OMPC_MAP_MODIFIER_unknown,
13183                                         OMPC_MAP_MODIFIER_unknown };
13184   SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13185 
13186   // Process map-type-modifiers, flag errors for duplicate modifiers.
13187   unsigned Count = 0;
13188   for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13189     if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13190         llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13191       Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13192       continue;
13193     }
13194     assert(Count < OMPMapClause::NumberOfModifiers &&
13195            "Modifiers exceed the allowed number of map type modifiers");
13196     Modifiers[Count] = MapTypeModifiers[I];
13197     ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13198     ++Count;
13199   }
13200 
13201   // We need to produce a map clause even if we don't have variables so that
13202   // other diagnostics related with non-existing map clauses are accurate.
13203   return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13204                               MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13205                               MVLI.VarComponents, Modifiers, ModifiersLoc,
13206                               MapType, IsMapTypeImplicit, MapLoc);
13207 }
13208 
13209 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13210                                                TypeResult ParsedType) {
13211   assert(ParsedType.isUsable());
13212 
13213   QualType ReductionType = GetTypeFromParser(ParsedType.get());
13214   if (ReductionType.isNull())
13215     return QualType();
13216 
13217   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13218   // A type name in a declare reduction directive cannot be a function type, an
13219   // array type, a reference type, or a type qualified with const, volatile or
13220   // restrict.
13221   if (ReductionType.hasQualifiers()) {
13222     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13223     return QualType();
13224   }
13225 
13226   if (ReductionType->isFunctionType()) {
13227     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13228     return QualType();
13229   }
13230   if (ReductionType->isReferenceType()) {
13231     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13232     return QualType();
13233   }
13234   if (ReductionType->isArrayType()) {
13235     Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13236     return QualType();
13237   }
13238   return ReductionType;
13239 }
13240 
13241 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13242     Scope *S, DeclContext *DC, DeclarationName Name,
13243     ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13244     AccessSpecifier AS, Decl *PrevDeclInScope) {
13245   SmallVector<Decl *, 8> Decls;
13246   Decls.reserve(ReductionTypes.size());
13247 
13248   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
13249                       forRedeclarationInCurContext());
13250   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13251   // A reduction-identifier may not be re-declared in the current scope for the
13252   // same type or for a type that is compatible according to the base language
13253   // rules.
13254   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13255   OMPDeclareReductionDecl *PrevDRD = nullptr;
13256   bool InCompoundScope = true;
13257   if (S != nullptr) {
13258     // Find previous declaration with the same name not referenced in other
13259     // declarations.
13260     FunctionScopeInfo *ParentFn = getEnclosingFunction();
13261     InCompoundScope =
13262         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13263     LookupName(Lookup, S);
13264     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13265                          /*AllowInlineNamespace=*/false);
13266     llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
13267     LookupResult::Filter Filter = Lookup.makeFilter();
13268     while (Filter.hasNext()) {
13269       auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13270       if (InCompoundScope) {
13271         auto I = UsedAsPrevious.find(PrevDecl);
13272         if (I == UsedAsPrevious.end())
13273           UsedAsPrevious[PrevDecl] = false;
13274         if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
13275           UsedAsPrevious[D] = true;
13276       }
13277       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13278           PrevDecl->getLocation();
13279     }
13280     Filter.done();
13281     if (InCompoundScope) {
13282       for (const auto &PrevData : UsedAsPrevious) {
13283         if (!PrevData.second) {
13284           PrevDRD = PrevData.first;
13285           break;
13286         }
13287       }
13288     }
13289   } else if (PrevDeclInScope != nullptr) {
13290     auto *PrevDRDInScope = PrevDRD =
13291         cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13292     do {
13293       PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13294           PrevDRDInScope->getLocation();
13295       PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13296     } while (PrevDRDInScope != nullptr);
13297   }
13298   for (const auto &TyData : ReductionTypes) {
13299     const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
13300     bool Invalid = false;
13301     if (I != PreviousRedeclTypes.end()) {
13302       Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13303           << TyData.first;
13304       Diag(I->second, diag::note_previous_definition);
13305       Invalid = true;
13306     }
13307     PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13308     auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13309                                                 Name, TyData.first, PrevDRD);
13310     DC->addDecl(DRD);
13311     DRD->setAccess(AS);
13312     Decls.push_back(DRD);
13313     if (Invalid)
13314       DRD->setInvalidDecl();
13315     else
13316       PrevDRD = DRD;
13317   }
13318 
13319   return DeclGroupPtrTy::make(
13320       DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13321 }
13322 
13323 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13324   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13325 
13326   // Enter new function scope.
13327   PushFunctionScope();
13328   setFunctionHasBranchProtectedScope();
13329   getCurFunction()->setHasOMPDeclareReductionCombiner();
13330 
13331   if (S != nullptr)
13332     PushDeclContext(S, DRD);
13333   else
13334     CurContext = DRD;
13335 
13336   PushExpressionEvaluationContext(
13337       ExpressionEvaluationContext::PotentiallyEvaluated);
13338 
13339   QualType ReductionType = DRD->getType();
13340   // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13341   // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13342   // uses semantics of argument handles by value, but it should be passed by
13343   // reference. C lang does not support references, so pass all parameters as
13344   // pointers.
13345   // Create 'T omp_in;' variable.
13346   VarDecl *OmpInParm =
13347       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
13348   // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13349   // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13350   // uses semantics of argument handles by value, but it should be passed by
13351   // reference. C lang does not support references, so pass all parameters as
13352   // pointers.
13353   // Create 'T omp_out;' variable.
13354   VarDecl *OmpOutParm =
13355       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13356   if (S != nullptr) {
13357     PushOnScopeChains(OmpInParm, S);
13358     PushOnScopeChains(OmpOutParm, S);
13359   } else {
13360     DRD->addDecl(OmpInParm);
13361     DRD->addDecl(OmpOutParm);
13362   }
13363   Expr *InE =
13364       ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13365   Expr *OutE =
13366       ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13367   DRD->setCombinerData(InE, OutE);
13368 }
13369 
13370 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13371   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13372   DiscardCleanupsInEvaluationContext();
13373   PopExpressionEvaluationContext();
13374 
13375   PopDeclContext();
13376   PopFunctionScopeInfo();
13377 
13378   if (Combiner != nullptr)
13379     DRD->setCombiner(Combiner);
13380   else
13381     DRD->setInvalidDecl();
13382 }
13383 
13384 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
13385   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13386 
13387   // Enter new function scope.
13388   PushFunctionScope();
13389   setFunctionHasBranchProtectedScope();
13390 
13391   if (S != nullptr)
13392     PushDeclContext(S, DRD);
13393   else
13394     CurContext = DRD;
13395 
13396   PushExpressionEvaluationContext(
13397       ExpressionEvaluationContext::PotentiallyEvaluated);
13398 
13399   QualType ReductionType = DRD->getType();
13400   // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13401   // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13402   // uses semantics of argument handles by value, but it should be passed by
13403   // reference. C lang does not support references, so pass all parameters as
13404   // pointers.
13405   // Create 'T omp_priv;' variable.
13406   VarDecl *OmpPrivParm =
13407       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
13408   // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13409   // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13410   // uses semantics of argument handles by value, but it should be passed by
13411   // reference. C lang does not support references, so pass all parameters as
13412   // pointers.
13413   // Create 'T omp_orig;' variable.
13414   VarDecl *OmpOrigParm =
13415       buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
13416   if (S != nullptr) {
13417     PushOnScopeChains(OmpPrivParm, S);
13418     PushOnScopeChains(OmpOrigParm, S);
13419   } else {
13420     DRD->addDecl(OmpPrivParm);
13421     DRD->addDecl(OmpOrigParm);
13422   }
13423   Expr *OrigE =
13424       ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13425   Expr *PrivE =
13426       ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13427   DRD->setInitializerData(OrigE, PrivE);
13428   return OmpPrivParm;
13429 }
13430 
13431 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13432                                                      VarDecl *OmpPrivParm) {
13433   auto *DRD = cast<OMPDeclareReductionDecl>(D);
13434   DiscardCleanupsInEvaluationContext();
13435   PopExpressionEvaluationContext();
13436 
13437   PopDeclContext();
13438   PopFunctionScopeInfo();
13439 
13440   if (Initializer != nullptr) {
13441     DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13442   } else if (OmpPrivParm->hasInit()) {
13443     DRD->setInitializer(OmpPrivParm->getInit(),
13444                         OmpPrivParm->isDirectInit()
13445                             ? OMPDeclareReductionDecl::DirectInit
13446                             : OMPDeclareReductionDecl::CopyInit);
13447   } else {
13448     DRD->setInvalidDecl();
13449   }
13450 }
13451 
13452 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13453     Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
13454   for (Decl *D : DeclReductions.get()) {
13455     if (IsValid) {
13456       if (S)
13457         PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13458                           /*AddToContext=*/false);
13459     } else {
13460       D->setInvalidDecl();
13461     }
13462   }
13463   return DeclReductions;
13464 }
13465 
13466 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
13467   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13468   QualType T = TInfo->getType();
13469   if (D.isInvalidType())
13470     return true;
13471 
13472   if (getLangOpts().CPlusPlus) {
13473     // Check that there are no default arguments (C++ only).
13474     CheckExtraCXXDefaultArguments(D);
13475   }
13476 
13477   return CreateParsedType(T, TInfo);
13478 }
13479 
13480 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
13481                                             TypeResult ParsedType) {
13482   assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
13483 
13484   QualType MapperType = GetTypeFromParser(ParsedType.get());
13485   assert(!MapperType.isNull() && "Expect valid mapper type");
13486 
13487   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13488   //  The type must be of struct, union or class type in C and C++
13489   if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
13490     Diag(TyLoc, diag::err_omp_mapper_wrong_type);
13491     return QualType();
13492   }
13493   return MapperType;
13494 }
13495 
13496 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
13497     Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
13498     SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
13499     Decl *PrevDeclInScope) {
13500   LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
13501                       forRedeclarationInCurContext());
13502   // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13503   //  A mapper-identifier may not be redeclared in the current scope for the
13504   //  same type or for a type that is compatible according to the base language
13505   //  rules.
13506   llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13507   OMPDeclareMapperDecl *PrevDMD = nullptr;
13508   bool InCompoundScope = true;
13509   if (S != nullptr) {
13510     // Find previous declaration with the same name not referenced in other
13511     // declarations.
13512     FunctionScopeInfo *ParentFn = getEnclosingFunction();
13513     InCompoundScope =
13514         (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13515     LookupName(Lookup, S);
13516     FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13517                          /*AllowInlineNamespace=*/false);
13518     llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
13519     LookupResult::Filter Filter = Lookup.makeFilter();
13520     while (Filter.hasNext()) {
13521       auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
13522       if (InCompoundScope) {
13523         auto I = UsedAsPrevious.find(PrevDecl);
13524         if (I == UsedAsPrevious.end())
13525           UsedAsPrevious[PrevDecl] = false;
13526         if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
13527           UsedAsPrevious[D] = true;
13528       }
13529       PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13530           PrevDecl->getLocation();
13531     }
13532     Filter.done();
13533     if (InCompoundScope) {
13534       for (const auto &PrevData : UsedAsPrevious) {
13535         if (!PrevData.second) {
13536           PrevDMD = PrevData.first;
13537           break;
13538         }
13539       }
13540     }
13541   } else if (PrevDeclInScope) {
13542     auto *PrevDMDInScope = PrevDMD =
13543         cast<OMPDeclareMapperDecl>(PrevDeclInScope);
13544     do {
13545       PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
13546           PrevDMDInScope->getLocation();
13547       PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
13548     } while (PrevDMDInScope != nullptr);
13549   }
13550   const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
13551   bool Invalid = false;
13552   if (I != PreviousRedeclTypes.end()) {
13553     Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
13554         << MapperType << Name;
13555     Diag(I->second, diag::note_previous_definition);
13556     Invalid = true;
13557   }
13558   auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
13559                                            MapperType, VN, PrevDMD);
13560   DC->addDecl(DMD);
13561   DMD->setAccess(AS);
13562   if (Invalid)
13563     DMD->setInvalidDecl();
13564 
13565   // Enter new function scope.
13566   PushFunctionScope();
13567   setFunctionHasBranchProtectedScope();
13568 
13569   CurContext = DMD;
13570 
13571   return DMD;
13572 }
13573 
13574 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
13575                                                     Scope *S,
13576                                                     QualType MapperType,
13577                                                     SourceLocation StartLoc,
13578                                                     DeclarationName VN) {
13579   VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
13580   if (S)
13581     PushOnScopeChains(VD, S);
13582   else
13583     DMD->addDecl(VD);
13584   Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
13585   DMD->setMapperVarRef(MapperVarRefExpr);
13586 }
13587 
13588 Sema::DeclGroupPtrTy
13589 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
13590                                            ArrayRef<OMPClause *> ClauseList) {
13591   PopDeclContext();
13592   PopFunctionScopeInfo();
13593 
13594   if (D) {
13595     if (S)
13596       PushOnScopeChains(D, S, /*AddToContext=*/false);
13597     D->CreateClauses(Context, ClauseList);
13598   }
13599 
13600   return DeclGroupPtrTy::make(DeclGroupRef(D));
13601 }
13602 
13603 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
13604                                            SourceLocation StartLoc,
13605                                            SourceLocation LParenLoc,
13606                                            SourceLocation EndLoc) {
13607   Expr *ValExpr = NumTeams;
13608   Stmt *HelperValStmt = nullptr;
13609 
13610   // OpenMP [teams Constrcut, Restrictions]
13611   // The num_teams expression must evaluate to a positive integer value.
13612   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
13613                                  /*StrictlyPositive=*/true))
13614     return nullptr;
13615 
13616   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13617   OpenMPDirectiveKind CaptureRegion =
13618       getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
13619   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13620     ValExpr = MakeFullExpr(ValExpr).get();
13621     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13622     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13623     HelperValStmt = buildPreInits(Context, Captures);
13624   }
13625 
13626   return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
13627                                          StartLoc, LParenLoc, EndLoc);
13628 }
13629 
13630 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
13631                                               SourceLocation StartLoc,
13632                                               SourceLocation LParenLoc,
13633                                               SourceLocation EndLoc) {
13634   Expr *ValExpr = ThreadLimit;
13635   Stmt *HelperValStmt = nullptr;
13636 
13637   // OpenMP [teams Constrcut, Restrictions]
13638   // The thread_limit expression must evaluate to a positive integer value.
13639   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
13640                                  /*StrictlyPositive=*/true))
13641     return nullptr;
13642 
13643   OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
13644   OpenMPDirectiveKind CaptureRegion =
13645       getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
13646   if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
13647     ValExpr = MakeFullExpr(ValExpr).get();
13648     llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13649     ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13650     HelperValStmt = buildPreInits(Context, Captures);
13651   }
13652 
13653   return new (Context) OMPThreadLimitClause(
13654       ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
13655 }
13656 
13657 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
13658                                            SourceLocation StartLoc,
13659                                            SourceLocation LParenLoc,
13660                                            SourceLocation EndLoc) {
13661   Expr *ValExpr = Priority;
13662 
13663   // OpenMP [2.9.1, task Constrcut]
13664   // The priority-value is a non-negative numerical scalar expression.
13665   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
13666                                  /*StrictlyPositive=*/false))
13667     return nullptr;
13668 
13669   return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13670 }
13671 
13672 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
13673                                             SourceLocation StartLoc,
13674                                             SourceLocation LParenLoc,
13675                                             SourceLocation EndLoc) {
13676   Expr *ValExpr = Grainsize;
13677 
13678   // OpenMP [2.9.2, taskloop Constrcut]
13679   // The parameter of the grainsize clause must be a positive integer
13680   // expression.
13681   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
13682                                  /*StrictlyPositive=*/true))
13683     return nullptr;
13684 
13685   return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13686 }
13687 
13688 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
13689                                            SourceLocation StartLoc,
13690                                            SourceLocation LParenLoc,
13691                                            SourceLocation EndLoc) {
13692   Expr *ValExpr = NumTasks;
13693 
13694   // OpenMP [2.9.2, taskloop Constrcut]
13695   // The parameter of the num_tasks clause must be a positive integer
13696   // expression.
13697   if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
13698                                  /*StrictlyPositive=*/true))
13699     return nullptr;
13700 
13701   return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13702 }
13703 
13704 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
13705                                        SourceLocation LParenLoc,
13706                                        SourceLocation EndLoc) {
13707   // OpenMP [2.13.2, critical construct, Description]
13708   // ... where hint-expression is an integer constant expression that evaluates
13709   // to a valid lock hint.
13710   ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
13711   if (HintExpr.isInvalid())
13712     return nullptr;
13713   return new (Context)
13714       OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
13715 }
13716 
13717 OMPClause *Sema::ActOnOpenMPDistScheduleClause(
13718     OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13719     SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
13720     SourceLocation EndLoc) {
13721   if (Kind == OMPC_DIST_SCHEDULE_unknown) {
13722     std::string Values;
13723     Values += "'";
13724     Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
13725     Values += "'";
13726     Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13727         << Values << getOpenMPClauseName(OMPC_dist_schedule);
13728     return nullptr;
13729   }
13730   Expr *ValExpr = ChunkSize;
13731   Stmt *HelperValStmt = nullptr;
13732   if (ChunkSize) {
13733     if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13734         !ChunkSize->isInstantiationDependent() &&
13735         !ChunkSize->containsUnexpandedParameterPack()) {
13736       SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
13737       ExprResult Val =
13738           PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13739       if (Val.isInvalid())
13740         return nullptr;
13741 
13742       ValExpr = Val.get();
13743 
13744       // OpenMP [2.7.1, Restrictions]
13745       //  chunk_size must be a loop invariant integer expression with a positive
13746       //  value.
13747       llvm::APSInt Result;
13748       if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13749         if (Result.isSigned() && !Result.isStrictlyPositive()) {
13750           Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13751               << "dist_schedule" << ChunkSize->getSourceRange();
13752           return nullptr;
13753         }
13754       } else if (getOpenMPCaptureRegionForClause(
13755                      DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
13756                      OMPD_unknown &&
13757                  !CurContext->isDependentContext()) {
13758         ValExpr = MakeFullExpr(ValExpr).get();
13759         llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
13760         ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13761         HelperValStmt = buildPreInits(Context, Captures);
13762       }
13763     }
13764   }
13765 
13766   return new (Context)
13767       OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
13768                             Kind, ValExpr, HelperValStmt);
13769 }
13770 
13771 OMPClause *Sema::ActOnOpenMPDefaultmapClause(
13772     OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
13773     SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
13774     SourceLocation KindLoc, SourceLocation EndLoc) {
13775   // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
13776   if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
13777     std::string Value;
13778     SourceLocation Loc;
13779     Value += "'";
13780     if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
13781       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
13782                                              OMPC_DEFAULTMAP_MODIFIER_tofrom);
13783       Loc = MLoc;
13784     } else {
13785       Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
13786                                              OMPC_DEFAULTMAP_scalar);
13787       Loc = KindLoc;
13788     }
13789     Value += "'";
13790     Diag(Loc, diag::err_omp_unexpected_clause_value)
13791         << Value << getOpenMPClauseName(OMPC_defaultmap);
13792     return nullptr;
13793   }
13794   DSAStack->setDefaultDMAToFromScalar(StartLoc);
13795 
13796   return new (Context)
13797       OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
13798 }
13799 
13800 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
13801   DeclContext *CurLexicalContext = getCurLexicalContext();
13802   if (!CurLexicalContext->isFileContext() &&
13803       !CurLexicalContext->isExternCContext() &&
13804       !CurLexicalContext->isExternCXXContext() &&
13805       !isa<CXXRecordDecl>(CurLexicalContext) &&
13806       !isa<ClassTemplateDecl>(CurLexicalContext) &&
13807       !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
13808       !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
13809     Diag(Loc, diag::err_omp_region_not_file_context);
13810     return false;
13811   }
13812   ++DeclareTargetNestingLevel;
13813   return true;
13814 }
13815 
13816 void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
13817   assert(DeclareTargetNestingLevel > 0 &&
13818          "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
13819   --DeclareTargetNestingLevel;
13820 }
13821 
13822 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
13823                                         CXXScopeSpec &ScopeSpec,
13824                                         const DeclarationNameInfo &Id,
13825                                         OMPDeclareTargetDeclAttr::MapTypeTy MT,
13826                                         NamedDeclSetType &SameDirectiveDecls) {
13827   LookupResult Lookup(*this, Id, LookupOrdinaryName);
13828   LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
13829 
13830   if (Lookup.isAmbiguous())
13831     return;
13832   Lookup.suppressDiagnostics();
13833 
13834   if (!Lookup.isSingleResult()) {
13835     if (TypoCorrection Corrected =
13836             CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
13837                         llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
13838                         CTK_ErrorRecovery)) {
13839       diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
13840                                   << Id.getName());
13841       checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
13842       return;
13843     }
13844 
13845     Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
13846     return;
13847   }
13848 
13849   NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
13850   if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
13851       isa<FunctionTemplateDecl>(ND)) {
13852     if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
13853       Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
13854     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
13855         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
13856             cast<ValueDecl>(ND));
13857     if (!Res) {
13858       auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
13859       ND->addAttr(A);
13860       if (ASTMutationListener *ML = Context.getASTMutationListener())
13861         ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
13862       checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
13863     } else if (*Res != MT) {
13864       Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
13865           << Id.getName();
13866     }
13867   } else {
13868     Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
13869   }
13870 }
13871 
13872 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
13873                                      Sema &SemaRef, Decl *D) {
13874   if (!D || !isa<VarDecl>(D))
13875     return;
13876   auto *VD = cast<VarDecl>(D);
13877   if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13878     return;
13879   SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
13880   SemaRef.Diag(SL, diag::note_used_here) << SR;
13881 }
13882 
13883 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
13884                                    Sema &SemaRef, DSAStackTy *Stack,
13885                                    ValueDecl *VD) {
13886   return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
13887          checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
13888                            /*FullCheck=*/false);
13889 }
13890 
13891 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
13892                                             SourceLocation IdLoc) {
13893   if (!D || D->isInvalidDecl())
13894     return;
13895   SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
13896   SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
13897   if (auto *VD = dyn_cast<VarDecl>(D)) {
13898     // Only global variables can be marked as declare target.
13899     if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
13900         !VD->isStaticDataMember())
13901       return;
13902     // 2.10.6: threadprivate variable cannot appear in a declare target
13903     // directive.
13904     if (DSAStack->isThreadPrivate(VD)) {
13905       Diag(SL, diag::err_omp_threadprivate_in_target);
13906       reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
13907       return;
13908     }
13909   }
13910   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
13911     D = FTD->getTemplatedDecl();
13912   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13913     llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
13914         OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
13915     if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
13916       assert(IdLoc.isValid() && "Source location is expected");
13917       Diag(IdLoc, diag::err_omp_function_in_link_clause);
13918       Diag(FD->getLocation(), diag::note_defined_here) << FD;
13919       return;
13920     }
13921   }
13922   if (auto *VD = dyn_cast<ValueDecl>(D)) {
13923     // Problem if any with var declared with incomplete type will be reported
13924     // as normal, so no need to check it here.
13925     if ((E || !VD->getType()->isIncompleteType()) &&
13926         !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
13927       return;
13928     if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
13929       // Checking declaration inside declare target region.
13930       if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
13931           isa<FunctionTemplateDecl>(D)) {
13932         auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13933             Context, OMPDeclareTargetDeclAttr::MT_To);
13934         D->addAttr(A);
13935         if (ASTMutationListener *ML = Context.getASTMutationListener())
13936           ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
13937       }
13938       return;
13939     }
13940   }
13941   if (!E)
13942     return;
13943   checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13944 }
13945 
13946 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13947                                      SourceLocation StartLoc,
13948                                      SourceLocation LParenLoc,
13949                                      SourceLocation EndLoc) {
13950   MappableVarListInfo MVLI(VarList);
13951   checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13952   if (MVLI.ProcessedVarList.empty())
13953     return nullptr;
13954 
13955   return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13956                              MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13957                              MVLI.VarComponents);
13958 }
13959 
13960 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13961                                        SourceLocation StartLoc,
13962                                        SourceLocation LParenLoc,
13963                                        SourceLocation EndLoc) {
13964   MappableVarListInfo MVLI(VarList);
13965   checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13966   if (MVLI.ProcessedVarList.empty())
13967     return nullptr;
13968 
13969   return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13970                                MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13971                                MVLI.VarComponents);
13972 }
13973 
13974 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13975                                                SourceLocation StartLoc,
13976                                                SourceLocation LParenLoc,
13977                                                SourceLocation EndLoc) {
13978   MappableVarListInfo MVLI(VarList);
13979   SmallVector<Expr *, 8> PrivateCopies;
13980   SmallVector<Expr *, 8> Inits;
13981 
13982   for (Expr *RefExpr : VarList) {
13983     assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13984     SourceLocation ELoc;
13985     SourceRange ERange;
13986     Expr *SimpleRefExpr = RefExpr;
13987     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13988     if (Res.second) {
13989       // It will be analyzed later.
13990       MVLI.ProcessedVarList.push_back(RefExpr);
13991       PrivateCopies.push_back(nullptr);
13992       Inits.push_back(nullptr);
13993     }
13994     ValueDecl *D = Res.first;
13995     if (!D)
13996       continue;
13997 
13998     QualType Type = D->getType();
13999     Type = Type.getNonReferenceType().getUnqualifiedType();
14000 
14001     auto *VD = dyn_cast<VarDecl>(D);
14002 
14003     // Item should be a pointer or reference to pointer.
14004     if (!Type->isPointerType()) {
14005       Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14006           << 0 << RefExpr->getSourceRange();
14007       continue;
14008     }
14009 
14010     // Build the private variable and the expression that refers to it.
14011     auto VDPrivate =
14012         buildVarDecl(*this, ELoc, Type, D->getName(),
14013                      D->hasAttrs() ? &D->getAttrs() : nullptr,
14014                      VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
14015     if (VDPrivate->isInvalidDecl())
14016       continue;
14017 
14018     CurContext->addDecl(VDPrivate);
14019     DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
14020         *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14021 
14022     // Add temporary variable to initialize the private copy of the pointer.
14023     VarDecl *VDInit =
14024         buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
14025     DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14026         *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
14027     AddInitializerToDecl(VDPrivate,
14028                          DefaultLvalueConversion(VDInitRefExpr).get(),
14029                          /*DirectInit=*/false);
14030 
14031     // If required, build a capture to implement the privatization initialized
14032     // with the current list item value.
14033     DeclRefExpr *Ref = nullptr;
14034     if (!VD)
14035       Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14036     MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14037     PrivateCopies.push_back(VDPrivateRefExpr);
14038     Inits.push_back(VDInitRefExpr);
14039 
14040     // We need to add a data sharing attribute for this variable to make sure it
14041     // is correctly captured. A variable that shows up in a use_device_ptr has
14042     // similar properties of a first private variable.
14043     DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14044 
14045     // Create a mappable component for the list item. List items in this clause
14046     // only need a component.
14047     MVLI.VarBaseDeclarations.push_back(D);
14048     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14049     MVLI.VarComponents.back().push_back(
14050         OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
14051   }
14052 
14053   if (MVLI.ProcessedVarList.empty())
14054     return nullptr;
14055 
14056   return OMPUseDevicePtrClause::Create(
14057       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
14058       PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
14059 }
14060 
14061 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
14062                                               SourceLocation StartLoc,
14063                                               SourceLocation LParenLoc,
14064                                               SourceLocation EndLoc) {
14065   MappableVarListInfo MVLI(VarList);
14066   for (Expr *RefExpr : VarList) {
14067     assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
14068     SourceLocation ELoc;
14069     SourceRange ERange;
14070     Expr *SimpleRefExpr = RefExpr;
14071     auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14072     if (Res.second) {
14073       // It will be analyzed later.
14074       MVLI.ProcessedVarList.push_back(RefExpr);
14075     }
14076     ValueDecl *D = Res.first;
14077     if (!D)
14078       continue;
14079 
14080     QualType Type = D->getType();
14081     // item should be a pointer or array or reference to pointer or array
14082     if (!Type.getNonReferenceType()->isPointerType() &&
14083         !Type.getNonReferenceType()->isArrayType()) {
14084       Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14085           << 0 << RefExpr->getSourceRange();
14086       continue;
14087     }
14088 
14089     // Check if the declaration in the clause does not show up in any data
14090     // sharing attribute.
14091     DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
14092     if (isOpenMPPrivate(DVar.CKind)) {
14093       Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14094           << getOpenMPClauseName(DVar.CKind)
14095           << getOpenMPClauseName(OMPC_is_device_ptr)
14096           << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
14097       reportOriginalDsa(*this, DSAStack, D, DVar);
14098       continue;
14099     }
14100 
14101     const Expr *ConflictExpr;
14102     if (DSAStack->checkMappableExprComponentListsForDecl(
14103             D, /*CurrentRegionOnly=*/true,
14104             [&ConflictExpr](
14105                 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14106                 OpenMPClauseKind) -> bool {
14107               ConflictExpr = R.front().getAssociatedExpression();
14108               return true;
14109             })) {
14110       Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14111       Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14112           << ConflictExpr->getSourceRange();
14113       continue;
14114     }
14115 
14116     // Store the components in the stack so that they can be used to check
14117     // against other clauses later on.
14118     OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14119     DSAStack->addMappableExpressionComponents(
14120         D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14121 
14122     // Record the expression we've just processed.
14123     MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14124 
14125     // Create a mappable component for the list item. List items in this clause
14126     // only need a component. We use a null declaration to signal fields in
14127     // 'this'.
14128     assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14129             isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14130            "Unexpected device pointer expression!");
14131     MVLI.VarBaseDeclarations.push_back(
14132         isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14133     MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14134     MVLI.VarComponents.back().push_back(MC);
14135   }
14136 
14137   if (MVLI.ProcessedVarList.empty())
14138     return nullptr;
14139 
14140   return OMPIsDevicePtrClause::Create(
14141       Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
14142       MVLI.VarBaseDeclarations, MVLI.VarComponents);
14143 }
14144