xref: /freebsd/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision 2f9966ff63d65bd474478888c9088eeae3f9c669)
1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
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 //  This file implements a semantic tree transformation that takes a given
9 //  AST and rebuilds it, possibly transforming some nodes in the process.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14 #define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15 
16 #include "CoroutineStmtBuilder.h"
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprConcepts.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/OpenMPClause.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/StmtObjC.h"
30 #include "clang/AST/StmtOpenMP.h"
31 #include "clang/Basic/DiagnosticParse.h"
32 #include "clang/Basic/OpenMPKinds.h"
33 #include "clang/Sema/Designator.h"
34 #include "clang/Sema/EnterExpressionEvaluationContext.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/Ownership.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaDiagnostic.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include <algorithm>
44 #include <optional>
45 
46 using namespace llvm::omp;
47 
48 namespace clang {
49 using namespace sema;
50 
51 /// A semantic tree transformation that allows one to transform one
52 /// abstract syntax tree into another.
53 ///
54 /// A new tree transformation is defined by creating a new subclass \c X of
55 /// \c TreeTransform<X> and then overriding certain operations to provide
56 /// behavior specific to that transformation. For example, template
57 /// instantiation is implemented as a tree transformation where the
58 /// transformation of TemplateTypeParmType nodes involves substituting the
59 /// template arguments for their corresponding template parameters; a similar
60 /// transformation is performed for non-type template parameters and
61 /// template template parameters.
62 ///
63 /// This tree-transformation template uses static polymorphism to allow
64 /// subclasses to customize any of its operations. Thus, a subclass can
65 /// override any of the transformation or rebuild operators by providing an
66 /// operation with the same signature as the default implementation. The
67 /// overriding function should not be virtual.
68 ///
69 /// Semantic tree transformations are split into two stages, either of which
70 /// can be replaced by a subclass. The "transform" step transforms an AST node
71 /// or the parts of an AST node using the various transformation functions,
72 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
73 /// node of the appropriate kind from the pieces. The default transformation
74 /// routines recursively transform the operands to composite AST nodes (e.g.,
75 /// the pointee type of a PointerType node) and, if any of those operand nodes
76 /// were changed by the transformation, invokes the rebuild operation to create
77 /// a new AST node.
78 ///
79 /// Subclasses can customize the transformation at various levels. The
80 /// most coarse-grained transformations involve replacing TransformType(),
81 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
82 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
83 /// new implementations.
84 ///
85 /// For more fine-grained transformations, subclasses can replace any of the
86 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
87 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
88 /// replacing TransformTemplateTypeParmType() allows template instantiation
89 /// to substitute template arguments for their corresponding template
90 /// parameters. Additionally, subclasses can override the \c RebuildXXX
91 /// functions to control how AST nodes are rebuilt when their operands change.
92 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
93 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
94 /// be able to use more efficient rebuild steps.
95 ///
96 /// There are a handful of other functions that can be overridden, allowing one
97 /// to avoid traversing nodes that don't need any transformation
98 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
99 /// operands have not changed (\c AlwaysRebuild()), and customize the
100 /// default locations and entity names used for type-checking
101 /// (\c getBaseLocation(), \c getBaseEntity()).
102 template<typename Derived>
103 class TreeTransform {
104   /// Private RAII object that helps us forget and then re-remember
105   /// the template argument corresponding to a partially-substituted parameter
106   /// pack.
107   class ForgetPartiallySubstitutedPackRAII {
108     Derived &Self;
109     TemplateArgument Old;
110 
111   public:
112     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
113       Old = Self.ForgetPartiallySubstitutedPack();
114     }
115 
116     ~ForgetPartiallySubstitutedPackRAII() {
117       Self.RememberPartiallySubstitutedPack(Old);
118     }
119   };
120 
121 protected:
122   Sema &SemaRef;
123 
124   /// The set of local declarations that have been transformed, for
125   /// cases where we are forced to build new declarations within the transformer
126   /// rather than in the subclass (e.g., lambda closure types).
127   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
128 
129 public:
130   /// Initializes a new tree transformer.
131   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
132 
133   /// Retrieves a reference to the derived class.
134   Derived &getDerived() { return static_cast<Derived&>(*this); }
135 
136   /// Retrieves a reference to the derived class.
137   const Derived &getDerived() const {
138     return static_cast<const Derived&>(*this);
139   }
140 
141   static inline ExprResult Owned(Expr *E) { return E; }
142   static inline StmtResult Owned(Stmt *S) { return S; }
143 
144   /// Retrieves a reference to the semantic analysis object used for
145   /// this tree transform.
146   Sema &getSema() const { return SemaRef; }
147 
148   /// Whether the transformation should always rebuild AST nodes, even
149   /// if none of the children have changed.
150   ///
151   /// Subclasses may override this function to specify when the transformation
152   /// should rebuild all AST nodes.
153   ///
154   /// We must always rebuild all AST nodes when performing variadic template
155   /// pack expansion, in order to avoid violating the AST invariant that each
156   /// statement node appears at most once in its containing declaration.
157   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
158 
159   /// Whether the transformation is forming an expression or statement that
160   /// replaces the original. In this case, we'll reuse mangling numbers from
161   /// existing lambdas.
162   bool ReplacingOriginal() { return false; }
163 
164   /// Wether CXXConstructExpr can be skipped when they are implicit.
165   /// They will be reconstructed when used if needed.
166   /// This is useful when the user that cause rebuilding of the
167   /// CXXConstructExpr is outside of the expression at which the TreeTransform
168   /// started.
169   bool AllowSkippingCXXConstructExpr() { return true; }
170 
171   /// Returns the location of the entity being transformed, if that
172   /// information was not available elsewhere in the AST.
173   ///
174   /// By default, returns no source-location information. Subclasses can
175   /// provide an alternative implementation that provides better location
176   /// information.
177   SourceLocation getBaseLocation() { return SourceLocation(); }
178 
179   /// Returns the name of the entity being transformed, if that
180   /// information was not available elsewhere in the AST.
181   ///
182   /// By default, returns an empty name. Subclasses can provide an alternative
183   /// implementation with a more precise name.
184   DeclarationName getBaseEntity() { return DeclarationName(); }
185 
186   /// Sets the "base" location and entity when that
187   /// information is known based on another transformation.
188   ///
189   /// By default, the source location and entity are ignored. Subclasses can
190   /// override this function to provide a customized implementation.
191   void setBase(SourceLocation Loc, DeclarationName Entity) { }
192 
193   /// RAII object that temporarily sets the base location and entity
194   /// used for reporting diagnostics in types.
195   class TemporaryBase {
196     TreeTransform &Self;
197     SourceLocation OldLocation;
198     DeclarationName OldEntity;
199 
200   public:
201     TemporaryBase(TreeTransform &Self, SourceLocation Location,
202                   DeclarationName Entity) : Self(Self) {
203       OldLocation = Self.getDerived().getBaseLocation();
204       OldEntity = Self.getDerived().getBaseEntity();
205 
206       if (Location.isValid())
207         Self.getDerived().setBase(Location, Entity);
208     }
209 
210     ~TemporaryBase() {
211       Self.getDerived().setBase(OldLocation, OldEntity);
212     }
213   };
214 
215   /// Determine whether the given type \p T has already been
216   /// transformed.
217   ///
218   /// Subclasses can provide an alternative implementation of this routine
219   /// to short-circuit evaluation when it is known that a given type will
220   /// not change. For example, template instantiation need not traverse
221   /// non-dependent types.
222   bool AlreadyTransformed(QualType T) {
223     return T.isNull();
224   }
225 
226   /// Transform a template parameter depth level.
227   ///
228   /// During a transformation that transforms template parameters, this maps
229   /// an old template parameter depth to a new depth.
230   unsigned TransformTemplateDepth(unsigned Depth) {
231     return Depth;
232   }
233 
234   /// Determine whether the given call argument should be dropped, e.g.,
235   /// because it is a default argument.
236   ///
237   /// Subclasses can provide an alternative implementation of this routine to
238   /// determine which kinds of call arguments get dropped. By default,
239   /// CXXDefaultArgument nodes are dropped (prior to transformation).
240   bool DropCallArgument(Expr *E) {
241     return E->isDefaultArgument();
242   }
243 
244   /// Determine whether we should expand a pack expansion with the
245   /// given set of parameter packs into separate arguments by repeatedly
246   /// transforming the pattern.
247   ///
248   /// By default, the transformer never tries to expand pack expansions.
249   /// Subclasses can override this routine to provide different behavior.
250   ///
251   /// \param EllipsisLoc The location of the ellipsis that identifies the
252   /// pack expansion.
253   ///
254   /// \param PatternRange The source range that covers the entire pattern of
255   /// the pack expansion.
256   ///
257   /// \param Unexpanded The set of unexpanded parameter packs within the
258   /// pattern.
259   ///
260   /// \param ShouldExpand Will be set to \c true if the transformer should
261   /// expand the corresponding pack expansions into separate arguments. When
262   /// set, \c NumExpansions must also be set.
263   ///
264   /// \param RetainExpansion Whether the caller should add an unexpanded
265   /// pack expansion after all of the expanded arguments. This is used
266   /// when extending explicitly-specified template argument packs per
267   /// C++0x [temp.arg.explicit]p9.
268   ///
269   /// \param NumExpansions The number of separate arguments that will be in
270   /// the expanded form of the corresponding pack expansion. This is both an
271   /// input and an output parameter, which can be set by the caller if the
272   /// number of expansions is known a priori (e.g., due to a prior substitution)
273   /// and will be set by the callee when the number of expansions is known.
274   /// The callee must set this value when \c ShouldExpand is \c true; it may
275   /// set this value in other cases.
276   ///
277   /// \returns true if an error occurred (e.g., because the parameter packs
278   /// are to be instantiated with arguments of different lengths), false
279   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
280   /// must be set.
281   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
282                                SourceRange PatternRange,
283                                ArrayRef<UnexpandedParameterPack> Unexpanded,
284                                bool &ShouldExpand, bool &RetainExpansion,
285                                std::optional<unsigned> &NumExpansions) {
286     ShouldExpand = false;
287     return false;
288   }
289 
290   /// "Forget" about the partially-substituted pack template argument,
291   /// when performing an instantiation that must preserve the parameter pack
292   /// use.
293   ///
294   /// This routine is meant to be overridden by the template instantiator.
295   TemplateArgument ForgetPartiallySubstitutedPack() {
296     return TemplateArgument();
297   }
298 
299   /// "Remember" the partially-substituted pack template argument
300   /// after performing an instantiation that must preserve the parameter pack
301   /// use.
302   ///
303   /// This routine is meant to be overridden by the template instantiator.
304   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
305 
306   /// Note to the derived class when a function parameter pack is
307   /// being expanded.
308   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
309 
310   /// Transforms the given type into another type.
311   ///
312   /// By default, this routine transforms a type by creating a
313   /// TypeSourceInfo for it and delegating to the appropriate
314   /// function.  This is expensive, but we don't mind, because
315   /// this method is deprecated anyway;  all users should be
316   /// switched to storing TypeSourceInfos.
317   ///
318   /// \returns the transformed type.
319   QualType TransformType(QualType T);
320 
321   /// Transforms the given type-with-location into a new
322   /// type-with-location.
323   ///
324   /// By default, this routine transforms a type by delegating to the
325   /// appropriate TransformXXXType to build a new type.  Subclasses
326   /// may override this function (to take over all type
327   /// transformations) or some set of the TransformXXXType functions
328   /// to alter the transformation.
329   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
330 
331   /// Transform the given type-with-location into a new
332   /// type, collecting location information in the given builder
333   /// as necessary.
334   ///
335   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
336 
337   /// Transform a type that is permitted to produce a
338   /// DeducedTemplateSpecializationType.
339   ///
340   /// This is used in the (relatively rare) contexts where it is acceptable
341   /// for transformation to produce a class template type with deduced
342   /// template arguments.
343   /// @{
344   QualType TransformTypeWithDeducedTST(QualType T);
345   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
346   /// @}
347 
348   /// The reason why the value of a statement is not discarded, if any.
349   enum StmtDiscardKind {
350     SDK_Discarded,
351     SDK_NotDiscarded,
352     SDK_StmtExprResult,
353   };
354 
355   /// Transform the given statement.
356   ///
357   /// By default, this routine transforms a statement by delegating to the
358   /// appropriate TransformXXXStmt function to transform a specific kind of
359   /// statement or the TransformExpr() function to transform an expression.
360   /// Subclasses may override this function to transform statements using some
361   /// other mechanism.
362   ///
363   /// \returns the transformed statement.
364   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
365 
366   /// Transform the given statement.
367   ///
368   /// By default, this routine transforms a statement by delegating to the
369   /// appropriate TransformOMPXXXClause function to transform a specific kind
370   /// of clause. Subclasses may override this function to transform statements
371   /// using some other mechanism.
372   ///
373   /// \returns the transformed OpenMP clause.
374   OMPClause *TransformOMPClause(OMPClause *S);
375 
376   /// Transform the given attribute.
377   ///
378   /// By default, this routine transforms a statement by delegating to the
379   /// appropriate TransformXXXAttr function to transform a specific kind
380   /// of attribute. Subclasses may override this function to transform
381   /// attributed statements/types using some other mechanism.
382   ///
383   /// \returns the transformed attribute
384   const Attr *TransformAttr(const Attr *S);
385 
386   // Transform the given statement attribute.
387   //
388   // Delegates to the appropriate TransformXXXAttr function to transform a
389   // specific kind of statement attribute. Unlike the non-statement taking
390   // version of this, this implements all attributes, not just pragmas.
391   const Attr *TransformStmtAttr(const Stmt *OrigS, const Stmt *InstS,
392                                 const Attr *A);
393 
394   // Transform the specified attribute.
395   //
396   // Subclasses should override the transformation of attributes with a pragma
397   // spelling to transform expressions stored within the attribute.
398   //
399   // \returns the transformed attribute.
400 #define ATTR(X)                                                                \
401   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
402 #include "clang/Basic/AttrList.inc"
403 
404   // Transform the specified attribute.
405   //
406   // Subclasses should override the transformation of attributes to do
407   // transformation and checking of statement attributes. By default, this
408   // delegates to the non-statement taking version.
409   //
410   // \returns the transformed attribute.
411 #define ATTR(X)                                                                \
412   const X##Attr *TransformStmt##X##Attr(const Stmt *, const Stmt *,            \
413                                         const X##Attr *A) {                    \
414     return getDerived().Transform##X##Attr(A);                                 \
415   }
416 #include "clang/Basic/AttrList.inc"
417 
418   /// Transform the given expression.
419   ///
420   /// By default, this routine transforms an expression by delegating to the
421   /// appropriate TransformXXXExpr function to build a new expression.
422   /// Subclasses may override this function to transform expressions using some
423   /// other mechanism.
424   ///
425   /// \returns the transformed expression.
426   ExprResult TransformExpr(Expr *E);
427 
428   /// Transform the given initializer.
429   ///
430   /// By default, this routine transforms an initializer by stripping off the
431   /// semantic nodes added by initialization, then passing the result to
432   /// TransformExpr or TransformExprs.
433   ///
434   /// \returns the transformed initializer.
435   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
436 
437   /// Transform the given list of expressions.
438   ///
439   /// This routine transforms a list of expressions by invoking
440   /// \c TransformExpr() for each subexpression. However, it also provides
441   /// support for variadic templates by expanding any pack expansions (if the
442   /// derived class permits such expansion) along the way. When pack expansions
443   /// are present, the number of outputs may not equal the number of inputs.
444   ///
445   /// \param Inputs The set of expressions to be transformed.
446   ///
447   /// \param NumInputs The number of expressions in \c Inputs.
448   ///
449   /// \param IsCall If \c true, then this transform is being performed on
450   /// function-call arguments, and any arguments that should be dropped, will
451   /// be.
452   ///
453   /// \param Outputs The transformed input expressions will be added to this
454   /// vector.
455   ///
456   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
457   /// due to transformation.
458   ///
459   /// \returns true if an error occurred, false otherwise.
460   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
461                       SmallVectorImpl<Expr *> &Outputs,
462                       bool *ArgChanged = nullptr);
463 
464   /// Transform the given declaration, which is referenced from a type
465   /// or expression.
466   ///
467   /// By default, acts as the identity function on declarations, unless the
468   /// transformer has had to transform the declaration itself. Subclasses
469   /// may override this function to provide alternate behavior.
470   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
471     llvm::DenseMap<Decl *, Decl *>::iterator Known
472       = TransformedLocalDecls.find(D);
473     if (Known != TransformedLocalDecls.end())
474       return Known->second;
475 
476     return D;
477   }
478 
479   /// Transform the specified condition.
480   ///
481   /// By default, this transforms the variable and expression and rebuilds
482   /// the condition.
483   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
484                                            Expr *Expr,
485                                            Sema::ConditionKind Kind);
486 
487   /// Transform the attributes associated with the given declaration and
488   /// place them on the new declaration.
489   ///
490   /// By default, this operation does nothing. Subclasses may override this
491   /// behavior to transform attributes.
492   void transformAttrs(Decl *Old, Decl *New) { }
493 
494   /// Note that a local declaration has been transformed by this
495   /// transformer.
496   ///
497   /// Local declarations are typically transformed via a call to
498   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
499   /// the transformer itself has to transform the declarations. This routine
500   /// can be overridden by a subclass that keeps track of such mappings.
501   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
502     assert(New.size() == 1 &&
503            "must override transformedLocalDecl if performing pack expansion");
504     TransformedLocalDecls[Old] = New.front();
505   }
506 
507   /// Transform the definition of the given declaration.
508   ///
509   /// By default, invokes TransformDecl() to transform the declaration.
510   /// Subclasses may override this function to provide alternate behavior.
511   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
512     return getDerived().TransformDecl(Loc, D);
513   }
514 
515   /// Transform the given declaration, which was the first part of a
516   /// nested-name-specifier in a member access expression.
517   ///
518   /// This specific declaration transformation only applies to the first
519   /// identifier in a nested-name-specifier of a member access expression, e.g.,
520   /// the \c T in \c x->T::member
521   ///
522   /// By default, invokes TransformDecl() to transform the declaration.
523   /// Subclasses may override this function to provide alternate behavior.
524   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
525     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
526   }
527 
528   /// Transform the set of declarations in an OverloadExpr.
529   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
530                                   LookupResult &R);
531 
532   /// Transform the given nested-name-specifier with source-location
533   /// information.
534   ///
535   /// By default, transforms all of the types and declarations within the
536   /// nested-name-specifier. Subclasses may override this function to provide
537   /// alternate behavior.
538   NestedNameSpecifierLoc
539   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
540                                   QualType ObjectType = QualType(),
541                                   NamedDecl *FirstQualifierInScope = nullptr);
542 
543   /// Transform the given declaration name.
544   ///
545   /// By default, transforms the types of conversion function, constructor,
546   /// and destructor names and then (if needed) rebuilds the declaration name.
547   /// Identifiers and selectors are returned unmodified. Subclasses may
548   /// override this function to provide alternate behavior.
549   DeclarationNameInfo
550   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
551 
552   bool TransformRequiresExprRequirements(
553       ArrayRef<concepts::Requirement *> Reqs,
554       llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
555   concepts::TypeRequirement *
556   TransformTypeRequirement(concepts::TypeRequirement *Req);
557   concepts::ExprRequirement *
558   TransformExprRequirement(concepts::ExprRequirement *Req);
559   concepts::NestedRequirement *
560   TransformNestedRequirement(concepts::NestedRequirement *Req);
561 
562   /// Transform the given template name.
563   ///
564   /// \param SS The nested-name-specifier that qualifies the template
565   /// name. This nested-name-specifier must already have been transformed.
566   ///
567   /// \param Name The template name to transform.
568   ///
569   /// \param NameLoc The source location of the template name.
570   ///
571   /// \param ObjectType If we're translating a template name within a member
572   /// access expression, this is the type of the object whose member template
573   /// is being referenced.
574   ///
575   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
576   /// also refers to a name within the current (lexical) scope, this is the
577   /// declaration it refers to.
578   ///
579   /// By default, transforms the template name by transforming the declarations
580   /// and nested-name-specifiers that occur within the template name.
581   /// Subclasses may override this function to provide alternate behavior.
582   TemplateName
583   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
584                         SourceLocation NameLoc,
585                         QualType ObjectType = QualType(),
586                         NamedDecl *FirstQualifierInScope = nullptr,
587                         bool AllowInjectedClassName = false);
588 
589   /// Transform the given template argument.
590   ///
591   /// By default, this operation transforms the type, expression, or
592   /// declaration stored within the template argument and constructs a
593   /// new template argument from the transformed result. Subclasses may
594   /// override this function to provide alternate behavior.
595   ///
596   /// Returns true if there was an error.
597   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
598                                  TemplateArgumentLoc &Output,
599                                  bool Uneval = false);
600 
601   /// Transform the given set of template arguments.
602   ///
603   /// By default, this operation transforms all of the template arguments
604   /// in the input set using \c TransformTemplateArgument(), and appends
605   /// the transformed arguments to the output list.
606   ///
607   /// Note that this overload of \c TransformTemplateArguments() is merely
608   /// a convenience function. Subclasses that wish to override this behavior
609   /// should override the iterator-based member template version.
610   ///
611   /// \param Inputs The set of template arguments to be transformed.
612   ///
613   /// \param NumInputs The number of template arguments in \p Inputs.
614   ///
615   /// \param Outputs The set of transformed template arguments output by this
616   /// routine.
617   ///
618   /// Returns true if an error occurred.
619   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
620                                   unsigned NumInputs,
621                                   TemplateArgumentListInfo &Outputs,
622                                   bool Uneval = false) {
623     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
624                                       Uneval);
625   }
626 
627   /// Transform the given set of template arguments.
628   ///
629   /// By default, this operation transforms all of the template arguments
630   /// in the input set using \c TransformTemplateArgument(), and appends
631   /// the transformed arguments to the output list.
632   ///
633   /// \param First An iterator to the first template argument.
634   ///
635   /// \param Last An iterator one step past the last template argument.
636   ///
637   /// \param Outputs The set of transformed template arguments output by this
638   /// routine.
639   ///
640   /// Returns true if an error occurred.
641   template<typename InputIterator>
642   bool TransformTemplateArguments(InputIterator First,
643                                   InputIterator Last,
644                                   TemplateArgumentListInfo &Outputs,
645                                   bool Uneval = false);
646 
647   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
648   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
649                                  TemplateArgumentLoc &ArgLoc);
650 
651   /// Fakes up a TypeSourceInfo for a type.
652   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
653     return SemaRef.Context.getTrivialTypeSourceInfo(T,
654                        getDerived().getBaseLocation());
655   }
656 
657 #define ABSTRACT_TYPELOC(CLASS, PARENT)
658 #define TYPELOC(CLASS, PARENT)                                   \
659   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
660 #include "clang/AST/TypeLocNodes.def"
661 
662   QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
663                                          TemplateTypeParmTypeLoc TL,
664                                          bool SuppressObjCLifetime);
665   QualType
666   TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
667                                          SubstTemplateTypeParmPackTypeLoc TL,
668                                          bool SuppressObjCLifetime);
669 
670   template<typename Fn>
671   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
672                                       FunctionProtoTypeLoc TL,
673                                       CXXRecordDecl *ThisContext,
674                                       Qualifiers ThisTypeQuals,
675                                       Fn TransformExceptionSpec);
676 
677   template <typename Fn>
678   QualType TransformAttributedType(TypeLocBuilder &TLB, AttributedTypeLoc TL,
679                                    Fn TransformModifiedType);
680 
681   bool TransformExceptionSpec(SourceLocation Loc,
682                               FunctionProtoType::ExceptionSpecInfo &ESI,
683                               SmallVectorImpl<QualType> &Exceptions,
684                               bool &Changed);
685 
686   StmtResult TransformSEHHandler(Stmt *Handler);
687 
688   QualType
689   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
690                                       TemplateSpecializationTypeLoc TL,
691                                       TemplateName Template);
692 
693   QualType
694   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
695                                       DependentTemplateSpecializationTypeLoc TL,
696                                                TemplateName Template,
697                                                CXXScopeSpec &SS);
698 
699   QualType TransformDependentTemplateSpecializationType(
700       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
701       NestedNameSpecifierLoc QualifierLoc);
702 
703   /// Transforms the parameters of a function type into the
704   /// given vectors.
705   ///
706   /// The result vectors should be kept in sync; null entries in the
707   /// variables vector are acceptable.
708   ///
709   /// LastParamTransformed, if non-null, will be set to the index of the last
710   /// parameter on which transfromation was started. In the event of an error,
711   /// this will contain the parameter which failed to instantiate.
712   ///
713   /// Return true on error.
714   bool TransformFunctionTypeParams(
715       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
716       const QualType *ParamTypes,
717       const FunctionProtoType::ExtParameterInfo *ParamInfos,
718       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
719       Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed);
720 
721   bool TransformFunctionTypeParams(
722       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
723       const QualType *ParamTypes,
724       const FunctionProtoType::ExtParameterInfo *ParamInfos,
725       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
726       Sema::ExtParameterInfoBuilder &PInfos) {
727     return getDerived().TransformFunctionTypeParams(
728         Loc, Params, ParamTypes, ParamInfos, PTypes, PVars, PInfos, nullptr);
729   }
730 
731   /// Transforms the parameters of a requires expresison into the given vectors.
732   ///
733   /// The result vectors should be kept in sync; null entries in the
734   /// variables vector are acceptable.
735   ///
736   /// Returns an unset ExprResult on success.  Returns an ExprResult the 'not
737   /// satisfied' RequiresExpr if subsitution failed, OR an ExprError, both of
738   /// which are cases where transformation shouldn't continue.
739   ExprResult TransformRequiresTypeParams(
740       SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
741       RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
742       SmallVectorImpl<QualType> &PTypes,
743       SmallVectorImpl<ParmVarDecl *> &TransParams,
744       Sema::ExtParameterInfoBuilder &PInfos) {
745     if (getDerived().TransformFunctionTypeParams(
746             KWLoc, Params, /*ParamTypes=*/nullptr,
747             /*ParamInfos=*/nullptr, PTypes, &TransParams, PInfos))
748       return ExprError();
749 
750     return ExprResult{};
751   }
752 
753   /// Transforms a single function-type parameter.  Return null
754   /// on error.
755   ///
756   /// \param indexAdjustment - A number to add to the parameter's
757   ///   scope index;  can be negative
758   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
759                                           int indexAdjustment,
760                                           std::optional<unsigned> NumExpansions,
761                                           bool ExpectParameterPack);
762 
763   /// Transform the body of a lambda-expression.
764   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
765   /// Alternative implementation of TransformLambdaBody that skips transforming
766   /// the body.
767   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
768 
769   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
770 
771   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
772   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
773 
774   TemplateParameterList *TransformTemplateParameterList(
775         TemplateParameterList *TPL) {
776     return TPL;
777   }
778 
779   ExprResult TransformAddressOfOperand(Expr *E);
780 
781   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
782                                                 bool IsAddressOfOperand,
783                                                 TypeSourceInfo **RecoveryTSI);
784 
785   ExprResult TransformParenDependentScopeDeclRefExpr(
786       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
787       TypeSourceInfo **RecoveryTSI);
788 
789   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
790 
791 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
792 // amount of stack usage with clang.
793 #define STMT(Node, Parent)                        \
794   LLVM_ATTRIBUTE_NOINLINE \
795   StmtResult Transform##Node(Node *S);
796 #define VALUESTMT(Node, Parent)                   \
797   LLVM_ATTRIBUTE_NOINLINE \
798   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
799 #define EXPR(Node, Parent)                        \
800   LLVM_ATTRIBUTE_NOINLINE \
801   ExprResult Transform##Node(Node *E);
802 #define ABSTRACT_STMT(Stmt)
803 #include "clang/AST/StmtNodes.inc"
804 
805 #define GEN_CLANG_CLAUSE_CLASS
806 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
807   LLVM_ATTRIBUTE_NOINLINE                                                      \
808   OMPClause *Transform##Class(Class *S);
809 #include "llvm/Frontend/OpenMP/OMP.inc"
810 
811   /// Build a new qualified type given its unqualified type and type location.
812   ///
813   /// By default, this routine adds type qualifiers only to types that can
814   /// have qualifiers, and silently suppresses those qualifiers that are not
815   /// permitted. Subclasses may override this routine to provide different
816   /// behavior.
817   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
818 
819   /// Build a new pointer type given its pointee type.
820   ///
821   /// By default, performs semantic analysis when building the pointer type.
822   /// Subclasses may override this routine to provide different behavior.
823   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
824 
825   /// Build a new block pointer type given its pointee type.
826   ///
827   /// By default, performs semantic analysis when building the block pointer
828   /// type. Subclasses may override this routine to provide different behavior.
829   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
830 
831   /// Build a new reference type given the type it references.
832   ///
833   /// By default, performs semantic analysis when building the
834   /// reference type. Subclasses may override this routine to provide
835   /// different behavior.
836   ///
837   /// \param LValue whether the type was written with an lvalue sigil
838   /// or an rvalue sigil.
839   QualType RebuildReferenceType(QualType ReferentType,
840                                 bool LValue,
841                                 SourceLocation Sigil);
842 
843   /// Build a new member pointer type given the pointee type and the
844   /// class type it refers into.
845   ///
846   /// By default, performs semantic analysis when building the member pointer
847   /// type. Subclasses may override this routine to provide different behavior.
848   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
849                                     SourceLocation Sigil);
850 
851   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
852                                     SourceLocation ProtocolLAngleLoc,
853                                     ArrayRef<ObjCProtocolDecl *> Protocols,
854                                     ArrayRef<SourceLocation> ProtocolLocs,
855                                     SourceLocation ProtocolRAngleLoc);
856 
857   /// Build an Objective-C object type.
858   ///
859   /// By default, performs semantic analysis when building the object type.
860   /// Subclasses may override this routine to provide different behavior.
861   QualType RebuildObjCObjectType(QualType BaseType,
862                                  SourceLocation Loc,
863                                  SourceLocation TypeArgsLAngleLoc,
864                                  ArrayRef<TypeSourceInfo *> TypeArgs,
865                                  SourceLocation TypeArgsRAngleLoc,
866                                  SourceLocation ProtocolLAngleLoc,
867                                  ArrayRef<ObjCProtocolDecl *> Protocols,
868                                  ArrayRef<SourceLocation> ProtocolLocs,
869                                  SourceLocation ProtocolRAngleLoc);
870 
871   /// Build a new Objective-C object pointer type given the pointee type.
872   ///
873   /// By default, directly builds the pointer type, with no additional semantic
874   /// analysis.
875   QualType RebuildObjCObjectPointerType(QualType PointeeType,
876                                         SourceLocation Star);
877 
878   /// Build a new array type given the element type, size
879   /// modifier, size of the array (if known), size expression, and index type
880   /// qualifiers.
881   ///
882   /// By default, performs semantic analysis when building the array type.
883   /// Subclasses may override this routine to provide different behavior.
884   /// Also by default, all of the other Rebuild*Array
885   QualType RebuildArrayType(QualType ElementType, ArraySizeModifier SizeMod,
886                             const llvm::APInt *Size, Expr *SizeExpr,
887                             unsigned IndexTypeQuals, SourceRange BracketsRange);
888 
889   /// Build a new constant array type given the element type, size
890   /// modifier, (known) size of the array, and index type qualifiers.
891   ///
892   /// By default, performs semantic analysis when building the array type.
893   /// Subclasses may override this routine to provide different behavior.
894   QualType RebuildConstantArrayType(QualType ElementType,
895                                     ArraySizeModifier SizeMod,
896                                     const llvm::APInt &Size, Expr *SizeExpr,
897                                     unsigned IndexTypeQuals,
898                                     SourceRange BracketsRange);
899 
900   /// Build a new incomplete array type given the element type, size
901   /// modifier, and index type qualifiers.
902   ///
903   /// By default, performs semantic analysis when building the array type.
904   /// Subclasses may override this routine to provide different behavior.
905   QualType RebuildIncompleteArrayType(QualType ElementType,
906                                       ArraySizeModifier SizeMod,
907                                       unsigned IndexTypeQuals,
908                                       SourceRange BracketsRange);
909 
910   /// Build a new variable-length array type given the element type,
911   /// size modifier, size expression, and index type qualifiers.
912   ///
913   /// By default, performs semantic analysis when building the array type.
914   /// Subclasses may override this routine to provide different behavior.
915   QualType RebuildVariableArrayType(QualType ElementType,
916                                     ArraySizeModifier SizeMod, Expr *SizeExpr,
917                                     unsigned IndexTypeQuals,
918                                     SourceRange BracketsRange);
919 
920   /// Build a new dependent-sized array type given the element type,
921   /// size modifier, size expression, and index type qualifiers.
922   ///
923   /// By default, performs semantic analysis when building the array type.
924   /// Subclasses may override this routine to provide different behavior.
925   QualType RebuildDependentSizedArrayType(QualType ElementType,
926                                           ArraySizeModifier SizeMod,
927                                           Expr *SizeExpr,
928                                           unsigned IndexTypeQuals,
929                                           SourceRange BracketsRange);
930 
931   /// Build a new vector type given the element type and
932   /// number of elements.
933   ///
934   /// By default, performs semantic analysis when building the vector type.
935   /// Subclasses may override this routine to provide different behavior.
936   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
937                              VectorKind VecKind);
938 
939   /// Build a new potentially dependently-sized extended vector type
940   /// given the element type and number of elements.
941   ///
942   /// By default, performs semantic analysis when building the vector type.
943   /// Subclasses may override this routine to provide different behavior.
944   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
945                                       SourceLocation AttributeLoc, VectorKind);
946 
947   /// Build a new extended vector type given the element type and
948   /// number of elements.
949   ///
950   /// By default, performs semantic analysis when building the vector type.
951   /// Subclasses may override this routine to provide different behavior.
952   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
953                                 SourceLocation AttributeLoc);
954 
955   /// Build a new potentially dependently-sized extended vector type
956   /// given the element type and number of elements.
957   ///
958   /// By default, performs semantic analysis when building the vector type.
959   /// Subclasses may override this routine to provide different behavior.
960   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
961                                               Expr *SizeExpr,
962                                               SourceLocation AttributeLoc);
963 
964   /// Build a new matrix type given the element type and dimensions.
965   QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
966                                      unsigned NumColumns);
967 
968   /// Build a new matrix type given the type and dependently-defined
969   /// dimensions.
970   QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
971                                            Expr *ColumnExpr,
972                                            SourceLocation AttributeLoc);
973 
974   /// Build a new DependentAddressSpaceType or return the pointee
975   /// type variable with the correct address space (retrieved from
976   /// AddrSpaceExpr) applied to it. The former will be returned in cases
977   /// where the address space remains dependent.
978   ///
979   /// By default, performs semantic analysis when building the type with address
980   /// space applied. Subclasses may override this routine to provide different
981   /// behavior.
982   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
983                                             Expr *AddrSpaceExpr,
984                                             SourceLocation AttributeLoc);
985 
986   /// Build a new function type.
987   ///
988   /// By default, performs semantic analysis when building the function type.
989   /// Subclasses may override this routine to provide different behavior.
990   QualType RebuildFunctionProtoType(QualType T,
991                                     MutableArrayRef<QualType> ParamTypes,
992                                     const FunctionProtoType::ExtProtoInfo &EPI);
993 
994   /// Build a new unprototyped function type.
995   QualType RebuildFunctionNoProtoType(QualType ResultType);
996 
997   /// Rebuild an unresolved typename type, given the decl that
998   /// the UnresolvedUsingTypenameDecl was transformed to.
999   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
1000 
1001   /// Build a new type found via an alias.
1002   QualType RebuildUsingType(UsingShadowDecl *Found, QualType Underlying) {
1003     return SemaRef.Context.getUsingType(Found, Underlying);
1004   }
1005 
1006   /// Build a new typedef type.
1007   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
1008     return SemaRef.Context.getTypeDeclType(Typedef);
1009   }
1010 
1011   /// Build a new MacroDefined type.
1012   QualType RebuildMacroQualifiedType(QualType T,
1013                                      const IdentifierInfo *MacroII) {
1014     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
1015   }
1016 
1017   /// Build a new class/struct/union type.
1018   QualType RebuildRecordType(RecordDecl *Record) {
1019     return SemaRef.Context.getTypeDeclType(Record);
1020   }
1021 
1022   /// Build a new Enum type.
1023   QualType RebuildEnumType(EnumDecl *Enum) {
1024     return SemaRef.Context.getTypeDeclType(Enum);
1025   }
1026 
1027   /// Build a new typeof(expr) type.
1028   ///
1029   /// By default, performs semantic analysis when building the typeof type.
1030   /// Subclasses may override this routine to provide different behavior.
1031   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc,
1032                                  TypeOfKind Kind);
1033 
1034   /// Build a new typeof(type) type.
1035   ///
1036   /// By default, builds a new TypeOfType with the given underlying type.
1037   QualType RebuildTypeOfType(QualType Underlying, TypeOfKind Kind);
1038 
1039   /// Build a new unary transform type.
1040   QualType RebuildUnaryTransformType(QualType BaseType,
1041                                      UnaryTransformType::UTTKind UKind,
1042                                      SourceLocation Loc);
1043 
1044   /// Build a new C++11 decltype type.
1045   ///
1046   /// By default, performs semantic analysis when building the decltype type.
1047   /// Subclasses may override this routine to provide different behavior.
1048   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
1049 
1050   /// Build a new C++11 auto type.
1051   ///
1052   /// By default, builds a new AutoType with the given deduced type.
1053   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
1054                            ConceptDecl *TypeConstraintConcept,
1055                            ArrayRef<TemplateArgument> TypeConstraintArgs) {
1056     // Note, IsDependent is always false here: we implicitly convert an 'auto'
1057     // which has been deduced to a dependent type into an undeduced 'auto', so
1058     // that we'll retry deduction after the transformation.
1059     return SemaRef.Context.getAutoType(Deduced, Keyword,
1060                                        /*IsDependent*/ false, /*IsPack=*/false,
1061                                        TypeConstraintConcept,
1062                                        TypeConstraintArgs);
1063   }
1064 
1065   /// By default, builds a new DeducedTemplateSpecializationType with the given
1066   /// deduced type.
1067   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
1068       QualType Deduced) {
1069     return SemaRef.Context.getDeducedTemplateSpecializationType(
1070         Template, Deduced, /*IsDependent*/ false);
1071   }
1072 
1073   /// Build a new template specialization type.
1074   ///
1075   /// By default, performs semantic analysis when building the template
1076   /// specialization type. Subclasses may override this routine to provide
1077   /// different behavior.
1078   QualType RebuildTemplateSpecializationType(TemplateName Template,
1079                                              SourceLocation TemplateLoc,
1080                                              TemplateArgumentListInfo &Args);
1081 
1082   /// Build a new parenthesized type.
1083   ///
1084   /// By default, builds a new ParenType type from the inner type.
1085   /// Subclasses may override this routine to provide different behavior.
1086   QualType RebuildParenType(QualType InnerType) {
1087     return SemaRef.BuildParenType(InnerType);
1088   }
1089 
1090   /// Build a new qualified name type.
1091   ///
1092   /// By default, builds a new ElaboratedType type from the keyword,
1093   /// the nested-name-specifier and the named type.
1094   /// Subclasses may override this routine to provide different behavior.
1095   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1096                                  ElaboratedTypeKeyword Keyword,
1097                                  NestedNameSpecifierLoc QualifierLoc,
1098                                  QualType Named) {
1099     return SemaRef.Context.getElaboratedType(Keyword,
1100                                          QualifierLoc.getNestedNameSpecifier(),
1101                                              Named);
1102   }
1103 
1104   /// Build a new typename type that refers to a template-id.
1105   ///
1106   /// By default, builds a new DependentNameType type from the
1107   /// nested-name-specifier and the given type. Subclasses may override
1108   /// this routine to provide different behavior.
1109   QualType RebuildDependentTemplateSpecializationType(
1110                                           ElaboratedTypeKeyword Keyword,
1111                                           NestedNameSpecifierLoc QualifierLoc,
1112                                           SourceLocation TemplateKWLoc,
1113                                           const IdentifierInfo *Name,
1114                                           SourceLocation NameLoc,
1115                                           TemplateArgumentListInfo &Args,
1116                                           bool AllowInjectedClassName) {
1117     // Rebuild the template name.
1118     // TODO: avoid TemplateName abstraction
1119     CXXScopeSpec SS;
1120     SS.Adopt(QualifierLoc);
1121     TemplateName InstName = getDerived().RebuildTemplateName(
1122         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1123         AllowInjectedClassName);
1124 
1125     if (InstName.isNull())
1126       return QualType();
1127 
1128     // If it's still dependent, make a dependent specialization.
1129     if (InstName.getAsDependentTemplateName())
1130       return SemaRef.Context.getDependentTemplateSpecializationType(
1131           Keyword, QualifierLoc.getNestedNameSpecifier(), Name,
1132           Args.arguments());
1133 
1134     // Otherwise, make an elaborated type wrapping a non-dependent
1135     // specialization.
1136     QualType T =
1137         getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1138     if (T.isNull())
1139       return QualType();
1140     return SemaRef.Context.getElaboratedType(
1141         Keyword, QualifierLoc.getNestedNameSpecifier(), T);
1142   }
1143 
1144   /// Build a new typename type that refers to an identifier.
1145   ///
1146   /// By default, performs semantic analysis when building the typename type
1147   /// (or elaborated type). Subclasses may override this routine to provide
1148   /// different behavior.
1149   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1150                                     SourceLocation KeywordLoc,
1151                                     NestedNameSpecifierLoc QualifierLoc,
1152                                     const IdentifierInfo *Id,
1153                                     SourceLocation IdLoc,
1154                                     bool DeducedTSTContext) {
1155     CXXScopeSpec SS;
1156     SS.Adopt(QualifierLoc);
1157 
1158     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1159       // If the name is still dependent, just build a new dependent name type.
1160       if (!SemaRef.computeDeclContext(SS))
1161         return SemaRef.Context.getDependentNameType(Keyword,
1162                                           QualifierLoc.getNestedNameSpecifier(),
1163                                                     Id);
1164     }
1165 
1166     if (Keyword == ElaboratedTypeKeyword::None ||
1167         Keyword == ElaboratedTypeKeyword::Typename) {
1168       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1169                                        *Id, IdLoc, DeducedTSTContext);
1170     }
1171 
1172     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1173 
1174     // We had a dependent elaborated-type-specifier that has been transformed
1175     // into a non-dependent elaborated-type-specifier. Find the tag we're
1176     // referring to.
1177     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1178     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1179     if (!DC)
1180       return QualType();
1181 
1182     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1183       return QualType();
1184 
1185     TagDecl *Tag = nullptr;
1186     SemaRef.LookupQualifiedName(Result, DC);
1187     switch (Result.getResultKind()) {
1188       case LookupResult::NotFound:
1189       case LookupResult::NotFoundInCurrentInstantiation:
1190         break;
1191 
1192       case LookupResult::Found:
1193         Tag = Result.getAsSingle<TagDecl>();
1194         break;
1195 
1196       case LookupResult::FoundOverloaded:
1197       case LookupResult::FoundUnresolvedValue:
1198         llvm_unreachable("Tag lookup cannot find non-tags");
1199 
1200       case LookupResult::Ambiguous:
1201         // Let the LookupResult structure handle ambiguities.
1202         return QualType();
1203     }
1204 
1205     if (!Tag) {
1206       // Check where the name exists but isn't a tag type and use that to emit
1207       // better diagnostics.
1208       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1209       SemaRef.LookupQualifiedName(Result, DC);
1210       switch (Result.getResultKind()) {
1211         case LookupResult::Found:
1212         case LookupResult::FoundOverloaded:
1213         case LookupResult::FoundUnresolvedValue: {
1214           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1215           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1216           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag)
1217               << SomeDecl << NTK << llvm::to_underlying(Kind);
1218           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1219           break;
1220         }
1221         default:
1222           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1223               << llvm::to_underlying(Kind) << Id << DC
1224               << QualifierLoc.getSourceRange();
1225           break;
1226       }
1227       return QualType();
1228     }
1229 
1230     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1231                                               IdLoc, Id)) {
1232       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1233       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1234       return QualType();
1235     }
1236 
1237     // Build the elaborated-type-specifier type.
1238     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1239     return SemaRef.Context.getElaboratedType(Keyword,
1240                                          QualifierLoc.getNestedNameSpecifier(),
1241                                              T);
1242   }
1243 
1244   /// Build a new pack expansion type.
1245   ///
1246   /// By default, builds a new PackExpansionType type from the given pattern.
1247   /// Subclasses may override this routine to provide different behavior.
1248   QualType RebuildPackExpansionType(QualType Pattern, SourceRange PatternRange,
1249                                     SourceLocation EllipsisLoc,
1250                                     std::optional<unsigned> NumExpansions) {
1251     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1252                                         NumExpansions);
1253   }
1254 
1255   /// Build a new atomic type given its value type.
1256   ///
1257   /// By default, performs semantic analysis when building the atomic type.
1258   /// Subclasses may override this routine to provide different behavior.
1259   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1260 
1261   /// Build a new pipe type given its value type.
1262   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1263                            bool isReadPipe);
1264 
1265   /// Build a bit-precise int given its value type.
1266   QualType RebuildBitIntType(bool IsUnsigned, unsigned NumBits,
1267                              SourceLocation Loc);
1268 
1269   /// Build a dependent bit-precise int given its value type.
1270   QualType RebuildDependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr,
1271                                       SourceLocation Loc);
1272 
1273   /// Build a new template name given a nested name specifier, a flag
1274   /// indicating whether the "template" keyword was provided, and the template
1275   /// that the template name refers to.
1276   ///
1277   /// By default, builds the new template name directly. Subclasses may override
1278   /// this routine to provide different behavior.
1279   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1280                                    bool TemplateKW,
1281                                    TemplateDecl *Template);
1282 
1283   /// Build a new template name given a nested name specifier and the
1284   /// name that is referred to as a template.
1285   ///
1286   /// By default, performs semantic analysis to determine whether the name can
1287   /// be resolved to a specific template, then builds the appropriate kind of
1288   /// template name. Subclasses may override this routine to provide different
1289   /// behavior.
1290   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1291                                    SourceLocation TemplateKWLoc,
1292                                    const IdentifierInfo &Name,
1293                                    SourceLocation NameLoc, QualType ObjectType,
1294                                    NamedDecl *FirstQualifierInScope,
1295                                    bool AllowInjectedClassName);
1296 
1297   /// Build a new template name given a nested name specifier and the
1298   /// overloaded operator name that is referred to as a template.
1299   ///
1300   /// By default, performs semantic analysis to determine whether the name can
1301   /// be resolved to a specific template, then builds the appropriate kind of
1302   /// template name. Subclasses may override this routine to provide different
1303   /// behavior.
1304   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1305                                    SourceLocation TemplateKWLoc,
1306                                    OverloadedOperatorKind Operator,
1307                                    SourceLocation NameLoc, QualType ObjectType,
1308                                    bool AllowInjectedClassName);
1309 
1310   /// Build a new template name given a template template parameter pack
1311   /// and the
1312   ///
1313   /// By default, performs semantic analysis to determine whether the name can
1314   /// be resolved to a specific template, then builds the appropriate kind of
1315   /// template name. Subclasses may override this routine to provide different
1316   /// behavior.
1317   TemplateName RebuildTemplateName(const TemplateArgument &ArgPack,
1318                                    Decl *AssociatedDecl, unsigned Index,
1319                                    bool Final) {
1320     return getSema().Context.getSubstTemplateTemplateParmPack(
1321         ArgPack, AssociatedDecl, Index, Final);
1322   }
1323 
1324   /// Build a new compound statement.
1325   ///
1326   /// By default, performs semantic analysis to build the new statement.
1327   /// Subclasses may override this routine to provide different behavior.
1328   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1329                                        MultiStmtArg Statements,
1330                                        SourceLocation RBraceLoc,
1331                                        bool IsStmtExpr) {
1332     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1333                                        IsStmtExpr);
1334   }
1335 
1336   /// Build a new case statement.
1337   ///
1338   /// By default, performs semantic analysis to build the new statement.
1339   /// Subclasses may override this routine to provide different behavior.
1340   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1341                                    Expr *LHS,
1342                                    SourceLocation EllipsisLoc,
1343                                    Expr *RHS,
1344                                    SourceLocation ColonLoc) {
1345     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1346                                    ColonLoc);
1347   }
1348 
1349   /// Attach the body to a new case statement.
1350   ///
1351   /// By default, performs semantic analysis to build the new statement.
1352   /// Subclasses may override this routine to provide different behavior.
1353   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1354     getSema().ActOnCaseStmtBody(S, Body);
1355     return S;
1356   }
1357 
1358   /// Build a new default statement.
1359   ///
1360   /// By default, performs semantic analysis to build the new statement.
1361   /// Subclasses may override this routine to provide different behavior.
1362   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1363                                       SourceLocation ColonLoc,
1364                                       Stmt *SubStmt) {
1365     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1366                                       /*CurScope=*/nullptr);
1367   }
1368 
1369   /// Build a new label statement.
1370   ///
1371   /// By default, performs semantic analysis to build the new statement.
1372   /// Subclasses may override this routine to provide different behavior.
1373   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1374                               SourceLocation ColonLoc, Stmt *SubStmt) {
1375     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1376   }
1377 
1378   /// Build a new attributed statement.
1379   ///
1380   /// By default, performs semantic analysis to build the new statement.
1381   /// Subclasses may override this routine to provide different behavior.
1382   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1383                                    ArrayRef<const Attr *> Attrs,
1384                                    Stmt *SubStmt) {
1385     if (SemaRef.CheckRebuiltStmtAttributes(Attrs))
1386       return StmtError();
1387     return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1388   }
1389 
1390   /// Build a new "if" statement.
1391   ///
1392   /// By default, performs semantic analysis to build the new statement.
1393   /// Subclasses may override this routine to provide different behavior.
1394   StmtResult RebuildIfStmt(SourceLocation IfLoc, IfStatementKind Kind,
1395                            SourceLocation LParenLoc, Sema::ConditionResult Cond,
1396                            SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1397                            SourceLocation ElseLoc, Stmt *Else) {
1398     return getSema().ActOnIfStmt(IfLoc, Kind, LParenLoc, Init, Cond, RParenLoc,
1399                                  Then, ElseLoc, Else);
1400   }
1401 
1402   /// Start building a new switch statement.
1403   ///
1404   /// By default, performs semantic analysis to build the new statement.
1405   /// Subclasses may override this routine to provide different behavior.
1406   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1407                                     SourceLocation LParenLoc, Stmt *Init,
1408                                     Sema::ConditionResult Cond,
1409                                     SourceLocation RParenLoc) {
1410     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1411                                             RParenLoc);
1412   }
1413 
1414   /// Attach the body to the switch statement.
1415   ///
1416   /// By default, performs semantic analysis to build the new statement.
1417   /// Subclasses may override this routine to provide different behavior.
1418   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1419                                    Stmt *Switch, Stmt *Body) {
1420     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1421   }
1422 
1423   /// Build a new while statement.
1424   ///
1425   /// By default, performs semantic analysis to build the new statement.
1426   /// Subclasses may override this routine to provide different behavior.
1427   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1428                               Sema::ConditionResult Cond,
1429                               SourceLocation RParenLoc, Stmt *Body) {
1430     return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1431   }
1432 
1433   /// Build a new do-while statement.
1434   ///
1435   /// By default, performs semantic analysis to build the new statement.
1436   /// Subclasses may override this routine to provide different behavior.
1437   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1438                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1439                            Expr *Cond, SourceLocation RParenLoc) {
1440     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1441                                  Cond, RParenLoc);
1442   }
1443 
1444   /// Build a new for statement.
1445   ///
1446   /// By default, performs semantic analysis to build the new statement.
1447   /// Subclasses may override this routine to provide different behavior.
1448   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1449                             Stmt *Init, Sema::ConditionResult Cond,
1450                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1451                             Stmt *Body) {
1452     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1453                                   Inc, RParenLoc, Body);
1454   }
1455 
1456   /// Build a new goto statement.
1457   ///
1458   /// By default, performs semantic analysis to build the new statement.
1459   /// Subclasses may override this routine to provide different behavior.
1460   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1461                              LabelDecl *Label) {
1462     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1463   }
1464 
1465   /// Build a new indirect goto statement.
1466   ///
1467   /// By default, performs semantic analysis to build the new statement.
1468   /// Subclasses may override this routine to provide different behavior.
1469   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1470                                      SourceLocation StarLoc,
1471                                      Expr *Target) {
1472     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1473   }
1474 
1475   /// Build a new return statement.
1476   ///
1477   /// By default, performs semantic analysis to build the new statement.
1478   /// Subclasses may override this routine to provide different behavior.
1479   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1480     return getSema().BuildReturnStmt(ReturnLoc, Result);
1481   }
1482 
1483   /// Build a new declaration statement.
1484   ///
1485   /// By default, performs semantic analysis to build the new statement.
1486   /// Subclasses may override this routine to provide different behavior.
1487   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1488                              SourceLocation StartLoc, SourceLocation EndLoc) {
1489     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1490     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1491   }
1492 
1493   /// Build a new inline asm statement.
1494   ///
1495   /// By default, performs semantic analysis to build the new statement.
1496   /// Subclasses may override this routine to provide different behavior.
1497   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1498                                bool IsVolatile, unsigned NumOutputs,
1499                                unsigned NumInputs, IdentifierInfo **Names,
1500                                MultiExprArg Constraints, MultiExprArg Exprs,
1501                                Expr *AsmString, MultiExprArg Clobbers,
1502                                unsigned NumLabels,
1503                                SourceLocation RParenLoc) {
1504     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1505                                      NumInputs, Names, Constraints, Exprs,
1506                                      AsmString, Clobbers, NumLabels, RParenLoc);
1507   }
1508 
1509   /// Build a new MS style inline asm statement.
1510   ///
1511   /// By default, performs semantic analysis to build the new statement.
1512   /// Subclasses may override this routine to provide different behavior.
1513   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1514                               ArrayRef<Token> AsmToks,
1515                               StringRef AsmString,
1516                               unsigned NumOutputs, unsigned NumInputs,
1517                               ArrayRef<StringRef> Constraints,
1518                               ArrayRef<StringRef> Clobbers,
1519                               ArrayRef<Expr*> Exprs,
1520                               SourceLocation EndLoc) {
1521     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1522                                     NumOutputs, NumInputs,
1523                                     Constraints, Clobbers, Exprs, EndLoc);
1524   }
1525 
1526   /// Build a new co_return statement.
1527   ///
1528   /// By default, performs semantic analysis to build the new statement.
1529   /// Subclasses may override this routine to provide different behavior.
1530   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1531                                  bool IsImplicit) {
1532     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1533   }
1534 
1535   /// Build a new co_await expression.
1536   ///
1537   /// By default, performs semantic analysis to build the new expression.
1538   /// Subclasses may override this routine to provide different behavior.
1539   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand,
1540                                 UnresolvedLookupExpr *OpCoawaitLookup,
1541                                 bool IsImplicit) {
1542     // This function rebuilds a coawait-expr given its operator.
1543     // For an explicit coawait-expr, the rebuild involves the full set
1544     // of transformations performed by BuildUnresolvedCoawaitExpr(),
1545     // including calling await_transform().
1546     // For an implicit coawait-expr, we need to rebuild the "operator
1547     // coawait" but not await_transform(), so use BuildResolvedCoawaitExpr().
1548     // This mirrors how the implicit CoawaitExpr is originally created
1549     // in Sema::ActOnCoroutineBodyStart().
1550     if (IsImplicit) {
1551       ExprResult Suspend = getSema().BuildOperatorCoawaitCall(
1552           CoawaitLoc, Operand, OpCoawaitLookup);
1553       if (Suspend.isInvalid())
1554         return ExprError();
1555       return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Operand,
1556                                                 Suspend.get(), true);
1557     }
1558 
1559     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Operand,
1560                                                 OpCoawaitLookup);
1561   }
1562 
1563   /// Build a new co_await expression.
1564   ///
1565   /// By default, performs semantic analysis to build the new expression.
1566   /// Subclasses may override this routine to provide different behavior.
1567   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1568                                          Expr *Result,
1569                                          UnresolvedLookupExpr *Lookup) {
1570     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1571   }
1572 
1573   /// Build a new co_yield expression.
1574   ///
1575   /// By default, performs semantic analysis to build the new expression.
1576   /// Subclasses may override this routine to provide different behavior.
1577   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1578     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1579   }
1580 
1581   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1582     return getSema().BuildCoroutineBodyStmt(Args);
1583   }
1584 
1585   /// Build a new Objective-C \@try statement.
1586   ///
1587   /// By default, performs semantic analysis to build the new statement.
1588   /// Subclasses may override this routine to provide different behavior.
1589   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1590                                         Stmt *TryBody,
1591                                         MultiStmtArg CatchStmts,
1592                                         Stmt *Finally) {
1593     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1594                                         Finally);
1595   }
1596 
1597   /// Rebuild an Objective-C exception declaration.
1598   ///
1599   /// By default, performs semantic analysis to build the new declaration.
1600   /// Subclasses may override this routine to provide different behavior.
1601   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1602                                     TypeSourceInfo *TInfo, QualType T) {
1603     return getSema().BuildObjCExceptionDecl(TInfo, T,
1604                                             ExceptionDecl->getInnerLocStart(),
1605                                             ExceptionDecl->getLocation(),
1606                                             ExceptionDecl->getIdentifier());
1607   }
1608 
1609   /// Build a new Objective-C \@catch statement.
1610   ///
1611   /// By default, performs semantic analysis to build the new statement.
1612   /// Subclasses may override this routine to provide different behavior.
1613   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1614                                           SourceLocation RParenLoc,
1615                                           VarDecl *Var,
1616                                           Stmt *Body) {
1617     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1618                                           Var, Body);
1619   }
1620 
1621   /// Build a new Objective-C \@finally statement.
1622   ///
1623   /// By default, performs semantic analysis to build the new statement.
1624   /// Subclasses may override this routine to provide different behavior.
1625   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1626                                             Stmt *Body) {
1627     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1628   }
1629 
1630   /// Build a new Objective-C \@throw statement.
1631   ///
1632   /// By default, performs semantic analysis to build the new statement.
1633   /// Subclasses may override this routine to provide different behavior.
1634   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1635                                           Expr *Operand) {
1636     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1637   }
1638 
1639   /// Build a new OpenMP Canonical loop.
1640   ///
1641   /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1642   /// OMPCanonicalLoop.
1643   StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1644     return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1645   }
1646 
1647   /// Build a new OpenMP executable directive.
1648   ///
1649   /// By default, performs semantic analysis to build the new statement.
1650   /// Subclasses may override this routine to provide different behavior.
1651   StmtResult RebuildOMPExecutableDirective(
1652       OpenMPDirectiveKind Kind, DeclarationNameInfo DirName,
1653       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
1654       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc,
1655       OpenMPDirectiveKind PrevMappedDirective = OMPD_unknown) {
1656 
1657     return getSema().ActOnOpenMPExecutableDirective(
1658         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc,
1659         PrevMappedDirective);
1660   }
1661 
1662   /// Build a new OpenMP 'if' clause.
1663   ///
1664   /// By default, performs semantic analysis to build the new OpenMP clause.
1665   /// Subclasses may override this routine to provide different behavior.
1666   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1667                                 Expr *Condition, SourceLocation StartLoc,
1668                                 SourceLocation LParenLoc,
1669                                 SourceLocation NameModifierLoc,
1670                                 SourceLocation ColonLoc,
1671                                 SourceLocation EndLoc) {
1672     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1673                                          LParenLoc, NameModifierLoc, ColonLoc,
1674                                          EndLoc);
1675   }
1676 
1677   /// Build a new OpenMP 'final' clause.
1678   ///
1679   /// By default, performs semantic analysis to build the new OpenMP clause.
1680   /// Subclasses may override this routine to provide different behavior.
1681   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1682                                    SourceLocation LParenLoc,
1683                                    SourceLocation EndLoc) {
1684     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1685                                             EndLoc);
1686   }
1687 
1688   /// Build a new OpenMP 'num_threads' clause.
1689   ///
1690   /// By default, performs semantic analysis to build the new OpenMP clause.
1691   /// Subclasses may override this routine to provide different behavior.
1692   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1693                                         SourceLocation StartLoc,
1694                                         SourceLocation LParenLoc,
1695                                         SourceLocation EndLoc) {
1696     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1697                                                  LParenLoc, EndLoc);
1698   }
1699 
1700   /// Build a new OpenMP 'safelen' clause.
1701   ///
1702   /// By default, performs semantic analysis to build the new OpenMP clause.
1703   /// Subclasses may override this routine to provide different behavior.
1704   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1705                                      SourceLocation LParenLoc,
1706                                      SourceLocation EndLoc) {
1707     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1708   }
1709 
1710   /// Build a new OpenMP 'simdlen' clause.
1711   ///
1712   /// By default, performs semantic analysis to build the new OpenMP clause.
1713   /// Subclasses may override this routine to provide different behavior.
1714   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1715                                      SourceLocation LParenLoc,
1716                                      SourceLocation EndLoc) {
1717     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1718   }
1719 
1720   OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1721                                    SourceLocation StartLoc,
1722                                    SourceLocation LParenLoc,
1723                                    SourceLocation EndLoc) {
1724     return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1725   }
1726 
1727   /// Build a new OpenMP 'full' clause.
1728   OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1729                                   SourceLocation EndLoc) {
1730     return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1731   }
1732 
1733   /// Build a new OpenMP 'partial' clause.
1734   OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1735                                      SourceLocation LParenLoc,
1736                                      SourceLocation EndLoc) {
1737     return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1738                                               EndLoc);
1739   }
1740 
1741   /// Build a new OpenMP 'allocator' clause.
1742   ///
1743   /// By default, performs semantic analysis to build the new OpenMP clause.
1744   /// Subclasses may override this routine to provide different behavior.
1745   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1746                                        SourceLocation LParenLoc,
1747                                        SourceLocation EndLoc) {
1748     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1749   }
1750 
1751   /// Build a new OpenMP 'collapse' clause.
1752   ///
1753   /// By default, performs semantic analysis to build the new OpenMP clause.
1754   /// Subclasses may override this routine to provide different behavior.
1755   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1756                                       SourceLocation LParenLoc,
1757                                       SourceLocation EndLoc) {
1758     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1759                                                EndLoc);
1760   }
1761 
1762   /// Build a new OpenMP 'default' clause.
1763   ///
1764   /// By default, performs semantic analysis to build the new OpenMP clause.
1765   /// Subclasses may override this routine to provide different behavior.
1766   OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1767                                      SourceLocation StartLoc,
1768                                      SourceLocation LParenLoc,
1769                                      SourceLocation EndLoc) {
1770     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1771                                               StartLoc, LParenLoc, EndLoc);
1772   }
1773 
1774   /// Build a new OpenMP 'proc_bind' clause.
1775   ///
1776   /// By default, performs semantic analysis to build the new OpenMP clause.
1777   /// Subclasses may override this routine to provide different behavior.
1778   OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1779                                       SourceLocation KindKwLoc,
1780                                       SourceLocation StartLoc,
1781                                       SourceLocation LParenLoc,
1782                                       SourceLocation EndLoc) {
1783     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1784                                                StartLoc, LParenLoc, EndLoc);
1785   }
1786 
1787   /// Build a new OpenMP 'schedule' clause.
1788   ///
1789   /// By default, performs semantic analysis to build the new OpenMP clause.
1790   /// Subclasses may override this routine to provide different behavior.
1791   OMPClause *RebuildOMPScheduleClause(
1792       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1793       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1794       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1795       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1796     return getSema().ActOnOpenMPScheduleClause(
1797         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1798         CommaLoc, EndLoc);
1799   }
1800 
1801   /// Build a new OpenMP 'ordered' clause.
1802   ///
1803   /// By default, performs semantic analysis to build the new OpenMP clause.
1804   /// Subclasses may override this routine to provide different behavior.
1805   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1806                                      SourceLocation EndLoc,
1807                                      SourceLocation LParenLoc, Expr *Num) {
1808     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1809   }
1810 
1811   /// Build a new OpenMP 'private' clause.
1812   ///
1813   /// By default, performs semantic analysis to build the new OpenMP clause.
1814   /// Subclasses may override this routine to provide different behavior.
1815   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1816                                      SourceLocation StartLoc,
1817                                      SourceLocation LParenLoc,
1818                                      SourceLocation EndLoc) {
1819     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1820                                               EndLoc);
1821   }
1822 
1823   /// Build a new OpenMP 'firstprivate' clause.
1824   ///
1825   /// By default, performs semantic analysis to build the new OpenMP clause.
1826   /// Subclasses may override this routine to provide different behavior.
1827   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1828                                           SourceLocation StartLoc,
1829                                           SourceLocation LParenLoc,
1830                                           SourceLocation EndLoc) {
1831     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1832                                                    EndLoc);
1833   }
1834 
1835   /// Build a new OpenMP 'lastprivate' clause.
1836   ///
1837   /// By default, performs semantic analysis to build the new OpenMP clause.
1838   /// Subclasses may override this routine to provide different behavior.
1839   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1840                                          OpenMPLastprivateModifier LPKind,
1841                                          SourceLocation LPKindLoc,
1842                                          SourceLocation ColonLoc,
1843                                          SourceLocation StartLoc,
1844                                          SourceLocation LParenLoc,
1845                                          SourceLocation EndLoc) {
1846     return getSema().ActOnOpenMPLastprivateClause(
1847         VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1848   }
1849 
1850   /// Build a new OpenMP 'shared' clause.
1851   ///
1852   /// By default, performs semantic analysis to build the new OpenMP clause.
1853   /// Subclasses may override this routine to provide different behavior.
1854   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1855                                     SourceLocation StartLoc,
1856                                     SourceLocation LParenLoc,
1857                                     SourceLocation EndLoc) {
1858     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1859                                              EndLoc);
1860   }
1861 
1862   /// Build a new OpenMP 'reduction' clause.
1863   ///
1864   /// By default, performs semantic analysis to build the new statement.
1865   /// Subclasses may override this routine to provide different behavior.
1866   OMPClause *RebuildOMPReductionClause(
1867       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1868       SourceLocation StartLoc, SourceLocation LParenLoc,
1869       SourceLocation ModifierLoc, SourceLocation ColonLoc,
1870       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1871       const DeclarationNameInfo &ReductionId,
1872       ArrayRef<Expr *> UnresolvedReductions) {
1873     return getSema().ActOnOpenMPReductionClause(
1874         VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1875         ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1876   }
1877 
1878   /// Build a new OpenMP 'task_reduction' clause.
1879   ///
1880   /// By default, performs semantic analysis to build the new statement.
1881   /// Subclasses may override this routine to provide different behavior.
1882   OMPClause *RebuildOMPTaskReductionClause(
1883       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1884       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1885       CXXScopeSpec &ReductionIdScopeSpec,
1886       const DeclarationNameInfo &ReductionId,
1887       ArrayRef<Expr *> UnresolvedReductions) {
1888     return getSema().ActOnOpenMPTaskReductionClause(
1889         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1890         ReductionId, UnresolvedReductions);
1891   }
1892 
1893   /// Build a new OpenMP 'in_reduction' clause.
1894   ///
1895   /// By default, performs semantic analysis to build the new statement.
1896   /// Subclasses may override this routine to provide different behavior.
1897   OMPClause *
1898   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1899                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1900                               SourceLocation EndLoc,
1901                               CXXScopeSpec &ReductionIdScopeSpec,
1902                               const DeclarationNameInfo &ReductionId,
1903                               ArrayRef<Expr *> UnresolvedReductions) {
1904     return getSema().ActOnOpenMPInReductionClause(
1905         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1906         ReductionId, UnresolvedReductions);
1907   }
1908 
1909   /// Build a new OpenMP 'linear' clause.
1910   ///
1911   /// By default, performs semantic analysis to build the new OpenMP clause.
1912   /// Subclasses may override this routine to provide different behavior.
1913   OMPClause *RebuildOMPLinearClause(
1914       ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
1915       SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier,
1916       SourceLocation ModifierLoc, SourceLocation ColonLoc,
1917       SourceLocation StepModifierLoc, SourceLocation EndLoc) {
1918     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1919                                              Modifier, ModifierLoc, ColonLoc,
1920                                              StepModifierLoc, EndLoc);
1921   }
1922 
1923   /// Build a new OpenMP 'aligned' clause.
1924   ///
1925   /// By default, performs semantic analysis to build the new OpenMP clause.
1926   /// Subclasses may override this routine to provide different behavior.
1927   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1928                                      SourceLocation StartLoc,
1929                                      SourceLocation LParenLoc,
1930                                      SourceLocation ColonLoc,
1931                                      SourceLocation EndLoc) {
1932     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1933                                               LParenLoc, ColonLoc, EndLoc);
1934   }
1935 
1936   /// Build a new OpenMP 'copyin' clause.
1937   ///
1938   /// By default, performs semantic analysis to build the new OpenMP clause.
1939   /// Subclasses may override this routine to provide different behavior.
1940   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1941                                     SourceLocation StartLoc,
1942                                     SourceLocation LParenLoc,
1943                                     SourceLocation EndLoc) {
1944     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1945                                              EndLoc);
1946   }
1947 
1948   /// Build a new OpenMP 'copyprivate' clause.
1949   ///
1950   /// By default, performs semantic analysis to build the new OpenMP clause.
1951   /// Subclasses may override this routine to provide different behavior.
1952   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1953                                          SourceLocation StartLoc,
1954                                          SourceLocation LParenLoc,
1955                                          SourceLocation EndLoc) {
1956     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1957                                                   EndLoc);
1958   }
1959 
1960   /// Build a new OpenMP 'flush' pseudo clause.
1961   ///
1962   /// By default, performs semantic analysis to build the new OpenMP clause.
1963   /// Subclasses may override this routine to provide different behavior.
1964   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1965                                    SourceLocation StartLoc,
1966                                    SourceLocation LParenLoc,
1967                                    SourceLocation EndLoc) {
1968     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1969                                             EndLoc);
1970   }
1971 
1972   /// Build a new OpenMP 'depobj' pseudo clause.
1973   ///
1974   /// By default, performs semantic analysis to build the new OpenMP clause.
1975   /// Subclasses may override this routine to provide different behavior.
1976   OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1977                                     SourceLocation LParenLoc,
1978                                     SourceLocation EndLoc) {
1979     return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1980                                              EndLoc);
1981   }
1982 
1983   /// Build a new OpenMP 'depend' pseudo clause.
1984   ///
1985   /// By default, performs semantic analysis to build the new OpenMP clause.
1986   /// Subclasses may override this routine to provide different behavior.
1987   OMPClause *RebuildOMPDependClause(OMPDependClause::DependDataTy Data,
1988                                     Expr *DepModifier, ArrayRef<Expr *> VarList,
1989                                     SourceLocation StartLoc,
1990                                     SourceLocation LParenLoc,
1991                                     SourceLocation EndLoc) {
1992     return getSema().ActOnOpenMPDependClause(Data, DepModifier, VarList,
1993                                              StartLoc, LParenLoc, EndLoc);
1994   }
1995 
1996   /// Build a new OpenMP 'device' clause.
1997   ///
1998   /// By default, performs semantic analysis to build the new statement.
1999   /// Subclasses may override this routine to provide different behavior.
2000   OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
2001                                     Expr *Device, SourceLocation StartLoc,
2002                                     SourceLocation LParenLoc,
2003                                     SourceLocation ModifierLoc,
2004                                     SourceLocation EndLoc) {
2005     return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
2006                                              LParenLoc, ModifierLoc, EndLoc);
2007   }
2008 
2009   /// Build a new OpenMP 'map' clause.
2010   ///
2011   /// By default, performs semantic analysis to build the new OpenMP clause.
2012   /// Subclasses may override this routine to provide different behavior.
2013   OMPClause *RebuildOMPMapClause(
2014       Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
2015       ArrayRef<SourceLocation> MapTypeModifiersLoc,
2016       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
2017       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
2018       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
2019       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
2020     return getSema().ActOnOpenMPMapClause(
2021         IteratorModifier, MapTypeModifiers, MapTypeModifiersLoc,
2022         MapperIdScopeSpec, MapperId, MapType, IsMapTypeImplicit, MapLoc,
2023         ColonLoc, VarList, Locs,
2024         /*NoDiagnose=*/false, UnresolvedMappers);
2025   }
2026 
2027   /// Build a new OpenMP 'allocate' clause.
2028   ///
2029   /// By default, performs semantic analysis to build the new OpenMP clause.
2030   /// Subclasses may override this routine to provide different behavior.
2031   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
2032                                       SourceLocation StartLoc,
2033                                       SourceLocation LParenLoc,
2034                                       SourceLocation ColonLoc,
2035                                       SourceLocation EndLoc) {
2036     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
2037                                                LParenLoc, ColonLoc, EndLoc);
2038   }
2039 
2040   /// Build a new OpenMP 'num_teams' clause.
2041   ///
2042   /// By default, performs semantic analysis to build the new statement.
2043   /// Subclasses may override this routine to provide different behavior.
2044   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
2045                                       SourceLocation LParenLoc,
2046                                       SourceLocation EndLoc) {
2047     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
2048                                                EndLoc);
2049   }
2050 
2051   /// Build a new OpenMP 'thread_limit' clause.
2052   ///
2053   /// By default, performs semantic analysis to build the new statement.
2054   /// Subclasses may override this routine to provide different behavior.
2055   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
2056                                          SourceLocation StartLoc,
2057                                          SourceLocation LParenLoc,
2058                                          SourceLocation EndLoc) {
2059     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
2060                                                   LParenLoc, EndLoc);
2061   }
2062 
2063   /// Build a new OpenMP 'priority' clause.
2064   ///
2065   /// By default, performs semantic analysis to build the new statement.
2066   /// Subclasses may override this routine to provide different behavior.
2067   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
2068                                       SourceLocation LParenLoc,
2069                                       SourceLocation EndLoc) {
2070     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
2071                                                EndLoc);
2072   }
2073 
2074   /// Build a new OpenMP 'grainsize' clause.
2075   ///
2076   /// By default, performs semantic analysis to build the new statement.
2077   /// Subclasses may override this routine to provide different behavior.
2078   OMPClause *RebuildOMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier,
2079                                        Expr *Device, SourceLocation StartLoc,
2080                                        SourceLocation LParenLoc,
2081                                        SourceLocation ModifierLoc,
2082                                        SourceLocation EndLoc) {
2083     return getSema().ActOnOpenMPGrainsizeClause(Modifier, Device, StartLoc,
2084                                                 LParenLoc, ModifierLoc, EndLoc);
2085   }
2086 
2087   /// Build a new OpenMP 'num_tasks' clause.
2088   ///
2089   /// By default, performs semantic analysis to build the new statement.
2090   /// Subclasses may override this routine to provide different behavior.
2091   OMPClause *RebuildOMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier,
2092                                       Expr *NumTasks, SourceLocation StartLoc,
2093                                       SourceLocation LParenLoc,
2094                                       SourceLocation ModifierLoc,
2095                                       SourceLocation EndLoc) {
2096     return getSema().ActOnOpenMPNumTasksClause(Modifier, NumTasks, StartLoc,
2097                                                LParenLoc, ModifierLoc, EndLoc);
2098   }
2099 
2100   /// Build a new OpenMP 'hint' clause.
2101   ///
2102   /// By default, performs semantic analysis to build the new statement.
2103   /// Subclasses may override this routine to provide different behavior.
2104   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2105                                   SourceLocation LParenLoc,
2106                                   SourceLocation EndLoc) {
2107     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2108   }
2109 
2110   /// Build a new OpenMP 'detach' clause.
2111   ///
2112   /// By default, performs semantic analysis to build the new statement.
2113   /// Subclasses may override this routine to provide different behavior.
2114   OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2115                                     SourceLocation LParenLoc,
2116                                     SourceLocation EndLoc) {
2117     return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2118   }
2119 
2120   /// Build a new OpenMP 'dist_schedule' clause.
2121   ///
2122   /// By default, performs semantic analysis to build the new OpenMP clause.
2123   /// Subclasses may override this routine to provide different behavior.
2124   OMPClause *
2125   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2126                                Expr *ChunkSize, SourceLocation StartLoc,
2127                                SourceLocation LParenLoc, SourceLocation KindLoc,
2128                                SourceLocation CommaLoc, SourceLocation EndLoc) {
2129     return getSema().ActOnOpenMPDistScheduleClause(
2130         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2131   }
2132 
2133   /// Build a new OpenMP 'to' clause.
2134   ///
2135   /// By default, performs semantic analysis to build the new statement.
2136   /// Subclasses may override this routine to provide different behavior.
2137   OMPClause *
2138   RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2139                      ArrayRef<SourceLocation> MotionModifiersLoc,
2140                      CXXScopeSpec &MapperIdScopeSpec,
2141                      DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2142                      ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2143                      ArrayRef<Expr *> UnresolvedMappers) {
2144     return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2145                                          MapperIdScopeSpec, MapperId, ColonLoc,
2146                                          VarList, Locs, UnresolvedMappers);
2147   }
2148 
2149   /// Build a new OpenMP 'from' clause.
2150   ///
2151   /// By default, performs semantic analysis to build the new statement.
2152   /// Subclasses may override this routine to provide different behavior.
2153   OMPClause *
2154   RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2155                        ArrayRef<SourceLocation> MotionModifiersLoc,
2156                        CXXScopeSpec &MapperIdScopeSpec,
2157                        DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2158                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2159                        ArrayRef<Expr *> UnresolvedMappers) {
2160     return getSema().ActOnOpenMPFromClause(
2161         MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2162         ColonLoc, VarList, Locs, UnresolvedMappers);
2163   }
2164 
2165   /// Build a new OpenMP 'use_device_ptr' clause.
2166   ///
2167   /// By default, performs semantic analysis to build the new OpenMP clause.
2168   /// Subclasses may override this routine to provide different behavior.
2169   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2170                                           const OMPVarListLocTy &Locs) {
2171     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2172   }
2173 
2174   /// Build a new OpenMP 'use_device_addr' clause.
2175   ///
2176   /// By default, performs semantic analysis to build the new OpenMP clause.
2177   /// Subclasses may override this routine to provide different behavior.
2178   OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2179                                            const OMPVarListLocTy &Locs) {
2180     return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2181   }
2182 
2183   /// Build a new OpenMP 'is_device_ptr' clause.
2184   ///
2185   /// By default, performs semantic analysis to build the new OpenMP clause.
2186   /// Subclasses may override this routine to provide different behavior.
2187   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2188                                          const OMPVarListLocTy &Locs) {
2189     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2190   }
2191 
2192   /// Build a new OpenMP 'has_device_addr' clause.
2193   ///
2194   /// By default, performs semantic analysis to build the new OpenMP clause.
2195   /// Subclasses may override this routine to provide different behavior.
2196   OMPClause *RebuildOMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
2197                                            const OMPVarListLocTy &Locs) {
2198     return getSema().ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
2199   }
2200 
2201   /// Build a new OpenMP 'defaultmap' clause.
2202   ///
2203   /// By default, performs semantic analysis to build the new OpenMP clause.
2204   /// Subclasses may override this routine to provide different behavior.
2205   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2206                                         OpenMPDefaultmapClauseKind Kind,
2207                                         SourceLocation StartLoc,
2208                                         SourceLocation LParenLoc,
2209                                         SourceLocation MLoc,
2210                                         SourceLocation KindLoc,
2211                                         SourceLocation EndLoc) {
2212     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2213                                                  MLoc, KindLoc, EndLoc);
2214   }
2215 
2216   /// Build a new OpenMP 'nontemporal' clause.
2217   ///
2218   /// By default, performs semantic analysis to build the new OpenMP clause.
2219   /// Subclasses may override this routine to provide different behavior.
2220   OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2221                                          SourceLocation StartLoc,
2222                                          SourceLocation LParenLoc,
2223                                          SourceLocation EndLoc) {
2224     return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2225                                                   EndLoc);
2226   }
2227 
2228   /// Build a new OpenMP 'inclusive' clause.
2229   ///
2230   /// By default, performs semantic analysis to build the new OpenMP clause.
2231   /// Subclasses may override this routine to provide different behavior.
2232   OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2233                                        SourceLocation StartLoc,
2234                                        SourceLocation LParenLoc,
2235                                        SourceLocation EndLoc) {
2236     return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2237                                                 EndLoc);
2238   }
2239 
2240   /// Build a new OpenMP 'exclusive' clause.
2241   ///
2242   /// By default, performs semantic analysis to build the new OpenMP clause.
2243   /// Subclasses may override this routine to provide different behavior.
2244   OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2245                                        SourceLocation StartLoc,
2246                                        SourceLocation LParenLoc,
2247                                        SourceLocation EndLoc) {
2248     return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2249                                                 EndLoc);
2250   }
2251 
2252   /// Build a new OpenMP 'uses_allocators' clause.
2253   ///
2254   /// By default, performs semantic analysis to build the new OpenMP clause.
2255   /// Subclasses may override this routine to provide different behavior.
2256   OMPClause *RebuildOMPUsesAllocatorsClause(
2257       ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2258       SourceLocation LParenLoc, SourceLocation EndLoc) {
2259     return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2260                                                     Data);
2261   }
2262 
2263   /// Build a new OpenMP 'affinity' clause.
2264   ///
2265   /// By default, performs semantic analysis to build the new OpenMP clause.
2266   /// Subclasses may override this routine to provide different behavior.
2267   OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2268                                       SourceLocation LParenLoc,
2269                                       SourceLocation ColonLoc,
2270                                       SourceLocation EndLoc, Expr *Modifier,
2271                                       ArrayRef<Expr *> Locators) {
2272     return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2273                                                EndLoc, Modifier, Locators);
2274   }
2275 
2276   /// Build a new OpenMP 'order' clause.
2277   ///
2278   /// By default, performs semantic analysis to build the new OpenMP clause.
2279   /// Subclasses may override this routine to provide different behavior.
2280   OMPClause *RebuildOMPOrderClause(
2281       OpenMPOrderClauseKind Kind, SourceLocation KindKwLoc,
2282       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
2283       OpenMPOrderClauseModifier Modifier, SourceLocation ModifierKwLoc) {
2284     return getSema().ActOnOpenMPOrderClause(Modifier, Kind, StartLoc, LParenLoc,
2285                                             ModifierKwLoc, KindKwLoc, EndLoc);
2286   }
2287 
2288   /// Build a new OpenMP 'init' clause.
2289   ///
2290   /// By default, performs semantic analysis to build the new OpenMP clause.
2291   /// Subclasses may override this routine to provide different behavior.
2292   OMPClause *RebuildOMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo,
2293                                   SourceLocation StartLoc,
2294                                   SourceLocation LParenLoc,
2295                                   SourceLocation VarLoc,
2296                                   SourceLocation EndLoc) {
2297     return getSema().ActOnOpenMPInitClause(InteropVar, InteropInfo, StartLoc,
2298                                            LParenLoc, VarLoc, EndLoc);
2299   }
2300 
2301   /// Build a new OpenMP 'use' clause.
2302   ///
2303   /// By default, performs semantic analysis to build the new OpenMP clause.
2304   /// Subclasses may override this routine to provide different behavior.
2305   OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2306                                  SourceLocation LParenLoc,
2307                                  SourceLocation VarLoc, SourceLocation EndLoc) {
2308     return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2309                                           VarLoc, EndLoc);
2310   }
2311 
2312   /// Build a new OpenMP 'destroy' clause.
2313   ///
2314   /// By default, performs semantic analysis to build the new OpenMP clause.
2315   /// Subclasses may override this routine to provide different behavior.
2316   OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2317                                      SourceLocation LParenLoc,
2318                                      SourceLocation VarLoc,
2319                                      SourceLocation EndLoc) {
2320     return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2321                                               VarLoc, EndLoc);
2322   }
2323 
2324   /// Build a new OpenMP 'novariants' clause.
2325   ///
2326   /// By default, performs semantic analysis to build the new OpenMP clause.
2327   /// Subclasses may override this routine to provide different behavior.
2328   OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2329                                         SourceLocation StartLoc,
2330                                         SourceLocation LParenLoc,
2331                                         SourceLocation EndLoc) {
2332     return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2333                                                  EndLoc);
2334   }
2335 
2336   /// Build a new OpenMP 'nocontext' clause.
2337   ///
2338   /// By default, performs semantic analysis to build the new OpenMP clause.
2339   /// Subclasses may override this routine to provide different behavior.
2340   OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2341                                        SourceLocation LParenLoc,
2342                                        SourceLocation EndLoc) {
2343     return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2344                                                 EndLoc);
2345   }
2346 
2347   /// Build a new OpenMP 'filter' clause.
2348   ///
2349   /// By default, performs semantic analysis to build the new OpenMP clause.
2350   /// Subclasses may override this routine to provide different behavior.
2351   OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2352                                     SourceLocation LParenLoc,
2353                                     SourceLocation EndLoc) {
2354     return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2355                                              EndLoc);
2356   }
2357 
2358   /// Build a new OpenMP 'bind' clause.
2359   ///
2360   /// By default, performs semantic analysis to build the new OpenMP clause.
2361   /// Subclasses may override this routine to provide different behavior.
2362   OMPClause *RebuildOMPBindClause(OpenMPBindClauseKind Kind,
2363                                   SourceLocation KindLoc,
2364                                   SourceLocation StartLoc,
2365                                   SourceLocation LParenLoc,
2366                                   SourceLocation EndLoc) {
2367     return getSema().ActOnOpenMPBindClause(Kind, KindLoc, StartLoc, LParenLoc,
2368                                            EndLoc);
2369   }
2370 
2371   /// Build a new OpenMP 'ompx_dyn_cgroup_mem' clause.
2372   ///
2373   /// By default, performs semantic analysis to build the new OpenMP clause.
2374   /// Subclasses may override this routine to provide different behavior.
2375   OMPClause *RebuildOMPXDynCGroupMemClause(Expr *Size, SourceLocation StartLoc,
2376                                            SourceLocation LParenLoc,
2377                                            SourceLocation EndLoc) {
2378     return getSema().ActOnOpenMPXDynCGroupMemClause(Size, StartLoc, LParenLoc,
2379                                                     EndLoc);
2380   }
2381 
2382   /// Build a new OpenMP 'ompx_attribute' clause.
2383   ///
2384   /// By default, performs semantic analysis to build the new OpenMP clause.
2385   /// Subclasses may override this routine to provide different behavior.
2386   OMPClause *RebuildOMPXAttributeClause(ArrayRef<const Attr *> Attrs,
2387                                         SourceLocation StartLoc,
2388                                         SourceLocation LParenLoc,
2389                                         SourceLocation EndLoc) {
2390     return getSema().ActOnOpenMPXAttributeClause(Attrs, StartLoc, LParenLoc,
2391                                                  EndLoc);
2392   }
2393 
2394   /// Build a new OpenMP 'ompx_bare' clause.
2395   ///
2396   /// By default, performs semantic analysis to build the new OpenMP clause.
2397   /// Subclasses may override this routine to provide different behavior.
2398   OMPClause *RebuildOMPXBareClause(SourceLocation StartLoc,
2399                                    SourceLocation EndLoc) {
2400     return getSema().ActOnOpenMPXBareClause(StartLoc, EndLoc);
2401   }
2402 
2403   /// Build a new OpenMP 'align' clause.
2404   ///
2405   /// By default, performs semantic analysis to build the new OpenMP clause.
2406   /// Subclasses may override this routine to provide different behavior.
2407   OMPClause *RebuildOMPAlignClause(Expr *A, SourceLocation StartLoc,
2408                                    SourceLocation LParenLoc,
2409                                    SourceLocation EndLoc) {
2410     return getSema().ActOnOpenMPAlignClause(A, StartLoc, LParenLoc, EndLoc);
2411   }
2412 
2413   /// Build a new OpenMP 'at' clause.
2414   ///
2415   /// By default, performs semantic analysis to build the new OpenMP clause.
2416   /// Subclasses may override this routine to provide different behavior.
2417   OMPClause *RebuildOMPAtClause(OpenMPAtClauseKind Kind, SourceLocation KwLoc,
2418                                 SourceLocation StartLoc,
2419                                 SourceLocation LParenLoc,
2420                                 SourceLocation EndLoc) {
2421     return getSema().ActOnOpenMPAtClause(Kind, KwLoc, StartLoc, LParenLoc,
2422                                          EndLoc);
2423   }
2424 
2425   /// Build a new OpenMP 'severity' clause.
2426   ///
2427   /// By default, performs semantic analysis to build the new OpenMP clause.
2428   /// Subclasses may override this routine to provide different behavior.
2429   OMPClause *RebuildOMPSeverityClause(OpenMPSeverityClauseKind Kind,
2430                                       SourceLocation KwLoc,
2431                                       SourceLocation StartLoc,
2432                                       SourceLocation LParenLoc,
2433                                       SourceLocation EndLoc) {
2434     return getSema().ActOnOpenMPSeverityClause(Kind, KwLoc, StartLoc, LParenLoc,
2435                                                EndLoc);
2436   }
2437 
2438   /// Build a new OpenMP 'message' clause.
2439   ///
2440   /// By default, performs semantic analysis to build the new OpenMP clause.
2441   /// Subclasses may override this routine to provide different behavior.
2442   OMPClause *RebuildOMPMessageClause(Expr *MS, SourceLocation StartLoc,
2443                                      SourceLocation LParenLoc,
2444                                      SourceLocation EndLoc) {
2445     return getSema().ActOnOpenMPMessageClause(MS, StartLoc, LParenLoc, EndLoc);
2446   }
2447 
2448   /// Build a new OpenMP 'doacross' clause.
2449   ///
2450   /// By default, performs semantic analysis to build the new OpenMP clause.
2451   /// Subclasses may override this routine to provide different behavior.
2452   OMPClause *
2453   RebuildOMPDoacrossClause(OpenMPDoacrossClauseModifier DepType,
2454                            SourceLocation DepLoc, SourceLocation ColonLoc,
2455                            ArrayRef<Expr *> VarList, SourceLocation StartLoc,
2456                            SourceLocation LParenLoc, SourceLocation EndLoc) {
2457     return getSema().ActOnOpenMPDoacrossClause(
2458         DepType, DepLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
2459   }
2460 
2461   /// Rebuild the operand to an Objective-C \@synchronized statement.
2462   ///
2463   /// By default, performs semantic analysis to build the new statement.
2464   /// Subclasses may override this routine to provide different behavior.
2465   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2466                                               Expr *object) {
2467     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2468   }
2469 
2470   /// Build a new Objective-C \@synchronized statement.
2471   ///
2472   /// By default, performs semantic analysis to build the new statement.
2473   /// Subclasses may override this routine to provide different behavior.
2474   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2475                                            Expr *Object, Stmt *Body) {
2476     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2477   }
2478 
2479   /// Build a new Objective-C \@autoreleasepool statement.
2480   ///
2481   /// By default, performs semantic analysis to build the new statement.
2482   /// Subclasses may override this routine to provide different behavior.
2483   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2484                                             Stmt *Body) {
2485     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2486   }
2487 
2488   /// Build a new Objective-C fast enumeration statement.
2489   ///
2490   /// By default, performs semantic analysis to build the new statement.
2491   /// Subclasses may override this routine to provide different behavior.
2492   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2493                                           Stmt *Element,
2494                                           Expr *Collection,
2495                                           SourceLocation RParenLoc,
2496                                           Stmt *Body) {
2497     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2498                                                 Element,
2499                                                 Collection,
2500                                                 RParenLoc);
2501     if (ForEachStmt.isInvalid())
2502       return StmtError();
2503 
2504     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2505   }
2506 
2507   /// Build a new C++ exception declaration.
2508   ///
2509   /// By default, performs semantic analysis to build the new decaration.
2510   /// Subclasses may override this routine to provide different behavior.
2511   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2512                                 TypeSourceInfo *Declarator,
2513                                 SourceLocation StartLoc,
2514                                 SourceLocation IdLoc,
2515                                 IdentifierInfo *Id) {
2516     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2517                                                        StartLoc, IdLoc, Id);
2518     if (Var)
2519       getSema().CurContext->addDecl(Var);
2520     return Var;
2521   }
2522 
2523   /// Build a new C++ catch statement.
2524   ///
2525   /// By default, performs semantic analysis to build the new statement.
2526   /// Subclasses may override this routine to provide different behavior.
2527   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2528                                  VarDecl *ExceptionDecl,
2529                                  Stmt *Handler) {
2530     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2531                                                       Handler));
2532   }
2533 
2534   /// Build a new C++ try statement.
2535   ///
2536   /// By default, performs semantic analysis to build the new statement.
2537   /// Subclasses may override this routine to provide different behavior.
2538   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2539                                ArrayRef<Stmt *> Handlers) {
2540     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2541   }
2542 
2543   /// Build a new C++0x range-based for statement.
2544   ///
2545   /// By default, performs semantic analysis to build the new statement.
2546   /// Subclasses may override this routine to provide different behavior.
2547   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2548                                     SourceLocation CoawaitLoc, Stmt *Init,
2549                                     SourceLocation ColonLoc, Stmt *Range,
2550                                     Stmt *Begin, Stmt *End, Expr *Cond,
2551                                     Expr *Inc, Stmt *LoopVar,
2552                                     SourceLocation RParenLoc) {
2553     // If we've just learned that the range is actually an Objective-C
2554     // collection, treat this as an Objective-C fast enumeration loop.
2555     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2556       if (RangeStmt->isSingleDecl()) {
2557         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2558           if (RangeVar->isInvalidDecl())
2559             return StmtError();
2560 
2561           Expr *RangeExpr = RangeVar->getInit();
2562           if (!RangeExpr->isTypeDependent() &&
2563               RangeExpr->getType()->isObjCObjectPointerType()) {
2564             // FIXME: Support init-statements in Objective-C++20 ranged for
2565             // statement.
2566             if (Init) {
2567               return SemaRef.Diag(Init->getBeginLoc(),
2568                                   diag::err_objc_for_range_init_stmt)
2569                          << Init->getSourceRange();
2570             }
2571             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2572                                                         RangeExpr, RParenLoc);
2573           }
2574         }
2575       }
2576     }
2577 
2578     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2579                                           Range, Begin, End, Cond, Inc, LoopVar,
2580                                           RParenLoc, Sema::BFRK_Rebuild);
2581   }
2582 
2583   /// Build a new C++0x range-based for statement.
2584   ///
2585   /// By default, performs semantic analysis to build the new statement.
2586   /// Subclasses may override this routine to provide different behavior.
2587   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2588                                           bool IsIfExists,
2589                                           NestedNameSpecifierLoc QualifierLoc,
2590                                           DeclarationNameInfo NameInfo,
2591                                           Stmt *Nested) {
2592     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2593                                                 QualifierLoc, NameInfo, Nested);
2594   }
2595 
2596   /// Attach body to a C++0x range-based for statement.
2597   ///
2598   /// By default, performs semantic analysis to finish the new statement.
2599   /// Subclasses may override this routine to provide different behavior.
2600   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2601     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2602   }
2603 
2604   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2605                                Stmt *TryBlock, Stmt *Handler) {
2606     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2607   }
2608 
2609   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2610                                   Stmt *Block) {
2611     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2612   }
2613 
2614   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2615     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2616   }
2617 
2618   ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2619                                              SourceLocation LParen,
2620                                              SourceLocation RParen,
2621                                              TypeSourceInfo *TSI) {
2622     return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2623   }
2624 
2625   /// Build a new predefined expression.
2626   ///
2627   /// By default, performs semantic analysis to build the new expression.
2628   /// Subclasses may override this routine to provide different behavior.
2629   ExprResult RebuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK) {
2630     return getSema().BuildPredefinedExpr(Loc, IK);
2631   }
2632 
2633   /// Build a new expression that references a declaration.
2634   ///
2635   /// By default, performs semantic analysis to build the new expression.
2636   /// Subclasses may override this routine to provide different behavior.
2637   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2638                                         LookupResult &R,
2639                                         bool RequiresADL) {
2640     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2641   }
2642 
2643 
2644   /// Build a new expression that references a declaration.
2645   ///
2646   /// By default, performs semantic analysis to build the new expression.
2647   /// Subclasses may override this routine to provide different behavior.
2648   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2649                                 ValueDecl *VD,
2650                                 const DeclarationNameInfo &NameInfo,
2651                                 NamedDecl *Found,
2652                                 TemplateArgumentListInfo *TemplateArgs) {
2653     CXXScopeSpec SS;
2654     SS.Adopt(QualifierLoc);
2655     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2656                                               TemplateArgs);
2657   }
2658 
2659   /// Build a new expression in parentheses.
2660   ///
2661   /// By default, performs semantic analysis to build the new expression.
2662   /// Subclasses may override this routine to provide different behavior.
2663   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2664                                     SourceLocation RParen) {
2665     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2666   }
2667 
2668   /// Build a new pseudo-destructor expression.
2669   ///
2670   /// By default, performs semantic analysis to build the new expression.
2671   /// Subclasses may override this routine to provide different behavior.
2672   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2673                                             SourceLocation OperatorLoc,
2674                                             bool isArrow,
2675                                             CXXScopeSpec &SS,
2676                                             TypeSourceInfo *ScopeType,
2677                                             SourceLocation CCLoc,
2678                                             SourceLocation TildeLoc,
2679                                         PseudoDestructorTypeStorage Destroyed);
2680 
2681   /// Build a new unary operator expression.
2682   ///
2683   /// By default, performs semantic analysis to build the new expression.
2684   /// Subclasses may override this routine to provide different behavior.
2685   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2686                                         UnaryOperatorKind Opc,
2687                                         Expr *SubExpr) {
2688     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2689   }
2690 
2691   /// Build a new builtin offsetof expression.
2692   ///
2693   /// By default, performs semantic analysis to build the new expression.
2694   /// Subclasses may override this routine to provide different behavior.
2695   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2696                                  TypeSourceInfo *Type,
2697                                  ArrayRef<Sema::OffsetOfComponent> Components,
2698                                  SourceLocation RParenLoc) {
2699     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2700                                           RParenLoc);
2701   }
2702 
2703   /// Build a new sizeof, alignof or vec_step expression with a
2704   /// type argument.
2705   ///
2706   /// By default, performs semantic analysis to build the new expression.
2707   /// Subclasses may override this routine to provide different behavior.
2708   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2709                                          SourceLocation OpLoc,
2710                                          UnaryExprOrTypeTrait ExprKind,
2711                                          SourceRange R) {
2712     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2713   }
2714 
2715   /// Build a new sizeof, alignof or vec step expression with an
2716   /// expression argument.
2717   ///
2718   /// By default, performs semantic analysis to build the new expression.
2719   /// Subclasses may override this routine to provide different behavior.
2720   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2721                                          UnaryExprOrTypeTrait ExprKind,
2722                                          SourceRange R) {
2723     ExprResult Result
2724       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2725     if (Result.isInvalid())
2726       return ExprError();
2727 
2728     return Result;
2729   }
2730 
2731   /// Build a new array subscript expression.
2732   ///
2733   /// By default, performs semantic analysis to build the new expression.
2734   /// Subclasses may override this routine to provide different behavior.
2735   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2736                                              SourceLocation LBracketLoc,
2737                                              Expr *RHS,
2738                                              SourceLocation RBracketLoc) {
2739     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2740                                              LBracketLoc, RHS,
2741                                              RBracketLoc);
2742   }
2743 
2744   /// Build a new matrix subscript expression.
2745   ///
2746   /// By default, performs semantic analysis to build the new expression.
2747   /// Subclasses may override this routine to provide different behavior.
2748   ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2749                                         Expr *ColumnIdx,
2750                                         SourceLocation RBracketLoc) {
2751     return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2752                                                       RBracketLoc);
2753   }
2754 
2755   /// Build a new array section expression.
2756   ///
2757   /// By default, performs semantic analysis to build the new expression.
2758   /// Subclasses may override this routine to provide different behavior.
2759   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2760                                         Expr *LowerBound,
2761                                         SourceLocation ColonLocFirst,
2762                                         SourceLocation ColonLocSecond,
2763                                         Expr *Length, Expr *Stride,
2764                                         SourceLocation RBracketLoc) {
2765     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2766                                               ColonLocFirst, ColonLocSecond,
2767                                               Length, Stride, RBracketLoc);
2768   }
2769 
2770   /// Build a new array shaping expression.
2771   ///
2772   /// By default, performs semantic analysis to build the new expression.
2773   /// Subclasses may override this routine to provide different behavior.
2774   ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2775                                         SourceLocation RParenLoc,
2776                                         ArrayRef<Expr *> Dims,
2777                                         ArrayRef<SourceRange> BracketsRanges) {
2778     return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2779                                               BracketsRanges);
2780   }
2781 
2782   /// Build a new iterator expression.
2783   ///
2784   /// By default, performs semantic analysis to build the new expression.
2785   /// Subclasses may override this routine to provide different behavior.
2786   ExprResult RebuildOMPIteratorExpr(
2787       SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2788       ArrayRef<Sema::OMPIteratorData> Data) {
2789     return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2790                                           LLoc, RLoc, Data);
2791   }
2792 
2793   /// Build a new call expression.
2794   ///
2795   /// By default, performs semantic analysis to build the new expression.
2796   /// Subclasses may override this routine to provide different behavior.
2797   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2798                                    MultiExprArg Args,
2799                                    SourceLocation RParenLoc,
2800                                    Expr *ExecConfig = nullptr) {
2801     return getSema().ActOnCallExpr(
2802         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2803   }
2804 
2805   ExprResult RebuildCxxSubscriptExpr(Expr *Callee, SourceLocation LParenLoc,
2806                                      MultiExprArg Args,
2807                                      SourceLocation RParenLoc) {
2808     return getSema().ActOnArraySubscriptExpr(
2809         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc);
2810   }
2811 
2812   /// Build a new member access expression.
2813   ///
2814   /// By default, performs semantic analysis to build the new expression.
2815   /// Subclasses may override this routine to provide different behavior.
2816   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2817                                bool isArrow,
2818                                NestedNameSpecifierLoc QualifierLoc,
2819                                SourceLocation TemplateKWLoc,
2820                                const DeclarationNameInfo &MemberNameInfo,
2821                                ValueDecl *Member,
2822                                NamedDecl *FoundDecl,
2823                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2824                                NamedDecl *FirstQualifierInScope) {
2825     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2826                                                                       isArrow);
2827     if (!Member->getDeclName()) {
2828       // We have a reference to an unnamed field.  This is always the
2829       // base of an anonymous struct/union member access, i.e. the
2830       // field is always of record type.
2831       assert(Member->getType()->isRecordType() &&
2832              "unnamed member not of record type?");
2833 
2834       BaseResult =
2835         getSema().PerformObjectMemberConversion(BaseResult.get(),
2836                                                 QualifierLoc.getNestedNameSpecifier(),
2837                                                 FoundDecl, Member);
2838       if (BaseResult.isInvalid())
2839         return ExprError();
2840       Base = BaseResult.get();
2841 
2842       CXXScopeSpec EmptySS;
2843       return getSema().BuildFieldReferenceExpr(
2844           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2845           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2846     }
2847 
2848     CXXScopeSpec SS;
2849     SS.Adopt(QualifierLoc);
2850 
2851     Base = BaseResult.get();
2852     QualType BaseType = Base->getType();
2853 
2854     if (isArrow && !BaseType->isPointerType())
2855       return ExprError();
2856 
2857     // FIXME: this involves duplicating earlier analysis in a lot of
2858     // cases; we should avoid this when possible.
2859     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2860     R.addDecl(FoundDecl);
2861     R.resolveKind();
2862 
2863     if (getSema().isUnevaluatedContext() && Base->isImplicitCXXThis() &&
2864         isa<FieldDecl, IndirectFieldDecl, MSPropertyDecl>(Member)) {
2865       if (auto *ThisClass = cast<CXXThisExpr>(Base)
2866                                 ->getType()
2867                                 ->getPointeeType()
2868                                 ->getAsCXXRecordDecl()) {
2869         auto *Class = cast<CXXRecordDecl>(Member->getDeclContext());
2870         // In unevaluated contexts, an expression supposed to be a member access
2871         // might reference a member in an unrelated class.
2872         if (!ThisClass->Equals(Class) && !ThisClass->isDerivedFrom(Class))
2873           return getSema().BuildDeclRefExpr(Member, Member->getType(),
2874                                             VK_LValue, Member->getLocation());
2875       }
2876     }
2877 
2878     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2879                                               SS, TemplateKWLoc,
2880                                               FirstQualifierInScope,
2881                                               R, ExplicitTemplateArgs,
2882                                               /*S*/nullptr);
2883   }
2884 
2885   /// Build a new binary operator expression.
2886   ///
2887   /// By default, performs semantic analysis to build the new expression.
2888   /// Subclasses may override this routine to provide different behavior.
2889   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2890                                          BinaryOperatorKind Opc,
2891                                          Expr *LHS, Expr *RHS) {
2892     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2893   }
2894 
2895   /// Build a new rewritten operator expression.
2896   ///
2897   /// By default, performs semantic analysis to build the new expression.
2898   /// Subclasses may override this routine to provide different behavior.
2899   ExprResult RebuildCXXRewrittenBinaryOperator(
2900       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2901       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2902     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2903                                            RHS, /*RequiresADL*/false);
2904   }
2905 
2906   /// Build a new conditional operator expression.
2907   ///
2908   /// By default, performs semantic analysis to build the new expression.
2909   /// Subclasses may override this routine to provide different behavior.
2910   ExprResult RebuildConditionalOperator(Expr *Cond,
2911                                         SourceLocation QuestionLoc,
2912                                         Expr *LHS,
2913                                         SourceLocation ColonLoc,
2914                                         Expr *RHS) {
2915     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2916                                         LHS, RHS);
2917   }
2918 
2919   /// Build a new C-style cast expression.
2920   ///
2921   /// By default, performs semantic analysis to build the new expression.
2922   /// Subclasses may override this routine to provide different behavior.
2923   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2924                                          TypeSourceInfo *TInfo,
2925                                          SourceLocation RParenLoc,
2926                                          Expr *SubExpr) {
2927     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2928                                          SubExpr);
2929   }
2930 
2931   /// Build a new compound literal expression.
2932   ///
2933   /// By default, performs semantic analysis to build the new expression.
2934   /// Subclasses may override this routine to provide different behavior.
2935   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2936                                               TypeSourceInfo *TInfo,
2937                                               SourceLocation RParenLoc,
2938                                               Expr *Init) {
2939     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2940                                               Init);
2941   }
2942 
2943   /// Build a new extended vector element access expression.
2944   ///
2945   /// By default, performs semantic analysis to build the new expression.
2946   /// Subclasses may override this routine to provide different behavior.
2947   ExprResult RebuildExtVectorElementExpr(Expr *Base, SourceLocation OpLoc,
2948                                          bool IsArrow,
2949                                          SourceLocation AccessorLoc,
2950                                          IdentifierInfo &Accessor) {
2951 
2952     CXXScopeSpec SS;
2953     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2954     return getSema().BuildMemberReferenceExpr(
2955         Base, Base->getType(), OpLoc, IsArrow, SS, SourceLocation(),
2956         /*FirstQualifierInScope*/ nullptr, NameInfo,
2957         /* TemplateArgs */ nullptr,
2958         /*S*/ nullptr);
2959   }
2960 
2961   /// Build a new initializer list expression.
2962   ///
2963   /// By default, performs semantic analysis to build the new expression.
2964   /// Subclasses may override this routine to provide different behavior.
2965   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2966                              MultiExprArg Inits,
2967                              SourceLocation RBraceLoc) {
2968     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2969   }
2970 
2971   /// Build a new designated initializer expression.
2972   ///
2973   /// By default, performs semantic analysis to build the new expression.
2974   /// Subclasses may override this routine to provide different behavior.
2975   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2976                                              MultiExprArg ArrayExprs,
2977                                              SourceLocation EqualOrColonLoc,
2978                                              bool GNUSyntax,
2979                                              Expr *Init) {
2980     ExprResult Result
2981       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2982                                            Init);
2983     if (Result.isInvalid())
2984       return ExprError();
2985 
2986     return Result;
2987   }
2988 
2989   /// Build a new value-initialized expression.
2990   ///
2991   /// By default, builds the implicit value initialization without performing
2992   /// any semantic analysis. Subclasses may override this routine to provide
2993   /// different behavior.
2994   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2995     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2996   }
2997 
2998   /// Build a new \c va_arg expression.
2999   ///
3000   /// By default, performs semantic analysis to build the new expression.
3001   /// Subclasses may override this routine to provide different behavior.
3002   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
3003                                     Expr *SubExpr, TypeSourceInfo *TInfo,
3004                                     SourceLocation RParenLoc) {
3005     return getSema().BuildVAArgExpr(BuiltinLoc,
3006                                     SubExpr, TInfo,
3007                                     RParenLoc);
3008   }
3009 
3010   /// Build a new expression list in parentheses.
3011   ///
3012   /// By default, performs semantic analysis to build the new expression.
3013   /// Subclasses may override this routine to provide different behavior.
3014   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
3015                                   MultiExprArg SubExprs,
3016                                   SourceLocation RParenLoc) {
3017     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
3018   }
3019 
3020   /// Build a new address-of-label expression.
3021   ///
3022   /// By default, performs semantic analysis, using the name of the label
3023   /// rather than attempting to map the label statement itself.
3024   /// Subclasses may override this routine to provide different behavior.
3025   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
3026                                   SourceLocation LabelLoc, LabelDecl *Label) {
3027     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
3028   }
3029 
3030   /// Build a new GNU statement expression.
3031   ///
3032   /// By default, performs semantic analysis to build the new expression.
3033   /// Subclasses may override this routine to provide different behavior.
3034   ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
3035                              SourceLocation RParenLoc, unsigned TemplateDepth) {
3036     return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
3037                                    TemplateDepth);
3038   }
3039 
3040   /// Build a new __builtin_choose_expr expression.
3041   ///
3042   /// By default, performs semantic analysis to build the new expression.
3043   /// Subclasses may override this routine to provide different behavior.
3044   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
3045                                      Expr *Cond, Expr *LHS, Expr *RHS,
3046                                      SourceLocation RParenLoc) {
3047     return SemaRef.ActOnChooseExpr(BuiltinLoc,
3048                                    Cond, LHS, RHS,
3049                                    RParenLoc);
3050   }
3051 
3052   /// Build a new generic selection expression with an expression predicate.
3053   ///
3054   /// By default, performs semantic analysis to build the new expression.
3055   /// Subclasses may override this routine to provide different behavior.
3056   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
3057                                          SourceLocation DefaultLoc,
3058                                          SourceLocation RParenLoc,
3059                                          Expr *ControllingExpr,
3060                                          ArrayRef<TypeSourceInfo *> Types,
3061                                          ArrayRef<Expr *> Exprs) {
3062     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
3063                                                 /*PredicateIsExpr=*/true,
3064                                                 ControllingExpr, Types, Exprs);
3065   }
3066 
3067   /// Build a new generic selection expression with a type predicate.
3068   ///
3069   /// By default, performs semantic analysis to build the new expression.
3070   /// Subclasses may override this routine to provide different behavior.
3071   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
3072                                          SourceLocation DefaultLoc,
3073                                          SourceLocation RParenLoc,
3074                                          TypeSourceInfo *ControllingType,
3075                                          ArrayRef<TypeSourceInfo *> Types,
3076                                          ArrayRef<Expr *> Exprs) {
3077     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
3078                                                 /*PredicateIsExpr=*/false,
3079                                                 ControllingType, Types, Exprs);
3080   }
3081 
3082   /// Build a new overloaded operator call expression.
3083   ///
3084   /// By default, performs semantic analysis to build the new expression.
3085   /// The semantic analysis provides the behavior of template instantiation,
3086   /// copying with transformations that turn what looks like an overloaded
3087   /// operator call into a use of a builtin operator, performing
3088   /// argument-dependent lookup, etc. Subclasses may override this routine to
3089   /// provide different behavior.
3090   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
3091                                         SourceLocation OpLoc,
3092                                         SourceLocation CalleeLoc,
3093                                         bool RequiresADL,
3094                                         const UnresolvedSetImpl &Functions,
3095                                         Expr *First, Expr *Second);
3096 
3097   /// Build a new C++ "named" cast expression, such as static_cast or
3098   /// reinterpret_cast.
3099   ///
3100   /// By default, this routine dispatches to one of the more-specific routines
3101   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
3102   /// Subclasses may override this routine to provide different behavior.
3103   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
3104                                            Stmt::StmtClass Class,
3105                                            SourceLocation LAngleLoc,
3106                                            TypeSourceInfo *TInfo,
3107                                            SourceLocation RAngleLoc,
3108                                            SourceLocation LParenLoc,
3109                                            Expr *SubExpr,
3110                                            SourceLocation RParenLoc) {
3111     switch (Class) {
3112     case Stmt::CXXStaticCastExprClass:
3113       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
3114                                                    RAngleLoc, LParenLoc,
3115                                                    SubExpr, RParenLoc);
3116 
3117     case Stmt::CXXDynamicCastExprClass:
3118       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
3119                                                     RAngleLoc, LParenLoc,
3120                                                     SubExpr, RParenLoc);
3121 
3122     case Stmt::CXXReinterpretCastExprClass:
3123       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
3124                                                         RAngleLoc, LParenLoc,
3125                                                         SubExpr,
3126                                                         RParenLoc);
3127 
3128     case Stmt::CXXConstCastExprClass:
3129       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
3130                                                    RAngleLoc, LParenLoc,
3131                                                    SubExpr, RParenLoc);
3132 
3133     case Stmt::CXXAddrspaceCastExprClass:
3134       return getDerived().RebuildCXXAddrspaceCastExpr(
3135           OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
3136 
3137     default:
3138       llvm_unreachable("Invalid C++ named cast");
3139     }
3140   }
3141 
3142   /// Build a new C++ static_cast expression.
3143   ///
3144   /// By default, performs semantic analysis to build the new expression.
3145   /// Subclasses may override this routine to provide different behavior.
3146   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
3147                                             SourceLocation LAngleLoc,
3148                                             TypeSourceInfo *TInfo,
3149                                             SourceLocation RAngleLoc,
3150                                             SourceLocation LParenLoc,
3151                                             Expr *SubExpr,
3152                                             SourceLocation RParenLoc) {
3153     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
3154                                        TInfo, SubExpr,
3155                                        SourceRange(LAngleLoc, RAngleLoc),
3156                                        SourceRange(LParenLoc, RParenLoc));
3157   }
3158 
3159   /// Build a new C++ dynamic_cast expression.
3160   ///
3161   /// By default, performs semantic analysis to build the new expression.
3162   /// Subclasses may override this routine to provide different behavior.
3163   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
3164                                              SourceLocation LAngleLoc,
3165                                              TypeSourceInfo *TInfo,
3166                                              SourceLocation RAngleLoc,
3167                                              SourceLocation LParenLoc,
3168                                              Expr *SubExpr,
3169                                              SourceLocation RParenLoc) {
3170     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
3171                                        TInfo, SubExpr,
3172                                        SourceRange(LAngleLoc, RAngleLoc),
3173                                        SourceRange(LParenLoc, RParenLoc));
3174   }
3175 
3176   /// Build a new C++ reinterpret_cast expression.
3177   ///
3178   /// By default, performs semantic analysis to build the new expression.
3179   /// Subclasses may override this routine to provide different behavior.
3180   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
3181                                                  SourceLocation LAngleLoc,
3182                                                  TypeSourceInfo *TInfo,
3183                                                  SourceLocation RAngleLoc,
3184                                                  SourceLocation LParenLoc,
3185                                                  Expr *SubExpr,
3186                                                  SourceLocation RParenLoc) {
3187     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
3188                                        TInfo, SubExpr,
3189                                        SourceRange(LAngleLoc, RAngleLoc),
3190                                        SourceRange(LParenLoc, RParenLoc));
3191   }
3192 
3193   /// Build a new C++ const_cast expression.
3194   ///
3195   /// By default, performs semantic analysis to build the new expression.
3196   /// Subclasses may override this routine to provide different behavior.
3197   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
3198                                            SourceLocation LAngleLoc,
3199                                            TypeSourceInfo *TInfo,
3200                                            SourceLocation RAngleLoc,
3201                                            SourceLocation LParenLoc,
3202                                            Expr *SubExpr,
3203                                            SourceLocation RParenLoc) {
3204     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
3205                                        TInfo, SubExpr,
3206                                        SourceRange(LAngleLoc, RAngleLoc),
3207                                        SourceRange(LParenLoc, RParenLoc));
3208   }
3209 
3210   ExprResult
3211   RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
3212                               TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
3213                               SourceLocation LParenLoc, Expr *SubExpr,
3214                               SourceLocation RParenLoc) {
3215     return getSema().BuildCXXNamedCast(
3216         OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
3217         SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
3218   }
3219 
3220   /// Build a new C++ functional-style cast expression.
3221   ///
3222   /// By default, performs semantic analysis to build the new expression.
3223   /// Subclasses may override this routine to provide different behavior.
3224   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
3225                                           SourceLocation LParenLoc,
3226                                           Expr *Sub,
3227                                           SourceLocation RParenLoc,
3228                                           bool ListInitialization) {
3229     // If Sub is a ParenListExpr, then Sub is the syntatic form of a
3230     // CXXParenListInitExpr. Pass its expanded arguments so that the
3231     // CXXParenListInitExpr can be rebuilt.
3232     if (auto *PLE = dyn_cast<ParenListExpr>(Sub))
3233       return getSema().BuildCXXTypeConstructExpr(
3234           TInfo, LParenLoc, MultiExprArg(PLE->getExprs(), PLE->getNumExprs()),
3235           RParenLoc, ListInitialization);
3236     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
3237                                                MultiExprArg(&Sub, 1), RParenLoc,
3238                                                ListInitialization);
3239   }
3240 
3241   /// Build a new C++ __builtin_bit_cast expression.
3242   ///
3243   /// By default, performs semantic analysis to build the new expression.
3244   /// Subclasses may override this routine to provide different behavior.
3245   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3246                                        TypeSourceInfo *TSI, Expr *Sub,
3247                                        SourceLocation RParenLoc) {
3248     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3249   }
3250 
3251   /// Build a new C++ typeid(type) expression.
3252   ///
3253   /// By default, performs semantic analysis to build the new expression.
3254   /// Subclasses may override this routine to provide different behavior.
3255   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3256                                         SourceLocation TypeidLoc,
3257                                         TypeSourceInfo *Operand,
3258                                         SourceLocation RParenLoc) {
3259     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3260                                     RParenLoc);
3261   }
3262 
3263 
3264   /// Build a new C++ typeid(expr) expression.
3265   ///
3266   /// By default, performs semantic analysis to build the new expression.
3267   /// Subclasses may override this routine to provide different behavior.
3268   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3269                                         SourceLocation TypeidLoc,
3270                                         Expr *Operand,
3271                                         SourceLocation RParenLoc) {
3272     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3273                                     RParenLoc);
3274   }
3275 
3276   /// Build a new C++ __uuidof(type) expression.
3277   ///
3278   /// By default, performs semantic analysis to build the new expression.
3279   /// Subclasses may override this routine to provide different behavior.
3280   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3281                                   TypeSourceInfo *Operand,
3282                                   SourceLocation RParenLoc) {
3283     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3284   }
3285 
3286   /// Build a new C++ __uuidof(expr) expression.
3287   ///
3288   /// By default, performs semantic analysis to build the new expression.
3289   /// Subclasses may override this routine to provide different behavior.
3290   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3291                                   Expr *Operand, SourceLocation RParenLoc) {
3292     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3293   }
3294 
3295   /// Build a new C++ "this" expression.
3296   ///
3297   /// By default, builds a new "this" expression without performing any
3298   /// semantic analysis. Subclasses may override this routine to provide
3299   /// different behavior.
3300   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3301                                 QualType ThisType,
3302                                 bool isImplicit) {
3303     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3304   }
3305 
3306   /// Build a new C++ throw expression.
3307   ///
3308   /// By default, performs semantic analysis to build the new expression.
3309   /// Subclasses may override this routine to provide different behavior.
3310   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3311                                  bool IsThrownVariableInScope) {
3312     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3313   }
3314 
3315   /// Build a new C++ default-argument expression.
3316   ///
3317   /// By default, builds a new default-argument expression, which does not
3318   /// require any semantic analysis. Subclasses may override this routine to
3319   /// provide different behavior.
3320   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param,
3321                                       Expr *RewrittenExpr) {
3322     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3323                                      RewrittenExpr, getSema().CurContext);
3324   }
3325 
3326   /// Build a new C++11 default-initialization expression.
3327   ///
3328   /// By default, builds a new default field initialization expression, which
3329   /// does not require any semantic analysis. Subclasses may override this
3330   /// routine to provide different behavior.
3331   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3332                                        FieldDecl *Field) {
3333     return getSema().BuildCXXDefaultInitExpr(Loc, Field);
3334   }
3335 
3336   /// Build a new C++ zero-initialization expression.
3337   ///
3338   /// By default, performs semantic analysis to build the new expression.
3339   /// Subclasses may override this routine to provide different behavior.
3340   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3341                                            SourceLocation LParenLoc,
3342                                            SourceLocation RParenLoc) {
3343     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, std::nullopt,
3344                                                RParenLoc,
3345                                                /*ListInitialization=*/false);
3346   }
3347 
3348   /// Build a new C++ "new" expression.
3349   ///
3350   /// By default, performs semantic analysis to build the new expression.
3351   /// Subclasses may override this routine to provide different behavior.
3352   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc, bool UseGlobal,
3353                                SourceLocation PlacementLParen,
3354                                MultiExprArg PlacementArgs,
3355                                SourceLocation PlacementRParen,
3356                                SourceRange TypeIdParens, QualType AllocatedType,
3357                                TypeSourceInfo *AllocatedTypeInfo,
3358                                std::optional<Expr *> ArraySize,
3359                                SourceRange DirectInitRange, Expr *Initializer) {
3360     return getSema().BuildCXXNew(StartLoc, UseGlobal,
3361                                  PlacementLParen,
3362                                  PlacementArgs,
3363                                  PlacementRParen,
3364                                  TypeIdParens,
3365                                  AllocatedType,
3366                                  AllocatedTypeInfo,
3367                                  ArraySize,
3368                                  DirectInitRange,
3369                                  Initializer);
3370   }
3371 
3372   /// Build a new C++ "delete" expression.
3373   ///
3374   /// By default, performs semantic analysis to build the new expression.
3375   /// Subclasses may override this routine to provide different behavior.
3376   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3377                                         bool IsGlobalDelete,
3378                                         bool IsArrayForm,
3379                                         Expr *Operand) {
3380     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3381                                     Operand);
3382   }
3383 
3384   /// Build a new type trait expression.
3385   ///
3386   /// By default, performs semantic analysis to build the new expression.
3387   /// Subclasses may override this routine to provide different behavior.
3388   ExprResult RebuildTypeTrait(TypeTrait Trait,
3389                               SourceLocation StartLoc,
3390                               ArrayRef<TypeSourceInfo *> Args,
3391                               SourceLocation RParenLoc) {
3392     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3393   }
3394 
3395   /// Build a new array type trait expression.
3396   ///
3397   /// By default, performs semantic analysis to build the new expression.
3398   /// Subclasses may override this routine to provide different behavior.
3399   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3400                                    SourceLocation StartLoc,
3401                                    TypeSourceInfo *TSInfo,
3402                                    Expr *DimExpr,
3403                                    SourceLocation RParenLoc) {
3404     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3405   }
3406 
3407   /// Build a new expression trait expression.
3408   ///
3409   /// By default, performs semantic analysis to build the new expression.
3410   /// Subclasses may override this routine to provide different behavior.
3411   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3412                                    SourceLocation StartLoc,
3413                                    Expr *Queried,
3414                                    SourceLocation RParenLoc) {
3415     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3416   }
3417 
3418   /// Build a new (previously unresolved) declaration reference
3419   /// expression.
3420   ///
3421   /// By default, performs semantic analysis to build the new expression.
3422   /// Subclasses may override this routine to provide different behavior.
3423   ExprResult RebuildDependentScopeDeclRefExpr(
3424                                           NestedNameSpecifierLoc QualifierLoc,
3425                                           SourceLocation TemplateKWLoc,
3426                                        const DeclarationNameInfo &NameInfo,
3427                               const TemplateArgumentListInfo *TemplateArgs,
3428                                           bool IsAddressOfOperand,
3429                                           TypeSourceInfo **RecoveryTSI) {
3430     CXXScopeSpec SS;
3431     SS.Adopt(QualifierLoc);
3432 
3433     if (TemplateArgs || TemplateKWLoc.isValid())
3434       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3435                                                     TemplateArgs);
3436 
3437     return getSema().BuildQualifiedDeclarationNameExpr(
3438         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3439   }
3440 
3441   /// Build a new template-id expression.
3442   ///
3443   /// By default, performs semantic analysis to build the new expression.
3444   /// Subclasses may override this routine to provide different behavior.
3445   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3446                                    SourceLocation TemplateKWLoc,
3447                                    LookupResult &R,
3448                                    bool RequiresADL,
3449                               const TemplateArgumentListInfo *TemplateArgs) {
3450     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3451                                          TemplateArgs);
3452   }
3453 
3454   /// Build a new object-construction expression.
3455   ///
3456   /// By default, performs semantic analysis to build the new expression.
3457   /// Subclasses may override this routine to provide different behavior.
3458   ExprResult RebuildCXXConstructExpr(
3459       QualType T, SourceLocation Loc, CXXConstructorDecl *Constructor,
3460       bool IsElidable, MultiExprArg Args, bool HadMultipleCandidates,
3461       bool ListInitialization, bool StdInitListInitialization,
3462       bool RequiresZeroInit, CXXConstructionKind ConstructKind,
3463       SourceRange ParenRange) {
3464     // Reconstruct the constructor we originally found, which might be
3465     // different if this is a call to an inherited constructor.
3466     CXXConstructorDecl *FoundCtor = Constructor;
3467     if (Constructor->isInheritingConstructor())
3468       FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3469 
3470     SmallVector<Expr *, 8> ConvertedArgs;
3471     if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3472                                           ConvertedArgs))
3473       return ExprError();
3474 
3475     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3476                                            IsElidable,
3477                                            ConvertedArgs,
3478                                            HadMultipleCandidates,
3479                                            ListInitialization,
3480                                            StdInitListInitialization,
3481                                            RequiresZeroInit, ConstructKind,
3482                                            ParenRange);
3483   }
3484 
3485   /// Build a new implicit construction via inherited constructor
3486   /// expression.
3487   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3488                                              CXXConstructorDecl *Constructor,
3489                                              bool ConstructsVBase,
3490                                              bool InheritedFromVBase) {
3491     return new (getSema().Context) CXXInheritedCtorInitExpr(
3492         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3493   }
3494 
3495   /// Build a new object-construction expression.
3496   ///
3497   /// By default, performs semantic analysis to build the new expression.
3498   /// Subclasses may override this routine to provide different behavior.
3499   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3500                                            SourceLocation LParenOrBraceLoc,
3501                                            MultiExprArg Args,
3502                                            SourceLocation RParenOrBraceLoc,
3503                                            bool ListInitialization) {
3504     return getSema().BuildCXXTypeConstructExpr(
3505         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3506   }
3507 
3508   /// Build a new object-construction expression.
3509   ///
3510   /// By default, performs semantic analysis to build the new expression.
3511   /// Subclasses may override this routine to provide different behavior.
3512   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3513                                                SourceLocation LParenLoc,
3514                                                MultiExprArg Args,
3515                                                SourceLocation RParenLoc,
3516                                                bool ListInitialization) {
3517     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3518                                                RParenLoc, ListInitialization);
3519   }
3520 
3521   /// Build a new member reference expression.
3522   ///
3523   /// By default, performs semantic analysis to build the new expression.
3524   /// Subclasses may override this routine to provide different behavior.
3525   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3526                                                 QualType BaseType,
3527                                                 bool IsArrow,
3528                                                 SourceLocation OperatorLoc,
3529                                           NestedNameSpecifierLoc QualifierLoc,
3530                                                 SourceLocation TemplateKWLoc,
3531                                             NamedDecl *FirstQualifierInScope,
3532                                    const DeclarationNameInfo &MemberNameInfo,
3533                               const TemplateArgumentListInfo *TemplateArgs) {
3534     CXXScopeSpec SS;
3535     SS.Adopt(QualifierLoc);
3536 
3537     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3538                                             OperatorLoc, IsArrow,
3539                                             SS, TemplateKWLoc,
3540                                             FirstQualifierInScope,
3541                                             MemberNameInfo,
3542                                             TemplateArgs, /*S*/nullptr);
3543   }
3544 
3545   /// Build a new member reference expression.
3546   ///
3547   /// By default, performs semantic analysis to build the new expression.
3548   /// Subclasses may override this routine to provide different behavior.
3549   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3550                                          SourceLocation OperatorLoc,
3551                                          bool IsArrow,
3552                                          NestedNameSpecifierLoc QualifierLoc,
3553                                          SourceLocation TemplateKWLoc,
3554                                          NamedDecl *FirstQualifierInScope,
3555                                          LookupResult &R,
3556                                 const TemplateArgumentListInfo *TemplateArgs) {
3557     CXXScopeSpec SS;
3558     SS.Adopt(QualifierLoc);
3559 
3560     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3561                                             OperatorLoc, IsArrow,
3562                                             SS, TemplateKWLoc,
3563                                             FirstQualifierInScope,
3564                                             R, TemplateArgs, /*S*/nullptr);
3565   }
3566 
3567   /// Build a new noexcept expression.
3568   ///
3569   /// By default, performs semantic analysis to build the new expression.
3570   /// Subclasses may override this routine to provide different behavior.
3571   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3572     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3573   }
3574 
3575   /// Build a new expression to compute the length of a parameter pack.
3576   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
3577                                    SourceLocation PackLoc,
3578                                    SourceLocation RParenLoc,
3579                                    std::optional<unsigned> Length,
3580                                    ArrayRef<TemplateArgument> PartialArgs) {
3581     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3582                                   RParenLoc, Length, PartialArgs);
3583   }
3584 
3585   /// Build a new expression representing a call to a source location
3586   ///  builtin.
3587   ///
3588   /// By default, performs semantic analysis to build the new expression.
3589   /// Subclasses may override this routine to provide different behavior.
3590   ExprResult RebuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
3591                                   SourceLocation BuiltinLoc,
3592                                   SourceLocation RPLoc,
3593                                   DeclContext *ParentContext) {
3594     return getSema().BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc,
3595                                         ParentContext);
3596   }
3597 
3598   /// Build a new Objective-C boxed expression.
3599   ///
3600   /// By default, performs semantic analysis to build the new expression.
3601   /// Subclasses may override this routine to provide different behavior.
3602   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3603       SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3604       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3605       TemplateArgumentListInfo *TALI) {
3606     CXXScopeSpec SS;
3607     SS.Adopt(NNS);
3608     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3609                                                          ConceptNameInfo,
3610                                                          FoundDecl,
3611                                                          NamedConcept, TALI);
3612     if (Result.isInvalid())
3613       return ExprError();
3614     return Result;
3615   }
3616 
3617   /// \brief Build a new requires expression.
3618   ///
3619   /// By default, performs semantic analysis to build the new expression.
3620   /// Subclasses may override this routine to provide different behavior.
3621   ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3622                                  RequiresExprBodyDecl *Body,
3623                                  SourceLocation LParenLoc,
3624                                  ArrayRef<ParmVarDecl *> LocalParameters,
3625                                  SourceLocation RParenLoc,
3626                                  ArrayRef<concepts::Requirement *> Requirements,
3627                                  SourceLocation ClosingBraceLoc) {
3628     return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body, LParenLoc,
3629                                 LocalParameters, RParenLoc, Requirements,
3630                                 ClosingBraceLoc);
3631   }
3632 
3633   concepts::TypeRequirement *
3634   RebuildTypeRequirement(
3635       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3636     return SemaRef.BuildTypeRequirement(SubstDiag);
3637   }
3638 
3639   concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3640     return SemaRef.BuildTypeRequirement(T);
3641   }
3642 
3643   concepts::ExprRequirement *
3644   RebuildExprRequirement(
3645       concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3646       SourceLocation NoexceptLoc,
3647       concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3648     return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3649                                         std::move(Ret));
3650   }
3651 
3652   concepts::ExprRequirement *
3653   RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3654                          concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3655     return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3656                                         std::move(Ret));
3657   }
3658 
3659   concepts::NestedRequirement *
3660   RebuildNestedRequirement(StringRef InvalidConstraintEntity,
3661                            const ASTConstraintSatisfaction &Satisfaction) {
3662     return SemaRef.BuildNestedRequirement(InvalidConstraintEntity,
3663                                           Satisfaction);
3664   }
3665 
3666   concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3667     return SemaRef.BuildNestedRequirement(Constraint);
3668   }
3669 
3670   /// \brief Build a new Objective-C boxed expression.
3671   ///
3672   /// By default, performs semantic analysis to build the new expression.
3673   /// Subclasses may override this routine to provide different behavior.
3674   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3675     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3676   }
3677 
3678   /// Build a new Objective-C array literal.
3679   ///
3680   /// By default, performs semantic analysis to build the new expression.
3681   /// Subclasses may override this routine to provide different behavior.
3682   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3683                                      Expr **Elements, unsigned NumElements) {
3684     return getSema().BuildObjCArrayLiteral(Range,
3685                                            MultiExprArg(Elements, NumElements));
3686   }
3687 
3688   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3689                                          Expr *Base, Expr *Key,
3690                                          ObjCMethodDecl *getterMethod,
3691                                          ObjCMethodDecl *setterMethod) {
3692     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3693                                                    getterMethod, setterMethod);
3694   }
3695 
3696   /// Build a new Objective-C dictionary literal.
3697   ///
3698   /// By default, performs semantic analysis to build the new expression.
3699   /// Subclasses may override this routine to provide different behavior.
3700   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3701                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3702     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3703   }
3704 
3705   /// Build a new Objective-C \@encode expression.
3706   ///
3707   /// By default, performs semantic analysis to build the new expression.
3708   /// Subclasses may override this routine to provide different behavior.
3709   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3710                                          TypeSourceInfo *EncodeTypeInfo,
3711                                          SourceLocation RParenLoc) {
3712     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3713   }
3714 
3715   /// Build a new Objective-C class message.
3716   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3717                                           Selector Sel,
3718                                           ArrayRef<SourceLocation> SelectorLocs,
3719                                           ObjCMethodDecl *Method,
3720                                           SourceLocation LBracLoc,
3721                                           MultiExprArg Args,
3722                                           SourceLocation RBracLoc) {
3723     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3724                                      ReceiverTypeInfo->getType(),
3725                                      /*SuperLoc=*/SourceLocation(),
3726                                      Sel, Method, LBracLoc, SelectorLocs,
3727                                      RBracLoc, Args);
3728   }
3729 
3730   /// Build a new Objective-C instance message.
3731   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3732                                           Selector Sel,
3733                                           ArrayRef<SourceLocation> SelectorLocs,
3734                                           ObjCMethodDecl *Method,
3735                                           SourceLocation LBracLoc,
3736                                           MultiExprArg Args,
3737                                           SourceLocation RBracLoc) {
3738     return SemaRef.BuildInstanceMessage(Receiver,
3739                                         Receiver->getType(),
3740                                         /*SuperLoc=*/SourceLocation(),
3741                                         Sel, Method, LBracLoc, SelectorLocs,
3742                                         RBracLoc, Args);
3743   }
3744 
3745   /// Build a new Objective-C instance/class message to 'super'.
3746   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3747                                     Selector Sel,
3748                                     ArrayRef<SourceLocation> SelectorLocs,
3749                                     QualType SuperType,
3750                                     ObjCMethodDecl *Method,
3751                                     SourceLocation LBracLoc,
3752                                     MultiExprArg Args,
3753                                     SourceLocation RBracLoc) {
3754     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3755                                           SuperType,
3756                                           SuperLoc,
3757                                           Sel, Method, LBracLoc, SelectorLocs,
3758                                           RBracLoc, Args)
3759                                       : SemaRef.BuildClassMessage(nullptr,
3760                                           SuperType,
3761                                           SuperLoc,
3762                                           Sel, Method, LBracLoc, SelectorLocs,
3763                                           RBracLoc, Args);
3764 
3765 
3766   }
3767 
3768   /// Build a new Objective-C ivar reference expression.
3769   ///
3770   /// By default, performs semantic analysis to build the new expression.
3771   /// Subclasses may override this routine to provide different behavior.
3772   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3773                                           SourceLocation IvarLoc,
3774                                           bool IsArrow, bool IsFreeIvar) {
3775     CXXScopeSpec SS;
3776     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3777     ExprResult Result = getSema().BuildMemberReferenceExpr(
3778         BaseArg, BaseArg->getType(),
3779         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3780         /*FirstQualifierInScope=*/nullptr, NameInfo,
3781         /*TemplateArgs=*/nullptr,
3782         /*S=*/nullptr);
3783     if (IsFreeIvar && Result.isUsable())
3784       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3785     return Result;
3786   }
3787 
3788   /// Build a new Objective-C property reference expression.
3789   ///
3790   /// By default, performs semantic analysis to build the new expression.
3791   /// Subclasses may override this routine to provide different behavior.
3792   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3793                                         ObjCPropertyDecl *Property,
3794                                         SourceLocation PropertyLoc) {
3795     CXXScopeSpec SS;
3796     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3797     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3798                                               /*FIXME:*/PropertyLoc,
3799                                               /*IsArrow=*/false,
3800                                               SS, SourceLocation(),
3801                                               /*FirstQualifierInScope=*/nullptr,
3802                                               NameInfo,
3803                                               /*TemplateArgs=*/nullptr,
3804                                               /*S=*/nullptr);
3805   }
3806 
3807   /// Build a new Objective-C property reference expression.
3808   ///
3809   /// By default, performs semantic analysis to build the new expression.
3810   /// Subclasses may override this routine to provide different behavior.
3811   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3812                                         ObjCMethodDecl *Getter,
3813                                         ObjCMethodDecl *Setter,
3814                                         SourceLocation PropertyLoc) {
3815     // Since these expressions can only be value-dependent, we do not
3816     // need to perform semantic analysis again.
3817     return Owned(
3818       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3819                                                   VK_LValue, OK_ObjCProperty,
3820                                                   PropertyLoc, Base));
3821   }
3822 
3823   /// Build a new Objective-C "isa" expression.
3824   ///
3825   /// By default, performs semantic analysis to build the new expression.
3826   /// Subclasses may override this routine to provide different behavior.
3827   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3828                                 SourceLocation OpLoc, bool IsArrow) {
3829     CXXScopeSpec SS;
3830     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3831     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3832                                               OpLoc, IsArrow,
3833                                               SS, SourceLocation(),
3834                                               /*FirstQualifierInScope=*/nullptr,
3835                                               NameInfo,
3836                                               /*TemplateArgs=*/nullptr,
3837                                               /*S=*/nullptr);
3838   }
3839 
3840   /// Build a new shuffle vector expression.
3841   ///
3842   /// By default, performs semantic analysis to build the new expression.
3843   /// Subclasses may override this routine to provide different behavior.
3844   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3845                                       MultiExprArg SubExprs,
3846                                       SourceLocation RParenLoc) {
3847     // Find the declaration for __builtin_shufflevector
3848     const IdentifierInfo &Name
3849       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3850     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3851     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3852     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3853 
3854     // Build a reference to the __builtin_shufflevector builtin
3855     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3856     Expr *Callee = new (SemaRef.Context)
3857         DeclRefExpr(SemaRef.Context, Builtin, false,
3858                     SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3859     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3860     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3861                                        CK_BuiltinFnToFnPtr).get();
3862 
3863     // Build the CallExpr
3864     ExprResult TheCall = CallExpr::Create(
3865         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3866         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3867         FPOptionsOverride());
3868 
3869     // Type-check the __builtin_shufflevector expression.
3870     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3871   }
3872 
3873   /// Build a new convert vector expression.
3874   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3875                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3876                                       SourceLocation RParenLoc) {
3877     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3878                                          BuiltinLoc, RParenLoc);
3879   }
3880 
3881   /// Build a new template argument pack expansion.
3882   ///
3883   /// By default, performs semantic analysis to build a new pack expansion
3884   /// for a template argument. Subclasses may override this routine to provide
3885   /// different behavior.
3886   TemplateArgumentLoc
3887   RebuildPackExpansion(TemplateArgumentLoc Pattern, SourceLocation EllipsisLoc,
3888                        std::optional<unsigned> NumExpansions) {
3889     switch (Pattern.getArgument().getKind()) {
3890     case TemplateArgument::Expression: {
3891       ExprResult Result
3892         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3893                                        EllipsisLoc, NumExpansions);
3894       if (Result.isInvalid())
3895         return TemplateArgumentLoc();
3896 
3897       return TemplateArgumentLoc(Result.get(), Result.get());
3898     }
3899 
3900     case TemplateArgument::Template:
3901       return TemplateArgumentLoc(
3902           SemaRef.Context,
3903           TemplateArgument(Pattern.getArgument().getAsTemplate(),
3904                            NumExpansions),
3905           Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3906           EllipsisLoc);
3907 
3908     case TemplateArgument::Null:
3909     case TemplateArgument::Integral:
3910     case TemplateArgument::Declaration:
3911     case TemplateArgument::StructuralValue:
3912     case TemplateArgument::Pack:
3913     case TemplateArgument::TemplateExpansion:
3914     case TemplateArgument::NullPtr:
3915       llvm_unreachable("Pack expansion pattern has no parameter packs");
3916 
3917     case TemplateArgument::Type:
3918       if (TypeSourceInfo *Expansion
3919             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3920                                            EllipsisLoc,
3921                                            NumExpansions))
3922         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3923                                    Expansion);
3924       break;
3925     }
3926 
3927     return TemplateArgumentLoc();
3928   }
3929 
3930   /// Build a new expression pack expansion.
3931   ///
3932   /// By default, performs semantic analysis to build a new pack expansion
3933   /// for an expression. Subclasses may override this routine to provide
3934   /// different behavior.
3935   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3936                                   std::optional<unsigned> NumExpansions) {
3937     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3938   }
3939 
3940   /// Build a new C++1z fold-expression.
3941   ///
3942   /// By default, performs semantic analysis in order to build a new fold
3943   /// expression.
3944   ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3945                                 SourceLocation LParenLoc, Expr *LHS,
3946                                 BinaryOperatorKind Operator,
3947                                 SourceLocation EllipsisLoc, Expr *RHS,
3948                                 SourceLocation RParenLoc,
3949                                 std::optional<unsigned> NumExpansions) {
3950     return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3951                                       EllipsisLoc, RHS, RParenLoc,
3952                                       NumExpansions);
3953   }
3954 
3955   /// Build an empty C++1z fold-expression with the given operator.
3956   ///
3957   /// By default, produces the fallback value for the fold-expression, or
3958   /// produce an error if there is no fallback value.
3959   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3960                                      BinaryOperatorKind Operator) {
3961     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3962   }
3963 
3964   /// Build a new atomic operation expression.
3965   ///
3966   /// By default, performs semantic analysis to build the new expression.
3967   /// Subclasses may override this routine to provide different behavior.
3968   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3969                                AtomicExpr::AtomicOp Op,
3970                                SourceLocation RParenLoc) {
3971     // Use this for all of the locations, since we don't know the difference
3972     // between the call and the expr at this point.
3973     SourceRange Range{BuiltinLoc, RParenLoc};
3974     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3975                                      Sema::AtomicArgumentOrder::AST);
3976   }
3977 
3978   ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3979                                  ArrayRef<Expr *> SubExprs, QualType Type) {
3980     return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3981   }
3982 
3983 private:
3984   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3985                                      QualType ObjectType,
3986                                      NamedDecl *FirstQualifierInScope,
3987                                      CXXScopeSpec &SS);
3988 
3989   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3990                                              QualType ObjectType,
3991                                              NamedDecl *FirstQualifierInScope,
3992                                              CXXScopeSpec &SS);
3993 
3994   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3995                                             NamedDecl *FirstQualifierInScope,
3996                                             CXXScopeSpec &SS);
3997 
3998   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3999                                       DependentNameTypeLoc TL,
4000                                       bool DeducibleTSTContext);
4001 };
4002 
4003 template <typename Derived>
4004 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
4005   if (!S)
4006     return S;
4007 
4008   switch (S->getStmtClass()) {
4009   case Stmt::NoStmtClass: break;
4010 
4011   // Transform individual statement nodes
4012   // Pass SDK into statements that can produce a value
4013 #define STMT(Node, Parent)                                              \
4014   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
4015 #define VALUESTMT(Node, Parent)                                         \
4016   case Stmt::Node##Class:                                               \
4017     return getDerived().Transform##Node(cast<Node>(S), SDK);
4018 #define ABSTRACT_STMT(Node)
4019 #define EXPR(Node, Parent)
4020 #include "clang/AST/StmtNodes.inc"
4021 
4022   // Transform expressions by calling TransformExpr.
4023 #define STMT(Node, Parent)
4024 #define ABSTRACT_STMT(Stmt)
4025 #define EXPR(Node, Parent) case Stmt::Node##Class:
4026 #include "clang/AST/StmtNodes.inc"
4027     {
4028       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
4029 
4030       if (SDK == SDK_StmtExprResult)
4031         E = getSema().ActOnStmtExprResult(E);
4032       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
4033     }
4034   }
4035 
4036   return S;
4037 }
4038 
4039 template<typename Derived>
4040 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
4041   if (!S)
4042     return S;
4043 
4044   switch (S->getClauseKind()) {
4045   default: break;
4046   // Transform individual clause nodes
4047 #define GEN_CLANG_CLAUSE_CLASS
4048 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
4049   case Enum:                                                                   \
4050     return getDerived().Transform##Class(cast<Class>(S));
4051 #include "llvm/Frontend/OpenMP/OMP.inc"
4052   }
4053 
4054   return S;
4055 }
4056 
4057 
4058 template<typename Derived>
4059 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
4060   if (!E)
4061     return E;
4062 
4063   switch (E->getStmtClass()) {
4064     case Stmt::NoStmtClass: break;
4065 #define STMT(Node, Parent) case Stmt::Node##Class: break;
4066 #define ABSTRACT_STMT(Stmt)
4067 #define EXPR(Node, Parent)                                              \
4068     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
4069 #include "clang/AST/StmtNodes.inc"
4070   }
4071 
4072   return E;
4073 }
4074 
4075 template<typename Derived>
4076 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
4077                                                         bool NotCopyInit) {
4078   // Initializers are instantiated like expressions, except that various outer
4079   // layers are stripped.
4080   if (!Init)
4081     return Init;
4082 
4083   if (auto *FE = dyn_cast<FullExpr>(Init))
4084     Init = FE->getSubExpr();
4085 
4086   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init)) {
4087     OpaqueValueExpr *OVE = AIL->getCommonExpr();
4088     Init = OVE->getSourceExpr();
4089   }
4090 
4091   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
4092     Init = MTE->getSubExpr();
4093 
4094   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
4095     Init = Binder->getSubExpr();
4096 
4097   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
4098     Init = ICE->getSubExprAsWritten();
4099 
4100   if (CXXStdInitializerListExpr *ILE =
4101           dyn_cast<CXXStdInitializerListExpr>(Init))
4102     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
4103 
4104   // If this is copy-initialization, we only need to reconstruct
4105   // InitListExprs. Other forms of copy-initialization will be a no-op if
4106   // the initializer is already the right type.
4107   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
4108   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
4109     return getDerived().TransformExpr(Init);
4110 
4111   // Revert value-initialization back to empty parens.
4112   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
4113     SourceRange Parens = VIE->getSourceRange();
4114     return getDerived().RebuildParenListExpr(Parens.getBegin(), std::nullopt,
4115                                              Parens.getEnd());
4116   }
4117 
4118   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
4119   if (isa<ImplicitValueInitExpr>(Init))
4120     return getDerived().RebuildParenListExpr(SourceLocation(), std::nullopt,
4121                                              SourceLocation());
4122 
4123   // Revert initialization by constructor back to a parenthesized or braced list
4124   // of expressions. Any other form of initializer can just be reused directly.
4125   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
4126     return getDerived().TransformExpr(Init);
4127 
4128   // If the initialization implicitly converted an initializer list to a
4129   // std::initializer_list object, unwrap the std::initializer_list too.
4130   if (Construct && Construct->isStdInitListInitialization())
4131     return TransformInitializer(Construct->getArg(0), NotCopyInit);
4132 
4133   // Enter a list-init context if this was list initialization.
4134   EnterExpressionEvaluationContext Context(
4135       getSema(), EnterExpressionEvaluationContext::InitList,
4136       Construct->isListInitialization());
4137 
4138   SmallVector<Expr*, 8> NewArgs;
4139   bool ArgChanged = false;
4140   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
4141                                   /*IsCall*/true, NewArgs, &ArgChanged))
4142     return ExprError();
4143 
4144   // If this was list initialization, revert to syntactic list form.
4145   if (Construct->isListInitialization())
4146     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
4147                                         Construct->getEndLoc());
4148 
4149   // Build a ParenListExpr to represent anything else.
4150   SourceRange Parens = Construct->getParenOrBraceRange();
4151   if (Parens.isInvalid()) {
4152     // This was a variable declaration's initialization for which no initializer
4153     // was specified.
4154     assert(NewArgs.empty() &&
4155            "no parens or braces but have direct init with arguments?");
4156     return ExprEmpty();
4157   }
4158   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
4159                                            Parens.getEnd());
4160 }
4161 
4162 template<typename Derived>
4163 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
4164                                             unsigned NumInputs,
4165                                             bool IsCall,
4166                                       SmallVectorImpl<Expr *> &Outputs,
4167                                             bool *ArgChanged) {
4168   for (unsigned I = 0; I != NumInputs; ++I) {
4169     // If requested, drop call arguments that need to be dropped.
4170     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
4171       if (ArgChanged)
4172         *ArgChanged = true;
4173 
4174       break;
4175     }
4176 
4177     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
4178       Expr *Pattern = Expansion->getPattern();
4179 
4180       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4181       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4182       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4183 
4184       // Determine whether the set of unexpanded parameter packs can and should
4185       // be expanded.
4186       bool Expand = true;
4187       bool RetainExpansion = false;
4188       std::optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
4189       std::optional<unsigned> NumExpansions = OrigNumExpansions;
4190       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
4191                                                Pattern->getSourceRange(),
4192                                                Unexpanded,
4193                                                Expand, RetainExpansion,
4194                                                NumExpansions))
4195         return true;
4196 
4197       if (!Expand) {
4198         // The transform has determined that we should perform a simple
4199         // transformation on the pack expansion, producing another pack
4200         // expansion.
4201         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4202         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
4203         if (OutPattern.isInvalid())
4204           return true;
4205 
4206         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
4207                                                 Expansion->getEllipsisLoc(),
4208                                                            NumExpansions);
4209         if (Out.isInvalid())
4210           return true;
4211 
4212         if (ArgChanged)
4213           *ArgChanged = true;
4214         Outputs.push_back(Out.get());
4215         continue;
4216       }
4217 
4218       // Record right away that the argument was changed.  This needs
4219       // to happen even if the array expands to nothing.
4220       if (ArgChanged) *ArgChanged = true;
4221 
4222       // The transform has determined that we should perform an elementwise
4223       // expansion of the pattern. Do so.
4224       for (unsigned I = 0; I != *NumExpansions; ++I) {
4225         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4226         ExprResult Out = getDerived().TransformExpr(Pattern);
4227         if (Out.isInvalid())
4228           return true;
4229 
4230         if (Out.get()->containsUnexpandedParameterPack()) {
4231           Out = getDerived().RebuildPackExpansion(
4232               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4233           if (Out.isInvalid())
4234             return true;
4235         }
4236 
4237         Outputs.push_back(Out.get());
4238       }
4239 
4240       // If we're supposed to retain a pack expansion, do so by temporarily
4241       // forgetting the partially-substituted parameter pack.
4242       if (RetainExpansion) {
4243         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4244 
4245         ExprResult Out = getDerived().TransformExpr(Pattern);
4246         if (Out.isInvalid())
4247           return true;
4248 
4249         Out = getDerived().RebuildPackExpansion(
4250             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4251         if (Out.isInvalid())
4252           return true;
4253 
4254         Outputs.push_back(Out.get());
4255       }
4256 
4257       continue;
4258     }
4259 
4260     ExprResult Result =
4261       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4262              : getDerived().TransformExpr(Inputs[I]);
4263     if (Result.isInvalid())
4264       return true;
4265 
4266     if (Result.get() != Inputs[I] && ArgChanged)
4267       *ArgChanged = true;
4268 
4269     Outputs.push_back(Result.get());
4270   }
4271 
4272   return false;
4273 }
4274 
4275 template <typename Derived>
4276 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4277     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4278   if (Var) {
4279     VarDecl *ConditionVar = cast_or_null<VarDecl>(
4280         getDerived().TransformDefinition(Var->getLocation(), Var));
4281 
4282     if (!ConditionVar)
4283       return Sema::ConditionError();
4284 
4285     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4286   }
4287 
4288   if (Expr) {
4289     ExprResult CondExpr = getDerived().TransformExpr(Expr);
4290 
4291     if (CondExpr.isInvalid())
4292       return Sema::ConditionError();
4293 
4294     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind,
4295                                     /*MissingOK=*/true);
4296   }
4297 
4298   return Sema::ConditionResult();
4299 }
4300 
4301 template <typename Derived>
4302 NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4303     NestedNameSpecifierLoc NNS, QualType ObjectType,
4304     NamedDecl *FirstQualifierInScope) {
4305   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4306 
4307   auto insertNNS = [&Qualifiers](NestedNameSpecifierLoc NNS) {
4308     for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4309          Qualifier = Qualifier.getPrefix())
4310       Qualifiers.push_back(Qualifier);
4311   };
4312   insertNNS(NNS);
4313 
4314   CXXScopeSpec SS;
4315   while (!Qualifiers.empty()) {
4316     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4317     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4318 
4319     switch (QNNS->getKind()) {
4320     case NestedNameSpecifier::Identifier: {
4321       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4322                                       Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4323                                       ObjectType);
4324       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4325                                               SS, FirstQualifierInScope, false))
4326         return NestedNameSpecifierLoc();
4327       break;
4328     }
4329 
4330     case NestedNameSpecifier::Namespace: {
4331       NamespaceDecl *NS =
4332           cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4333               Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4334       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4335       break;
4336     }
4337 
4338     case NestedNameSpecifier::NamespaceAlias: {
4339       NamespaceAliasDecl *Alias =
4340           cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4341               Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4342       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4343                 Q.getLocalEndLoc());
4344       break;
4345     }
4346 
4347     case NestedNameSpecifier::Global:
4348       // There is no meaningful transformation that one could perform on the
4349       // global scope.
4350       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4351       break;
4352 
4353     case NestedNameSpecifier::Super: {
4354       CXXRecordDecl *RD =
4355           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4356               SourceLocation(), QNNS->getAsRecordDecl()));
4357       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4358       break;
4359     }
4360 
4361     case NestedNameSpecifier::TypeSpecWithTemplate:
4362     case NestedNameSpecifier::TypeSpec: {
4363       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4364                                               FirstQualifierInScope, SS);
4365 
4366       if (!TL)
4367         return NestedNameSpecifierLoc();
4368 
4369       QualType T = TL.getType();
4370       if (T->isDependentType() || T->isRecordType() ||
4371           (SemaRef.getLangOpts().CPlusPlus11 && T->isEnumeralType())) {
4372         if (T->isEnumeralType())
4373           SemaRef.Diag(TL.getBeginLoc(),
4374                        diag::warn_cxx98_compat_enum_nested_name_spec);
4375 
4376         if (const auto ETL = TL.getAs<ElaboratedTypeLoc>()) {
4377           SS.Adopt(ETL.getQualifierLoc());
4378           TL = ETL.getNamedTypeLoc();
4379         }
4380         SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4381                   Q.getLocalEndLoc());
4382         break;
4383       }
4384       // If the nested-name-specifier is an invalid type def, don't emit an
4385       // error because a previous error should have already been emitted.
4386       TypedefTypeLoc TTL = TL.getAsAdjusted<TypedefTypeLoc>();
4387       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4388         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4389             << T << SS.getRange();
4390       }
4391       return NestedNameSpecifierLoc();
4392     }
4393     }
4394 
4395     // The qualifier-in-scope and object type only apply to the leftmost entity.
4396     FirstQualifierInScope = nullptr;
4397     ObjectType = QualType();
4398   }
4399 
4400   // Don't rebuild the nested-name-specifier if we don't have to.
4401   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4402       !getDerived().AlwaysRebuild())
4403     return NNS;
4404 
4405   // If we can re-use the source-location data from the original
4406   // nested-name-specifier, do so.
4407   if (SS.location_size() == NNS.getDataLength() &&
4408       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4409     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4410 
4411   // Allocate new nested-name-specifier location information.
4412   return SS.getWithLocInContext(SemaRef.Context);
4413 }
4414 
4415 template<typename Derived>
4416 DeclarationNameInfo
4417 TreeTransform<Derived>
4418 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4419   DeclarationName Name = NameInfo.getName();
4420   if (!Name)
4421     return DeclarationNameInfo();
4422 
4423   switch (Name.getNameKind()) {
4424   case DeclarationName::Identifier:
4425   case DeclarationName::ObjCZeroArgSelector:
4426   case DeclarationName::ObjCOneArgSelector:
4427   case DeclarationName::ObjCMultiArgSelector:
4428   case DeclarationName::CXXOperatorName:
4429   case DeclarationName::CXXLiteralOperatorName:
4430   case DeclarationName::CXXUsingDirective:
4431     return NameInfo;
4432 
4433   case DeclarationName::CXXDeductionGuideName: {
4434     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4435     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4436         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4437     if (!NewTemplate)
4438       return DeclarationNameInfo();
4439 
4440     DeclarationNameInfo NewNameInfo(NameInfo);
4441     NewNameInfo.setName(
4442         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4443     return NewNameInfo;
4444   }
4445 
4446   case DeclarationName::CXXConstructorName:
4447   case DeclarationName::CXXDestructorName:
4448   case DeclarationName::CXXConversionFunctionName: {
4449     TypeSourceInfo *NewTInfo;
4450     CanQualType NewCanTy;
4451     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4452       NewTInfo = getDerived().TransformType(OldTInfo);
4453       if (!NewTInfo)
4454         return DeclarationNameInfo();
4455       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4456     }
4457     else {
4458       NewTInfo = nullptr;
4459       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4460       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4461       if (NewT.isNull())
4462         return DeclarationNameInfo();
4463       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4464     }
4465 
4466     DeclarationName NewName
4467       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4468                                                            NewCanTy);
4469     DeclarationNameInfo NewNameInfo(NameInfo);
4470     NewNameInfo.setName(NewName);
4471     NewNameInfo.setNamedTypeInfo(NewTInfo);
4472     return NewNameInfo;
4473   }
4474   }
4475 
4476   llvm_unreachable("Unknown name kind.");
4477 }
4478 
4479 template<typename Derived>
4480 TemplateName
4481 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4482                                               TemplateName Name,
4483                                               SourceLocation NameLoc,
4484                                               QualType ObjectType,
4485                                               NamedDecl *FirstQualifierInScope,
4486                                               bool AllowInjectedClassName) {
4487   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4488     TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
4489     assert(Template && "qualified template name must refer to a template");
4490 
4491     TemplateDecl *TransTemplate
4492       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4493                                                               Template));
4494     if (!TransTemplate)
4495       return TemplateName();
4496 
4497     if (!getDerived().AlwaysRebuild() &&
4498         SS.getScopeRep() == QTN->getQualifier() &&
4499         TransTemplate == Template)
4500       return Name;
4501 
4502     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4503                                             TransTemplate);
4504   }
4505 
4506   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4507     if (SS.getScopeRep()) {
4508       // These apply to the scope specifier, not the template.
4509       ObjectType = QualType();
4510       FirstQualifierInScope = nullptr;
4511     }
4512 
4513     if (!getDerived().AlwaysRebuild() &&
4514         SS.getScopeRep() == DTN->getQualifier() &&
4515         ObjectType.isNull())
4516       return Name;
4517 
4518     // FIXME: Preserve the location of the "template" keyword.
4519     SourceLocation TemplateKWLoc = NameLoc;
4520 
4521     if (DTN->isIdentifier()) {
4522       return getDerived().RebuildTemplateName(SS,
4523                                               TemplateKWLoc,
4524                                               *DTN->getIdentifier(),
4525                                               NameLoc,
4526                                               ObjectType,
4527                                               FirstQualifierInScope,
4528                                               AllowInjectedClassName);
4529     }
4530 
4531     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4532                                             DTN->getOperator(), NameLoc,
4533                                             ObjectType, AllowInjectedClassName);
4534   }
4535 
4536   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4537     TemplateDecl *TransTemplate
4538       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4539                                                               Template));
4540     if (!TransTemplate)
4541       return TemplateName();
4542 
4543     if (!getDerived().AlwaysRebuild() &&
4544         TransTemplate == Template)
4545       return Name;
4546 
4547     return TemplateName(TransTemplate);
4548   }
4549 
4550   if (SubstTemplateTemplateParmPackStorage *SubstPack
4551       = Name.getAsSubstTemplateTemplateParmPack()) {
4552     return getDerived().RebuildTemplateName(
4553         SubstPack->getArgumentPack(), SubstPack->getAssociatedDecl(),
4554         SubstPack->getIndex(), SubstPack->getFinal());
4555   }
4556 
4557   // These should be getting filtered out before they reach the AST.
4558   llvm_unreachable("overloaded function decl survived to here");
4559 }
4560 
4561 template<typename Derived>
4562 void TreeTransform<Derived>::InventTemplateArgumentLoc(
4563                                          const TemplateArgument &Arg,
4564                                          TemplateArgumentLoc &Output) {
4565   Output = getSema().getTrivialTemplateArgumentLoc(
4566       Arg, QualType(), getDerived().getBaseLocation());
4567 }
4568 
4569 template <typename Derived>
4570 bool TreeTransform<Derived>::TransformTemplateArgument(
4571     const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4572     bool Uneval) {
4573   const TemplateArgument &Arg = Input.getArgument();
4574   switch (Arg.getKind()) {
4575   case TemplateArgument::Null:
4576   case TemplateArgument::Pack:
4577     llvm_unreachable("Unexpected TemplateArgument");
4578 
4579   case TemplateArgument::Integral:
4580   case TemplateArgument::NullPtr:
4581   case TemplateArgument::Declaration:
4582   case TemplateArgument::StructuralValue: {
4583     // Transform a resolved template argument straight to a resolved template
4584     // argument. We get here when substituting into an already-substituted
4585     // template type argument during concept satisfaction checking.
4586     QualType T = Arg.getNonTypeTemplateArgumentType();
4587     QualType NewT = getDerived().TransformType(T);
4588     if (NewT.isNull())
4589       return true;
4590 
4591     ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4592                        ? Arg.getAsDecl()
4593                        : nullptr;
4594     ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4595                               getDerived().getBaseLocation(), D))
4596                         : nullptr;
4597     if (D && !NewD)
4598       return true;
4599 
4600     if (NewT == T && D == NewD)
4601       Output = Input;
4602     else if (Arg.getKind() == TemplateArgument::Integral)
4603       Output = TemplateArgumentLoc(
4604           TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4605           TemplateArgumentLocInfo());
4606     else if (Arg.getKind() == TemplateArgument::NullPtr)
4607       Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4608                                    TemplateArgumentLocInfo());
4609     else if (Arg.getKind() == TemplateArgument::Declaration)
4610       Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4611                                    TemplateArgumentLocInfo());
4612     else if (Arg.getKind() == TemplateArgument::StructuralValue)
4613       Output = TemplateArgumentLoc(
4614           TemplateArgument(getSema().Context, NewT, Arg.getAsStructuralValue()),
4615           TemplateArgumentLocInfo());
4616     else
4617       llvm_unreachable("unexpected template argument kind");
4618 
4619     return false;
4620   }
4621 
4622   case TemplateArgument::Type: {
4623     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4624     if (!DI)
4625       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4626 
4627     DI = getDerived().TransformType(DI);
4628     if (!DI)
4629       return true;
4630 
4631     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4632     return false;
4633   }
4634 
4635   case TemplateArgument::Template: {
4636     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4637     if (QualifierLoc) {
4638       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4639       if (!QualifierLoc)
4640         return true;
4641     }
4642 
4643     CXXScopeSpec SS;
4644     SS.Adopt(QualifierLoc);
4645     TemplateName Template = getDerived().TransformTemplateName(
4646         SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4647     if (Template.isNull())
4648       return true;
4649 
4650     Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4651                                  QualifierLoc, Input.getTemplateNameLoc());
4652     return false;
4653   }
4654 
4655   case TemplateArgument::TemplateExpansion:
4656     llvm_unreachable("Caller should expand pack expansions");
4657 
4658   case TemplateArgument::Expression: {
4659     // Template argument expressions are constant expressions.
4660     EnterExpressionEvaluationContext Unevaluated(
4661         getSema(),
4662         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4663                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4664         Sema::ReuseLambdaContextDecl, /*ExprContext=*/
4665         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4666 
4667     Expr *InputExpr = Input.getSourceExpression();
4668     if (!InputExpr)
4669       InputExpr = Input.getArgument().getAsExpr();
4670 
4671     ExprResult E = getDerived().TransformExpr(InputExpr);
4672     E = SemaRef.ActOnConstantExpression(E);
4673     if (E.isInvalid())
4674       return true;
4675     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4676     return false;
4677   }
4678   }
4679 
4680   // Work around bogus GCC warning
4681   return true;
4682 }
4683 
4684 /// Iterator adaptor that invents template argument location information
4685 /// for each of the template arguments in its underlying iterator.
4686 template<typename Derived, typename InputIterator>
4687 class TemplateArgumentLocInventIterator {
4688   TreeTransform<Derived> &Self;
4689   InputIterator Iter;
4690 
4691 public:
4692   typedef TemplateArgumentLoc value_type;
4693   typedef TemplateArgumentLoc reference;
4694   typedef typename std::iterator_traits<InputIterator>::difference_type
4695     difference_type;
4696   typedef std::input_iterator_tag iterator_category;
4697 
4698   class pointer {
4699     TemplateArgumentLoc Arg;
4700 
4701   public:
4702     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4703 
4704     const TemplateArgumentLoc *operator->() const { return &Arg; }
4705   };
4706 
4707   TemplateArgumentLocInventIterator() { }
4708 
4709   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4710                                              InputIterator Iter)
4711     : Self(Self), Iter(Iter) { }
4712 
4713   TemplateArgumentLocInventIterator &operator++() {
4714     ++Iter;
4715     return *this;
4716   }
4717 
4718   TemplateArgumentLocInventIterator operator++(int) {
4719     TemplateArgumentLocInventIterator Old(*this);
4720     ++(*this);
4721     return Old;
4722   }
4723 
4724   reference operator*() const {
4725     TemplateArgumentLoc Result;
4726     Self.InventTemplateArgumentLoc(*Iter, Result);
4727     return Result;
4728   }
4729 
4730   pointer operator->() const { return pointer(**this); }
4731 
4732   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4733                          const TemplateArgumentLocInventIterator &Y) {
4734     return X.Iter == Y.Iter;
4735   }
4736 
4737   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4738                          const TemplateArgumentLocInventIterator &Y) {
4739     return X.Iter != Y.Iter;
4740   }
4741 };
4742 
4743 template<typename Derived>
4744 template<typename InputIterator>
4745 bool TreeTransform<Derived>::TransformTemplateArguments(
4746     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4747     bool Uneval) {
4748   for (; First != Last; ++First) {
4749     TemplateArgumentLoc Out;
4750     TemplateArgumentLoc In = *First;
4751 
4752     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4753       // Unpack argument packs, which we translate them into separate
4754       // arguments.
4755       // FIXME: We could do much better if we could guarantee that the
4756       // TemplateArgumentLocInfo for the pack expansion would be usable for
4757       // all of the template arguments in the argument pack.
4758       typedef TemplateArgumentLocInventIterator<Derived,
4759                                                 TemplateArgument::pack_iterator>
4760         PackLocIterator;
4761       if (TransformTemplateArguments(PackLocIterator(*this,
4762                                                  In.getArgument().pack_begin()),
4763                                      PackLocIterator(*this,
4764                                                    In.getArgument().pack_end()),
4765                                      Outputs, Uneval))
4766         return true;
4767 
4768       continue;
4769     }
4770 
4771     if (In.getArgument().isPackExpansion()) {
4772       // We have a pack expansion, for which we will be substituting into
4773       // the pattern.
4774       SourceLocation Ellipsis;
4775       std::optional<unsigned> OrigNumExpansions;
4776       TemplateArgumentLoc Pattern
4777         = getSema().getTemplateArgumentPackExpansionPattern(
4778               In, Ellipsis, OrigNumExpansions);
4779 
4780       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4781       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4782       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4783 
4784       // Determine whether the set of unexpanded parameter packs can and should
4785       // be expanded.
4786       bool Expand = true;
4787       bool RetainExpansion = false;
4788       std::optional<unsigned> NumExpansions = OrigNumExpansions;
4789       if (getDerived().TryExpandParameterPacks(Ellipsis,
4790                                                Pattern.getSourceRange(),
4791                                                Unexpanded,
4792                                                Expand,
4793                                                RetainExpansion,
4794                                                NumExpansions))
4795         return true;
4796 
4797       if (!Expand) {
4798         // The transform has determined that we should perform a simple
4799         // transformation on the pack expansion, producing another pack
4800         // expansion.
4801         TemplateArgumentLoc OutPattern;
4802         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4803         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4804           return true;
4805 
4806         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4807                                                 NumExpansions);
4808         if (Out.getArgument().isNull())
4809           return true;
4810 
4811         Outputs.addArgument(Out);
4812         continue;
4813       }
4814 
4815       // The transform has determined that we should perform an elementwise
4816       // expansion of the pattern. Do so.
4817       for (unsigned I = 0; I != *NumExpansions; ++I) {
4818         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4819 
4820         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4821           return true;
4822 
4823         if (Out.getArgument().containsUnexpandedParameterPack()) {
4824           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4825                                                   OrigNumExpansions);
4826           if (Out.getArgument().isNull())
4827             return true;
4828         }
4829 
4830         Outputs.addArgument(Out);
4831       }
4832 
4833       // If we're supposed to retain a pack expansion, do so by temporarily
4834       // forgetting the partially-substituted parameter pack.
4835       if (RetainExpansion) {
4836         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4837 
4838         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4839           return true;
4840 
4841         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4842                                                 OrigNumExpansions);
4843         if (Out.getArgument().isNull())
4844           return true;
4845 
4846         Outputs.addArgument(Out);
4847       }
4848 
4849       continue;
4850     }
4851 
4852     // The simple case:
4853     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4854       return true;
4855 
4856     Outputs.addArgument(Out);
4857   }
4858 
4859   return false;
4860 
4861 }
4862 
4863 //===----------------------------------------------------------------------===//
4864 // Type transformation
4865 //===----------------------------------------------------------------------===//
4866 
4867 template<typename Derived>
4868 QualType TreeTransform<Derived>::TransformType(QualType T) {
4869   if (getDerived().AlreadyTransformed(T))
4870     return T;
4871 
4872   // Temporary workaround.  All of these transformations should
4873   // eventually turn into transformations on TypeLocs.
4874   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4875                                                 getDerived().getBaseLocation());
4876 
4877   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4878 
4879   if (!NewDI)
4880     return QualType();
4881 
4882   return NewDI->getType();
4883 }
4884 
4885 template<typename Derived>
4886 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4887   // Refine the base location to the type's location.
4888   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4889                        getDerived().getBaseEntity());
4890   if (getDerived().AlreadyTransformed(DI->getType()))
4891     return DI;
4892 
4893   TypeLocBuilder TLB;
4894 
4895   TypeLoc TL = DI->getTypeLoc();
4896   TLB.reserve(TL.getFullDataSize());
4897 
4898   QualType Result = getDerived().TransformType(TLB, TL);
4899   if (Result.isNull())
4900     return nullptr;
4901 
4902   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4903 }
4904 
4905 template<typename Derived>
4906 QualType
4907 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4908   switch (T.getTypeLocClass()) {
4909 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4910 #define TYPELOC(CLASS, PARENT)                                                 \
4911   case TypeLoc::CLASS:                                                         \
4912     return getDerived().Transform##CLASS##Type(TLB,                            \
4913                                                T.castAs<CLASS##TypeLoc>());
4914 #include "clang/AST/TypeLocNodes.def"
4915   }
4916 
4917   llvm_unreachable("unhandled type loc!");
4918 }
4919 
4920 template<typename Derived>
4921 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4922   if (!isa<DependentNameType>(T))
4923     return TransformType(T);
4924 
4925   if (getDerived().AlreadyTransformed(T))
4926     return T;
4927   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4928                                                 getDerived().getBaseLocation());
4929   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4930   return NewDI ? NewDI->getType() : QualType();
4931 }
4932 
4933 template<typename Derived>
4934 TypeSourceInfo *
4935 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4936   if (!isa<DependentNameType>(DI->getType()))
4937     return TransformType(DI);
4938 
4939   // Refine the base location to the type's location.
4940   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4941                        getDerived().getBaseEntity());
4942   if (getDerived().AlreadyTransformed(DI->getType()))
4943     return DI;
4944 
4945   TypeLocBuilder TLB;
4946 
4947   TypeLoc TL = DI->getTypeLoc();
4948   TLB.reserve(TL.getFullDataSize());
4949 
4950   auto QTL = TL.getAs<QualifiedTypeLoc>();
4951   if (QTL)
4952     TL = QTL.getUnqualifiedLoc();
4953 
4954   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4955 
4956   QualType Result = getDerived().TransformDependentNameType(
4957       TLB, DNTL, /*DeducedTSTContext*/true);
4958   if (Result.isNull())
4959     return nullptr;
4960 
4961   if (QTL) {
4962     Result = getDerived().RebuildQualifiedType(Result, QTL);
4963     if (Result.isNull())
4964       return nullptr;
4965     TLB.TypeWasModifiedSafely(Result);
4966   }
4967 
4968   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4969 }
4970 
4971 template<typename Derived>
4972 QualType
4973 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4974                                                QualifiedTypeLoc T) {
4975   QualType Result;
4976   TypeLoc UnqualTL = T.getUnqualifiedLoc();
4977   auto SuppressObjCLifetime =
4978       T.getType().getLocalQualifiers().hasObjCLifetime();
4979   if (auto TTP = UnqualTL.getAs<TemplateTypeParmTypeLoc>()) {
4980     Result = getDerived().TransformTemplateTypeParmType(TLB, TTP,
4981                                                         SuppressObjCLifetime);
4982   } else if (auto STTP = UnqualTL.getAs<SubstTemplateTypeParmPackTypeLoc>()) {
4983     Result = getDerived().TransformSubstTemplateTypeParmPackType(
4984         TLB, STTP, SuppressObjCLifetime);
4985   } else {
4986     Result = getDerived().TransformType(TLB, UnqualTL);
4987   }
4988 
4989   if (Result.isNull())
4990     return QualType();
4991 
4992   Result = getDerived().RebuildQualifiedType(Result, T);
4993 
4994   if (Result.isNull())
4995     return QualType();
4996 
4997   // RebuildQualifiedType might have updated the type, but not in a way
4998   // that invalidates the TypeLoc. (There's no location information for
4999   // qualifiers.)
5000   TLB.TypeWasModifiedSafely(Result);
5001 
5002   return Result;
5003 }
5004 
5005 template <typename Derived>
5006 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
5007                                                       QualifiedTypeLoc TL) {
5008 
5009   SourceLocation Loc = TL.getBeginLoc();
5010   Qualifiers Quals = TL.getType().getLocalQualifiers();
5011 
5012   if ((T.getAddressSpace() != LangAS::Default &&
5013        Quals.getAddressSpace() != LangAS::Default) &&
5014       T.getAddressSpace() != Quals.getAddressSpace()) {
5015     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
5016         << TL.getType() << T;
5017     return QualType();
5018   }
5019 
5020   // C++ [dcl.fct]p7:
5021   //   [When] adding cv-qualifications on top of the function type [...] the
5022   //   cv-qualifiers are ignored.
5023   if (T->isFunctionType()) {
5024     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
5025                                                      Quals.getAddressSpace());
5026     return T;
5027   }
5028 
5029   // C++ [dcl.ref]p1:
5030   //   when the cv-qualifiers are introduced through the use of a typedef-name
5031   //   or decltype-specifier [...] the cv-qualifiers are ignored.
5032   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
5033   // applied to a reference type.
5034   if (T->isReferenceType()) {
5035     // The only qualifier that applies to a reference type is restrict.
5036     if (!Quals.hasRestrict())
5037       return T;
5038     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
5039   }
5040 
5041   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
5042   // resulting type.
5043   if (Quals.hasObjCLifetime()) {
5044     if (!T->isObjCLifetimeType() && !T->isDependentType())
5045       Quals.removeObjCLifetime();
5046     else if (T.getObjCLifetime()) {
5047       // Objective-C ARC:
5048       //   A lifetime qualifier applied to a substituted template parameter
5049       //   overrides the lifetime qualifier from the template argument.
5050       const AutoType *AutoTy;
5051       if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
5052         // 'auto' types behave the same way as template parameters.
5053         QualType Deduced = AutoTy->getDeducedType();
5054         Qualifiers Qs = Deduced.getQualifiers();
5055         Qs.removeObjCLifetime();
5056         Deduced =
5057             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
5058         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
5059                                         AutoTy->isDependentType(),
5060                                         /*isPack=*/false,
5061                                         AutoTy->getTypeConstraintConcept(),
5062                                         AutoTy->getTypeConstraintArguments());
5063       } else {
5064         // Otherwise, complain about the addition of a qualifier to an
5065         // already-qualified type.
5066         // FIXME: Why is this check not in Sema::BuildQualifiedType?
5067         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
5068         Quals.removeObjCLifetime();
5069       }
5070     }
5071   }
5072 
5073   return SemaRef.BuildQualifiedType(T, Loc, Quals);
5074 }
5075 
5076 template<typename Derived>
5077 TypeLoc
5078 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
5079                                                    QualType ObjectType,
5080                                                    NamedDecl *UnqualLookup,
5081                                                    CXXScopeSpec &SS) {
5082   if (getDerived().AlreadyTransformed(TL.getType()))
5083     return TL;
5084 
5085   TypeSourceInfo *TSI =
5086       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
5087   if (TSI)
5088     return TSI->getTypeLoc();
5089   return TypeLoc();
5090 }
5091 
5092 template<typename Derived>
5093 TypeSourceInfo *
5094 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
5095                                                    QualType ObjectType,
5096                                                    NamedDecl *UnqualLookup,
5097                                                    CXXScopeSpec &SS) {
5098   if (getDerived().AlreadyTransformed(TSInfo->getType()))
5099     return TSInfo;
5100 
5101   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
5102                                    UnqualLookup, SS);
5103 }
5104 
5105 template <typename Derived>
5106 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
5107     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
5108     CXXScopeSpec &SS) {
5109   QualType T = TL.getType();
5110   assert(!getDerived().AlreadyTransformed(T));
5111 
5112   TypeLocBuilder TLB;
5113   QualType Result;
5114 
5115   if (isa<TemplateSpecializationType>(T)) {
5116     TemplateSpecializationTypeLoc SpecTL =
5117         TL.castAs<TemplateSpecializationTypeLoc>();
5118 
5119     TemplateName Template = getDerived().TransformTemplateName(
5120         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
5121         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
5122     if (Template.isNull())
5123       return nullptr;
5124 
5125     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
5126                                                               Template);
5127   } else if (isa<DependentTemplateSpecializationType>(T)) {
5128     DependentTemplateSpecializationTypeLoc SpecTL =
5129         TL.castAs<DependentTemplateSpecializationTypeLoc>();
5130 
5131     TemplateName Template
5132       = getDerived().RebuildTemplateName(SS,
5133                                          SpecTL.getTemplateKeywordLoc(),
5134                                          *SpecTL.getTypePtr()->getIdentifier(),
5135                                          SpecTL.getTemplateNameLoc(),
5136                                          ObjectType, UnqualLookup,
5137                                          /*AllowInjectedClassName*/true);
5138     if (Template.isNull())
5139       return nullptr;
5140 
5141     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
5142                                                                        SpecTL,
5143                                                                        Template,
5144                                                                        SS);
5145   } else {
5146     // Nothing special needs to be done for these.
5147     Result = getDerived().TransformType(TLB, TL);
5148   }
5149 
5150   if (Result.isNull())
5151     return nullptr;
5152 
5153   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
5154 }
5155 
5156 template <class TyLoc> static inline
5157 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
5158   TyLoc NewT = TLB.push<TyLoc>(T.getType());
5159   NewT.setNameLoc(T.getNameLoc());
5160   return T.getType();
5161 }
5162 
5163 template<typename Derived>
5164 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
5165                                                       BuiltinTypeLoc T) {
5166   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
5167   NewT.setBuiltinLoc(T.getBuiltinLoc());
5168   if (T.needsExtraLocalData())
5169     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
5170   return T.getType();
5171 }
5172 
5173 template<typename Derived>
5174 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
5175                                                       ComplexTypeLoc T) {
5176   // FIXME: recurse?
5177   return TransformTypeSpecType(TLB, T);
5178 }
5179 
5180 template <typename Derived>
5181 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
5182                                                        AdjustedTypeLoc TL) {
5183   // Adjustments applied during transformation are handled elsewhere.
5184   return getDerived().TransformType(TLB, TL.getOriginalLoc());
5185 }
5186 
5187 template<typename Derived>
5188 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
5189                                                       DecayedTypeLoc TL) {
5190   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
5191   if (OriginalType.isNull())
5192     return QualType();
5193 
5194   QualType Result = TL.getType();
5195   if (getDerived().AlwaysRebuild() ||
5196       OriginalType != TL.getOriginalLoc().getType())
5197     Result = SemaRef.Context.getDecayedType(OriginalType);
5198   TLB.push<DecayedTypeLoc>(Result);
5199   // Nothing to set for DecayedTypeLoc.
5200   return Result;
5201 }
5202 
5203 template<typename Derived>
5204 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
5205                                                       PointerTypeLoc TL) {
5206   QualType PointeeType
5207     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5208   if (PointeeType.isNull())
5209     return QualType();
5210 
5211   QualType Result = TL.getType();
5212   if (PointeeType->getAs<ObjCObjectType>()) {
5213     // A dependent pointer type 'T *' has is being transformed such
5214     // that an Objective-C class type is being replaced for 'T'. The
5215     // resulting pointer type is an ObjCObjectPointerType, not a
5216     // PointerType.
5217     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
5218 
5219     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
5220     NewT.setStarLoc(TL.getStarLoc());
5221     return Result;
5222   }
5223 
5224   if (getDerived().AlwaysRebuild() ||
5225       PointeeType != TL.getPointeeLoc().getType()) {
5226     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
5227     if (Result.isNull())
5228       return QualType();
5229   }
5230 
5231   // Objective-C ARC can add lifetime qualifiers to the type that we're
5232   // pointing to.
5233   TLB.TypeWasModifiedSafely(Result->getPointeeType());
5234 
5235   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
5236   NewT.setSigilLoc(TL.getSigilLoc());
5237   return Result;
5238 }
5239 
5240 template<typename Derived>
5241 QualType
5242 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
5243                                                   BlockPointerTypeLoc TL) {
5244   QualType PointeeType
5245     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5246   if (PointeeType.isNull())
5247     return QualType();
5248 
5249   QualType Result = TL.getType();
5250   if (getDerived().AlwaysRebuild() ||
5251       PointeeType != TL.getPointeeLoc().getType()) {
5252     Result = getDerived().RebuildBlockPointerType(PointeeType,
5253                                                   TL.getSigilLoc());
5254     if (Result.isNull())
5255       return QualType();
5256   }
5257 
5258   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5259   NewT.setSigilLoc(TL.getSigilLoc());
5260   return Result;
5261 }
5262 
5263 /// Transforms a reference type.  Note that somewhat paradoxically we
5264 /// don't care whether the type itself is an l-value type or an r-value
5265 /// type;  we only care if the type was *written* as an l-value type
5266 /// or an r-value type.
5267 template<typename Derived>
5268 QualType
5269 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5270                                                ReferenceTypeLoc TL) {
5271   const ReferenceType *T = TL.getTypePtr();
5272 
5273   // Note that this works with the pointee-as-written.
5274   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5275   if (PointeeType.isNull())
5276     return QualType();
5277 
5278   QualType Result = TL.getType();
5279   if (getDerived().AlwaysRebuild() ||
5280       PointeeType != T->getPointeeTypeAsWritten()) {
5281     Result = getDerived().RebuildReferenceType(PointeeType,
5282                                                T->isSpelledAsLValue(),
5283                                                TL.getSigilLoc());
5284     if (Result.isNull())
5285       return QualType();
5286   }
5287 
5288   // Objective-C ARC can add lifetime qualifiers to the type that we're
5289   // referring to.
5290   TLB.TypeWasModifiedSafely(
5291       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5292 
5293   // r-value references can be rebuilt as l-value references.
5294   ReferenceTypeLoc NewTL;
5295   if (isa<LValueReferenceType>(Result))
5296     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5297   else
5298     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5299   NewTL.setSigilLoc(TL.getSigilLoc());
5300 
5301   return Result;
5302 }
5303 
5304 template<typename Derived>
5305 QualType
5306 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5307                                                  LValueReferenceTypeLoc TL) {
5308   return TransformReferenceType(TLB, TL);
5309 }
5310 
5311 template<typename Derived>
5312 QualType
5313 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5314                                                  RValueReferenceTypeLoc TL) {
5315   return TransformReferenceType(TLB, TL);
5316 }
5317 
5318 template<typename Derived>
5319 QualType
5320 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5321                                                    MemberPointerTypeLoc TL) {
5322   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5323   if (PointeeType.isNull())
5324     return QualType();
5325 
5326   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5327   TypeSourceInfo *NewClsTInfo = nullptr;
5328   if (OldClsTInfo) {
5329     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5330     if (!NewClsTInfo)
5331       return QualType();
5332   }
5333 
5334   const MemberPointerType *T = TL.getTypePtr();
5335   QualType OldClsType = QualType(T->getClass(), 0);
5336   QualType NewClsType;
5337   if (NewClsTInfo)
5338     NewClsType = NewClsTInfo->getType();
5339   else {
5340     NewClsType = getDerived().TransformType(OldClsType);
5341     if (NewClsType.isNull())
5342       return QualType();
5343   }
5344 
5345   QualType Result = TL.getType();
5346   if (getDerived().AlwaysRebuild() ||
5347       PointeeType != T->getPointeeType() ||
5348       NewClsType != OldClsType) {
5349     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5350                                                    TL.getStarLoc());
5351     if (Result.isNull())
5352       return QualType();
5353   }
5354 
5355   // If we had to adjust the pointee type when building a member pointer, make
5356   // sure to push TypeLoc info for it.
5357   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5358   if (MPT && PointeeType != MPT->getPointeeType()) {
5359     assert(isa<AdjustedType>(MPT->getPointeeType()));
5360     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5361   }
5362 
5363   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5364   NewTL.setSigilLoc(TL.getSigilLoc());
5365   NewTL.setClassTInfo(NewClsTInfo);
5366 
5367   return Result;
5368 }
5369 
5370 template<typename Derived>
5371 QualType
5372 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5373                                                    ConstantArrayTypeLoc TL) {
5374   const ConstantArrayType *T = TL.getTypePtr();
5375   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5376   if (ElementType.isNull())
5377     return QualType();
5378 
5379   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5380   Expr *OldSize = TL.getSizeExpr();
5381   if (!OldSize)
5382     OldSize = const_cast<Expr*>(T->getSizeExpr());
5383   Expr *NewSize = nullptr;
5384   if (OldSize) {
5385     EnterExpressionEvaluationContext Unevaluated(
5386         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5387     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5388     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5389   }
5390 
5391   QualType Result = TL.getType();
5392   if (getDerived().AlwaysRebuild() ||
5393       ElementType != T->getElementType() ||
5394       (T->getSizeExpr() && NewSize != OldSize)) {
5395     Result = getDerived().RebuildConstantArrayType(ElementType,
5396                                                    T->getSizeModifier(),
5397                                                    T->getSize(), NewSize,
5398                                              T->getIndexTypeCVRQualifiers(),
5399                                                    TL.getBracketsRange());
5400     if (Result.isNull())
5401       return QualType();
5402   }
5403 
5404   // We might have either a ConstantArrayType or a VariableArrayType now:
5405   // a ConstantArrayType is allowed to have an element type which is a
5406   // VariableArrayType if the type is dependent.  Fortunately, all array
5407   // types have the same location layout.
5408   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5409   NewTL.setLBracketLoc(TL.getLBracketLoc());
5410   NewTL.setRBracketLoc(TL.getRBracketLoc());
5411   NewTL.setSizeExpr(NewSize);
5412 
5413   return Result;
5414 }
5415 
5416 template<typename Derived>
5417 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5418                                               TypeLocBuilder &TLB,
5419                                               IncompleteArrayTypeLoc TL) {
5420   const IncompleteArrayType *T = TL.getTypePtr();
5421   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5422   if (ElementType.isNull())
5423     return QualType();
5424 
5425   QualType Result = TL.getType();
5426   if (getDerived().AlwaysRebuild() ||
5427       ElementType != T->getElementType()) {
5428     Result = getDerived().RebuildIncompleteArrayType(ElementType,
5429                                                      T->getSizeModifier(),
5430                                            T->getIndexTypeCVRQualifiers(),
5431                                                      TL.getBracketsRange());
5432     if (Result.isNull())
5433       return QualType();
5434   }
5435 
5436   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5437   NewTL.setLBracketLoc(TL.getLBracketLoc());
5438   NewTL.setRBracketLoc(TL.getRBracketLoc());
5439   NewTL.setSizeExpr(nullptr);
5440 
5441   return Result;
5442 }
5443 
5444 template<typename Derived>
5445 QualType
5446 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5447                                                    VariableArrayTypeLoc TL) {
5448   const VariableArrayType *T = TL.getTypePtr();
5449   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5450   if (ElementType.isNull())
5451     return QualType();
5452 
5453   ExprResult SizeResult;
5454   {
5455     EnterExpressionEvaluationContext Context(
5456         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5457     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5458   }
5459   if (SizeResult.isInvalid())
5460     return QualType();
5461   SizeResult =
5462       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5463   if (SizeResult.isInvalid())
5464     return QualType();
5465 
5466   Expr *Size = SizeResult.get();
5467 
5468   QualType Result = TL.getType();
5469   if (getDerived().AlwaysRebuild() ||
5470       ElementType != T->getElementType() ||
5471       Size != T->getSizeExpr()) {
5472     Result = getDerived().RebuildVariableArrayType(ElementType,
5473                                                    T->getSizeModifier(),
5474                                                    Size,
5475                                              T->getIndexTypeCVRQualifiers(),
5476                                                    TL.getBracketsRange());
5477     if (Result.isNull())
5478       return QualType();
5479   }
5480 
5481   // We might have constant size array now, but fortunately it has the same
5482   // location layout.
5483   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5484   NewTL.setLBracketLoc(TL.getLBracketLoc());
5485   NewTL.setRBracketLoc(TL.getRBracketLoc());
5486   NewTL.setSizeExpr(Size);
5487 
5488   return Result;
5489 }
5490 
5491 template<typename Derived>
5492 QualType
5493 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5494                                              DependentSizedArrayTypeLoc TL) {
5495   const DependentSizedArrayType *T = TL.getTypePtr();
5496   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5497   if (ElementType.isNull())
5498     return QualType();
5499 
5500   // Array bounds are constant expressions.
5501   EnterExpressionEvaluationContext Unevaluated(
5502       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5503 
5504   // If we have a VLA then it won't be a constant.
5505   SemaRef.ExprEvalContexts.back().InConditionallyConstantEvaluateContext = true;
5506 
5507   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5508   Expr *origSize = TL.getSizeExpr();
5509   if (!origSize) origSize = T->getSizeExpr();
5510 
5511   ExprResult sizeResult
5512     = getDerived().TransformExpr(origSize);
5513   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5514   if (sizeResult.isInvalid())
5515     return QualType();
5516 
5517   Expr *size = sizeResult.get();
5518 
5519   QualType Result = TL.getType();
5520   if (getDerived().AlwaysRebuild() ||
5521       ElementType != T->getElementType() ||
5522       size != origSize) {
5523     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5524                                                          T->getSizeModifier(),
5525                                                          size,
5526                                                 T->getIndexTypeCVRQualifiers(),
5527                                                         TL.getBracketsRange());
5528     if (Result.isNull())
5529       return QualType();
5530   }
5531 
5532   // We might have any sort of array type now, but fortunately they
5533   // all have the same location layout.
5534   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5535   NewTL.setLBracketLoc(TL.getLBracketLoc());
5536   NewTL.setRBracketLoc(TL.getRBracketLoc());
5537   NewTL.setSizeExpr(size);
5538 
5539   return Result;
5540 }
5541 
5542 template <typename Derived>
5543 QualType TreeTransform<Derived>::TransformDependentVectorType(
5544     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5545   const DependentVectorType *T = TL.getTypePtr();
5546   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5547   if (ElementType.isNull())
5548     return QualType();
5549 
5550   EnterExpressionEvaluationContext Unevaluated(
5551       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5552 
5553   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5554   Size = SemaRef.ActOnConstantExpression(Size);
5555   if (Size.isInvalid())
5556     return QualType();
5557 
5558   QualType Result = TL.getType();
5559   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5560       Size.get() != T->getSizeExpr()) {
5561     Result = getDerived().RebuildDependentVectorType(
5562         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5563     if (Result.isNull())
5564       return QualType();
5565   }
5566 
5567   // Result might be dependent or not.
5568   if (isa<DependentVectorType>(Result)) {
5569     DependentVectorTypeLoc NewTL =
5570         TLB.push<DependentVectorTypeLoc>(Result);
5571     NewTL.setNameLoc(TL.getNameLoc());
5572   } else {
5573     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5574     NewTL.setNameLoc(TL.getNameLoc());
5575   }
5576 
5577   return Result;
5578 }
5579 
5580 template<typename Derived>
5581 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5582                                       TypeLocBuilder &TLB,
5583                                       DependentSizedExtVectorTypeLoc TL) {
5584   const DependentSizedExtVectorType *T = TL.getTypePtr();
5585 
5586   // FIXME: ext vector locs should be nested
5587   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5588   if (ElementType.isNull())
5589     return QualType();
5590 
5591   // Vector sizes are constant expressions.
5592   EnterExpressionEvaluationContext Unevaluated(
5593       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5594 
5595   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5596   Size = SemaRef.ActOnConstantExpression(Size);
5597   if (Size.isInvalid())
5598     return QualType();
5599 
5600   QualType Result = TL.getType();
5601   if (getDerived().AlwaysRebuild() ||
5602       ElementType != T->getElementType() ||
5603       Size.get() != T->getSizeExpr()) {
5604     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5605                                                              Size.get(),
5606                                                          T->getAttributeLoc());
5607     if (Result.isNull())
5608       return QualType();
5609   }
5610 
5611   // Result might be dependent or not.
5612   if (isa<DependentSizedExtVectorType>(Result)) {
5613     DependentSizedExtVectorTypeLoc NewTL
5614       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5615     NewTL.setNameLoc(TL.getNameLoc());
5616   } else {
5617     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5618     NewTL.setNameLoc(TL.getNameLoc());
5619   }
5620 
5621   return Result;
5622 }
5623 
5624 template <typename Derived>
5625 QualType
5626 TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5627                                                     ConstantMatrixTypeLoc TL) {
5628   const ConstantMatrixType *T = TL.getTypePtr();
5629   QualType ElementType = getDerived().TransformType(T->getElementType());
5630   if (ElementType.isNull())
5631     return QualType();
5632 
5633   QualType Result = TL.getType();
5634   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5635     Result = getDerived().RebuildConstantMatrixType(
5636         ElementType, T->getNumRows(), T->getNumColumns());
5637     if (Result.isNull())
5638       return QualType();
5639   }
5640 
5641   ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5642   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5643   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5644   NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5645   NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5646 
5647   return Result;
5648 }
5649 
5650 template <typename Derived>
5651 QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5652     TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5653   const DependentSizedMatrixType *T = TL.getTypePtr();
5654 
5655   QualType ElementType = getDerived().TransformType(T->getElementType());
5656   if (ElementType.isNull()) {
5657     return QualType();
5658   }
5659 
5660   // Matrix dimensions are constant expressions.
5661   EnterExpressionEvaluationContext Unevaluated(
5662       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5663 
5664   Expr *origRows = TL.getAttrRowOperand();
5665   if (!origRows)
5666     origRows = T->getRowExpr();
5667   Expr *origColumns = TL.getAttrColumnOperand();
5668   if (!origColumns)
5669     origColumns = T->getColumnExpr();
5670 
5671   ExprResult rowResult = getDerived().TransformExpr(origRows);
5672   rowResult = SemaRef.ActOnConstantExpression(rowResult);
5673   if (rowResult.isInvalid())
5674     return QualType();
5675 
5676   ExprResult columnResult = getDerived().TransformExpr(origColumns);
5677   columnResult = SemaRef.ActOnConstantExpression(columnResult);
5678   if (columnResult.isInvalid())
5679     return QualType();
5680 
5681   Expr *rows = rowResult.get();
5682   Expr *columns = columnResult.get();
5683 
5684   QualType Result = TL.getType();
5685   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5686       rows != origRows || columns != origColumns) {
5687     Result = getDerived().RebuildDependentSizedMatrixType(
5688         ElementType, rows, columns, T->getAttributeLoc());
5689 
5690     if (Result.isNull())
5691       return QualType();
5692   }
5693 
5694   // We might have any sort of matrix type now, but fortunately they
5695   // all have the same location layout.
5696   MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5697   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5698   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5699   NewTL.setAttrRowOperand(rows);
5700   NewTL.setAttrColumnOperand(columns);
5701   return Result;
5702 }
5703 
5704 template <typename Derived>
5705 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5706     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5707   const DependentAddressSpaceType *T = TL.getTypePtr();
5708 
5709   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5710 
5711   if (pointeeType.isNull())
5712     return QualType();
5713 
5714   // Address spaces are constant expressions.
5715   EnterExpressionEvaluationContext Unevaluated(
5716       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5717 
5718   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5719   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5720   if (AddrSpace.isInvalid())
5721     return QualType();
5722 
5723   QualType Result = TL.getType();
5724   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5725       AddrSpace.get() != T->getAddrSpaceExpr()) {
5726     Result = getDerived().RebuildDependentAddressSpaceType(
5727         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5728     if (Result.isNull())
5729       return QualType();
5730   }
5731 
5732   // Result might be dependent or not.
5733   if (isa<DependentAddressSpaceType>(Result)) {
5734     DependentAddressSpaceTypeLoc NewTL =
5735         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5736 
5737     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5738     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5739     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5740 
5741   } else {
5742     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5743         Result, getDerived().getBaseLocation());
5744     TransformType(TLB, DI->getTypeLoc());
5745   }
5746 
5747   return Result;
5748 }
5749 
5750 template <typename Derived>
5751 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5752                                                      VectorTypeLoc TL) {
5753   const VectorType *T = TL.getTypePtr();
5754   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5755   if (ElementType.isNull())
5756     return QualType();
5757 
5758   QualType Result = TL.getType();
5759   if (getDerived().AlwaysRebuild() ||
5760       ElementType != T->getElementType()) {
5761     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5762                                             T->getVectorKind());
5763     if (Result.isNull())
5764       return QualType();
5765   }
5766 
5767   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5768   NewTL.setNameLoc(TL.getNameLoc());
5769 
5770   return Result;
5771 }
5772 
5773 template<typename Derived>
5774 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5775                                                         ExtVectorTypeLoc TL) {
5776   const VectorType *T = TL.getTypePtr();
5777   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5778   if (ElementType.isNull())
5779     return QualType();
5780 
5781   QualType Result = TL.getType();
5782   if (getDerived().AlwaysRebuild() ||
5783       ElementType != T->getElementType()) {
5784     Result = getDerived().RebuildExtVectorType(ElementType,
5785                                                T->getNumElements(),
5786                                                /*FIXME*/ SourceLocation());
5787     if (Result.isNull())
5788       return QualType();
5789   }
5790 
5791   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5792   NewTL.setNameLoc(TL.getNameLoc());
5793 
5794   return Result;
5795 }
5796 
5797 template <typename Derived>
5798 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5799     ParmVarDecl *OldParm, int indexAdjustment,
5800     std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
5801   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5802   TypeSourceInfo *NewDI = nullptr;
5803 
5804   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5805     // If we're substituting into a pack expansion type and we know the
5806     // length we want to expand to, just substitute for the pattern.
5807     TypeLoc OldTL = OldDI->getTypeLoc();
5808     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5809 
5810     TypeLocBuilder TLB;
5811     TypeLoc NewTL = OldDI->getTypeLoc();
5812     TLB.reserve(NewTL.getFullDataSize());
5813 
5814     QualType Result = getDerived().TransformType(TLB,
5815                                                OldExpansionTL.getPatternLoc());
5816     if (Result.isNull())
5817       return nullptr;
5818 
5819     Result = RebuildPackExpansionType(Result,
5820                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5821                                       OldExpansionTL.getEllipsisLoc(),
5822                                       NumExpansions);
5823     if (Result.isNull())
5824       return nullptr;
5825 
5826     PackExpansionTypeLoc NewExpansionTL
5827       = TLB.push<PackExpansionTypeLoc>(Result);
5828     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5829     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5830   } else
5831     NewDI = getDerived().TransformType(OldDI);
5832   if (!NewDI)
5833     return nullptr;
5834 
5835   if (NewDI == OldDI && indexAdjustment == 0)
5836     return OldParm;
5837 
5838   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5839                                              OldParm->getDeclContext(),
5840                                              OldParm->getInnerLocStart(),
5841                                              OldParm->getLocation(),
5842                                              OldParm->getIdentifier(),
5843                                              NewDI->getType(),
5844                                              NewDI,
5845                                              OldParm->getStorageClass(),
5846                                              /* DefArg */ nullptr);
5847   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5848                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5849   transformedLocalDecl(OldParm, {newParm});
5850   return newParm;
5851 }
5852 
5853 template <typename Derived>
5854 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5855     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5856     const QualType *ParamTypes,
5857     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5858     SmallVectorImpl<QualType> &OutParamTypes,
5859     SmallVectorImpl<ParmVarDecl *> *PVars,
5860     Sema::ExtParameterInfoBuilder &PInfos,
5861     unsigned *LastParamTransformed) {
5862   int indexAdjustment = 0;
5863 
5864   unsigned NumParams = Params.size();
5865   for (unsigned i = 0; i != NumParams; ++i) {
5866     if (LastParamTransformed)
5867       *LastParamTransformed = i;
5868     if (ParmVarDecl *OldParm = Params[i]) {
5869       assert(OldParm->getFunctionScopeIndex() == i);
5870 
5871       std::optional<unsigned> NumExpansions;
5872       ParmVarDecl *NewParm = nullptr;
5873       if (OldParm->isParameterPack()) {
5874         // We have a function parameter pack that may need to be expanded.
5875         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5876 
5877         // Find the parameter packs that could be expanded.
5878         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5879         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5880         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5881         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5882 
5883         // Determine whether we should expand the parameter packs.
5884         bool ShouldExpand = false;
5885         bool RetainExpansion = false;
5886         std::optional<unsigned> OrigNumExpansions;
5887         if (Unexpanded.size() > 0) {
5888           OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5889           NumExpansions = OrigNumExpansions;
5890           if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5891                                                    Pattern.getSourceRange(),
5892                                                    Unexpanded,
5893                                                    ShouldExpand,
5894                                                    RetainExpansion,
5895                                                    NumExpansions)) {
5896             return true;
5897           }
5898         } else {
5899 #ifndef NDEBUG
5900           const AutoType *AT =
5901               Pattern.getType().getTypePtr()->getContainedAutoType();
5902           assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&
5903                  "Could not find parameter packs or undeduced auto type!");
5904 #endif
5905         }
5906 
5907         if (ShouldExpand) {
5908           // Expand the function parameter pack into multiple, separate
5909           // parameters.
5910           getDerived().ExpandingFunctionParameterPack(OldParm);
5911           for (unsigned I = 0; I != *NumExpansions; ++I) {
5912             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5913             ParmVarDecl *NewParm
5914               = getDerived().TransformFunctionTypeParam(OldParm,
5915                                                         indexAdjustment++,
5916                                                         OrigNumExpansions,
5917                                                 /*ExpectParameterPack=*/false);
5918             if (!NewParm)
5919               return true;
5920 
5921             if (ParamInfos)
5922               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5923             OutParamTypes.push_back(NewParm->getType());
5924             if (PVars)
5925               PVars->push_back(NewParm);
5926           }
5927 
5928           // If we're supposed to retain a pack expansion, do so by temporarily
5929           // forgetting the partially-substituted parameter pack.
5930           if (RetainExpansion) {
5931             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5932             ParmVarDecl *NewParm
5933               = getDerived().TransformFunctionTypeParam(OldParm,
5934                                                         indexAdjustment++,
5935                                                         OrigNumExpansions,
5936                                                 /*ExpectParameterPack=*/false);
5937             if (!NewParm)
5938               return true;
5939 
5940             if (ParamInfos)
5941               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5942             OutParamTypes.push_back(NewParm->getType());
5943             if (PVars)
5944               PVars->push_back(NewParm);
5945           }
5946 
5947           // The next parameter should have the same adjustment as the
5948           // last thing we pushed, but we post-incremented indexAdjustment
5949           // on every push.  Also, if we push nothing, the adjustment should
5950           // go down by one.
5951           indexAdjustment--;
5952 
5953           // We're done with the pack expansion.
5954           continue;
5955         }
5956 
5957         // We'll substitute the parameter now without expanding the pack
5958         // expansion.
5959         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5960         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5961                                                           indexAdjustment,
5962                                                           NumExpansions,
5963                                                   /*ExpectParameterPack=*/true);
5964         assert(NewParm->isParameterPack() &&
5965                "Parameter pack no longer a parameter pack after "
5966                "transformation.");
5967       } else {
5968         NewParm = getDerived().TransformFunctionTypeParam(
5969             OldParm, indexAdjustment, std::nullopt,
5970             /*ExpectParameterPack=*/false);
5971       }
5972 
5973       if (!NewParm)
5974         return true;
5975 
5976       if (ParamInfos)
5977         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5978       OutParamTypes.push_back(NewParm->getType());
5979       if (PVars)
5980         PVars->push_back(NewParm);
5981       continue;
5982     }
5983 
5984     // Deal with the possibility that we don't have a parameter
5985     // declaration for this parameter.
5986     assert(ParamTypes);
5987     QualType OldType = ParamTypes[i];
5988     bool IsPackExpansion = false;
5989     std::optional<unsigned> NumExpansions;
5990     QualType NewType;
5991     if (const PackExpansionType *Expansion
5992                                        = dyn_cast<PackExpansionType>(OldType)) {
5993       // We have a function parameter pack that may need to be expanded.
5994       QualType Pattern = Expansion->getPattern();
5995       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5996       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5997 
5998       // Determine whether we should expand the parameter packs.
5999       bool ShouldExpand = false;
6000       bool RetainExpansion = false;
6001       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
6002                                                Unexpanded,
6003                                                ShouldExpand,
6004                                                RetainExpansion,
6005                                                NumExpansions)) {
6006         return true;
6007       }
6008 
6009       if (ShouldExpand) {
6010         // Expand the function parameter pack into multiple, separate
6011         // parameters.
6012         for (unsigned I = 0; I != *NumExpansions; ++I) {
6013           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
6014           QualType NewType = getDerived().TransformType(Pattern);
6015           if (NewType.isNull())
6016             return true;
6017 
6018           if (NewType->containsUnexpandedParameterPack()) {
6019             NewType = getSema().getASTContext().getPackExpansionType(
6020                 NewType, std::nullopt);
6021 
6022             if (NewType.isNull())
6023               return true;
6024           }
6025 
6026           if (ParamInfos)
6027             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6028           OutParamTypes.push_back(NewType);
6029           if (PVars)
6030             PVars->push_back(nullptr);
6031         }
6032 
6033         // We're done with the pack expansion.
6034         continue;
6035       }
6036 
6037       // If we're supposed to retain a pack expansion, do so by temporarily
6038       // forgetting the partially-substituted parameter pack.
6039       if (RetainExpansion) {
6040         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
6041         QualType NewType = getDerived().TransformType(Pattern);
6042         if (NewType.isNull())
6043           return true;
6044 
6045         if (ParamInfos)
6046           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6047         OutParamTypes.push_back(NewType);
6048         if (PVars)
6049           PVars->push_back(nullptr);
6050       }
6051 
6052       // We'll substitute the parameter now without expanding the pack
6053       // expansion.
6054       OldType = Expansion->getPattern();
6055       IsPackExpansion = true;
6056       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6057       NewType = getDerived().TransformType(OldType);
6058     } else {
6059       NewType = getDerived().TransformType(OldType);
6060     }
6061 
6062     if (NewType.isNull())
6063       return true;
6064 
6065     if (IsPackExpansion)
6066       NewType = getSema().Context.getPackExpansionType(NewType,
6067                                                        NumExpansions);
6068 
6069     if (ParamInfos)
6070       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6071     OutParamTypes.push_back(NewType);
6072     if (PVars)
6073       PVars->push_back(nullptr);
6074   }
6075 
6076 #ifndef NDEBUG
6077   if (PVars) {
6078     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
6079       if (ParmVarDecl *parm = (*PVars)[i])
6080         assert(parm->getFunctionScopeIndex() == i);
6081   }
6082 #endif
6083 
6084   return false;
6085 }
6086 
6087 template<typename Derived>
6088 QualType
6089 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
6090                                                    FunctionProtoTypeLoc TL) {
6091   SmallVector<QualType, 4> ExceptionStorage;
6092   return getDerived().TransformFunctionProtoType(
6093       TLB, TL, nullptr, Qualifiers(),
6094       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
6095         return getDerived().TransformExceptionSpec(TL.getBeginLoc(), ESI,
6096                                                    ExceptionStorage, Changed);
6097       });
6098 }
6099 
6100 template<typename Derived> template<typename Fn>
6101 QualType TreeTransform<Derived>::TransformFunctionProtoType(
6102     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
6103     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
6104 
6105   // Transform the parameters and return type.
6106   //
6107   // We are required to instantiate the params and return type in source order.
6108   // When the function has a trailing return type, we instantiate the
6109   // parameters before the return type,  since the return type can then refer
6110   // to the parameters themselves (via decltype, sizeof, etc.).
6111   //
6112   SmallVector<QualType, 4> ParamTypes;
6113   SmallVector<ParmVarDecl*, 4> ParamDecls;
6114   Sema::ExtParameterInfoBuilder ExtParamInfos;
6115   const FunctionProtoType *T = TL.getTypePtr();
6116 
6117   QualType ResultType;
6118 
6119   if (T->hasTrailingReturn()) {
6120     if (getDerived().TransformFunctionTypeParams(
6121             TL.getBeginLoc(), TL.getParams(),
6122             TL.getTypePtr()->param_type_begin(),
6123             T->getExtParameterInfosOrNull(),
6124             ParamTypes, &ParamDecls, ExtParamInfos))
6125       return QualType();
6126 
6127     {
6128       // C++11 [expr.prim.general]p3:
6129       //   If a declaration declares a member function or member function
6130       //   template of a class X, the expression this is a prvalue of type
6131       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6132       //   and the end of the function-definition, member-declarator, or
6133       //   declarator.
6134       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
6135 
6136       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6137       if (ResultType.isNull())
6138         return QualType();
6139     }
6140   }
6141   else {
6142     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6143     if (ResultType.isNull())
6144       return QualType();
6145 
6146     if (getDerived().TransformFunctionTypeParams(
6147             TL.getBeginLoc(), TL.getParams(),
6148             TL.getTypePtr()->param_type_begin(),
6149             T->getExtParameterInfosOrNull(),
6150             ParamTypes, &ParamDecls, ExtParamInfos))
6151       return QualType();
6152   }
6153 
6154   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
6155 
6156   bool EPIChanged = false;
6157   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
6158     return QualType();
6159 
6160   // Handle extended parameter information.
6161   if (auto NewExtParamInfos =
6162         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
6163     if (!EPI.ExtParameterInfos ||
6164         llvm::ArrayRef(EPI.ExtParameterInfos, TL.getNumParams()) !=
6165             llvm::ArrayRef(NewExtParamInfos, ParamTypes.size())) {
6166       EPIChanged = true;
6167     }
6168     EPI.ExtParameterInfos = NewExtParamInfos;
6169   } else if (EPI.ExtParameterInfos) {
6170     EPIChanged = true;
6171     EPI.ExtParameterInfos = nullptr;
6172   }
6173 
6174   QualType Result = TL.getType();
6175   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
6176       T->getParamTypes() != llvm::ArrayRef(ParamTypes) || EPIChanged) {
6177     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
6178     if (Result.isNull())
6179       return QualType();
6180   }
6181 
6182   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
6183   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6184   NewTL.setLParenLoc(TL.getLParenLoc());
6185   NewTL.setRParenLoc(TL.getRParenLoc());
6186   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
6187   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6188   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
6189     NewTL.setParam(i, ParamDecls[i]);
6190 
6191   return Result;
6192 }
6193 
6194 template<typename Derived>
6195 bool TreeTransform<Derived>::TransformExceptionSpec(
6196     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
6197     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
6198   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
6199 
6200   // Instantiate a dynamic noexcept expression, if any.
6201   if (isComputedNoexcept(ESI.Type)) {
6202     // Update this scrope because ContextDecl in Sema will be used in
6203     // TransformExpr.
6204     auto *Method = dyn_cast_if_present<CXXMethodDecl>(ESI.SourceTemplate);
6205     Sema::CXXThisScopeRAII ThisScope(
6206         SemaRef, Method ? Method->getParent() : nullptr,
6207         Method ? Method->getMethodQualifiers() : Qualifiers{},
6208         Method != nullptr);
6209     EnterExpressionEvaluationContext Unevaluated(
6210         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
6211     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
6212     if (NoexceptExpr.isInvalid())
6213       return true;
6214 
6215     ExceptionSpecificationType EST = ESI.Type;
6216     NoexceptExpr =
6217         getSema().ActOnNoexceptSpec(NoexceptExpr.get(), EST);
6218     if (NoexceptExpr.isInvalid())
6219       return true;
6220 
6221     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
6222       Changed = true;
6223     ESI.NoexceptExpr = NoexceptExpr.get();
6224     ESI.Type = EST;
6225   }
6226 
6227   if (ESI.Type != EST_Dynamic)
6228     return false;
6229 
6230   // Instantiate a dynamic exception specification's type.
6231   for (QualType T : ESI.Exceptions) {
6232     if (const PackExpansionType *PackExpansion =
6233             T->getAs<PackExpansionType>()) {
6234       Changed = true;
6235 
6236       // We have a pack expansion. Instantiate it.
6237       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6238       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6239                                               Unexpanded);
6240       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6241 
6242       // Determine whether the set of unexpanded parameter packs can and
6243       // should
6244       // be expanded.
6245       bool Expand = false;
6246       bool RetainExpansion = false;
6247       std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6248       // FIXME: Track the location of the ellipsis (and track source location
6249       // information for the types in the exception specification in general).
6250       if (getDerived().TryExpandParameterPacks(
6251               Loc, SourceRange(), Unexpanded, Expand,
6252               RetainExpansion, NumExpansions))
6253         return true;
6254 
6255       if (!Expand) {
6256         // We can't expand this pack expansion into separate arguments yet;
6257         // just substitute into the pattern and create a new pack expansion
6258         // type.
6259         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6260         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6261         if (U.isNull())
6262           return true;
6263 
6264         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
6265         Exceptions.push_back(U);
6266         continue;
6267       }
6268 
6269       // Substitute into the pack expansion pattern for each slice of the
6270       // pack.
6271       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6272         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6273 
6274         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6275         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6276           return true;
6277 
6278         Exceptions.push_back(U);
6279       }
6280     } else {
6281       QualType U = getDerived().TransformType(T);
6282       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6283         return true;
6284       if (T != U)
6285         Changed = true;
6286 
6287       Exceptions.push_back(U);
6288     }
6289   }
6290 
6291   ESI.Exceptions = Exceptions;
6292   if (ESI.Exceptions.empty())
6293     ESI.Type = EST_DynamicNone;
6294   return false;
6295 }
6296 
6297 template<typename Derived>
6298 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6299                                                  TypeLocBuilder &TLB,
6300                                                  FunctionNoProtoTypeLoc TL) {
6301   const FunctionNoProtoType *T = TL.getTypePtr();
6302   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6303   if (ResultType.isNull())
6304     return QualType();
6305 
6306   QualType Result = TL.getType();
6307   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6308     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6309 
6310   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6311   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6312   NewTL.setLParenLoc(TL.getLParenLoc());
6313   NewTL.setRParenLoc(TL.getRParenLoc());
6314   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6315 
6316   return Result;
6317 }
6318 
6319 template <typename Derived>
6320 QualType TreeTransform<Derived>::TransformUnresolvedUsingType(
6321     TypeLocBuilder &TLB, UnresolvedUsingTypeLoc TL) {
6322   const UnresolvedUsingType *T = TL.getTypePtr();
6323   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6324   if (!D)
6325     return QualType();
6326 
6327   QualType Result = TL.getType();
6328   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6329     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6330     if (Result.isNull())
6331       return QualType();
6332   }
6333 
6334   // We might get an arbitrary type spec type back.  We should at
6335   // least always get a type spec type, though.
6336   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6337   NewTL.setNameLoc(TL.getNameLoc());
6338 
6339   return Result;
6340 }
6341 
6342 template <typename Derived>
6343 QualType TreeTransform<Derived>::TransformUsingType(TypeLocBuilder &TLB,
6344                                                     UsingTypeLoc TL) {
6345   const UsingType *T = TL.getTypePtr();
6346 
6347   auto *Found = cast_or_null<UsingShadowDecl>(getDerived().TransformDecl(
6348       TL.getLocalSourceRange().getBegin(), T->getFoundDecl()));
6349   if (!Found)
6350     return QualType();
6351 
6352   QualType Underlying = getDerived().TransformType(T->desugar());
6353   if (Underlying.isNull())
6354     return QualType();
6355 
6356   QualType Result = TL.getType();
6357   if (getDerived().AlwaysRebuild() || Found != T->getFoundDecl() ||
6358       Underlying != T->getUnderlyingType()) {
6359     Result = getDerived().RebuildUsingType(Found, Underlying);
6360     if (Result.isNull())
6361       return QualType();
6362   }
6363 
6364   TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc());
6365   return Result;
6366 }
6367 
6368 template<typename Derived>
6369 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6370                                                       TypedefTypeLoc TL) {
6371   const TypedefType *T = TL.getTypePtr();
6372   TypedefNameDecl *Typedef
6373     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6374                                                                T->getDecl()));
6375   if (!Typedef)
6376     return QualType();
6377 
6378   QualType Result = TL.getType();
6379   if (getDerived().AlwaysRebuild() ||
6380       Typedef != T->getDecl()) {
6381     Result = getDerived().RebuildTypedefType(Typedef);
6382     if (Result.isNull())
6383       return QualType();
6384   }
6385 
6386   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6387   NewTL.setNameLoc(TL.getNameLoc());
6388 
6389   return Result;
6390 }
6391 
6392 template<typename Derived>
6393 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6394                                                       TypeOfExprTypeLoc TL) {
6395   // typeof expressions are not potentially evaluated contexts
6396   EnterExpressionEvaluationContext Unevaluated(
6397       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6398       Sema::ReuseLambdaContextDecl);
6399 
6400   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6401   if (E.isInvalid())
6402     return QualType();
6403 
6404   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6405   if (E.isInvalid())
6406     return QualType();
6407 
6408   QualType Result = TL.getType();
6409   TypeOfKind Kind = Result->getAs<TypeOfExprType>()->getKind();
6410   if (getDerived().AlwaysRebuild() || E.get() != TL.getUnderlyingExpr()) {
6411     Result =
6412         getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc(), Kind);
6413     if (Result.isNull())
6414       return QualType();
6415   }
6416 
6417   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6418   NewTL.setTypeofLoc(TL.getTypeofLoc());
6419   NewTL.setLParenLoc(TL.getLParenLoc());
6420   NewTL.setRParenLoc(TL.getRParenLoc());
6421 
6422   return Result;
6423 }
6424 
6425 template<typename Derived>
6426 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6427                                                      TypeOfTypeLoc TL) {
6428   TypeSourceInfo* Old_Under_TI = TL.getUnmodifiedTInfo();
6429   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6430   if (!New_Under_TI)
6431     return QualType();
6432 
6433   QualType Result = TL.getType();
6434   TypeOfKind Kind = Result->getAs<TypeOfType>()->getKind();
6435   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6436     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType(), Kind);
6437     if (Result.isNull())
6438       return QualType();
6439   }
6440 
6441   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6442   NewTL.setTypeofLoc(TL.getTypeofLoc());
6443   NewTL.setLParenLoc(TL.getLParenLoc());
6444   NewTL.setRParenLoc(TL.getRParenLoc());
6445   NewTL.setUnmodifiedTInfo(New_Under_TI);
6446 
6447   return Result;
6448 }
6449 
6450 template<typename Derived>
6451 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6452                                                        DecltypeTypeLoc TL) {
6453   const DecltypeType *T = TL.getTypePtr();
6454 
6455   // decltype expressions are not potentially evaluated contexts
6456   EnterExpressionEvaluationContext Unevaluated(
6457       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6458       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6459 
6460   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6461   if (E.isInvalid())
6462     return QualType();
6463 
6464   E = getSema().ActOnDecltypeExpression(E.get());
6465   if (E.isInvalid())
6466     return QualType();
6467 
6468   QualType Result = TL.getType();
6469   if (getDerived().AlwaysRebuild() ||
6470       E.get() != T->getUnderlyingExpr()) {
6471     Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
6472     if (Result.isNull())
6473       return QualType();
6474   }
6475   else E.get();
6476 
6477   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6478   NewTL.setDecltypeLoc(TL.getDecltypeLoc());
6479   NewTL.setRParenLoc(TL.getRParenLoc());
6480   return Result;
6481 }
6482 
6483 template<typename Derived>
6484 QualType TreeTransform<Derived>::TransformUnaryTransformType(
6485                                                             TypeLocBuilder &TLB,
6486                                                      UnaryTransformTypeLoc TL) {
6487   QualType Result = TL.getType();
6488   if (Result->isDependentType()) {
6489     const UnaryTransformType *T = TL.getTypePtr();
6490     QualType NewBase =
6491       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6492     Result = getDerived().RebuildUnaryTransformType(NewBase,
6493                                                     T->getUTTKind(),
6494                                                     TL.getKWLoc());
6495     if (Result.isNull())
6496       return QualType();
6497   }
6498 
6499   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6500   NewTL.setKWLoc(TL.getKWLoc());
6501   NewTL.setParensRange(TL.getParensRange());
6502   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6503   return Result;
6504 }
6505 
6506 template<typename Derived>
6507 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6508     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6509   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6510 
6511   CXXScopeSpec SS;
6512   TemplateName TemplateName = getDerived().TransformTemplateName(
6513       SS, T->getTemplateName(), TL.getTemplateNameLoc());
6514   if (TemplateName.isNull())
6515     return QualType();
6516 
6517   QualType OldDeduced = T->getDeducedType();
6518   QualType NewDeduced;
6519   if (!OldDeduced.isNull()) {
6520     NewDeduced = getDerived().TransformType(OldDeduced);
6521     if (NewDeduced.isNull())
6522       return QualType();
6523   }
6524 
6525   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6526       TemplateName, NewDeduced);
6527   if (Result.isNull())
6528     return QualType();
6529 
6530   DeducedTemplateSpecializationTypeLoc NewTL =
6531       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6532   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6533 
6534   return Result;
6535 }
6536 
6537 template<typename Derived>
6538 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6539                                                      RecordTypeLoc TL) {
6540   const RecordType *T = TL.getTypePtr();
6541   RecordDecl *Record
6542     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6543                                                           T->getDecl()));
6544   if (!Record)
6545     return QualType();
6546 
6547   QualType Result = TL.getType();
6548   if (getDerived().AlwaysRebuild() ||
6549       Record != T->getDecl()) {
6550     Result = getDerived().RebuildRecordType(Record);
6551     if (Result.isNull())
6552       return QualType();
6553   }
6554 
6555   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6556   NewTL.setNameLoc(TL.getNameLoc());
6557 
6558   return Result;
6559 }
6560 
6561 template<typename Derived>
6562 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6563                                                    EnumTypeLoc TL) {
6564   const EnumType *T = TL.getTypePtr();
6565   EnumDecl *Enum
6566     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6567                                                         T->getDecl()));
6568   if (!Enum)
6569     return QualType();
6570 
6571   QualType Result = TL.getType();
6572   if (getDerived().AlwaysRebuild() ||
6573       Enum != T->getDecl()) {
6574     Result = getDerived().RebuildEnumType(Enum);
6575     if (Result.isNull())
6576       return QualType();
6577   }
6578 
6579   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6580   NewTL.setNameLoc(TL.getNameLoc());
6581 
6582   return Result;
6583 }
6584 
6585 template<typename Derived>
6586 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6587                                          TypeLocBuilder &TLB,
6588                                          InjectedClassNameTypeLoc TL) {
6589   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6590                                        TL.getTypePtr()->getDecl());
6591   if (!D) return QualType();
6592 
6593   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6594   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6595   return T;
6596 }
6597 
6598 template<typename Derived>
6599 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6600                                                 TypeLocBuilder &TLB,
6601                                                 TemplateTypeParmTypeLoc TL) {
6602   return getDerived().TransformTemplateTypeParmType(
6603       TLB, TL,
6604       /*SuppressObjCLifetime=*/false);
6605 }
6606 
6607 template <typename Derived>
6608 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6609     TypeLocBuilder &TLB, TemplateTypeParmTypeLoc TL, bool) {
6610   return TransformTypeSpecType(TLB, TL);
6611 }
6612 
6613 template<typename Derived>
6614 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6615                                          TypeLocBuilder &TLB,
6616                                          SubstTemplateTypeParmTypeLoc TL) {
6617   const SubstTemplateTypeParmType *T = TL.getTypePtr();
6618 
6619   Decl *NewReplaced =
6620       getDerived().TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
6621 
6622   // Substitute into the replacement type, which itself might involve something
6623   // that needs to be transformed. This only tends to occur with default
6624   // template arguments of template template parameters.
6625   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6626   QualType Replacement = getDerived().TransformType(T->getReplacementType());
6627   if (Replacement.isNull())
6628     return QualType();
6629 
6630   QualType Result = SemaRef.Context.getSubstTemplateTypeParmType(
6631       Replacement, NewReplaced, T->getIndex(), T->getPackIndex());
6632 
6633   // Propagate type-source information.
6634   SubstTemplateTypeParmTypeLoc NewTL
6635     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6636   NewTL.setNameLoc(TL.getNameLoc());
6637   return Result;
6638 
6639 }
6640 
6641 template<typename Derived>
6642 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6643                                           TypeLocBuilder &TLB,
6644                                           SubstTemplateTypeParmPackTypeLoc TL) {
6645   return getDerived().TransformSubstTemplateTypeParmPackType(
6646       TLB, TL, /*SuppressObjCLifetime=*/false);
6647 }
6648 
6649 template <typename Derived>
6650 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6651     TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, bool) {
6652   return TransformTypeSpecType(TLB, TL);
6653 }
6654 
6655 template<typename Derived>
6656 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6657                                                         TypeLocBuilder &TLB,
6658                                            TemplateSpecializationTypeLoc TL) {
6659   const TemplateSpecializationType *T = TL.getTypePtr();
6660 
6661   // The nested-name-specifier never matters in a TemplateSpecializationType,
6662   // because we can't have a dependent nested-name-specifier anyway.
6663   CXXScopeSpec SS;
6664   TemplateName Template
6665     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6666                                          TL.getTemplateNameLoc());
6667   if (Template.isNull())
6668     return QualType();
6669 
6670   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6671 }
6672 
6673 template<typename Derived>
6674 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6675                                                      AtomicTypeLoc TL) {
6676   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6677   if (ValueType.isNull())
6678     return QualType();
6679 
6680   QualType Result = TL.getType();
6681   if (getDerived().AlwaysRebuild() ||
6682       ValueType != TL.getValueLoc().getType()) {
6683     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6684     if (Result.isNull())
6685       return QualType();
6686   }
6687 
6688   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6689   NewTL.setKWLoc(TL.getKWLoc());
6690   NewTL.setLParenLoc(TL.getLParenLoc());
6691   NewTL.setRParenLoc(TL.getRParenLoc());
6692 
6693   return Result;
6694 }
6695 
6696 template <typename Derived>
6697 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6698                                                    PipeTypeLoc TL) {
6699   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6700   if (ValueType.isNull())
6701     return QualType();
6702 
6703   QualType Result = TL.getType();
6704   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6705     const PipeType *PT = Result->castAs<PipeType>();
6706     bool isReadPipe = PT->isReadOnly();
6707     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6708     if (Result.isNull())
6709       return QualType();
6710   }
6711 
6712   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6713   NewTL.setKWLoc(TL.getKWLoc());
6714 
6715   return Result;
6716 }
6717 
6718 template <typename Derived>
6719 QualType TreeTransform<Derived>::TransformBitIntType(TypeLocBuilder &TLB,
6720                                                      BitIntTypeLoc TL) {
6721   const BitIntType *EIT = TL.getTypePtr();
6722   QualType Result = TL.getType();
6723 
6724   if (getDerived().AlwaysRebuild()) {
6725     Result = getDerived().RebuildBitIntType(EIT->isUnsigned(),
6726                                             EIT->getNumBits(), TL.getNameLoc());
6727     if (Result.isNull())
6728       return QualType();
6729   }
6730 
6731   BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6732   NewTL.setNameLoc(TL.getNameLoc());
6733   return Result;
6734 }
6735 
6736 template <typename Derived>
6737 QualType TreeTransform<Derived>::TransformDependentBitIntType(
6738     TypeLocBuilder &TLB, DependentBitIntTypeLoc TL) {
6739   const DependentBitIntType *EIT = TL.getTypePtr();
6740 
6741   EnterExpressionEvaluationContext Unevaluated(
6742       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6743   ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6744   BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6745 
6746   if (BitsExpr.isInvalid())
6747     return QualType();
6748 
6749   QualType Result = TL.getType();
6750 
6751   if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6752     Result = getDerived().RebuildDependentBitIntType(
6753         EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6754 
6755     if (Result.isNull())
6756       return QualType();
6757   }
6758 
6759   if (isa<DependentBitIntType>(Result)) {
6760     DependentBitIntTypeLoc NewTL = TLB.push<DependentBitIntTypeLoc>(Result);
6761     NewTL.setNameLoc(TL.getNameLoc());
6762   } else {
6763     BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6764     NewTL.setNameLoc(TL.getNameLoc());
6765   }
6766   return Result;
6767 }
6768 
6769   /// Simple iterator that traverses the template arguments in a
6770   /// container that provides a \c getArgLoc() member function.
6771   ///
6772   /// This iterator is intended to be used with the iterator form of
6773   /// \c TreeTransform<Derived>::TransformTemplateArguments().
6774   template<typename ArgLocContainer>
6775   class TemplateArgumentLocContainerIterator {
6776     ArgLocContainer *Container;
6777     unsigned Index;
6778 
6779   public:
6780     typedef TemplateArgumentLoc value_type;
6781     typedef TemplateArgumentLoc reference;
6782     typedef int difference_type;
6783     typedef std::input_iterator_tag iterator_category;
6784 
6785     class pointer {
6786       TemplateArgumentLoc Arg;
6787 
6788     public:
6789       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6790 
6791       const TemplateArgumentLoc *operator->() const {
6792         return &Arg;
6793       }
6794     };
6795 
6796 
6797     TemplateArgumentLocContainerIterator() {}
6798 
6799     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6800                                  unsigned Index)
6801       : Container(&Container), Index(Index) { }
6802 
6803     TemplateArgumentLocContainerIterator &operator++() {
6804       ++Index;
6805       return *this;
6806     }
6807 
6808     TemplateArgumentLocContainerIterator operator++(int) {
6809       TemplateArgumentLocContainerIterator Old(*this);
6810       ++(*this);
6811       return Old;
6812     }
6813 
6814     TemplateArgumentLoc operator*() const {
6815       return Container->getArgLoc(Index);
6816     }
6817 
6818     pointer operator->() const {
6819       return pointer(Container->getArgLoc(Index));
6820     }
6821 
6822     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6823                            const TemplateArgumentLocContainerIterator &Y) {
6824       return X.Container == Y.Container && X.Index == Y.Index;
6825     }
6826 
6827     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6828                            const TemplateArgumentLocContainerIterator &Y) {
6829       return !(X == Y);
6830     }
6831   };
6832 
6833 template<typename Derived>
6834 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6835                                                    AutoTypeLoc TL) {
6836   const AutoType *T = TL.getTypePtr();
6837   QualType OldDeduced = T->getDeducedType();
6838   QualType NewDeduced;
6839   if (!OldDeduced.isNull()) {
6840     NewDeduced = getDerived().TransformType(OldDeduced);
6841     if (NewDeduced.isNull())
6842       return QualType();
6843   }
6844 
6845   ConceptDecl *NewCD = nullptr;
6846   TemplateArgumentListInfo NewTemplateArgs;
6847   NestedNameSpecifierLoc NewNestedNameSpec;
6848   if (T->isConstrained()) {
6849     assert(TL.getConceptReference());
6850     NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6851         TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6852 
6853     NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6854     NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6855     typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6856     if (getDerived().TransformTemplateArguments(
6857             ArgIterator(TL, 0), ArgIterator(TL, TL.getNumArgs()),
6858             NewTemplateArgs))
6859       return QualType();
6860 
6861     if (TL.getNestedNameSpecifierLoc()) {
6862       NewNestedNameSpec
6863         = getDerived().TransformNestedNameSpecifierLoc(
6864             TL.getNestedNameSpecifierLoc());
6865       if (!NewNestedNameSpec)
6866         return QualType();
6867     }
6868   }
6869 
6870   QualType Result = TL.getType();
6871   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6872       T->isDependentType() || T->isConstrained()) {
6873     // FIXME: Maybe don't rebuild if all template arguments are the same.
6874     llvm::SmallVector<TemplateArgument, 4> NewArgList;
6875     NewArgList.reserve(NewTemplateArgs.size());
6876     for (const auto &ArgLoc : NewTemplateArgs.arguments())
6877       NewArgList.push_back(ArgLoc.getArgument());
6878     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6879                                           NewArgList);
6880     if (Result.isNull())
6881       return QualType();
6882   }
6883 
6884   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6885   NewTL.setNameLoc(TL.getNameLoc());
6886   NewTL.setRParenLoc(TL.getRParenLoc());
6887   NewTL.setConceptReference(nullptr);
6888 
6889   if (T->isConstrained()) {
6890     DeclarationNameInfo DNI = DeclarationNameInfo(
6891         TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6892         TL.getConceptNameLoc(),
6893         TL.getTypePtr()->getTypeConstraintConcept()->getDeclName());
6894     auto *CR = ConceptReference::Create(
6895         SemaRef.Context, NewNestedNameSpec, TL.getTemplateKWLoc(), DNI,
6896         TL.getFoundDecl(), TL.getTypePtr()->getTypeConstraintConcept(),
6897         ASTTemplateArgumentListInfo::Create(SemaRef.Context, NewTemplateArgs));
6898     NewTL.setConceptReference(CR);
6899   }
6900 
6901   return Result;
6902 }
6903 
6904 template <typename Derived>
6905 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6906                                                         TypeLocBuilder &TLB,
6907                                            TemplateSpecializationTypeLoc TL,
6908                                                       TemplateName Template) {
6909   TemplateArgumentListInfo NewTemplateArgs;
6910   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6911   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6912   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6913     ArgIterator;
6914   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6915                                               ArgIterator(TL, TL.getNumArgs()),
6916                                               NewTemplateArgs))
6917     return QualType();
6918 
6919   // FIXME: maybe don't rebuild if all the template arguments are the same.
6920 
6921   QualType Result =
6922     getDerived().RebuildTemplateSpecializationType(Template,
6923                                                    TL.getTemplateNameLoc(),
6924                                                    NewTemplateArgs);
6925 
6926   if (!Result.isNull()) {
6927     // Specializations of template template parameters are represented as
6928     // TemplateSpecializationTypes, and substitution of type alias templates
6929     // within a dependent context can transform them into
6930     // DependentTemplateSpecializationTypes.
6931     if (isa<DependentTemplateSpecializationType>(Result)) {
6932       DependentTemplateSpecializationTypeLoc NewTL
6933         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6934       NewTL.setElaboratedKeywordLoc(SourceLocation());
6935       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6936       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6937       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6938       NewTL.setLAngleLoc(TL.getLAngleLoc());
6939       NewTL.setRAngleLoc(TL.getRAngleLoc());
6940       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6941         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6942       return Result;
6943     }
6944 
6945     TemplateSpecializationTypeLoc NewTL
6946       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6947     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6948     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6949     NewTL.setLAngleLoc(TL.getLAngleLoc());
6950     NewTL.setRAngleLoc(TL.getRAngleLoc());
6951     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6952       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6953   }
6954 
6955   return Result;
6956 }
6957 
6958 template <typename Derived>
6959 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6960                                      TypeLocBuilder &TLB,
6961                                      DependentTemplateSpecializationTypeLoc TL,
6962                                      TemplateName Template,
6963                                      CXXScopeSpec &SS) {
6964   TemplateArgumentListInfo NewTemplateArgs;
6965   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6966   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6967   typedef TemplateArgumentLocContainerIterator<
6968             DependentTemplateSpecializationTypeLoc> ArgIterator;
6969   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6970                                               ArgIterator(TL, TL.getNumArgs()),
6971                                               NewTemplateArgs))
6972     return QualType();
6973 
6974   // FIXME: maybe don't rebuild if all the template arguments are the same.
6975 
6976   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6977     QualType Result = getSema().Context.getDependentTemplateSpecializationType(
6978         TL.getTypePtr()->getKeyword(), DTN->getQualifier(),
6979         DTN->getIdentifier(), NewTemplateArgs.arguments());
6980 
6981     DependentTemplateSpecializationTypeLoc NewTL
6982       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6983     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6984     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6985     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6986     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6987     NewTL.setLAngleLoc(TL.getLAngleLoc());
6988     NewTL.setRAngleLoc(TL.getRAngleLoc());
6989     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6990       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6991     return Result;
6992   }
6993 
6994   QualType Result
6995     = getDerived().RebuildTemplateSpecializationType(Template,
6996                                                      TL.getTemplateNameLoc(),
6997                                                      NewTemplateArgs);
6998 
6999   if (!Result.isNull()) {
7000     /// FIXME: Wrap this in an elaborated-type-specifier?
7001     TemplateSpecializationTypeLoc NewTL
7002       = TLB.push<TemplateSpecializationTypeLoc>(Result);
7003     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7004     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7005     NewTL.setLAngleLoc(TL.getLAngleLoc());
7006     NewTL.setRAngleLoc(TL.getRAngleLoc());
7007     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
7008       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
7009   }
7010 
7011   return Result;
7012 }
7013 
7014 template<typename Derived>
7015 QualType
7016 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
7017                                                 ElaboratedTypeLoc TL) {
7018   const ElaboratedType *T = TL.getTypePtr();
7019 
7020   NestedNameSpecifierLoc QualifierLoc;
7021   // NOTE: the qualifier in an ElaboratedType is optional.
7022   if (TL.getQualifierLoc()) {
7023     QualifierLoc
7024       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7025     if (!QualifierLoc)
7026       return QualType();
7027   }
7028 
7029   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
7030   if (NamedT.isNull())
7031     return QualType();
7032 
7033   // C++0x [dcl.type.elab]p2:
7034   //   If the identifier resolves to a typedef-name or the simple-template-id
7035   //   resolves to an alias template specialization, the
7036   //   elaborated-type-specifier is ill-formed.
7037   if (T->getKeyword() != ElaboratedTypeKeyword::None &&
7038       T->getKeyword() != ElaboratedTypeKeyword::Typename) {
7039     if (const TemplateSpecializationType *TST =
7040           NamedT->getAs<TemplateSpecializationType>()) {
7041       TemplateName Template = TST->getTemplateName();
7042       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
7043               Template.getAsTemplateDecl())) {
7044         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
7045                      diag::err_tag_reference_non_tag)
7046             << TAT << Sema::NTK_TypeAliasTemplate
7047             << llvm::to_underlying(
7048                    ElaboratedType::getTagTypeKindForKeyword(T->getKeyword()));
7049         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
7050       }
7051     }
7052   }
7053 
7054   QualType Result = TL.getType();
7055   if (getDerived().AlwaysRebuild() ||
7056       QualifierLoc != TL.getQualifierLoc() ||
7057       NamedT != T->getNamedType()) {
7058     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
7059                                                 T->getKeyword(),
7060                                                 QualifierLoc, NamedT);
7061     if (Result.isNull())
7062       return QualType();
7063   }
7064 
7065   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7066   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7067   NewTL.setQualifierLoc(QualifierLoc);
7068   return Result;
7069 }
7070 
7071 template <typename Derived>
7072 template <typename Fn>
7073 QualType TreeTransform<Derived>::TransformAttributedType(
7074     TypeLocBuilder &TLB, AttributedTypeLoc TL, Fn TransformModifiedTypeFn) {
7075   const AttributedType *oldType = TL.getTypePtr();
7076   QualType modifiedType = TransformModifiedTypeFn(TLB, TL.getModifiedLoc());
7077   if (modifiedType.isNull())
7078     return QualType();
7079 
7080   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
7081   const Attr *oldAttr = TL.getAttr();
7082   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
7083   if (oldAttr && !newAttr)
7084     return QualType();
7085 
7086   QualType result = TL.getType();
7087 
7088   // FIXME: dependent operand expressions?
7089   if (getDerived().AlwaysRebuild() ||
7090       modifiedType != oldType->getModifiedType()) {
7091     // TODO: this is really lame; we should really be rebuilding the
7092     // equivalent type from first principles.
7093     QualType equivalentType
7094       = getDerived().TransformType(oldType->getEquivalentType());
7095     if (equivalentType.isNull())
7096       return QualType();
7097 
7098     // Check whether we can add nullability; it is only represented as
7099     // type sugar, and therefore cannot be diagnosed in any other way.
7100     if (auto nullability = oldType->getImmediateNullability()) {
7101       if (!modifiedType->canHaveNullability()) {
7102         SemaRef.Diag((TL.getAttr() ? TL.getAttr()->getLocation()
7103                                    : TL.getModifiedLoc().getBeginLoc()),
7104                      diag::err_nullability_nonpointer)
7105             << DiagNullabilityKind(*nullability, false) << modifiedType;
7106         return QualType();
7107       }
7108     }
7109 
7110     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
7111                                                modifiedType,
7112                                                equivalentType);
7113   }
7114 
7115   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
7116   newTL.setAttr(newAttr);
7117   return result;
7118 }
7119 
7120 template <typename Derived>
7121 QualType TreeTransform<Derived>::TransformAttributedType(TypeLocBuilder &TLB,
7122                                                          AttributedTypeLoc TL) {
7123   return getDerived().TransformAttributedType(
7124       TLB, TL, [&](TypeLocBuilder &TLB, TypeLoc ModifiedLoc) -> QualType {
7125         return getDerived().TransformType(TLB, ModifiedLoc);
7126       });
7127 }
7128 
7129 template <typename Derived>
7130 QualType TreeTransform<Derived>::TransformBTFTagAttributedType(
7131     TypeLocBuilder &TLB, BTFTagAttributedTypeLoc TL) {
7132   // The BTFTagAttributedType is available for C only.
7133   llvm_unreachable("Unexpected TreeTransform for BTFTagAttributedType");
7134 }
7135 
7136 template<typename Derived>
7137 QualType
7138 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
7139                                            ParenTypeLoc TL) {
7140   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7141   if (Inner.isNull())
7142     return QualType();
7143 
7144   QualType Result = TL.getType();
7145   if (getDerived().AlwaysRebuild() ||
7146       Inner != TL.getInnerLoc().getType()) {
7147     Result = getDerived().RebuildParenType(Inner);
7148     if (Result.isNull())
7149       return QualType();
7150   }
7151 
7152   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
7153   NewTL.setLParenLoc(TL.getLParenLoc());
7154   NewTL.setRParenLoc(TL.getRParenLoc());
7155   return Result;
7156 }
7157 
7158 template <typename Derived>
7159 QualType
7160 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
7161                                                     MacroQualifiedTypeLoc TL) {
7162   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7163   if (Inner.isNull())
7164     return QualType();
7165 
7166   QualType Result = TL.getType();
7167   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
7168     Result =
7169         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
7170     if (Result.isNull())
7171       return QualType();
7172   }
7173 
7174   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
7175   NewTL.setExpansionLoc(TL.getExpansionLoc());
7176   return Result;
7177 }
7178 
7179 template<typename Derived>
7180 QualType TreeTransform<Derived>::TransformDependentNameType(
7181     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
7182   return TransformDependentNameType(TLB, TL, false);
7183 }
7184 
7185 template<typename Derived>
7186 QualType TreeTransform<Derived>::TransformDependentNameType(
7187     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
7188   const DependentNameType *T = TL.getTypePtr();
7189 
7190   NestedNameSpecifierLoc QualifierLoc
7191     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7192   if (!QualifierLoc)
7193     return QualType();
7194 
7195   QualType Result
7196     = getDerived().RebuildDependentNameType(T->getKeyword(),
7197                                             TL.getElaboratedKeywordLoc(),
7198                                             QualifierLoc,
7199                                             T->getIdentifier(),
7200                                             TL.getNameLoc(),
7201                                             DeducedTSTContext);
7202   if (Result.isNull())
7203     return QualType();
7204 
7205   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
7206     QualType NamedT = ElabT->getNamedType();
7207     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
7208 
7209     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7210     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7211     NewTL.setQualifierLoc(QualifierLoc);
7212   } else {
7213     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
7214     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7215     NewTL.setQualifierLoc(QualifierLoc);
7216     NewTL.setNameLoc(TL.getNameLoc());
7217   }
7218   return Result;
7219 }
7220 
7221 template<typename Derived>
7222 QualType TreeTransform<Derived>::
7223           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7224                                  DependentTemplateSpecializationTypeLoc TL) {
7225   NestedNameSpecifierLoc QualifierLoc;
7226   if (TL.getQualifierLoc()) {
7227     QualifierLoc
7228       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7229     if (!QualifierLoc)
7230       return QualType();
7231   }
7232 
7233   return getDerived()
7234            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
7235 }
7236 
7237 template<typename Derived>
7238 QualType TreeTransform<Derived>::
7239 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7240                                    DependentTemplateSpecializationTypeLoc TL,
7241                                        NestedNameSpecifierLoc QualifierLoc) {
7242   const DependentTemplateSpecializationType *T = TL.getTypePtr();
7243 
7244   TemplateArgumentListInfo NewTemplateArgs;
7245   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
7246   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
7247 
7248   typedef TemplateArgumentLocContainerIterator<
7249   DependentTemplateSpecializationTypeLoc> ArgIterator;
7250   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
7251                                               ArgIterator(TL, TL.getNumArgs()),
7252                                               NewTemplateArgs))
7253     return QualType();
7254 
7255   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
7256       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
7257       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
7258       /*AllowInjectedClassName*/ false);
7259   if (Result.isNull())
7260     return QualType();
7261 
7262   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
7263     QualType NamedT = ElabT->getNamedType();
7264 
7265     // Copy information relevant to the template specialization.
7266     TemplateSpecializationTypeLoc NamedTL
7267       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
7268     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7269     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7270     NamedTL.setLAngleLoc(TL.getLAngleLoc());
7271     NamedTL.setRAngleLoc(TL.getRAngleLoc());
7272     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7273       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7274 
7275     // Copy information relevant to the elaborated type.
7276     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7277     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7278     NewTL.setQualifierLoc(QualifierLoc);
7279   } else if (isa<DependentTemplateSpecializationType>(Result)) {
7280     DependentTemplateSpecializationTypeLoc SpecTL
7281       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
7282     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7283     SpecTL.setQualifierLoc(QualifierLoc);
7284     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7285     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7286     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7287     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7288     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7289       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7290   } else {
7291     TemplateSpecializationTypeLoc SpecTL
7292       = TLB.push<TemplateSpecializationTypeLoc>(Result);
7293     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7294     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7295     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7296     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7297     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7298       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7299   }
7300   return Result;
7301 }
7302 
7303 template<typename Derived>
7304 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
7305                                                       PackExpansionTypeLoc TL) {
7306   QualType Pattern
7307     = getDerived().TransformType(TLB, TL.getPatternLoc());
7308   if (Pattern.isNull())
7309     return QualType();
7310 
7311   QualType Result = TL.getType();
7312   if (getDerived().AlwaysRebuild() ||
7313       Pattern != TL.getPatternLoc().getType()) {
7314     Result = getDerived().RebuildPackExpansionType(Pattern,
7315                                            TL.getPatternLoc().getSourceRange(),
7316                                                    TL.getEllipsisLoc(),
7317                                            TL.getTypePtr()->getNumExpansions());
7318     if (Result.isNull())
7319       return QualType();
7320   }
7321 
7322   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
7323   NewT.setEllipsisLoc(TL.getEllipsisLoc());
7324   return Result;
7325 }
7326 
7327 template<typename Derived>
7328 QualType
7329 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
7330                                                    ObjCInterfaceTypeLoc TL) {
7331   // ObjCInterfaceType is never dependent.
7332   TLB.pushFullCopy(TL);
7333   return TL.getType();
7334 }
7335 
7336 template<typename Derived>
7337 QualType
7338 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7339                                                    ObjCTypeParamTypeLoc TL) {
7340   const ObjCTypeParamType *T = TL.getTypePtr();
7341   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7342       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7343   if (!OTP)
7344     return QualType();
7345 
7346   QualType Result = TL.getType();
7347   if (getDerived().AlwaysRebuild() ||
7348       OTP != T->getDecl()) {
7349     Result = getDerived().RebuildObjCTypeParamType(
7350         OTP, TL.getProtocolLAngleLoc(),
7351         llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7352         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7353     if (Result.isNull())
7354       return QualType();
7355   }
7356 
7357   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7358   if (TL.getNumProtocols()) {
7359     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7360     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7361       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7362     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7363   }
7364   return Result;
7365 }
7366 
7367 template<typename Derived>
7368 QualType
7369 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7370                                                 ObjCObjectTypeLoc TL) {
7371   // Transform base type.
7372   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7373   if (BaseType.isNull())
7374     return QualType();
7375 
7376   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7377 
7378   // Transform type arguments.
7379   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7380   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7381     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7382     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7383     QualType TypeArg = TypeArgInfo->getType();
7384     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7385       AnyChanged = true;
7386 
7387       // We have a pack expansion. Instantiate it.
7388       const auto *PackExpansion = PackExpansionLoc.getType()
7389                                     ->castAs<PackExpansionType>();
7390       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7391       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7392                                               Unexpanded);
7393       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
7394 
7395       // Determine whether the set of unexpanded parameter packs can
7396       // and should be expanded.
7397       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7398       bool Expand = false;
7399       bool RetainExpansion = false;
7400       std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7401       if (getDerived().TryExpandParameterPacks(
7402             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7403             Unexpanded, Expand, RetainExpansion, NumExpansions))
7404         return QualType();
7405 
7406       if (!Expand) {
7407         // We can't expand this pack expansion into separate arguments yet;
7408         // just substitute into the pattern and create a new pack expansion
7409         // type.
7410         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7411 
7412         TypeLocBuilder TypeArgBuilder;
7413         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7414         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7415                                                              PatternLoc);
7416         if (NewPatternType.isNull())
7417           return QualType();
7418 
7419         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7420                                       NewPatternType, NumExpansions);
7421         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7422         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7423         NewTypeArgInfos.push_back(
7424           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7425         continue;
7426       }
7427 
7428       // Substitute into the pack expansion pattern for each slice of the
7429       // pack.
7430       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7431         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7432 
7433         TypeLocBuilder TypeArgBuilder;
7434         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7435 
7436         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7437                                                          PatternLoc);
7438         if (NewTypeArg.isNull())
7439           return QualType();
7440 
7441         NewTypeArgInfos.push_back(
7442           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7443       }
7444 
7445       continue;
7446     }
7447 
7448     TypeLocBuilder TypeArgBuilder;
7449     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7450     QualType NewTypeArg =
7451         getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7452     if (NewTypeArg.isNull())
7453       return QualType();
7454 
7455     // If nothing changed, just keep the old TypeSourceInfo.
7456     if (NewTypeArg == TypeArg) {
7457       NewTypeArgInfos.push_back(TypeArgInfo);
7458       continue;
7459     }
7460 
7461     NewTypeArgInfos.push_back(
7462       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7463     AnyChanged = true;
7464   }
7465 
7466   QualType Result = TL.getType();
7467   if (getDerived().AlwaysRebuild() || AnyChanged) {
7468     // Rebuild the type.
7469     Result = getDerived().RebuildObjCObjectType(
7470         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7471         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7472         llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7473         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7474 
7475     if (Result.isNull())
7476       return QualType();
7477   }
7478 
7479   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7480   NewT.setHasBaseTypeAsWritten(true);
7481   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7482   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7483     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7484   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7485   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7486   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7487     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7488   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7489   return Result;
7490 }
7491 
7492 template<typename Derived>
7493 QualType
7494 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7495                                                ObjCObjectPointerTypeLoc TL) {
7496   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7497   if (PointeeType.isNull())
7498     return QualType();
7499 
7500   QualType Result = TL.getType();
7501   if (getDerived().AlwaysRebuild() ||
7502       PointeeType != TL.getPointeeLoc().getType()) {
7503     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7504                                                        TL.getStarLoc());
7505     if (Result.isNull())
7506       return QualType();
7507   }
7508 
7509   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7510   NewT.setStarLoc(TL.getStarLoc());
7511   return Result;
7512 }
7513 
7514 //===----------------------------------------------------------------------===//
7515 // Statement transformation
7516 //===----------------------------------------------------------------------===//
7517 template<typename Derived>
7518 StmtResult
7519 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7520   return S;
7521 }
7522 
7523 template<typename Derived>
7524 StmtResult
7525 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7526   return getDerived().TransformCompoundStmt(S, false);
7527 }
7528 
7529 template<typename Derived>
7530 StmtResult
7531 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7532                                               bool IsStmtExpr) {
7533   Sema::CompoundScopeRAII CompoundScope(getSema());
7534   Sema::FPFeaturesStateRAII FPSave(getSema());
7535   if (S->hasStoredFPFeatures())
7536     getSema().resetFPOptions(
7537         S->getStoredFPFeatures().applyOverrides(getSema().getLangOpts()));
7538 
7539   const Stmt *ExprResult = S->getStmtExprResult();
7540   bool SubStmtInvalid = false;
7541   bool SubStmtChanged = false;
7542   SmallVector<Stmt*, 8> Statements;
7543   for (auto *B : S->body()) {
7544     StmtResult Result = getDerived().TransformStmt(
7545         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7546 
7547     if (Result.isInvalid()) {
7548       // Immediately fail if this was a DeclStmt, since it's very
7549       // likely that this will cause problems for future statements.
7550       if (isa<DeclStmt>(B))
7551         return StmtError();
7552 
7553       // Otherwise, just keep processing substatements and fail later.
7554       SubStmtInvalid = true;
7555       continue;
7556     }
7557 
7558     SubStmtChanged = SubStmtChanged || Result.get() != B;
7559     Statements.push_back(Result.getAs<Stmt>());
7560   }
7561 
7562   if (SubStmtInvalid)
7563     return StmtError();
7564 
7565   if (!getDerived().AlwaysRebuild() &&
7566       !SubStmtChanged)
7567     return S;
7568 
7569   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7570                                           Statements,
7571                                           S->getRBracLoc(),
7572                                           IsStmtExpr);
7573 }
7574 
7575 template<typename Derived>
7576 StmtResult
7577 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7578   ExprResult LHS, RHS;
7579   {
7580     EnterExpressionEvaluationContext Unevaluated(
7581         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7582 
7583     // Transform the left-hand case value.
7584     LHS = getDerived().TransformExpr(S->getLHS());
7585     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7586     if (LHS.isInvalid())
7587       return StmtError();
7588 
7589     // Transform the right-hand case value (for the GNU case-range extension).
7590     RHS = getDerived().TransformExpr(S->getRHS());
7591     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7592     if (RHS.isInvalid())
7593       return StmtError();
7594   }
7595 
7596   // Build the case statement.
7597   // Case statements are always rebuilt so that they will attached to their
7598   // transformed switch statement.
7599   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7600                                                        LHS.get(),
7601                                                        S->getEllipsisLoc(),
7602                                                        RHS.get(),
7603                                                        S->getColonLoc());
7604   if (Case.isInvalid())
7605     return StmtError();
7606 
7607   // Transform the statement following the case
7608   StmtResult SubStmt =
7609       getDerived().TransformStmt(S->getSubStmt());
7610   if (SubStmt.isInvalid())
7611     return StmtError();
7612 
7613   // Attach the body to the case statement
7614   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7615 }
7616 
7617 template <typename Derived>
7618 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7619   // Transform the statement following the default case
7620   StmtResult SubStmt =
7621       getDerived().TransformStmt(S->getSubStmt());
7622   if (SubStmt.isInvalid())
7623     return StmtError();
7624 
7625   // Default statements are always rebuilt
7626   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7627                                          SubStmt.get());
7628 }
7629 
7630 template<typename Derived>
7631 StmtResult
7632 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7633   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7634   if (SubStmt.isInvalid())
7635     return StmtError();
7636 
7637   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7638                                         S->getDecl());
7639   if (!LD)
7640     return StmtError();
7641 
7642   // If we're transforming "in-place" (we're not creating new local
7643   // declarations), assume we're replacing the old label statement
7644   // and clear out the reference to it.
7645   if (LD == S->getDecl())
7646     S->getDecl()->setStmt(nullptr);
7647 
7648   // FIXME: Pass the real colon location in.
7649   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7650                                        cast<LabelDecl>(LD), SourceLocation(),
7651                                        SubStmt.get());
7652 }
7653 
7654 template <typename Derived>
7655 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7656   if (!R)
7657     return R;
7658 
7659   switch (R->getKind()) {
7660 // Transform attributes by calling TransformXXXAttr.
7661 #define ATTR(X)                                                                \
7662   case attr::X:                                                                \
7663     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7664 #include "clang/Basic/AttrList.inc"
7665   }
7666   return R;
7667 }
7668 
7669 template <typename Derived>
7670 const Attr *TreeTransform<Derived>::TransformStmtAttr(const Stmt *OrigS,
7671                                                       const Stmt *InstS,
7672                                                       const Attr *R) {
7673   if (!R)
7674     return R;
7675 
7676   switch (R->getKind()) {
7677 // Transform attributes by calling TransformStmtXXXAttr.
7678 #define ATTR(X)                                                                \
7679   case attr::X:                                                                \
7680     return getDerived().TransformStmt##X##Attr(OrigS, InstS, cast<X##Attr>(R));
7681 #include "clang/Basic/AttrList.inc"
7682   }
7683   return TransformAttr(R);
7684 }
7685 
7686 template <typename Derived>
7687 StmtResult
7688 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7689                                                 StmtDiscardKind SDK) {
7690   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7691   if (SubStmt.isInvalid())
7692     return StmtError();
7693 
7694   bool AttrsChanged = false;
7695   SmallVector<const Attr *, 1> Attrs;
7696 
7697   // Visit attributes and keep track if any are transformed.
7698   for (const auto *I : S->getAttrs()) {
7699     const Attr *R =
7700         getDerived().TransformStmtAttr(S->getSubStmt(), SubStmt.get(), I);
7701     AttrsChanged |= (I != R);
7702     if (R)
7703       Attrs.push_back(R);
7704   }
7705 
7706   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7707     return S;
7708 
7709   // If transforming the attributes failed for all of the attributes in the
7710   // statement, don't make an AttributedStmt without attributes.
7711   if (Attrs.empty())
7712     return SubStmt;
7713 
7714   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7715                                             SubStmt.get());
7716 }
7717 
7718 template<typename Derived>
7719 StmtResult
7720 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7721   // Transform the initialization statement
7722   StmtResult Init = getDerived().TransformStmt(S->getInit());
7723   if (Init.isInvalid())
7724     return StmtError();
7725 
7726   Sema::ConditionResult Cond;
7727   if (!S->isConsteval()) {
7728     // Transform the condition
7729     Cond = getDerived().TransformCondition(
7730         S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7731         S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7732                          : Sema::ConditionKind::Boolean);
7733     if (Cond.isInvalid())
7734       return StmtError();
7735   }
7736 
7737   // If this is a constexpr if, determine which arm we should instantiate.
7738   std::optional<bool> ConstexprConditionValue;
7739   if (S->isConstexpr())
7740     ConstexprConditionValue = Cond.getKnownValue();
7741 
7742   // Transform the "then" branch.
7743   StmtResult Then;
7744   if (!ConstexprConditionValue || *ConstexprConditionValue) {
7745     Then = getDerived().TransformStmt(S->getThen());
7746     if (Then.isInvalid())
7747       return StmtError();
7748   } else {
7749     // Discarded branch is replaced with empty CompoundStmt so we can keep
7750     // proper source location for start and end of original branch, so
7751     // subsequent transformations like CoverageMapping work properly
7752     Then = new (getSema().Context)
7753         CompoundStmt(S->getThen()->getBeginLoc(), S->getThen()->getEndLoc());
7754   }
7755 
7756   // Transform the "else" branch.
7757   StmtResult Else;
7758   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7759     Else = getDerived().TransformStmt(S->getElse());
7760     if (Else.isInvalid())
7761       return StmtError();
7762   } else if (S->getElse() && ConstexprConditionValue &&
7763              *ConstexprConditionValue) {
7764     // Same thing here as with <then> branch, we are discarding it, we can't
7765     // replace it with NULL nor NullStmt as we need to keep for source location
7766     // range, for CoverageMapping
7767     Else = new (getSema().Context)
7768         CompoundStmt(S->getElse()->getBeginLoc(), S->getElse()->getEndLoc());
7769   }
7770 
7771   if (!getDerived().AlwaysRebuild() &&
7772       Init.get() == S->getInit() &&
7773       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7774       Then.get() == S->getThen() &&
7775       Else.get() == S->getElse())
7776     return S;
7777 
7778   return getDerived().RebuildIfStmt(
7779       S->getIfLoc(), S->getStatementKind(), S->getLParenLoc(), Cond,
7780       S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7781 }
7782 
7783 template<typename Derived>
7784 StmtResult
7785 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7786   // Transform the initialization statement
7787   StmtResult Init = getDerived().TransformStmt(S->getInit());
7788   if (Init.isInvalid())
7789     return StmtError();
7790 
7791   // Transform the condition.
7792   Sema::ConditionResult Cond = getDerived().TransformCondition(
7793       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7794       Sema::ConditionKind::Switch);
7795   if (Cond.isInvalid())
7796     return StmtError();
7797 
7798   // Rebuild the switch statement.
7799   StmtResult Switch =
7800       getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7801                                           Init.get(), Cond, S->getRParenLoc());
7802   if (Switch.isInvalid())
7803     return StmtError();
7804 
7805   // Transform the body of the switch statement.
7806   StmtResult Body = getDerived().TransformStmt(S->getBody());
7807   if (Body.isInvalid())
7808     return StmtError();
7809 
7810   // Complete the switch statement.
7811   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7812                                             Body.get());
7813 }
7814 
7815 template<typename Derived>
7816 StmtResult
7817 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7818   // Transform the condition
7819   Sema::ConditionResult Cond = getDerived().TransformCondition(
7820       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7821       Sema::ConditionKind::Boolean);
7822   if (Cond.isInvalid())
7823     return StmtError();
7824 
7825   // Transform the body
7826   StmtResult Body = getDerived().TransformStmt(S->getBody());
7827   if (Body.isInvalid())
7828     return StmtError();
7829 
7830   if (!getDerived().AlwaysRebuild() &&
7831       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7832       Body.get() == S->getBody())
7833     return Owned(S);
7834 
7835   return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7836                                        Cond, S->getRParenLoc(), Body.get());
7837 }
7838 
7839 template<typename Derived>
7840 StmtResult
7841 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7842   // Transform the body
7843   StmtResult Body = getDerived().TransformStmt(S->getBody());
7844   if (Body.isInvalid())
7845     return StmtError();
7846 
7847   // Transform the condition
7848   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7849   if (Cond.isInvalid())
7850     return StmtError();
7851 
7852   if (!getDerived().AlwaysRebuild() &&
7853       Cond.get() == S->getCond() &&
7854       Body.get() == S->getBody())
7855     return S;
7856 
7857   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7858                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
7859                                     S->getRParenLoc());
7860 }
7861 
7862 template<typename Derived>
7863 StmtResult
7864 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7865   if (getSema().getLangOpts().OpenMP)
7866     getSema().startOpenMPLoop();
7867 
7868   // Transform the initialization statement
7869   StmtResult Init = getDerived().TransformStmt(S->getInit());
7870   if (Init.isInvalid())
7871     return StmtError();
7872 
7873   // In OpenMP loop region loop control variable must be captured and be
7874   // private. Perform analysis of first part (if any).
7875   if (getSema().getLangOpts().OpenMP && Init.isUsable())
7876     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7877 
7878   // Transform the condition
7879   Sema::ConditionResult Cond = getDerived().TransformCondition(
7880       S->getForLoc(), S->getConditionVariable(), S->getCond(),
7881       Sema::ConditionKind::Boolean);
7882   if (Cond.isInvalid())
7883     return StmtError();
7884 
7885   // Transform the increment
7886   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7887   if (Inc.isInvalid())
7888     return StmtError();
7889 
7890   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7891   if (S->getInc() && !FullInc.get())
7892     return StmtError();
7893 
7894   // Transform the body
7895   StmtResult Body = getDerived().TransformStmt(S->getBody());
7896   if (Body.isInvalid())
7897     return StmtError();
7898 
7899   if (!getDerived().AlwaysRebuild() &&
7900       Init.get() == S->getInit() &&
7901       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7902       Inc.get() == S->getInc() &&
7903       Body.get() == S->getBody())
7904     return S;
7905 
7906   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7907                                      Init.get(), Cond, FullInc,
7908                                      S->getRParenLoc(), Body.get());
7909 }
7910 
7911 template<typename Derived>
7912 StmtResult
7913 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7914   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7915                                         S->getLabel());
7916   if (!LD)
7917     return StmtError();
7918 
7919   // Goto statements must always be rebuilt, to resolve the label.
7920   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7921                                       cast<LabelDecl>(LD));
7922 }
7923 
7924 template<typename Derived>
7925 StmtResult
7926 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7927   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7928   if (Target.isInvalid())
7929     return StmtError();
7930   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7931 
7932   if (!getDerived().AlwaysRebuild() &&
7933       Target.get() == S->getTarget())
7934     return S;
7935 
7936   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7937                                               Target.get());
7938 }
7939 
7940 template<typename Derived>
7941 StmtResult
7942 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7943   return S;
7944 }
7945 
7946 template<typename Derived>
7947 StmtResult
7948 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7949   return S;
7950 }
7951 
7952 template<typename Derived>
7953 StmtResult
7954 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7955   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7956                                                         /*NotCopyInit*/false);
7957   if (Result.isInvalid())
7958     return StmtError();
7959 
7960   // FIXME: We always rebuild the return statement because there is no way
7961   // to tell whether the return type of the function has changed.
7962   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7963 }
7964 
7965 template<typename Derived>
7966 StmtResult
7967 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7968   bool DeclChanged = false;
7969   SmallVector<Decl *, 4> Decls;
7970   for (auto *D : S->decls()) {
7971     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7972     if (!Transformed)
7973       return StmtError();
7974 
7975     if (Transformed != D)
7976       DeclChanged = true;
7977 
7978     Decls.push_back(Transformed);
7979   }
7980 
7981   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7982     return S;
7983 
7984   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7985 }
7986 
7987 template<typename Derived>
7988 StmtResult
7989 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7990 
7991   SmallVector<Expr*, 8> Constraints;
7992   SmallVector<Expr*, 8> Exprs;
7993   SmallVector<IdentifierInfo *, 4> Names;
7994 
7995   ExprResult AsmString;
7996   SmallVector<Expr*, 8> Clobbers;
7997 
7998   bool ExprsChanged = false;
7999 
8000   // Go through the outputs.
8001   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
8002     Names.push_back(S->getOutputIdentifier(I));
8003 
8004     // No need to transform the constraint literal.
8005     Constraints.push_back(S->getOutputConstraintLiteral(I));
8006 
8007     // Transform the output expr.
8008     Expr *OutputExpr = S->getOutputExpr(I);
8009     ExprResult Result = getDerived().TransformExpr(OutputExpr);
8010     if (Result.isInvalid())
8011       return StmtError();
8012 
8013     ExprsChanged |= Result.get() != OutputExpr;
8014 
8015     Exprs.push_back(Result.get());
8016   }
8017 
8018   // Go through the inputs.
8019   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
8020     Names.push_back(S->getInputIdentifier(I));
8021 
8022     // No need to transform the constraint literal.
8023     Constraints.push_back(S->getInputConstraintLiteral(I));
8024 
8025     // Transform the input expr.
8026     Expr *InputExpr = S->getInputExpr(I);
8027     ExprResult Result = getDerived().TransformExpr(InputExpr);
8028     if (Result.isInvalid())
8029       return StmtError();
8030 
8031     ExprsChanged |= Result.get() != InputExpr;
8032 
8033     Exprs.push_back(Result.get());
8034   }
8035 
8036   // Go through the Labels.
8037   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
8038     Names.push_back(S->getLabelIdentifier(I));
8039 
8040     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
8041     if (Result.isInvalid())
8042       return StmtError();
8043     ExprsChanged |= Result.get() != S->getLabelExpr(I);
8044     Exprs.push_back(Result.get());
8045   }
8046   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
8047     return S;
8048 
8049   // Go through the clobbers.
8050   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
8051     Clobbers.push_back(S->getClobberStringLiteral(I));
8052 
8053   // No need to transform the asm string literal.
8054   AsmString = S->getAsmString();
8055   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
8056                                         S->isVolatile(), S->getNumOutputs(),
8057                                         S->getNumInputs(), Names.data(),
8058                                         Constraints, Exprs, AsmString.get(),
8059                                         Clobbers, S->getNumLabels(),
8060                                         S->getRParenLoc());
8061 }
8062 
8063 template<typename Derived>
8064 StmtResult
8065 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
8066   ArrayRef<Token> AsmToks = llvm::ArrayRef(S->getAsmToks(), S->getNumAsmToks());
8067 
8068   bool HadError = false, HadChange = false;
8069 
8070   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
8071   SmallVector<Expr*, 8> TransformedExprs;
8072   TransformedExprs.reserve(SrcExprs.size());
8073   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
8074     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
8075     if (!Result.isUsable()) {
8076       HadError = true;
8077     } else {
8078       HadChange |= (Result.get() != SrcExprs[i]);
8079       TransformedExprs.push_back(Result.get());
8080     }
8081   }
8082 
8083   if (HadError) return StmtError();
8084   if (!HadChange && !getDerived().AlwaysRebuild())
8085     return Owned(S);
8086 
8087   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
8088                                        AsmToks, S->getAsmString(),
8089                                        S->getNumOutputs(), S->getNumInputs(),
8090                                        S->getAllConstraints(), S->getClobbers(),
8091                                        TransformedExprs, S->getEndLoc());
8092 }
8093 
8094 // C++ Coroutines
8095 template<typename Derived>
8096 StmtResult
8097 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
8098   auto *ScopeInfo = SemaRef.getCurFunction();
8099   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
8100   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
8101          ScopeInfo->NeedsCoroutineSuspends &&
8102          ScopeInfo->CoroutineSuspends.first == nullptr &&
8103          ScopeInfo->CoroutineSuspends.second == nullptr &&
8104          "expected clean scope info");
8105 
8106   // Set that we have (possibly-invalid) suspend points before we do anything
8107   // that may fail.
8108   ScopeInfo->setNeedsCoroutineSuspends(false);
8109 
8110   // We re-build the coroutine promise object (and the coroutine parameters its
8111   // type and constructor depend on) based on the types used in our current
8112   // function. We must do so, and set it on the current FunctionScopeInfo,
8113   // before attempting to transform the other parts of the coroutine body
8114   // statement, such as the implicit suspend statements (because those
8115   // statements reference the FunctionScopeInfo::CoroutinePromise).
8116   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
8117     return StmtError();
8118   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
8119   if (!Promise)
8120     return StmtError();
8121   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
8122   ScopeInfo->CoroutinePromise = Promise;
8123 
8124   // Transform the implicit coroutine statements constructed using dependent
8125   // types during the previous parse: initial and final suspensions, the return
8126   // object, and others. We also transform the coroutine function's body.
8127   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
8128   if (InitSuspend.isInvalid())
8129     return StmtError();
8130   StmtResult FinalSuspend =
8131       getDerived().TransformStmt(S->getFinalSuspendStmt());
8132   if (FinalSuspend.isInvalid() ||
8133       !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
8134     return StmtError();
8135   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
8136   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
8137 
8138   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
8139   if (BodyRes.isInvalid())
8140     return StmtError();
8141 
8142   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
8143   if (Builder.isInvalid())
8144     return StmtError();
8145 
8146   Expr *ReturnObject = S->getReturnValueInit();
8147   assert(ReturnObject && "the return object is expected to be valid");
8148   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
8149                                                      /*NoCopyInit*/ false);
8150   if (Res.isInvalid())
8151     return StmtError();
8152   Builder.ReturnValue = Res.get();
8153 
8154   // If during the previous parse the coroutine still had a dependent promise
8155   // statement, we may need to build some implicit coroutine statements
8156   // (such as exception and fallthrough handlers) for the first time.
8157   if (S->hasDependentPromiseType()) {
8158     // We can only build these statements, however, if the current promise type
8159     // is not dependent.
8160     if (!Promise->getType()->isDependentType()) {
8161       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
8162              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
8163              "these nodes should not have been built yet");
8164       if (!Builder.buildDependentStatements())
8165         return StmtError();
8166     }
8167   } else {
8168     if (auto *OnFallthrough = S->getFallthroughHandler()) {
8169       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
8170       if (Res.isInvalid())
8171         return StmtError();
8172       Builder.OnFallthrough = Res.get();
8173     }
8174 
8175     if (auto *OnException = S->getExceptionHandler()) {
8176       StmtResult Res = getDerived().TransformStmt(OnException);
8177       if (Res.isInvalid())
8178         return StmtError();
8179       Builder.OnException = Res.get();
8180     }
8181 
8182     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
8183       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
8184       if (Res.isInvalid())
8185         return StmtError();
8186       Builder.ReturnStmtOnAllocFailure = Res.get();
8187     }
8188 
8189     // Transform any additional statements we may have already built
8190     assert(S->getAllocate() && S->getDeallocate() &&
8191            "allocation and deallocation calls must already be built");
8192     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
8193     if (AllocRes.isInvalid())
8194       return StmtError();
8195     Builder.Allocate = AllocRes.get();
8196 
8197     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
8198     if (DeallocRes.isInvalid())
8199       return StmtError();
8200     Builder.Deallocate = DeallocRes.get();
8201 
8202     if (auto *ResultDecl = S->getResultDecl()) {
8203       StmtResult Res = getDerived().TransformStmt(ResultDecl);
8204       if (Res.isInvalid())
8205         return StmtError();
8206       Builder.ResultDecl = Res.get();
8207     }
8208 
8209     if (auto *ReturnStmt = S->getReturnStmt()) {
8210       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
8211       if (Res.isInvalid())
8212         return StmtError();
8213       Builder.ReturnStmt = Res.get();
8214     }
8215   }
8216 
8217   return getDerived().RebuildCoroutineBodyStmt(Builder);
8218 }
8219 
8220 template<typename Derived>
8221 StmtResult
8222 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
8223   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
8224                                                         /*NotCopyInit*/false);
8225   if (Result.isInvalid())
8226     return StmtError();
8227 
8228   // Always rebuild; we don't know if this needs to be injected into a new
8229   // context or if the promise type has changed.
8230   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
8231                                           S->isImplicit());
8232 }
8233 
8234 template <typename Derived>
8235 ExprResult TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
8236   ExprResult Operand = getDerived().TransformInitializer(E->getOperand(),
8237                                                          /*NotCopyInit*/ false);
8238   if (Operand.isInvalid())
8239     return ExprError();
8240 
8241   // Rebuild the common-expr from the operand rather than transforming it
8242   // separately.
8243 
8244   // FIXME: getCurScope() should not be used during template instantiation.
8245   // We should pick up the set of unqualified lookup results for operator
8246   // co_await during the initial parse.
8247   ExprResult Lookup = getSema().BuildOperatorCoawaitLookupExpr(
8248       getSema().getCurScope(), E->getKeywordLoc());
8249 
8250   // Always rebuild; we don't know if this needs to be injected into a new
8251   // context or if the promise type has changed.
8252   return getDerived().RebuildCoawaitExpr(
8253       E->getKeywordLoc(), Operand.get(),
8254       cast<UnresolvedLookupExpr>(Lookup.get()), E->isImplicit());
8255 }
8256 
8257 template <typename Derived>
8258 ExprResult
8259 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
8260   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
8261                                                         /*NotCopyInit*/ false);
8262   if (OperandResult.isInvalid())
8263     return ExprError();
8264 
8265   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
8266           E->getOperatorCoawaitLookup());
8267 
8268   if (LookupResult.isInvalid())
8269     return ExprError();
8270 
8271   // Always rebuild; we don't know if this needs to be injected into a new
8272   // context or if the promise type has changed.
8273   return getDerived().RebuildDependentCoawaitExpr(
8274       E->getKeywordLoc(), OperandResult.get(),
8275       cast<UnresolvedLookupExpr>(LookupResult.get()));
8276 }
8277 
8278 template<typename Derived>
8279 ExprResult
8280 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
8281   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
8282                                                         /*NotCopyInit*/false);
8283   if (Result.isInvalid())
8284     return ExprError();
8285 
8286   // Always rebuild; we don't know if this needs to be injected into a new
8287   // context or if the promise type has changed.
8288   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
8289 }
8290 
8291 // Objective-C Statements.
8292 
8293 template<typename Derived>
8294 StmtResult
8295 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
8296   // Transform the body of the @try.
8297   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
8298   if (TryBody.isInvalid())
8299     return StmtError();
8300 
8301   // Transform the @catch statements (if present).
8302   bool AnyCatchChanged = false;
8303   SmallVector<Stmt*, 8> CatchStmts;
8304   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
8305     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
8306     if (Catch.isInvalid())
8307       return StmtError();
8308     if (Catch.get() != S->getCatchStmt(I))
8309       AnyCatchChanged = true;
8310     CatchStmts.push_back(Catch.get());
8311   }
8312 
8313   // Transform the @finally statement (if present).
8314   StmtResult Finally;
8315   if (S->getFinallyStmt()) {
8316     Finally = getDerived().TransformStmt(S->getFinallyStmt());
8317     if (Finally.isInvalid())
8318       return StmtError();
8319   }
8320 
8321   // If nothing changed, just retain this statement.
8322   if (!getDerived().AlwaysRebuild() &&
8323       TryBody.get() == S->getTryBody() &&
8324       !AnyCatchChanged &&
8325       Finally.get() == S->getFinallyStmt())
8326     return S;
8327 
8328   // Build a new statement.
8329   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
8330                                            CatchStmts, Finally.get());
8331 }
8332 
8333 template<typename Derived>
8334 StmtResult
8335 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
8336   // Transform the @catch parameter, if there is one.
8337   VarDecl *Var = nullptr;
8338   if (VarDecl *FromVar = S->getCatchParamDecl()) {
8339     TypeSourceInfo *TSInfo = nullptr;
8340     if (FromVar->getTypeSourceInfo()) {
8341       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
8342       if (!TSInfo)
8343         return StmtError();
8344     }
8345 
8346     QualType T;
8347     if (TSInfo)
8348       T = TSInfo->getType();
8349     else {
8350       T = getDerived().TransformType(FromVar->getType());
8351       if (T.isNull())
8352         return StmtError();
8353     }
8354 
8355     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
8356     if (!Var)
8357       return StmtError();
8358   }
8359 
8360   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
8361   if (Body.isInvalid())
8362     return StmtError();
8363 
8364   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
8365                                              S->getRParenLoc(),
8366                                              Var, Body.get());
8367 }
8368 
8369 template<typename Derived>
8370 StmtResult
8371 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
8372   // Transform the body.
8373   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8374   if (Body.isInvalid())
8375     return StmtError();
8376 
8377   // If nothing changed, just retain this statement.
8378   if (!getDerived().AlwaysRebuild() &&
8379       Body.get() == S->getFinallyBody())
8380     return S;
8381 
8382   // Build a new statement.
8383   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8384                                                Body.get());
8385 }
8386 
8387 template<typename Derived>
8388 StmtResult
8389 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8390   ExprResult Operand;
8391   if (S->getThrowExpr()) {
8392     Operand = getDerived().TransformExpr(S->getThrowExpr());
8393     if (Operand.isInvalid())
8394       return StmtError();
8395   }
8396 
8397   if (!getDerived().AlwaysRebuild() &&
8398       Operand.get() == S->getThrowExpr())
8399     return S;
8400 
8401   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8402 }
8403 
8404 template<typename Derived>
8405 StmtResult
8406 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8407                                                   ObjCAtSynchronizedStmt *S) {
8408   // Transform the object we are locking.
8409   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8410   if (Object.isInvalid())
8411     return StmtError();
8412   Object =
8413     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8414                                                   Object.get());
8415   if (Object.isInvalid())
8416     return StmtError();
8417 
8418   // Transform the body.
8419   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8420   if (Body.isInvalid())
8421     return StmtError();
8422 
8423   // If nothing change, just retain the current statement.
8424   if (!getDerived().AlwaysRebuild() &&
8425       Object.get() == S->getSynchExpr() &&
8426       Body.get() == S->getSynchBody())
8427     return S;
8428 
8429   // Build a new statement.
8430   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8431                                                     Object.get(), Body.get());
8432 }
8433 
8434 template<typename Derived>
8435 StmtResult
8436 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8437                                               ObjCAutoreleasePoolStmt *S) {
8438   // Transform the body.
8439   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8440   if (Body.isInvalid())
8441     return StmtError();
8442 
8443   // If nothing changed, just retain this statement.
8444   if (!getDerived().AlwaysRebuild() &&
8445       Body.get() == S->getSubStmt())
8446     return S;
8447 
8448   // Build a new statement.
8449   return getDerived().RebuildObjCAutoreleasePoolStmt(
8450                         S->getAtLoc(), Body.get());
8451 }
8452 
8453 template<typename Derived>
8454 StmtResult
8455 TreeTransform<Derived>::TransformObjCForCollectionStmt(
8456                                                   ObjCForCollectionStmt *S) {
8457   // Transform the element statement.
8458   StmtResult Element =
8459       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8460   if (Element.isInvalid())
8461     return StmtError();
8462 
8463   // Transform the collection expression.
8464   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8465   if (Collection.isInvalid())
8466     return StmtError();
8467 
8468   // Transform the body.
8469   StmtResult Body = getDerived().TransformStmt(S->getBody());
8470   if (Body.isInvalid())
8471     return StmtError();
8472 
8473   // If nothing changed, just retain this statement.
8474   if (!getDerived().AlwaysRebuild() &&
8475       Element.get() == S->getElement() &&
8476       Collection.get() == S->getCollection() &&
8477       Body.get() == S->getBody())
8478     return S;
8479 
8480   // Build a new statement.
8481   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8482                                                    Element.get(),
8483                                                    Collection.get(),
8484                                                    S->getRParenLoc(),
8485                                                    Body.get());
8486 }
8487 
8488 template <typename Derived>
8489 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8490   // Transform the exception declaration, if any.
8491   VarDecl *Var = nullptr;
8492   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8493     TypeSourceInfo *T =
8494         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8495     if (!T)
8496       return StmtError();
8497 
8498     Var = getDerived().RebuildExceptionDecl(
8499         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8500         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8501     if (!Var || Var->isInvalidDecl())
8502       return StmtError();
8503   }
8504 
8505   // Transform the actual exception handler.
8506   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8507   if (Handler.isInvalid())
8508     return StmtError();
8509 
8510   if (!getDerived().AlwaysRebuild() && !Var &&
8511       Handler.get() == S->getHandlerBlock())
8512     return S;
8513 
8514   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8515 }
8516 
8517 template <typename Derived>
8518 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8519   // Transform the try block itself.
8520   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8521   if (TryBlock.isInvalid())
8522     return StmtError();
8523 
8524   // Transform the handlers.
8525   bool HandlerChanged = false;
8526   SmallVector<Stmt *, 8> Handlers;
8527   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8528     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8529     if (Handler.isInvalid())
8530       return StmtError();
8531 
8532     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8533     Handlers.push_back(Handler.getAs<Stmt>());
8534   }
8535 
8536   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8537       !HandlerChanged)
8538     return S;
8539 
8540   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8541                                         Handlers);
8542 }
8543 
8544 template<typename Derived>
8545 StmtResult
8546 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8547   StmtResult Init =
8548       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8549   if (Init.isInvalid())
8550     return StmtError();
8551 
8552   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8553   if (Range.isInvalid())
8554     return StmtError();
8555 
8556   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8557   if (Begin.isInvalid())
8558     return StmtError();
8559   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8560   if (End.isInvalid())
8561     return StmtError();
8562 
8563   ExprResult Cond = getDerived().TransformExpr(S->getCond());
8564   if (Cond.isInvalid())
8565     return StmtError();
8566   if (Cond.get())
8567     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8568   if (Cond.isInvalid())
8569     return StmtError();
8570   if (Cond.get())
8571     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8572 
8573   ExprResult Inc = getDerived().TransformExpr(S->getInc());
8574   if (Inc.isInvalid())
8575     return StmtError();
8576   if (Inc.get())
8577     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8578 
8579   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8580   if (LoopVar.isInvalid())
8581     return StmtError();
8582 
8583   StmtResult NewStmt = S;
8584   if (getDerived().AlwaysRebuild() ||
8585       Init.get() != S->getInit() ||
8586       Range.get() != S->getRangeStmt() ||
8587       Begin.get() != S->getBeginStmt() ||
8588       End.get() != S->getEndStmt() ||
8589       Cond.get() != S->getCond() ||
8590       Inc.get() != S->getInc() ||
8591       LoopVar.get() != S->getLoopVarStmt()) {
8592     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8593                                                   S->getCoawaitLoc(), Init.get(),
8594                                                   S->getColonLoc(), Range.get(),
8595                                                   Begin.get(), End.get(),
8596                                                   Cond.get(),
8597                                                   Inc.get(), LoopVar.get(),
8598                                                   S->getRParenLoc());
8599     if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8600       // Might not have attached any initializer to the loop variable.
8601       getSema().ActOnInitializerError(
8602           cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8603       return StmtError();
8604     }
8605   }
8606 
8607   StmtResult Body = getDerived().TransformStmt(S->getBody());
8608   if (Body.isInvalid())
8609     return StmtError();
8610 
8611   // Body has changed but we didn't rebuild the for-range statement. Rebuild
8612   // it now so we have a new statement to attach the body to.
8613   if (Body.get() != S->getBody() && NewStmt.get() == S) {
8614     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8615                                                   S->getCoawaitLoc(), Init.get(),
8616                                                   S->getColonLoc(), Range.get(),
8617                                                   Begin.get(), End.get(),
8618                                                   Cond.get(),
8619                                                   Inc.get(), LoopVar.get(),
8620                                                   S->getRParenLoc());
8621     if (NewStmt.isInvalid())
8622       return StmtError();
8623   }
8624 
8625   if (NewStmt.get() == S)
8626     return S;
8627 
8628   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8629 }
8630 
8631 template<typename Derived>
8632 StmtResult
8633 TreeTransform<Derived>::TransformMSDependentExistsStmt(
8634                                                     MSDependentExistsStmt *S) {
8635   // Transform the nested-name-specifier, if any.
8636   NestedNameSpecifierLoc QualifierLoc;
8637   if (S->getQualifierLoc()) {
8638     QualifierLoc
8639       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8640     if (!QualifierLoc)
8641       return StmtError();
8642   }
8643 
8644   // Transform the declaration name.
8645   DeclarationNameInfo NameInfo = S->getNameInfo();
8646   if (NameInfo.getName()) {
8647     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8648     if (!NameInfo.getName())
8649       return StmtError();
8650   }
8651 
8652   // Check whether anything changed.
8653   if (!getDerived().AlwaysRebuild() &&
8654       QualifierLoc == S->getQualifierLoc() &&
8655       NameInfo.getName() == S->getNameInfo().getName())
8656     return S;
8657 
8658   // Determine whether this name exists, if we can.
8659   CXXScopeSpec SS;
8660   SS.Adopt(QualifierLoc);
8661   bool Dependent = false;
8662   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8663   case Sema::IER_Exists:
8664     if (S->isIfExists())
8665       break;
8666 
8667     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8668 
8669   case Sema::IER_DoesNotExist:
8670     if (S->isIfNotExists())
8671       break;
8672 
8673     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8674 
8675   case Sema::IER_Dependent:
8676     Dependent = true;
8677     break;
8678 
8679   case Sema::IER_Error:
8680     return StmtError();
8681   }
8682 
8683   // We need to continue with the instantiation, so do so now.
8684   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8685   if (SubStmt.isInvalid())
8686     return StmtError();
8687 
8688   // If we have resolved the name, just transform to the substatement.
8689   if (!Dependent)
8690     return SubStmt;
8691 
8692   // The name is still dependent, so build a dependent expression again.
8693   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8694                                                    S->isIfExists(),
8695                                                    QualifierLoc,
8696                                                    NameInfo,
8697                                                    SubStmt.get());
8698 }
8699 
8700 template<typename Derived>
8701 ExprResult
8702 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8703   NestedNameSpecifierLoc QualifierLoc;
8704   if (E->getQualifierLoc()) {
8705     QualifierLoc
8706     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8707     if (!QualifierLoc)
8708       return ExprError();
8709   }
8710 
8711   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8712     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8713   if (!PD)
8714     return ExprError();
8715 
8716   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8717   if (Base.isInvalid())
8718     return ExprError();
8719 
8720   return new (SemaRef.getASTContext())
8721       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8722                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8723                         QualifierLoc, E->getMemberLoc());
8724 }
8725 
8726 template <typename Derived>
8727 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8728     MSPropertySubscriptExpr *E) {
8729   auto BaseRes = getDerived().TransformExpr(E->getBase());
8730   if (BaseRes.isInvalid())
8731     return ExprError();
8732   auto IdxRes = getDerived().TransformExpr(E->getIdx());
8733   if (IdxRes.isInvalid())
8734     return ExprError();
8735 
8736   if (!getDerived().AlwaysRebuild() &&
8737       BaseRes.get() == E->getBase() &&
8738       IdxRes.get() == E->getIdx())
8739     return E;
8740 
8741   return getDerived().RebuildArraySubscriptExpr(
8742       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8743 }
8744 
8745 template <typename Derived>
8746 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8747   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8748   if (TryBlock.isInvalid())
8749     return StmtError();
8750 
8751   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8752   if (Handler.isInvalid())
8753     return StmtError();
8754 
8755   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8756       Handler.get() == S->getHandler())
8757     return S;
8758 
8759   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8760                                         TryBlock.get(), Handler.get());
8761 }
8762 
8763 template <typename Derived>
8764 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8765   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8766   if (Block.isInvalid())
8767     return StmtError();
8768 
8769   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8770 }
8771 
8772 template <typename Derived>
8773 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8774   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8775   if (FilterExpr.isInvalid())
8776     return StmtError();
8777 
8778   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8779   if (Block.isInvalid())
8780     return StmtError();
8781 
8782   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8783                                            Block.get());
8784 }
8785 
8786 template <typename Derived>
8787 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8788   if (isa<SEHFinallyStmt>(Handler))
8789     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8790   else
8791     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8792 }
8793 
8794 template<typename Derived>
8795 StmtResult
8796 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8797   return S;
8798 }
8799 
8800 //===----------------------------------------------------------------------===//
8801 // OpenMP directive transformation
8802 //===----------------------------------------------------------------------===//
8803 
8804 template <typename Derived>
8805 StmtResult
8806 TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8807   // OMPCanonicalLoops are eliminated during transformation, since they will be
8808   // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8809   // after transformation.
8810   return getDerived().TransformStmt(L->getLoopStmt());
8811 }
8812 
8813 template <typename Derived>
8814 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8815     OMPExecutableDirective *D) {
8816 
8817   // Transform the clauses
8818   llvm::SmallVector<OMPClause *, 16> TClauses;
8819   ArrayRef<OMPClause *> Clauses = D->clauses();
8820   TClauses.reserve(Clauses.size());
8821   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8822        I != E; ++I) {
8823     if (*I) {
8824       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8825       OMPClause *Clause = getDerived().TransformOMPClause(*I);
8826       getDerived().getSema().EndOpenMPClause();
8827       if (Clause)
8828         TClauses.push_back(Clause);
8829     } else {
8830       TClauses.push_back(nullptr);
8831     }
8832   }
8833   StmtResult AssociatedStmt;
8834   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8835     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8836                                                   /*CurScope=*/nullptr);
8837     StmtResult Body;
8838     {
8839       Sema::CompoundScopeRAII CompoundScope(getSema());
8840       Stmt *CS;
8841       if (D->getDirectiveKind() == OMPD_atomic ||
8842           D->getDirectiveKind() == OMPD_critical ||
8843           D->getDirectiveKind() == OMPD_section ||
8844           D->getDirectiveKind() == OMPD_master)
8845         CS = D->getAssociatedStmt();
8846       else
8847         CS = D->getRawStmt();
8848       Body = getDerived().TransformStmt(CS);
8849       if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8850           getSema().getLangOpts().OpenMPIRBuilder)
8851         Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8852     }
8853     AssociatedStmt =
8854         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8855     if (AssociatedStmt.isInvalid()) {
8856       return StmtError();
8857     }
8858   }
8859   if (TClauses.size() != Clauses.size()) {
8860     return StmtError();
8861   }
8862 
8863   // Transform directive name for 'omp critical' directive.
8864   DeclarationNameInfo DirName;
8865   if (D->getDirectiveKind() == OMPD_critical) {
8866     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8867     DirName = getDerived().TransformDeclarationNameInfo(DirName);
8868   }
8869   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8870   if (D->getDirectiveKind() == OMPD_cancellation_point) {
8871     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8872   } else if (D->getDirectiveKind() == OMPD_cancel) {
8873     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8874   }
8875 
8876   return getDerived().RebuildOMPExecutableDirective(
8877       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8878       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc(),
8879       D->getMappedDirective());
8880 }
8881 
8882 template <typename Derived>
8883 StmtResult
8884 TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
8885   // TODO: Fix This
8886   SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
8887       << getOpenMPDirectiveName(D->getDirectiveKind());
8888   return StmtError();
8889 }
8890 
8891 template <typename Derived>
8892 StmtResult
8893 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8894   DeclarationNameInfo DirName;
8895   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8896                                              D->getBeginLoc());
8897   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8898   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8899   return Res;
8900 }
8901 
8902 template <typename Derived>
8903 StmtResult
8904 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8905   DeclarationNameInfo DirName;
8906   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8907                                              D->getBeginLoc());
8908   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8909   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8910   return Res;
8911 }
8912 
8913 template <typename Derived>
8914 StmtResult
8915 TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8916   DeclarationNameInfo DirName;
8917   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8918                                              nullptr, D->getBeginLoc());
8919   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8920   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8921   return Res;
8922 }
8923 
8924 template <typename Derived>
8925 StmtResult
8926 TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8927   DeclarationNameInfo DirName;
8928   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8929                                              nullptr, D->getBeginLoc());
8930   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8931   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8932   return Res;
8933 }
8934 
8935 template <typename Derived>
8936 StmtResult
8937 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8938   DeclarationNameInfo DirName;
8939   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8940                                              D->getBeginLoc());
8941   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8942   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8943   return Res;
8944 }
8945 
8946 template <typename Derived>
8947 StmtResult
8948 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8949   DeclarationNameInfo DirName;
8950   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8951                                              D->getBeginLoc());
8952   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8953   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8954   return Res;
8955 }
8956 
8957 template <typename Derived>
8958 StmtResult
8959 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8960   DeclarationNameInfo DirName;
8961   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8962                                              D->getBeginLoc());
8963   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8964   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8965   return Res;
8966 }
8967 
8968 template <typename Derived>
8969 StmtResult
8970 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8971   DeclarationNameInfo DirName;
8972   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8973                                              D->getBeginLoc());
8974   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8975   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8976   return Res;
8977 }
8978 
8979 template <typename Derived>
8980 StmtResult
8981 TreeTransform<Derived>::TransformOMPScopeDirective(OMPScopeDirective *D) {
8982   DeclarationNameInfo DirName;
8983   getDerived().getSema().StartOpenMPDSABlock(OMPD_scope, DirName, nullptr,
8984                                              D->getBeginLoc());
8985   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8986   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8987   return Res;
8988 }
8989 
8990 template <typename Derived>
8991 StmtResult
8992 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8993   DeclarationNameInfo DirName;
8994   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8995                                              D->getBeginLoc());
8996   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8997   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8998   return Res;
8999 }
9000 
9001 template <typename Derived>
9002 StmtResult
9003 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
9004   DeclarationNameInfo DirName;
9005   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
9006                                              D->getBeginLoc());
9007   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9008   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9009   return Res;
9010 }
9011 
9012 template <typename Derived>
9013 StmtResult
9014 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
9015   getDerived().getSema().StartOpenMPDSABlock(
9016       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
9017   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9018   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9019   return Res;
9020 }
9021 
9022 template <typename Derived>
9023 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
9024     OMPParallelForDirective *D) {
9025   DeclarationNameInfo DirName;
9026   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
9027                                              nullptr, D->getBeginLoc());
9028   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9029   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9030   return Res;
9031 }
9032 
9033 template <typename Derived>
9034 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
9035     OMPParallelForSimdDirective *D) {
9036   DeclarationNameInfo DirName;
9037   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
9038                                              nullptr, D->getBeginLoc());
9039   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9040   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9041   return Res;
9042 }
9043 
9044 template <typename Derived>
9045 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
9046     OMPParallelMasterDirective *D) {
9047   DeclarationNameInfo DirName;
9048   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
9049                                              nullptr, D->getBeginLoc());
9050   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9051   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9052   return Res;
9053 }
9054 
9055 template <typename Derived>
9056 StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedDirective(
9057     OMPParallelMaskedDirective *D) {
9058   DeclarationNameInfo DirName;
9059   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_masked, DirName,
9060                                              nullptr, D->getBeginLoc());
9061   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9062   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9063   return Res;
9064 }
9065 
9066 template <typename Derived>
9067 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
9068     OMPParallelSectionsDirective *D) {
9069   DeclarationNameInfo DirName;
9070   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
9071                                              nullptr, D->getBeginLoc());
9072   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9073   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9074   return Res;
9075 }
9076 
9077 template <typename Derived>
9078 StmtResult
9079 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
9080   DeclarationNameInfo DirName;
9081   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
9082                                              D->getBeginLoc());
9083   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9084   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9085   return Res;
9086 }
9087 
9088 template <typename Derived>
9089 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
9090     OMPTaskyieldDirective *D) {
9091   DeclarationNameInfo DirName;
9092   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
9093                                              D->getBeginLoc());
9094   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9095   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9096   return Res;
9097 }
9098 
9099 template <typename Derived>
9100 StmtResult
9101 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
9102   DeclarationNameInfo DirName;
9103   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
9104                                              D->getBeginLoc());
9105   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9106   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9107   return Res;
9108 }
9109 
9110 template <typename Derived>
9111 StmtResult
9112 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
9113   DeclarationNameInfo DirName;
9114   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
9115                                              D->getBeginLoc());
9116   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9117   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9118   return Res;
9119 }
9120 
9121 template <typename Derived>
9122 StmtResult
9123 TreeTransform<Derived>::TransformOMPErrorDirective(OMPErrorDirective *D) {
9124   DeclarationNameInfo DirName;
9125   getDerived().getSema().StartOpenMPDSABlock(OMPD_error, DirName, nullptr,
9126                                              D->getBeginLoc());
9127   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9128   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9129   return Res;
9130 }
9131 
9132 template <typename Derived>
9133 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
9134     OMPTaskgroupDirective *D) {
9135   DeclarationNameInfo DirName;
9136   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
9137                                              D->getBeginLoc());
9138   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9139   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9140   return Res;
9141 }
9142 
9143 template <typename Derived>
9144 StmtResult
9145 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
9146   DeclarationNameInfo DirName;
9147   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
9148                                              D->getBeginLoc());
9149   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9150   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9151   return Res;
9152 }
9153 
9154 template <typename Derived>
9155 StmtResult
9156 TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
9157   DeclarationNameInfo DirName;
9158   getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
9159                                              D->getBeginLoc());
9160   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9161   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9162   return Res;
9163 }
9164 
9165 template <typename Derived>
9166 StmtResult
9167 TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
9168   DeclarationNameInfo DirName;
9169   getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
9170                                              D->getBeginLoc());
9171   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9172   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9173   return Res;
9174 }
9175 
9176 template <typename Derived>
9177 StmtResult
9178 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
9179   DeclarationNameInfo DirName;
9180   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
9181                                              D->getBeginLoc());
9182   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9183   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9184   return Res;
9185 }
9186 
9187 template <typename Derived>
9188 StmtResult
9189 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
9190   DeclarationNameInfo DirName;
9191   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
9192                                              D->getBeginLoc());
9193   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9194   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9195   return Res;
9196 }
9197 
9198 template <typename Derived>
9199 StmtResult
9200 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
9201   DeclarationNameInfo DirName;
9202   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
9203                                              D->getBeginLoc());
9204   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9205   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9206   return Res;
9207 }
9208 
9209 template <typename Derived>
9210 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
9211     OMPTargetDataDirective *D) {
9212   DeclarationNameInfo DirName;
9213   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
9214                                              D->getBeginLoc());
9215   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9216   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9217   return Res;
9218 }
9219 
9220 template <typename Derived>
9221 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
9222     OMPTargetEnterDataDirective *D) {
9223   DeclarationNameInfo DirName;
9224   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
9225                                              nullptr, D->getBeginLoc());
9226   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9227   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9228   return Res;
9229 }
9230 
9231 template <typename Derived>
9232 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
9233     OMPTargetExitDataDirective *D) {
9234   DeclarationNameInfo DirName;
9235   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
9236                                              nullptr, D->getBeginLoc());
9237   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9238   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9239   return Res;
9240 }
9241 
9242 template <typename Derived>
9243 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
9244     OMPTargetParallelDirective *D) {
9245   DeclarationNameInfo DirName;
9246   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
9247                                              nullptr, D->getBeginLoc());
9248   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9249   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9250   return Res;
9251 }
9252 
9253 template <typename Derived>
9254 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
9255     OMPTargetParallelForDirective *D) {
9256   DeclarationNameInfo DirName;
9257   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
9258                                              nullptr, D->getBeginLoc());
9259   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9260   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9261   return Res;
9262 }
9263 
9264 template <typename Derived>
9265 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
9266     OMPTargetUpdateDirective *D) {
9267   DeclarationNameInfo DirName;
9268   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
9269                                              nullptr, D->getBeginLoc());
9270   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9271   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9272   return Res;
9273 }
9274 
9275 template <typename Derived>
9276 StmtResult
9277 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
9278   DeclarationNameInfo DirName;
9279   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
9280                                              D->getBeginLoc());
9281   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9282   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9283   return Res;
9284 }
9285 
9286 template <typename Derived>
9287 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
9288     OMPCancellationPointDirective *D) {
9289   DeclarationNameInfo DirName;
9290   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
9291                                              nullptr, D->getBeginLoc());
9292   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9293   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9294   return Res;
9295 }
9296 
9297 template <typename Derived>
9298 StmtResult
9299 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
9300   DeclarationNameInfo DirName;
9301   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
9302                                              D->getBeginLoc());
9303   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9304   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9305   return Res;
9306 }
9307 
9308 template <typename Derived>
9309 StmtResult
9310 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
9311   DeclarationNameInfo DirName;
9312   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
9313                                              D->getBeginLoc());
9314   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9315   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9316   return Res;
9317 }
9318 
9319 template <typename Derived>
9320 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
9321     OMPTaskLoopSimdDirective *D) {
9322   DeclarationNameInfo DirName;
9323   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
9324                                              nullptr, D->getBeginLoc());
9325   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9326   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9327   return Res;
9328 }
9329 
9330 template <typename Derived>
9331 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
9332     OMPMasterTaskLoopDirective *D) {
9333   DeclarationNameInfo DirName;
9334   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
9335                                              nullptr, D->getBeginLoc());
9336   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9337   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9338   return Res;
9339 }
9340 
9341 template <typename Derived>
9342 StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopDirective(
9343     OMPMaskedTaskLoopDirective *D) {
9344   DeclarationNameInfo DirName;
9345   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop, DirName,
9346                                              nullptr, D->getBeginLoc());
9347   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9348   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9349   return Res;
9350 }
9351 
9352 template <typename Derived>
9353 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
9354     OMPMasterTaskLoopSimdDirective *D) {
9355   DeclarationNameInfo DirName;
9356   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
9357                                              nullptr, D->getBeginLoc());
9358   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9359   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9360   return Res;
9361 }
9362 
9363 template <typename Derived>
9364 StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopSimdDirective(
9365     OMPMaskedTaskLoopSimdDirective *D) {
9366   DeclarationNameInfo DirName;
9367   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop_simd, DirName,
9368                                              nullptr, D->getBeginLoc());
9369   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9370   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9371   return Res;
9372 }
9373 
9374 template <typename Derived>
9375 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
9376     OMPParallelMasterTaskLoopDirective *D) {
9377   DeclarationNameInfo DirName;
9378   getDerived().getSema().StartOpenMPDSABlock(
9379       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
9380   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9381   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9382   return Res;
9383 }
9384 
9385 template <typename Derived>
9386 StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopDirective(
9387     OMPParallelMaskedTaskLoopDirective *D) {
9388   DeclarationNameInfo DirName;
9389   getDerived().getSema().StartOpenMPDSABlock(
9390       OMPD_parallel_masked_taskloop, DirName, nullptr, D->getBeginLoc());
9391   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9392   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9393   return Res;
9394 }
9395 
9396 template <typename Derived>
9397 StmtResult
9398 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
9399     OMPParallelMasterTaskLoopSimdDirective *D) {
9400   DeclarationNameInfo DirName;
9401   getDerived().getSema().StartOpenMPDSABlock(
9402       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9403   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9404   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9405   return Res;
9406 }
9407 
9408 template <typename Derived>
9409 StmtResult
9410 TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopSimdDirective(
9411     OMPParallelMaskedTaskLoopSimdDirective *D) {
9412   DeclarationNameInfo DirName;
9413   getDerived().getSema().StartOpenMPDSABlock(
9414       OMPD_parallel_masked_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9415   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9416   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9417   return Res;
9418 }
9419 
9420 template <typename Derived>
9421 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
9422     OMPDistributeDirective *D) {
9423   DeclarationNameInfo DirName;
9424   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
9425                                              D->getBeginLoc());
9426   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9427   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9428   return Res;
9429 }
9430 
9431 template <typename Derived>
9432 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
9433     OMPDistributeParallelForDirective *D) {
9434   DeclarationNameInfo DirName;
9435   getDerived().getSema().StartOpenMPDSABlock(
9436       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9437   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9438   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9439   return Res;
9440 }
9441 
9442 template <typename Derived>
9443 StmtResult
9444 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
9445     OMPDistributeParallelForSimdDirective *D) {
9446   DeclarationNameInfo DirName;
9447   getDerived().getSema().StartOpenMPDSABlock(
9448       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9449   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9450   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9451   return Res;
9452 }
9453 
9454 template <typename Derived>
9455 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
9456     OMPDistributeSimdDirective *D) {
9457   DeclarationNameInfo DirName;
9458   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
9459                                              nullptr, D->getBeginLoc());
9460   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9461   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9462   return Res;
9463 }
9464 
9465 template <typename Derived>
9466 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9467     OMPTargetParallelForSimdDirective *D) {
9468   DeclarationNameInfo DirName;
9469   getDerived().getSema().StartOpenMPDSABlock(
9470       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9471   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9472   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9473   return Res;
9474 }
9475 
9476 template <typename Derived>
9477 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9478     OMPTargetSimdDirective *D) {
9479   DeclarationNameInfo DirName;
9480   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9481                                              D->getBeginLoc());
9482   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9483   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9484   return Res;
9485 }
9486 
9487 template <typename Derived>
9488 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9489     OMPTeamsDistributeDirective *D) {
9490   DeclarationNameInfo DirName;
9491   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9492                                              nullptr, D->getBeginLoc());
9493   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9494   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9495   return Res;
9496 }
9497 
9498 template <typename Derived>
9499 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9500     OMPTeamsDistributeSimdDirective *D) {
9501   DeclarationNameInfo DirName;
9502   getDerived().getSema().StartOpenMPDSABlock(
9503       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9504   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9505   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9506   return Res;
9507 }
9508 
9509 template <typename Derived>
9510 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9511     OMPTeamsDistributeParallelForSimdDirective *D) {
9512   DeclarationNameInfo DirName;
9513   getDerived().getSema().StartOpenMPDSABlock(
9514       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9515       D->getBeginLoc());
9516   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9517   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9518   return Res;
9519 }
9520 
9521 template <typename Derived>
9522 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9523     OMPTeamsDistributeParallelForDirective *D) {
9524   DeclarationNameInfo DirName;
9525   getDerived().getSema().StartOpenMPDSABlock(
9526       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9527   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9528   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9529   return Res;
9530 }
9531 
9532 template <typename Derived>
9533 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9534     OMPTargetTeamsDirective *D) {
9535   DeclarationNameInfo DirName;
9536   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9537                                              nullptr, D->getBeginLoc());
9538   auto Res = getDerived().TransformOMPExecutableDirective(D);
9539   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9540   return Res;
9541 }
9542 
9543 template <typename Derived>
9544 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9545     OMPTargetTeamsDistributeDirective *D) {
9546   DeclarationNameInfo DirName;
9547   getDerived().getSema().StartOpenMPDSABlock(
9548       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9549   auto Res = getDerived().TransformOMPExecutableDirective(D);
9550   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9551   return Res;
9552 }
9553 
9554 template <typename Derived>
9555 StmtResult
9556 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9557     OMPTargetTeamsDistributeParallelForDirective *D) {
9558   DeclarationNameInfo DirName;
9559   getDerived().getSema().StartOpenMPDSABlock(
9560       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9561       D->getBeginLoc());
9562   auto Res = getDerived().TransformOMPExecutableDirective(D);
9563   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9564   return Res;
9565 }
9566 
9567 template <typename Derived>
9568 StmtResult TreeTransform<Derived>::
9569     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9570         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9571   DeclarationNameInfo DirName;
9572   getDerived().getSema().StartOpenMPDSABlock(
9573       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9574       D->getBeginLoc());
9575   auto Res = getDerived().TransformOMPExecutableDirective(D);
9576   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9577   return Res;
9578 }
9579 
9580 template <typename Derived>
9581 StmtResult
9582 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9583     OMPTargetTeamsDistributeSimdDirective *D) {
9584   DeclarationNameInfo DirName;
9585   getDerived().getSema().StartOpenMPDSABlock(
9586       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9587   auto Res = getDerived().TransformOMPExecutableDirective(D);
9588   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9589   return Res;
9590 }
9591 
9592 template <typename Derived>
9593 StmtResult
9594 TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9595   DeclarationNameInfo DirName;
9596   getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9597                                              D->getBeginLoc());
9598   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9599   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9600   return Res;
9601 }
9602 
9603 template <typename Derived>
9604 StmtResult
9605 TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9606   DeclarationNameInfo DirName;
9607   getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9608                                              D->getBeginLoc());
9609   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9610   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9611   return Res;
9612 }
9613 
9614 template <typename Derived>
9615 StmtResult
9616 TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9617   DeclarationNameInfo DirName;
9618   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9619                                              D->getBeginLoc());
9620   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9621   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9622   return Res;
9623 }
9624 
9625 template <typename Derived>
9626 StmtResult TreeTransform<Derived>::TransformOMPGenericLoopDirective(
9627     OMPGenericLoopDirective *D) {
9628   DeclarationNameInfo DirName;
9629   getDerived().getSema().StartOpenMPDSABlock(OMPD_loop, DirName, nullptr,
9630                                              D->getBeginLoc());
9631   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9632   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9633   return Res;
9634 }
9635 
9636 template <typename Derived>
9637 StmtResult TreeTransform<Derived>::TransformOMPTeamsGenericLoopDirective(
9638     OMPTeamsGenericLoopDirective *D) {
9639   DeclarationNameInfo DirName;
9640   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_loop, DirName, nullptr,
9641                                              D->getBeginLoc());
9642   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9643   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9644   return Res;
9645 }
9646 
9647 template <typename Derived>
9648 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsGenericLoopDirective(
9649     OMPTargetTeamsGenericLoopDirective *D) {
9650   DeclarationNameInfo DirName;
9651   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_loop, DirName,
9652                                              nullptr, D->getBeginLoc());
9653   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9654   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9655   return Res;
9656 }
9657 
9658 template <typename Derived>
9659 StmtResult TreeTransform<Derived>::TransformOMPParallelGenericLoopDirective(
9660     OMPParallelGenericLoopDirective *D) {
9661   DeclarationNameInfo DirName;
9662   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_loop, DirName,
9663                                              nullptr, D->getBeginLoc());
9664   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9665   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9666   return Res;
9667 }
9668 
9669 template <typename Derived>
9670 StmtResult
9671 TreeTransform<Derived>::TransformOMPTargetParallelGenericLoopDirective(
9672     OMPTargetParallelGenericLoopDirective *D) {
9673   DeclarationNameInfo DirName;
9674   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_loop, DirName,
9675                                              nullptr, D->getBeginLoc());
9676   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9677   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9678   return Res;
9679 }
9680 
9681 //===----------------------------------------------------------------------===//
9682 // OpenMP clause transformation
9683 //===----------------------------------------------------------------------===//
9684 template <typename Derived>
9685 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9686   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9687   if (Cond.isInvalid())
9688     return nullptr;
9689   return getDerived().RebuildOMPIfClause(
9690       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9691       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9692 }
9693 
9694 template <typename Derived>
9695 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9696   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9697   if (Cond.isInvalid())
9698     return nullptr;
9699   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9700                                             C->getLParenLoc(), C->getEndLoc());
9701 }
9702 
9703 template <typename Derived>
9704 OMPClause *
9705 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9706   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9707   if (NumThreads.isInvalid())
9708     return nullptr;
9709   return getDerived().RebuildOMPNumThreadsClause(
9710       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9711 }
9712 
9713 template <typename Derived>
9714 OMPClause *
9715 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9716   ExprResult E = getDerived().TransformExpr(C->getSafelen());
9717   if (E.isInvalid())
9718     return nullptr;
9719   return getDerived().RebuildOMPSafelenClause(
9720       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9721 }
9722 
9723 template <typename Derived>
9724 OMPClause *
9725 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9726   ExprResult E = getDerived().TransformExpr(C->getAllocator());
9727   if (E.isInvalid())
9728     return nullptr;
9729   return getDerived().RebuildOMPAllocatorClause(
9730       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9731 }
9732 
9733 template <typename Derived>
9734 OMPClause *
9735 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9736   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9737   if (E.isInvalid())
9738     return nullptr;
9739   return getDerived().RebuildOMPSimdlenClause(
9740       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9741 }
9742 
9743 template <typename Derived>
9744 OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9745   SmallVector<Expr *, 4> TransformedSizes;
9746   TransformedSizes.reserve(C->getNumSizes());
9747   bool Changed = false;
9748   for (Expr *E : C->getSizesRefs()) {
9749     if (!E) {
9750       TransformedSizes.push_back(nullptr);
9751       continue;
9752     }
9753 
9754     ExprResult T = getDerived().TransformExpr(E);
9755     if (T.isInvalid())
9756       return nullptr;
9757     if (E != T.get())
9758       Changed = true;
9759     TransformedSizes.push_back(T.get());
9760   }
9761 
9762   if (!Changed && !getDerived().AlwaysRebuild())
9763     return C;
9764   return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9765                                C->getLParenLoc(), C->getEndLoc());
9766 }
9767 
9768 template <typename Derived>
9769 OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9770   if (!getDerived().AlwaysRebuild())
9771     return C;
9772   return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9773 }
9774 
9775 template <typename Derived>
9776 OMPClause *
9777 TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9778   ExprResult T = getDerived().TransformExpr(C->getFactor());
9779   if (T.isInvalid())
9780     return nullptr;
9781   Expr *Factor = T.get();
9782   bool Changed = Factor != C->getFactor();
9783 
9784   if (!Changed && !getDerived().AlwaysRebuild())
9785     return C;
9786   return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9787                                  C->getEndLoc());
9788 }
9789 
9790 template <typename Derived>
9791 OMPClause *
9792 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9793   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9794   if (E.isInvalid())
9795     return nullptr;
9796   return getDerived().RebuildOMPCollapseClause(
9797       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9798 }
9799 
9800 template <typename Derived>
9801 OMPClause *
9802 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9803   return getDerived().RebuildOMPDefaultClause(
9804       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9805       C->getLParenLoc(), C->getEndLoc());
9806 }
9807 
9808 template <typename Derived>
9809 OMPClause *
9810 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9811   return getDerived().RebuildOMPProcBindClause(
9812       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9813       C->getLParenLoc(), C->getEndLoc());
9814 }
9815 
9816 template <typename Derived>
9817 OMPClause *
9818 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9819   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9820   if (E.isInvalid())
9821     return nullptr;
9822   return getDerived().RebuildOMPScheduleClause(
9823       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9824       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9825       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9826       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9827 }
9828 
9829 template <typename Derived>
9830 OMPClause *
9831 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9832   ExprResult E;
9833   if (auto *Num = C->getNumForLoops()) {
9834     E = getDerived().TransformExpr(Num);
9835     if (E.isInvalid())
9836       return nullptr;
9837   }
9838   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9839                                               C->getLParenLoc(), E.get());
9840 }
9841 
9842 template <typename Derived>
9843 OMPClause *
9844 TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9845   ExprResult E;
9846   if (Expr *Evt = C->getEventHandler()) {
9847     E = getDerived().TransformExpr(Evt);
9848     if (E.isInvalid())
9849       return nullptr;
9850   }
9851   return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9852                                              C->getLParenLoc(), C->getEndLoc());
9853 }
9854 
9855 template <typename Derived>
9856 OMPClause *
9857 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9858   // No need to rebuild this clause, no template-dependent parameters.
9859   return C;
9860 }
9861 
9862 template <typename Derived>
9863 OMPClause *
9864 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9865   // No need to rebuild this clause, no template-dependent parameters.
9866   return C;
9867 }
9868 
9869 template <typename Derived>
9870 OMPClause *
9871 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9872   // No need to rebuild this clause, no template-dependent parameters.
9873   return C;
9874 }
9875 
9876 template <typename Derived>
9877 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9878   // No need to rebuild this clause, no template-dependent parameters.
9879   return C;
9880 }
9881 
9882 template <typename Derived>
9883 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9884   // No need to rebuild this clause, no template-dependent parameters.
9885   return C;
9886 }
9887 
9888 template <typename Derived>
9889 OMPClause *
9890 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9891   // No need to rebuild this clause, no template-dependent parameters.
9892   return C;
9893 }
9894 
9895 template <typename Derived>
9896 OMPClause *
9897 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9898   // No need to rebuild this clause, no template-dependent parameters.
9899   return C;
9900 }
9901 
9902 template <typename Derived>
9903 OMPClause *
9904 TreeTransform<Derived>::TransformOMPCompareClause(OMPCompareClause *C) {
9905   // No need to rebuild this clause, no template-dependent parameters.
9906   return C;
9907 }
9908 
9909 template <typename Derived>
9910 OMPClause *TreeTransform<Derived>::TransformOMPFailClause(OMPFailClause *C) {
9911   // No need to rebuild this clause, no template-dependent parameters.
9912   return C;
9913 }
9914 
9915 template <typename Derived>
9916 OMPClause *
9917 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9918   // No need to rebuild this clause, no template-dependent parameters.
9919   return C;
9920 }
9921 
9922 template <typename Derived>
9923 OMPClause *
9924 TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9925   // No need to rebuild this clause, no template-dependent parameters.
9926   return C;
9927 }
9928 
9929 template <typename Derived>
9930 OMPClause *
9931 TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9932   // No need to rebuild this clause, no template-dependent parameters.
9933   return C;
9934 }
9935 
9936 template <typename Derived>
9937 OMPClause *
9938 TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9939   // No need to rebuild this clause, no template-dependent parameters.
9940   return C;
9941 }
9942 
9943 template <typename Derived>
9944 OMPClause *
9945 TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9946   // No need to rebuild this clause, no template-dependent parameters.
9947   return C;
9948 }
9949 
9950 template <typename Derived>
9951 OMPClause *
9952 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9953   // No need to rebuild this clause, no template-dependent parameters.
9954   return C;
9955 }
9956 
9957 template <typename Derived>
9958 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9959   // No need to rebuild this clause, no template-dependent parameters.
9960   return C;
9961 }
9962 
9963 template <typename Derived>
9964 OMPClause *
9965 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9966   // No need to rebuild this clause, no template-dependent parameters.
9967   return C;
9968 }
9969 
9970 template <typename Derived>
9971 OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9972   ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9973   if (IVR.isInvalid())
9974     return nullptr;
9975 
9976   OMPInteropInfo InteropInfo(C->getIsTarget(), C->getIsTargetSync());
9977   InteropInfo.PreferTypes.reserve(C->varlist_size() - 1);
9978   for (Expr *E : llvm::drop_begin(C->varlists())) {
9979     ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9980     if (ER.isInvalid())
9981       return nullptr;
9982     InteropInfo.PreferTypes.push_back(ER.get());
9983   }
9984   return getDerived().RebuildOMPInitClause(IVR.get(), InteropInfo,
9985                                            C->getBeginLoc(), C->getLParenLoc(),
9986                                            C->getVarLoc(), C->getEndLoc());
9987 }
9988 
9989 template <typename Derived>
9990 OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9991   ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9992   if (ER.isInvalid())
9993     return nullptr;
9994   return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9995                                           C->getLParenLoc(), C->getVarLoc(),
9996                                           C->getEndLoc());
9997 }
9998 
9999 template <typename Derived>
10000 OMPClause *
10001 TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
10002   ExprResult ER;
10003   if (Expr *IV = C->getInteropVar()) {
10004     ER = getDerived().TransformExpr(IV);
10005     if (ER.isInvalid())
10006       return nullptr;
10007   }
10008   return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
10009                                               C->getLParenLoc(), C->getVarLoc(),
10010                                               C->getEndLoc());
10011 }
10012 
10013 template <typename Derived>
10014 OMPClause *
10015 TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
10016   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
10017   if (Cond.isInvalid())
10018     return nullptr;
10019   return getDerived().RebuildOMPNovariantsClause(
10020       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10021 }
10022 
10023 template <typename Derived>
10024 OMPClause *
10025 TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
10026   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
10027   if (Cond.isInvalid())
10028     return nullptr;
10029   return getDerived().RebuildOMPNocontextClause(
10030       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10031 }
10032 
10033 template <typename Derived>
10034 OMPClause *
10035 TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
10036   ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
10037   if (ThreadID.isInvalid())
10038     return nullptr;
10039   return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
10040                                              C->getLParenLoc(), C->getEndLoc());
10041 }
10042 
10043 template <typename Derived>
10044 OMPClause *TreeTransform<Derived>::TransformOMPAlignClause(OMPAlignClause *C) {
10045   ExprResult E = getDerived().TransformExpr(C->getAlignment());
10046   if (E.isInvalid())
10047     return nullptr;
10048   return getDerived().RebuildOMPAlignClause(E.get(), C->getBeginLoc(),
10049                                             C->getLParenLoc(), C->getEndLoc());
10050 }
10051 
10052 template <typename Derived>
10053 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
10054     OMPUnifiedAddressClause *C) {
10055   llvm_unreachable("unified_address clause cannot appear in dependent context");
10056 }
10057 
10058 template <typename Derived>
10059 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
10060     OMPUnifiedSharedMemoryClause *C) {
10061   llvm_unreachable(
10062       "unified_shared_memory clause cannot appear in dependent context");
10063 }
10064 
10065 template <typename Derived>
10066 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
10067     OMPReverseOffloadClause *C) {
10068   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
10069 }
10070 
10071 template <typename Derived>
10072 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
10073     OMPDynamicAllocatorsClause *C) {
10074   llvm_unreachable(
10075       "dynamic_allocators clause cannot appear in dependent context");
10076 }
10077 
10078 template <typename Derived>
10079 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
10080     OMPAtomicDefaultMemOrderClause *C) {
10081   llvm_unreachable(
10082       "atomic_default_mem_order clause cannot appear in dependent context");
10083 }
10084 
10085 template <typename Derived>
10086 OMPClause *TreeTransform<Derived>::TransformOMPAtClause(OMPAtClause *C) {
10087   return getDerived().RebuildOMPAtClause(C->getAtKind(), C->getAtKindKwLoc(),
10088                                          C->getBeginLoc(), C->getLParenLoc(),
10089                                          C->getEndLoc());
10090 }
10091 
10092 template <typename Derived>
10093 OMPClause *
10094 TreeTransform<Derived>::TransformOMPSeverityClause(OMPSeverityClause *C) {
10095   return getDerived().RebuildOMPSeverityClause(
10096       C->getSeverityKind(), C->getSeverityKindKwLoc(), C->getBeginLoc(),
10097       C->getLParenLoc(), C->getEndLoc());
10098 }
10099 
10100 template <typename Derived>
10101 OMPClause *
10102 TreeTransform<Derived>::TransformOMPMessageClause(OMPMessageClause *C) {
10103   ExprResult E = getDerived().TransformExpr(C->getMessageString());
10104   if (E.isInvalid())
10105     return nullptr;
10106   return getDerived().RebuildOMPMessageClause(
10107       C->getMessageString(), C->getBeginLoc(), C->getLParenLoc(),
10108       C->getEndLoc());
10109 }
10110 
10111 template <typename Derived>
10112 OMPClause *
10113 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
10114   llvm::SmallVector<Expr *, 16> Vars;
10115   Vars.reserve(C->varlist_size());
10116   for (auto *VE : C->varlists()) {
10117     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10118     if (EVar.isInvalid())
10119       return nullptr;
10120     Vars.push_back(EVar.get());
10121   }
10122   return getDerived().RebuildOMPPrivateClause(
10123       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10124 }
10125 
10126 template <typename Derived>
10127 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
10128     OMPFirstprivateClause *C) {
10129   llvm::SmallVector<Expr *, 16> Vars;
10130   Vars.reserve(C->varlist_size());
10131   for (auto *VE : C->varlists()) {
10132     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10133     if (EVar.isInvalid())
10134       return nullptr;
10135     Vars.push_back(EVar.get());
10136   }
10137   return getDerived().RebuildOMPFirstprivateClause(
10138       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10139 }
10140 
10141 template <typename Derived>
10142 OMPClause *
10143 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
10144   llvm::SmallVector<Expr *, 16> Vars;
10145   Vars.reserve(C->varlist_size());
10146   for (auto *VE : C->varlists()) {
10147     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10148     if (EVar.isInvalid())
10149       return nullptr;
10150     Vars.push_back(EVar.get());
10151   }
10152   return getDerived().RebuildOMPLastprivateClause(
10153       Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
10154       C->getLParenLoc(), C->getEndLoc());
10155 }
10156 
10157 template <typename Derived>
10158 OMPClause *
10159 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
10160   llvm::SmallVector<Expr *, 16> Vars;
10161   Vars.reserve(C->varlist_size());
10162   for (auto *VE : C->varlists()) {
10163     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10164     if (EVar.isInvalid())
10165       return nullptr;
10166     Vars.push_back(EVar.get());
10167   }
10168   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
10169                                              C->getLParenLoc(), C->getEndLoc());
10170 }
10171 
10172 template <typename Derived>
10173 OMPClause *
10174 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
10175   llvm::SmallVector<Expr *, 16> Vars;
10176   Vars.reserve(C->varlist_size());
10177   for (auto *VE : C->varlists()) {
10178     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10179     if (EVar.isInvalid())
10180       return nullptr;
10181     Vars.push_back(EVar.get());
10182   }
10183   CXXScopeSpec ReductionIdScopeSpec;
10184   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10185 
10186   DeclarationNameInfo NameInfo = C->getNameInfo();
10187   if (NameInfo.getName()) {
10188     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10189     if (!NameInfo.getName())
10190       return nullptr;
10191   }
10192   // Build a list of all UDR decls with the same names ranged by the Scopes.
10193   // The Scope boundary is a duplication of the previous decl.
10194   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10195   for (auto *E : C->reduction_ops()) {
10196     // Transform all the decls.
10197     if (E) {
10198       auto *ULE = cast<UnresolvedLookupExpr>(E);
10199       UnresolvedSet<8> Decls;
10200       for (auto *D : ULE->decls()) {
10201         NamedDecl *InstD =
10202             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10203         Decls.addDecl(InstD, InstD->getAccess());
10204       }
10205       UnresolvedReductions.push_back(
10206        UnresolvedLookupExpr::Create(
10207           SemaRef.Context, /*NamingClass=*/nullptr,
10208           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
10209           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
10210           Decls.begin(), Decls.end()));
10211     } else
10212       UnresolvedReductions.push_back(nullptr);
10213   }
10214   return getDerived().RebuildOMPReductionClause(
10215       Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
10216       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
10217       ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10218 }
10219 
10220 template <typename Derived>
10221 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
10222     OMPTaskReductionClause *C) {
10223   llvm::SmallVector<Expr *, 16> Vars;
10224   Vars.reserve(C->varlist_size());
10225   for (auto *VE : C->varlists()) {
10226     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10227     if (EVar.isInvalid())
10228       return nullptr;
10229     Vars.push_back(EVar.get());
10230   }
10231   CXXScopeSpec ReductionIdScopeSpec;
10232   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10233 
10234   DeclarationNameInfo NameInfo = C->getNameInfo();
10235   if (NameInfo.getName()) {
10236     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10237     if (!NameInfo.getName())
10238       return nullptr;
10239   }
10240   // Build a list of all UDR decls with the same names ranged by the Scopes.
10241   // The Scope boundary is a duplication of the previous decl.
10242   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10243   for (auto *E : C->reduction_ops()) {
10244     // Transform all the decls.
10245     if (E) {
10246       auto *ULE = cast<UnresolvedLookupExpr>(E);
10247       UnresolvedSet<8> Decls;
10248       for (auto *D : ULE->decls()) {
10249         NamedDecl *InstD =
10250             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10251         Decls.addDecl(InstD, InstD->getAccess());
10252       }
10253       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10254           SemaRef.Context, /*NamingClass=*/nullptr,
10255           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10256           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10257     } else
10258       UnresolvedReductions.push_back(nullptr);
10259   }
10260   return getDerived().RebuildOMPTaskReductionClause(
10261       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10262       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10263 }
10264 
10265 template <typename Derived>
10266 OMPClause *
10267 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
10268   llvm::SmallVector<Expr *, 16> Vars;
10269   Vars.reserve(C->varlist_size());
10270   for (auto *VE : C->varlists()) {
10271     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10272     if (EVar.isInvalid())
10273       return nullptr;
10274     Vars.push_back(EVar.get());
10275   }
10276   CXXScopeSpec ReductionIdScopeSpec;
10277   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10278 
10279   DeclarationNameInfo NameInfo = C->getNameInfo();
10280   if (NameInfo.getName()) {
10281     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10282     if (!NameInfo.getName())
10283       return nullptr;
10284   }
10285   // Build a list of all UDR decls with the same names ranged by the Scopes.
10286   // The Scope boundary is a duplication of the previous decl.
10287   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10288   for (auto *E : C->reduction_ops()) {
10289     // Transform all the decls.
10290     if (E) {
10291       auto *ULE = cast<UnresolvedLookupExpr>(E);
10292       UnresolvedSet<8> Decls;
10293       for (auto *D : ULE->decls()) {
10294         NamedDecl *InstD =
10295             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10296         Decls.addDecl(InstD, InstD->getAccess());
10297       }
10298       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10299           SemaRef.Context, /*NamingClass=*/nullptr,
10300           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10301           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10302     } else
10303       UnresolvedReductions.push_back(nullptr);
10304   }
10305   return getDerived().RebuildOMPInReductionClause(
10306       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10307       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10308 }
10309 
10310 template <typename Derived>
10311 OMPClause *
10312 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
10313   llvm::SmallVector<Expr *, 16> Vars;
10314   Vars.reserve(C->varlist_size());
10315   for (auto *VE : C->varlists()) {
10316     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10317     if (EVar.isInvalid())
10318       return nullptr;
10319     Vars.push_back(EVar.get());
10320   }
10321   ExprResult Step = getDerived().TransformExpr(C->getStep());
10322   if (Step.isInvalid())
10323     return nullptr;
10324   return getDerived().RebuildOMPLinearClause(
10325       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
10326       C->getModifierLoc(), C->getColonLoc(), C->getStepModifierLoc(),
10327       C->getEndLoc());
10328 }
10329 
10330 template <typename Derived>
10331 OMPClause *
10332 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
10333   llvm::SmallVector<Expr *, 16> Vars;
10334   Vars.reserve(C->varlist_size());
10335   for (auto *VE : C->varlists()) {
10336     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10337     if (EVar.isInvalid())
10338       return nullptr;
10339     Vars.push_back(EVar.get());
10340   }
10341   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
10342   if (Alignment.isInvalid())
10343     return nullptr;
10344   return getDerived().RebuildOMPAlignedClause(
10345       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
10346       C->getColonLoc(), C->getEndLoc());
10347 }
10348 
10349 template <typename Derived>
10350 OMPClause *
10351 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
10352   llvm::SmallVector<Expr *, 16> Vars;
10353   Vars.reserve(C->varlist_size());
10354   for (auto *VE : C->varlists()) {
10355     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10356     if (EVar.isInvalid())
10357       return nullptr;
10358     Vars.push_back(EVar.get());
10359   }
10360   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
10361                                              C->getLParenLoc(), C->getEndLoc());
10362 }
10363 
10364 template <typename Derived>
10365 OMPClause *
10366 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
10367   llvm::SmallVector<Expr *, 16> Vars;
10368   Vars.reserve(C->varlist_size());
10369   for (auto *VE : C->varlists()) {
10370     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10371     if (EVar.isInvalid())
10372       return nullptr;
10373     Vars.push_back(EVar.get());
10374   }
10375   return getDerived().RebuildOMPCopyprivateClause(
10376       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10377 }
10378 
10379 template <typename Derived>
10380 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
10381   llvm::SmallVector<Expr *, 16> Vars;
10382   Vars.reserve(C->varlist_size());
10383   for (auto *VE : C->varlists()) {
10384     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10385     if (EVar.isInvalid())
10386       return nullptr;
10387     Vars.push_back(EVar.get());
10388   }
10389   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
10390                                             C->getLParenLoc(), C->getEndLoc());
10391 }
10392 
10393 template <typename Derived>
10394 OMPClause *
10395 TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
10396   ExprResult E = getDerived().TransformExpr(C->getDepobj());
10397   if (E.isInvalid())
10398     return nullptr;
10399   return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
10400                                              C->getLParenLoc(), C->getEndLoc());
10401 }
10402 
10403 template <typename Derived>
10404 OMPClause *
10405 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
10406   llvm::SmallVector<Expr *, 16> Vars;
10407   Expr *DepModifier = C->getModifier();
10408   if (DepModifier) {
10409     ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
10410     if (DepModRes.isInvalid())
10411       return nullptr;
10412     DepModifier = DepModRes.get();
10413   }
10414   Vars.reserve(C->varlist_size());
10415   for (auto *VE : C->varlists()) {
10416     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10417     if (EVar.isInvalid())
10418       return nullptr;
10419     Vars.push_back(EVar.get());
10420   }
10421   return getDerived().RebuildOMPDependClause(
10422       {C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(),
10423        C->getOmpAllMemoryLoc()},
10424       DepModifier, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10425 }
10426 
10427 template <typename Derived>
10428 OMPClause *
10429 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
10430   ExprResult E = getDerived().TransformExpr(C->getDevice());
10431   if (E.isInvalid())
10432     return nullptr;
10433   return getDerived().RebuildOMPDeviceClause(
10434       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10435       C->getModifierLoc(), C->getEndLoc());
10436 }
10437 
10438 template <typename Derived, class T>
10439 bool transformOMPMappableExprListClause(
10440     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
10441     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
10442     DeclarationNameInfo &MapperIdInfo,
10443     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
10444   // Transform expressions in the list.
10445   Vars.reserve(C->varlist_size());
10446   for (auto *VE : C->varlists()) {
10447     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
10448     if (EVar.isInvalid())
10449       return true;
10450     Vars.push_back(EVar.get());
10451   }
10452   // Transform mapper scope specifier and identifier.
10453   NestedNameSpecifierLoc QualifierLoc;
10454   if (C->getMapperQualifierLoc()) {
10455     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
10456         C->getMapperQualifierLoc());
10457     if (!QualifierLoc)
10458       return true;
10459   }
10460   MapperIdScopeSpec.Adopt(QualifierLoc);
10461   MapperIdInfo = C->getMapperIdInfo();
10462   if (MapperIdInfo.getName()) {
10463     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
10464     if (!MapperIdInfo.getName())
10465       return true;
10466   }
10467   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
10468   // the previous user-defined mapper lookup in dependent environment.
10469   for (auto *E : C->mapperlists()) {
10470     // Transform all the decls.
10471     if (E) {
10472       auto *ULE = cast<UnresolvedLookupExpr>(E);
10473       UnresolvedSet<8> Decls;
10474       for (auto *D : ULE->decls()) {
10475         NamedDecl *InstD =
10476             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
10477         Decls.addDecl(InstD, InstD->getAccess());
10478       }
10479       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
10480           TT.getSema().Context, /*NamingClass=*/nullptr,
10481           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
10482           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
10483           Decls.end()));
10484     } else {
10485       UnresolvedMappers.push_back(nullptr);
10486     }
10487   }
10488   return false;
10489 }
10490 
10491 template <typename Derived>
10492 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
10493   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10494   llvm::SmallVector<Expr *, 16> Vars;
10495   Expr *IteratorModifier = C->getIteratorModifier();
10496   if (IteratorModifier) {
10497     ExprResult MapModRes = getDerived().TransformExpr(IteratorModifier);
10498     if (MapModRes.isInvalid())
10499       return nullptr;
10500     IteratorModifier = MapModRes.get();
10501   }
10502   CXXScopeSpec MapperIdScopeSpec;
10503   DeclarationNameInfo MapperIdInfo;
10504   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10505   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
10506           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10507     return nullptr;
10508   return getDerived().RebuildOMPMapClause(
10509       IteratorModifier, C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
10510       MapperIdScopeSpec, MapperIdInfo, C->getMapType(), C->isImplicitMapType(),
10511       C->getMapLoc(), C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10512 }
10513 
10514 template <typename Derived>
10515 OMPClause *
10516 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
10517   Expr *Allocator = C->getAllocator();
10518   if (Allocator) {
10519     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
10520     if (AllocatorRes.isInvalid())
10521       return nullptr;
10522     Allocator = AllocatorRes.get();
10523   }
10524   llvm::SmallVector<Expr *, 16> Vars;
10525   Vars.reserve(C->varlist_size());
10526   for (auto *VE : C->varlists()) {
10527     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10528     if (EVar.isInvalid())
10529       return nullptr;
10530     Vars.push_back(EVar.get());
10531   }
10532   return getDerived().RebuildOMPAllocateClause(
10533       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10534       C->getEndLoc());
10535 }
10536 
10537 template <typename Derived>
10538 OMPClause *
10539 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
10540   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
10541   if (E.isInvalid())
10542     return nullptr;
10543   return getDerived().RebuildOMPNumTeamsClause(
10544       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10545 }
10546 
10547 template <typename Derived>
10548 OMPClause *
10549 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
10550   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
10551   if (E.isInvalid())
10552     return nullptr;
10553   return getDerived().RebuildOMPThreadLimitClause(
10554       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10555 }
10556 
10557 template <typename Derived>
10558 OMPClause *
10559 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
10560   ExprResult E = getDerived().TransformExpr(C->getPriority());
10561   if (E.isInvalid())
10562     return nullptr;
10563   return getDerived().RebuildOMPPriorityClause(
10564       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10565 }
10566 
10567 template <typename Derived>
10568 OMPClause *
10569 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
10570   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
10571   if (E.isInvalid())
10572     return nullptr;
10573   return getDerived().RebuildOMPGrainsizeClause(
10574       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10575       C->getModifierLoc(), C->getEndLoc());
10576 }
10577 
10578 template <typename Derived>
10579 OMPClause *
10580 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10581   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10582   if (E.isInvalid())
10583     return nullptr;
10584   return getDerived().RebuildOMPNumTasksClause(
10585       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10586       C->getModifierLoc(), C->getEndLoc());
10587 }
10588 
10589 template <typename Derived>
10590 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10591   ExprResult E = getDerived().TransformExpr(C->getHint());
10592   if (E.isInvalid())
10593     return nullptr;
10594   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10595                                            C->getLParenLoc(), C->getEndLoc());
10596 }
10597 
10598 template <typename Derived>
10599 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10600     OMPDistScheduleClause *C) {
10601   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10602   if (E.isInvalid())
10603     return nullptr;
10604   return getDerived().RebuildOMPDistScheduleClause(
10605       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10606       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10607 }
10608 
10609 template <typename Derived>
10610 OMPClause *
10611 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10612   // Rebuild Defaultmap Clause since we need to invoke the checking of
10613   // defaultmap(none:variable-category) after template initialization.
10614   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10615                                                  C->getDefaultmapKind(),
10616                                                  C->getBeginLoc(),
10617                                                  C->getLParenLoc(),
10618                                                  C->getDefaultmapModifierLoc(),
10619                                                  C->getDefaultmapKindLoc(),
10620                                                  C->getEndLoc());
10621 }
10622 
10623 template <typename Derived>
10624 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10625   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10626   llvm::SmallVector<Expr *, 16> Vars;
10627   CXXScopeSpec MapperIdScopeSpec;
10628   DeclarationNameInfo MapperIdInfo;
10629   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10630   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10631           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10632     return nullptr;
10633   return getDerived().RebuildOMPToClause(
10634       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10635       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10636 }
10637 
10638 template <typename Derived>
10639 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10640   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10641   llvm::SmallVector<Expr *, 16> Vars;
10642   CXXScopeSpec MapperIdScopeSpec;
10643   DeclarationNameInfo MapperIdInfo;
10644   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10645   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10646           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10647     return nullptr;
10648   return getDerived().RebuildOMPFromClause(
10649       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10650       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10651 }
10652 
10653 template <typename Derived>
10654 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10655     OMPUseDevicePtrClause *C) {
10656   llvm::SmallVector<Expr *, 16> Vars;
10657   Vars.reserve(C->varlist_size());
10658   for (auto *VE : C->varlists()) {
10659     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10660     if (EVar.isInvalid())
10661       return nullptr;
10662     Vars.push_back(EVar.get());
10663   }
10664   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10665   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10666 }
10667 
10668 template <typename Derived>
10669 OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10670     OMPUseDeviceAddrClause *C) {
10671   llvm::SmallVector<Expr *, 16> Vars;
10672   Vars.reserve(C->varlist_size());
10673   for (auto *VE : C->varlists()) {
10674     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10675     if (EVar.isInvalid())
10676       return nullptr;
10677     Vars.push_back(EVar.get());
10678   }
10679   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10680   return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10681 }
10682 
10683 template <typename Derived>
10684 OMPClause *
10685 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10686   llvm::SmallVector<Expr *, 16> Vars;
10687   Vars.reserve(C->varlist_size());
10688   for (auto *VE : C->varlists()) {
10689     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10690     if (EVar.isInvalid())
10691       return nullptr;
10692     Vars.push_back(EVar.get());
10693   }
10694   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10695   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10696 }
10697 
10698 template <typename Derived>
10699 OMPClause *TreeTransform<Derived>::TransformOMPHasDeviceAddrClause(
10700     OMPHasDeviceAddrClause *C) {
10701   llvm::SmallVector<Expr *, 16> Vars;
10702   Vars.reserve(C->varlist_size());
10703   for (auto *VE : C->varlists()) {
10704     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10705     if (EVar.isInvalid())
10706       return nullptr;
10707     Vars.push_back(EVar.get());
10708   }
10709   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10710   return getDerived().RebuildOMPHasDeviceAddrClause(Vars, Locs);
10711 }
10712 
10713 template <typename Derived>
10714 OMPClause *
10715 TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10716   llvm::SmallVector<Expr *, 16> Vars;
10717   Vars.reserve(C->varlist_size());
10718   for (auto *VE : C->varlists()) {
10719     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10720     if (EVar.isInvalid())
10721       return nullptr;
10722     Vars.push_back(EVar.get());
10723   }
10724   return getDerived().RebuildOMPNontemporalClause(
10725       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10726 }
10727 
10728 template <typename Derived>
10729 OMPClause *
10730 TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10731   llvm::SmallVector<Expr *, 16> Vars;
10732   Vars.reserve(C->varlist_size());
10733   for (auto *VE : C->varlists()) {
10734     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10735     if (EVar.isInvalid())
10736       return nullptr;
10737     Vars.push_back(EVar.get());
10738   }
10739   return getDerived().RebuildOMPInclusiveClause(
10740       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10741 }
10742 
10743 template <typename Derived>
10744 OMPClause *
10745 TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10746   llvm::SmallVector<Expr *, 16> Vars;
10747   Vars.reserve(C->varlist_size());
10748   for (auto *VE : C->varlists()) {
10749     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10750     if (EVar.isInvalid())
10751       return nullptr;
10752     Vars.push_back(EVar.get());
10753   }
10754   return getDerived().RebuildOMPExclusiveClause(
10755       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10756 }
10757 
10758 template <typename Derived>
10759 OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10760     OMPUsesAllocatorsClause *C) {
10761   SmallVector<Sema::UsesAllocatorsData, 16> Data;
10762   Data.reserve(C->getNumberOfAllocators());
10763   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10764     OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10765     ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10766     if (Allocator.isInvalid())
10767       continue;
10768     ExprResult AllocatorTraits;
10769     if (Expr *AT = D.AllocatorTraits) {
10770       AllocatorTraits = getDerived().TransformExpr(AT);
10771       if (AllocatorTraits.isInvalid())
10772         continue;
10773     }
10774     Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10775     NewD.Allocator = Allocator.get();
10776     NewD.AllocatorTraits = AllocatorTraits.get();
10777     NewD.LParenLoc = D.LParenLoc;
10778     NewD.RParenLoc = D.RParenLoc;
10779   }
10780   return getDerived().RebuildOMPUsesAllocatorsClause(
10781       Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10782 }
10783 
10784 template <typename Derived>
10785 OMPClause *
10786 TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10787   SmallVector<Expr *, 4> Locators;
10788   Locators.reserve(C->varlist_size());
10789   ExprResult ModifierRes;
10790   if (Expr *Modifier = C->getModifier()) {
10791     ModifierRes = getDerived().TransformExpr(Modifier);
10792     if (ModifierRes.isInvalid())
10793       return nullptr;
10794   }
10795   for (Expr *E : C->varlists()) {
10796     ExprResult Locator = getDerived().TransformExpr(E);
10797     if (Locator.isInvalid())
10798       continue;
10799     Locators.push_back(Locator.get());
10800   }
10801   return getDerived().RebuildOMPAffinityClause(
10802       C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10803       ModifierRes.get(), Locators);
10804 }
10805 
10806 template <typename Derived>
10807 OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10808   return getDerived().RebuildOMPOrderClause(
10809       C->getKind(), C->getKindKwLoc(), C->getBeginLoc(), C->getLParenLoc(),
10810       C->getEndLoc(), C->getModifier(), C->getModifierKwLoc());
10811 }
10812 
10813 template <typename Derived>
10814 OMPClause *TreeTransform<Derived>::TransformOMPBindClause(OMPBindClause *C) {
10815   return getDerived().RebuildOMPBindClause(
10816       C->getBindKind(), C->getBindKindLoc(), C->getBeginLoc(),
10817       C->getLParenLoc(), C->getEndLoc());
10818 }
10819 
10820 template <typename Derived>
10821 OMPClause *TreeTransform<Derived>::TransformOMPXDynCGroupMemClause(
10822     OMPXDynCGroupMemClause *C) {
10823   ExprResult Size = getDerived().TransformExpr(C->getSize());
10824   if (Size.isInvalid())
10825     return nullptr;
10826   return getDerived().RebuildOMPXDynCGroupMemClause(
10827       Size.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10828 }
10829 
10830 template <typename Derived>
10831 OMPClause *
10832 TreeTransform<Derived>::TransformOMPDoacrossClause(OMPDoacrossClause *C) {
10833   llvm::SmallVector<Expr *, 16> Vars;
10834   Vars.reserve(C->varlist_size());
10835   for (auto *VE : C->varlists()) {
10836     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10837     if (EVar.isInvalid())
10838       return nullptr;
10839     Vars.push_back(EVar.get());
10840   }
10841   return getDerived().RebuildOMPDoacrossClause(
10842       C->getDependenceType(), C->getDependenceLoc(), C->getColonLoc(), Vars,
10843       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10844 }
10845 
10846 template <typename Derived>
10847 OMPClause *
10848 TreeTransform<Derived>::TransformOMPXAttributeClause(OMPXAttributeClause *C) {
10849   SmallVector<const Attr *> NewAttrs;
10850   for (auto *A : C->getAttrs())
10851     NewAttrs.push_back(getDerived().TransformAttr(A));
10852   return getDerived().RebuildOMPXAttributeClause(
10853       NewAttrs, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10854 }
10855 
10856 template <typename Derived>
10857 OMPClause *TreeTransform<Derived>::TransformOMPXBareClause(OMPXBareClause *C) {
10858   return getDerived().RebuildOMPXBareClause(C->getBeginLoc(), C->getEndLoc());
10859 }
10860 
10861 //===----------------------------------------------------------------------===//
10862 // Expression transformation
10863 //===----------------------------------------------------------------------===//
10864 template<typename Derived>
10865 ExprResult
10866 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10867   return TransformExpr(E->getSubExpr());
10868 }
10869 
10870 template <typename Derived>
10871 ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10872     SYCLUniqueStableNameExpr *E) {
10873   if (!E->isTypeDependent())
10874     return E;
10875 
10876   TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10877 
10878   if (!NewT)
10879     return ExprError();
10880 
10881   if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10882     return E;
10883 
10884   return getDerived().RebuildSYCLUniqueStableNameExpr(
10885       E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10886 }
10887 
10888 template<typename Derived>
10889 ExprResult
10890 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10891   if (!E->isTypeDependent())
10892     return E;
10893 
10894   return getDerived().RebuildPredefinedExpr(E->getLocation(),
10895                                             E->getIdentKind());
10896 }
10897 
10898 template<typename Derived>
10899 ExprResult
10900 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10901   NestedNameSpecifierLoc QualifierLoc;
10902   if (E->getQualifierLoc()) {
10903     QualifierLoc
10904       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10905     if (!QualifierLoc)
10906       return ExprError();
10907   }
10908 
10909   ValueDecl *ND
10910     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10911                                                          E->getDecl()));
10912   if (!ND)
10913     return ExprError();
10914 
10915   NamedDecl *Found = ND;
10916   if (E->getFoundDecl() != E->getDecl()) {
10917     Found = cast_or_null<NamedDecl>(
10918         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10919     if (!Found)
10920       return ExprError();
10921   }
10922 
10923   DeclarationNameInfo NameInfo = E->getNameInfo();
10924   if (NameInfo.getName()) {
10925     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10926     if (!NameInfo.getName())
10927       return ExprError();
10928   }
10929 
10930   if (!getDerived().AlwaysRebuild() &&
10931       QualifierLoc == E->getQualifierLoc() &&
10932       ND == E->getDecl() &&
10933       Found == E->getFoundDecl() &&
10934       NameInfo.getName() == E->getDecl()->getDeclName() &&
10935       !E->hasExplicitTemplateArgs()) {
10936 
10937     // Mark it referenced in the new context regardless.
10938     // FIXME: this is a bit instantiation-specific.
10939     SemaRef.MarkDeclRefReferenced(E);
10940 
10941     return E;
10942   }
10943 
10944   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10945   if (E->hasExplicitTemplateArgs()) {
10946     TemplateArgs = &TransArgs;
10947     TransArgs.setLAngleLoc(E->getLAngleLoc());
10948     TransArgs.setRAngleLoc(E->getRAngleLoc());
10949     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10950                                                 E->getNumTemplateArgs(),
10951                                                 TransArgs))
10952       return ExprError();
10953   }
10954 
10955   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10956                                          Found, TemplateArgs);
10957 }
10958 
10959 template<typename Derived>
10960 ExprResult
10961 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10962   return E;
10963 }
10964 
10965 template <typename Derived>
10966 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10967     FixedPointLiteral *E) {
10968   return E;
10969 }
10970 
10971 template<typename Derived>
10972 ExprResult
10973 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10974   return E;
10975 }
10976 
10977 template<typename Derived>
10978 ExprResult
10979 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10980   return E;
10981 }
10982 
10983 template<typename Derived>
10984 ExprResult
10985 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10986   return E;
10987 }
10988 
10989 template<typename Derived>
10990 ExprResult
10991 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10992   return E;
10993 }
10994 
10995 template<typename Derived>
10996 ExprResult
10997 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10998   return getDerived().TransformCallExpr(E);
10999 }
11000 
11001 template<typename Derived>
11002 ExprResult
11003 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
11004   ExprResult ControllingExpr;
11005   TypeSourceInfo *ControllingType = nullptr;
11006   if (E->isExprPredicate())
11007     ControllingExpr = getDerived().TransformExpr(E->getControllingExpr());
11008   else
11009     ControllingType = getDerived().TransformType(E->getControllingType());
11010 
11011   if (ControllingExpr.isInvalid() && !ControllingType)
11012     return ExprError();
11013 
11014   SmallVector<Expr *, 4> AssocExprs;
11015   SmallVector<TypeSourceInfo *, 4> AssocTypes;
11016   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
11017     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
11018     if (TSI) {
11019       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
11020       if (!AssocType)
11021         return ExprError();
11022       AssocTypes.push_back(AssocType);
11023     } else {
11024       AssocTypes.push_back(nullptr);
11025     }
11026 
11027     ExprResult AssocExpr =
11028         getDerived().TransformExpr(Assoc.getAssociationExpr());
11029     if (AssocExpr.isInvalid())
11030       return ExprError();
11031     AssocExprs.push_back(AssocExpr.get());
11032   }
11033 
11034   if (!ControllingType)
11035   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
11036                                                   E->getDefaultLoc(),
11037                                                   E->getRParenLoc(),
11038                                                   ControllingExpr.get(),
11039                                                   AssocTypes,
11040                                                   AssocExprs);
11041   return getDerived().RebuildGenericSelectionExpr(
11042       E->getGenericLoc(), E->getDefaultLoc(), E->getRParenLoc(),
11043       ControllingType, AssocTypes, AssocExprs);
11044 }
11045 
11046 template<typename Derived>
11047 ExprResult
11048 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
11049   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11050   if (SubExpr.isInvalid())
11051     return ExprError();
11052 
11053   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
11054     return E;
11055 
11056   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
11057                                        E->getRParen());
11058 }
11059 
11060 /// The operand of a unary address-of operator has special rules: it's
11061 /// allowed to refer to a non-static member of a class even if there's no 'this'
11062 /// object available.
11063 template<typename Derived>
11064 ExprResult
11065 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
11066   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
11067     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
11068   else
11069     return getDerived().TransformExpr(E);
11070 }
11071 
11072 template<typename Derived>
11073 ExprResult
11074 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
11075   ExprResult SubExpr;
11076   if (E->getOpcode() == UO_AddrOf)
11077     SubExpr = TransformAddressOfOperand(E->getSubExpr());
11078   else
11079     SubExpr = TransformExpr(E->getSubExpr());
11080   if (SubExpr.isInvalid())
11081     return ExprError();
11082 
11083   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
11084     return E;
11085 
11086   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
11087                                            E->getOpcode(),
11088                                            SubExpr.get());
11089 }
11090 
11091 template<typename Derived>
11092 ExprResult
11093 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
11094   // Transform the type.
11095   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
11096   if (!Type)
11097     return ExprError();
11098 
11099   // Transform all of the components into components similar to what the
11100   // parser uses.
11101   // FIXME: It would be slightly more efficient in the non-dependent case to
11102   // just map FieldDecls, rather than requiring the rebuilder to look for
11103   // the fields again. However, __builtin_offsetof is rare enough in
11104   // template code that we don't care.
11105   bool ExprChanged = false;
11106   typedef Sema::OffsetOfComponent Component;
11107   SmallVector<Component, 4> Components;
11108   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
11109     const OffsetOfNode &ON = E->getComponent(I);
11110     Component Comp;
11111     Comp.isBrackets = true;
11112     Comp.LocStart = ON.getSourceRange().getBegin();
11113     Comp.LocEnd = ON.getSourceRange().getEnd();
11114     switch (ON.getKind()) {
11115     case OffsetOfNode::Array: {
11116       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
11117       ExprResult Index = getDerived().TransformExpr(FromIndex);
11118       if (Index.isInvalid())
11119         return ExprError();
11120 
11121       ExprChanged = ExprChanged || Index.get() != FromIndex;
11122       Comp.isBrackets = true;
11123       Comp.U.E = Index.get();
11124       break;
11125     }
11126 
11127     case OffsetOfNode::Field:
11128     case OffsetOfNode::Identifier:
11129       Comp.isBrackets = false;
11130       Comp.U.IdentInfo = ON.getFieldName();
11131       if (!Comp.U.IdentInfo)
11132         continue;
11133 
11134       break;
11135 
11136     case OffsetOfNode::Base:
11137       // Will be recomputed during the rebuild.
11138       continue;
11139     }
11140 
11141     Components.push_back(Comp);
11142   }
11143 
11144   // If nothing changed, retain the existing expression.
11145   if (!getDerived().AlwaysRebuild() &&
11146       Type == E->getTypeSourceInfo() &&
11147       !ExprChanged)
11148     return E;
11149 
11150   // Build a new offsetof expression.
11151   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
11152                                           Components, E->getRParenLoc());
11153 }
11154 
11155 template<typename Derived>
11156 ExprResult
11157 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
11158   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
11159          "opaque value expression requires transformation");
11160   return E;
11161 }
11162 
11163 template<typename Derived>
11164 ExprResult
11165 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
11166   return E;
11167 }
11168 
11169 template <typename Derived>
11170 ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
11171   llvm::SmallVector<Expr *, 8> Children;
11172   bool Changed = false;
11173   for (Expr *C : E->subExpressions()) {
11174     ExprResult NewC = getDerived().TransformExpr(C);
11175     if (NewC.isInvalid())
11176       return ExprError();
11177     Children.push_back(NewC.get());
11178 
11179     Changed |= NewC.get() != C;
11180   }
11181   if (!getDerived().AlwaysRebuild() && !Changed)
11182     return E;
11183   return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
11184                                           Children, E->getType());
11185 }
11186 
11187 template<typename Derived>
11188 ExprResult
11189 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
11190   // Rebuild the syntactic form.  The original syntactic form has
11191   // opaque-value expressions in it, so strip those away and rebuild
11192   // the result.  This is a really awful way of doing this, but the
11193   // better solution (rebuilding the semantic expressions and
11194   // rebinding OVEs as necessary) doesn't work; we'd need
11195   // TreeTransform to not strip away implicit conversions.
11196   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
11197   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
11198   if (result.isInvalid()) return ExprError();
11199 
11200   // If that gives us a pseudo-object result back, the pseudo-object
11201   // expression must have been an lvalue-to-rvalue conversion which we
11202   // should reapply.
11203   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
11204     result = SemaRef.checkPseudoObjectRValue(result.get());
11205 
11206   return result;
11207 }
11208 
11209 template<typename Derived>
11210 ExprResult
11211 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
11212                                                 UnaryExprOrTypeTraitExpr *E) {
11213   if (E->isArgumentType()) {
11214     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
11215 
11216     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11217     if (!NewT)
11218       return ExprError();
11219 
11220     if (!getDerived().AlwaysRebuild() && OldT == NewT)
11221       return E;
11222 
11223     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
11224                                                     E->getKind(),
11225                                                     E->getSourceRange());
11226   }
11227 
11228   // C++0x [expr.sizeof]p1:
11229   //   The operand is either an expression, which is an unevaluated operand
11230   //   [...]
11231   EnterExpressionEvaluationContext Unevaluated(
11232       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
11233       Sema::ReuseLambdaContextDecl);
11234 
11235   // Try to recover if we have something like sizeof(T::X) where X is a type.
11236   // Notably, there must be *exactly* one set of parens if X is a type.
11237   TypeSourceInfo *RecoveryTSI = nullptr;
11238   ExprResult SubExpr;
11239   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
11240   if (auto *DRE =
11241           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
11242     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
11243         PE, DRE, false, &RecoveryTSI);
11244   else
11245     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
11246 
11247   if (RecoveryTSI) {
11248     return getDerived().RebuildUnaryExprOrTypeTrait(
11249         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
11250   } else if (SubExpr.isInvalid())
11251     return ExprError();
11252 
11253   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
11254     return E;
11255 
11256   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
11257                                                   E->getOperatorLoc(),
11258                                                   E->getKind(),
11259                                                   E->getSourceRange());
11260 }
11261 
11262 template<typename Derived>
11263 ExprResult
11264 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
11265   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11266   if (LHS.isInvalid())
11267     return ExprError();
11268 
11269   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11270   if (RHS.isInvalid())
11271     return ExprError();
11272 
11273 
11274   if (!getDerived().AlwaysRebuild() &&
11275       LHS.get() == E->getLHS() &&
11276       RHS.get() == E->getRHS())
11277     return E;
11278 
11279   return getDerived().RebuildArraySubscriptExpr(
11280       LHS.get(),
11281       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
11282 }
11283 
11284 template <typename Derived>
11285 ExprResult
11286 TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
11287   ExprResult Base = getDerived().TransformExpr(E->getBase());
11288   if (Base.isInvalid())
11289     return ExprError();
11290 
11291   ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
11292   if (RowIdx.isInvalid())
11293     return ExprError();
11294 
11295   ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
11296   if (ColumnIdx.isInvalid())
11297     return ExprError();
11298 
11299   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11300       RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
11301     return E;
11302 
11303   return getDerived().RebuildMatrixSubscriptExpr(
11304       Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
11305 }
11306 
11307 template <typename Derived>
11308 ExprResult
11309 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
11310   ExprResult Base = getDerived().TransformExpr(E->getBase());
11311   if (Base.isInvalid())
11312     return ExprError();
11313 
11314   ExprResult LowerBound;
11315   if (E->getLowerBound()) {
11316     LowerBound = getDerived().TransformExpr(E->getLowerBound());
11317     if (LowerBound.isInvalid())
11318       return ExprError();
11319   }
11320 
11321   ExprResult Length;
11322   if (E->getLength()) {
11323     Length = getDerived().TransformExpr(E->getLength());
11324     if (Length.isInvalid())
11325       return ExprError();
11326   }
11327 
11328   ExprResult Stride;
11329   if (Expr *Str = E->getStride()) {
11330     Stride = getDerived().TransformExpr(Str);
11331     if (Stride.isInvalid())
11332       return ExprError();
11333   }
11334 
11335   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11336       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
11337     return E;
11338 
11339   return getDerived().RebuildOMPArraySectionExpr(
11340       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
11341       E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
11342       E->getRBracketLoc());
11343 }
11344 
11345 template <typename Derived>
11346 ExprResult
11347 TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
11348   ExprResult Base = getDerived().TransformExpr(E->getBase());
11349   if (Base.isInvalid())
11350     return ExprError();
11351 
11352   SmallVector<Expr *, 4> Dims;
11353   bool ErrorFound = false;
11354   for (Expr *Dim : E->getDimensions()) {
11355     ExprResult DimRes = getDerived().TransformExpr(Dim);
11356     if (DimRes.isInvalid()) {
11357       ErrorFound = true;
11358       continue;
11359     }
11360     Dims.push_back(DimRes.get());
11361   }
11362 
11363   if (ErrorFound)
11364     return ExprError();
11365   return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
11366                                                  E->getRParenLoc(), Dims,
11367                                                  E->getBracketsRanges());
11368 }
11369 
11370 template <typename Derived>
11371 ExprResult
11372 TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
11373   unsigned NumIterators = E->numOfIterators();
11374   SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
11375 
11376   bool ErrorFound = false;
11377   bool NeedToRebuild = getDerived().AlwaysRebuild();
11378   for (unsigned I = 0; I < NumIterators; ++I) {
11379     auto *D = cast<VarDecl>(E->getIteratorDecl(I));
11380     Data[I].DeclIdent = D->getIdentifier();
11381     Data[I].DeclIdentLoc = D->getLocation();
11382     if (D->getLocation() == D->getBeginLoc()) {
11383       assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&
11384              "Implicit type must be int.");
11385     } else {
11386       TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
11387       QualType DeclTy = getDerived().TransformType(D->getType());
11388       Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
11389     }
11390     OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
11391     ExprResult Begin = getDerived().TransformExpr(Range.Begin);
11392     ExprResult End = getDerived().TransformExpr(Range.End);
11393     ExprResult Step = getDerived().TransformExpr(Range.Step);
11394     ErrorFound = ErrorFound ||
11395                  !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
11396                                                !Data[I].Type.get().isNull())) ||
11397                  Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
11398     if (ErrorFound)
11399       continue;
11400     Data[I].Range.Begin = Begin.get();
11401     Data[I].Range.End = End.get();
11402     Data[I].Range.Step = Step.get();
11403     Data[I].AssignLoc = E->getAssignLoc(I);
11404     Data[I].ColonLoc = E->getColonLoc(I);
11405     Data[I].SecColonLoc = E->getSecondColonLoc(I);
11406     NeedToRebuild =
11407         NeedToRebuild ||
11408         (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
11409                                        D->getType().getTypePtrOrNull()) ||
11410         Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
11411         Range.Step != Data[I].Range.Step;
11412   }
11413   if (ErrorFound)
11414     return ExprError();
11415   if (!NeedToRebuild)
11416     return E;
11417 
11418   ExprResult Res = getDerived().RebuildOMPIteratorExpr(
11419       E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
11420   if (!Res.isUsable())
11421     return Res;
11422   auto *IE = cast<OMPIteratorExpr>(Res.get());
11423   for (unsigned I = 0; I < NumIterators; ++I)
11424     getDerived().transformedLocalDecl(E->getIteratorDecl(I),
11425                                       IE->getIteratorDecl(I));
11426   return Res;
11427 }
11428 
11429 template<typename Derived>
11430 ExprResult
11431 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
11432   // Transform the callee.
11433   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11434   if (Callee.isInvalid())
11435     return ExprError();
11436 
11437   // Transform arguments.
11438   bool ArgChanged = false;
11439   SmallVector<Expr*, 8> Args;
11440   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11441                                   &ArgChanged))
11442     return ExprError();
11443 
11444   if (!getDerived().AlwaysRebuild() &&
11445       Callee.get() == E->getCallee() &&
11446       !ArgChanged)
11447     return SemaRef.MaybeBindToTemporary(E);
11448 
11449   // FIXME: Wrong source location information for the '('.
11450   SourceLocation FakeLParenLoc
11451     = ((Expr *)Callee.get())->getSourceRange().getBegin();
11452 
11453   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11454   if (E->hasStoredFPFeatures()) {
11455     FPOptionsOverride NewOverrides = E->getFPFeatures();
11456     getSema().CurFPFeatures =
11457         NewOverrides.applyOverrides(getSema().getLangOpts());
11458     getSema().FpPragmaStack.CurrentValue = NewOverrides;
11459   }
11460 
11461   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11462                                       Args,
11463                                       E->getRParenLoc());
11464 }
11465 
11466 template<typename Derived>
11467 ExprResult
11468 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
11469   ExprResult Base = getDerived().TransformExpr(E->getBase());
11470   if (Base.isInvalid())
11471     return ExprError();
11472 
11473   NestedNameSpecifierLoc QualifierLoc;
11474   if (E->hasQualifier()) {
11475     QualifierLoc
11476       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11477 
11478     if (!QualifierLoc)
11479       return ExprError();
11480   }
11481   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11482 
11483   ValueDecl *Member
11484     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
11485                                                          E->getMemberDecl()));
11486   if (!Member)
11487     return ExprError();
11488 
11489   NamedDecl *FoundDecl = E->getFoundDecl();
11490   if (FoundDecl == E->getMemberDecl()) {
11491     FoundDecl = Member;
11492   } else {
11493     FoundDecl = cast_or_null<NamedDecl>(
11494                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
11495     if (!FoundDecl)
11496       return ExprError();
11497   }
11498 
11499   if (!getDerived().AlwaysRebuild() &&
11500       Base.get() == E->getBase() &&
11501       QualifierLoc == E->getQualifierLoc() &&
11502       Member == E->getMemberDecl() &&
11503       FoundDecl == E->getFoundDecl() &&
11504       !E->hasExplicitTemplateArgs()) {
11505 
11506     // Skip for member expression of (this->f), rebuilt thisi->f is needed
11507     // for Openmp where the field need to be privatizized in the case.
11508     if (!(isa<CXXThisExpr>(E->getBase()) &&
11509           getSema().isOpenMPRebuildMemberExpr(cast<ValueDecl>(Member)))) {
11510       // Mark it referenced in the new context regardless.
11511       // FIXME: this is a bit instantiation-specific.
11512       SemaRef.MarkMemberReferenced(E);
11513       return E;
11514     }
11515   }
11516 
11517   TemplateArgumentListInfo TransArgs;
11518   if (E->hasExplicitTemplateArgs()) {
11519     TransArgs.setLAngleLoc(E->getLAngleLoc());
11520     TransArgs.setRAngleLoc(E->getRAngleLoc());
11521     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11522                                                 E->getNumTemplateArgs(),
11523                                                 TransArgs))
11524       return ExprError();
11525   }
11526 
11527   // FIXME: Bogus source location for the operator
11528   SourceLocation FakeOperatorLoc =
11529       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
11530 
11531   // FIXME: to do this check properly, we will need to preserve the
11532   // first-qualifier-in-scope here, just in case we had a dependent
11533   // base (and therefore couldn't do the check) and a
11534   // nested-name-qualifier (and therefore could do the lookup).
11535   NamedDecl *FirstQualifierInScope = nullptr;
11536   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
11537   if (MemberNameInfo.getName()) {
11538     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
11539     if (!MemberNameInfo.getName())
11540       return ExprError();
11541   }
11542 
11543   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
11544                                         E->isArrow(),
11545                                         QualifierLoc,
11546                                         TemplateKWLoc,
11547                                         MemberNameInfo,
11548                                         Member,
11549                                         FoundDecl,
11550                                         (E->hasExplicitTemplateArgs()
11551                                            ? &TransArgs : nullptr),
11552                                         FirstQualifierInScope);
11553 }
11554 
11555 template<typename Derived>
11556 ExprResult
11557 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
11558   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11559   if (LHS.isInvalid())
11560     return ExprError();
11561 
11562   ExprResult RHS =
11563       getDerived().TransformInitializer(E->getRHS(), /*NotCopyInit=*/false);
11564   if (RHS.isInvalid())
11565     return ExprError();
11566 
11567   if (!getDerived().AlwaysRebuild() &&
11568       LHS.get() == E->getLHS() &&
11569       RHS.get() == E->getRHS())
11570     return E;
11571 
11572   if (E->isCompoundAssignmentOp())
11573     // FPFeatures has already been established from trailing storage
11574     return getDerived().RebuildBinaryOperator(
11575         E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
11576   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11577   FPOptionsOverride NewOverrides(E->getFPFeatures());
11578   getSema().CurFPFeatures =
11579       NewOverrides.applyOverrides(getSema().getLangOpts());
11580   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11581   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
11582                                             LHS.get(), RHS.get());
11583 }
11584 
11585 template <typename Derived>
11586 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
11587     CXXRewrittenBinaryOperator *E) {
11588   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
11589 
11590   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
11591   if (LHS.isInvalid())
11592     return ExprError();
11593 
11594   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
11595   if (RHS.isInvalid())
11596     return ExprError();
11597 
11598   // Extract the already-resolved callee declarations so that we can restrict
11599   // ourselves to using them as the unqualified lookup results when rebuilding.
11600   UnresolvedSet<2> UnqualLookups;
11601   bool ChangedAnyLookups = false;
11602   Expr *PossibleBinOps[] = {E->getSemanticForm(),
11603                             const_cast<Expr *>(Decomp.InnerBinOp)};
11604   for (Expr *PossibleBinOp : PossibleBinOps) {
11605     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
11606     if (!Op)
11607       continue;
11608     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
11609     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
11610       continue;
11611 
11612     // Transform the callee in case we built a call to a local extern
11613     // declaration.
11614     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
11615         E->getOperatorLoc(), Callee->getFoundDecl()));
11616     if (!Found)
11617       return ExprError();
11618     if (Found != Callee->getFoundDecl())
11619       ChangedAnyLookups = true;
11620     UnqualLookups.addDecl(Found);
11621   }
11622 
11623   if (!getDerived().AlwaysRebuild() && !ChangedAnyLookups &&
11624       LHS.get() == Decomp.LHS && RHS.get() == Decomp.RHS) {
11625     // Mark all functions used in the rewrite as referenced. Note that when
11626     // a < b is rewritten to (a <=> b) < 0, both the <=> and the < might be
11627     // function calls, and/or there might be a user-defined conversion sequence
11628     // applied to the operands of the <.
11629     // FIXME: this is a bit instantiation-specific.
11630     const Expr *StopAt[] = {Decomp.LHS, Decomp.RHS};
11631     SemaRef.MarkDeclarationsReferencedInExpr(E, false, StopAt);
11632     return E;
11633   }
11634 
11635   return getDerived().RebuildCXXRewrittenBinaryOperator(
11636       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
11637 }
11638 
11639 template<typename Derived>
11640 ExprResult
11641 TreeTransform<Derived>::TransformCompoundAssignOperator(
11642                                                       CompoundAssignOperator *E) {
11643   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11644   FPOptionsOverride NewOverrides(E->getFPFeatures());
11645   getSema().CurFPFeatures =
11646       NewOverrides.applyOverrides(getSema().getLangOpts());
11647   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11648   return getDerived().TransformBinaryOperator(E);
11649 }
11650 
11651 template<typename Derived>
11652 ExprResult TreeTransform<Derived>::
11653 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
11654   // Just rebuild the common and RHS expressions and see whether we
11655   // get any changes.
11656 
11657   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
11658   if (commonExpr.isInvalid())
11659     return ExprError();
11660 
11661   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11662   if (rhs.isInvalid())
11663     return ExprError();
11664 
11665   if (!getDerived().AlwaysRebuild() &&
11666       commonExpr.get() == e->getCommon() &&
11667       rhs.get() == e->getFalseExpr())
11668     return e;
11669 
11670   return getDerived().RebuildConditionalOperator(commonExpr.get(),
11671                                                  e->getQuestionLoc(),
11672                                                  nullptr,
11673                                                  e->getColonLoc(),
11674                                                  rhs.get());
11675 }
11676 
11677 template<typename Derived>
11678 ExprResult
11679 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11680   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11681   if (Cond.isInvalid())
11682     return ExprError();
11683 
11684   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11685   if (LHS.isInvalid())
11686     return ExprError();
11687 
11688   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11689   if (RHS.isInvalid())
11690     return ExprError();
11691 
11692   if (!getDerived().AlwaysRebuild() &&
11693       Cond.get() == E->getCond() &&
11694       LHS.get() == E->getLHS() &&
11695       RHS.get() == E->getRHS())
11696     return E;
11697 
11698   return getDerived().RebuildConditionalOperator(Cond.get(),
11699                                                  E->getQuestionLoc(),
11700                                                  LHS.get(),
11701                                                  E->getColonLoc(),
11702                                                  RHS.get());
11703 }
11704 
11705 template<typename Derived>
11706 ExprResult
11707 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11708   // Implicit casts are eliminated during transformation, since they
11709   // will be recomputed by semantic analysis after transformation.
11710   return getDerived().TransformExpr(E->getSubExprAsWritten());
11711 }
11712 
11713 template<typename Derived>
11714 ExprResult
11715 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11716   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11717   if (!Type)
11718     return ExprError();
11719 
11720   ExprResult SubExpr
11721     = getDerived().TransformExpr(E->getSubExprAsWritten());
11722   if (SubExpr.isInvalid())
11723     return ExprError();
11724 
11725   if (!getDerived().AlwaysRebuild() &&
11726       Type == E->getTypeInfoAsWritten() &&
11727       SubExpr.get() == E->getSubExpr())
11728     return E;
11729 
11730   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11731                                             Type,
11732                                             E->getRParenLoc(),
11733                                             SubExpr.get());
11734 }
11735 
11736 template<typename Derived>
11737 ExprResult
11738 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11739   TypeSourceInfo *OldT = E->getTypeSourceInfo();
11740   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11741   if (!NewT)
11742     return ExprError();
11743 
11744   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11745   if (Init.isInvalid())
11746     return ExprError();
11747 
11748   if (!getDerived().AlwaysRebuild() &&
11749       OldT == NewT &&
11750       Init.get() == E->getInitializer())
11751     return SemaRef.MaybeBindToTemporary(E);
11752 
11753   // Note: the expression type doesn't necessarily match the
11754   // type-as-written, but that's okay, because it should always be
11755   // derivable from the initializer.
11756 
11757   return getDerived().RebuildCompoundLiteralExpr(
11758       E->getLParenLoc(), NewT,
11759       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11760 }
11761 
11762 template<typename Derived>
11763 ExprResult
11764 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11765   ExprResult Base = getDerived().TransformExpr(E->getBase());
11766   if (Base.isInvalid())
11767     return ExprError();
11768 
11769   if (!getDerived().AlwaysRebuild() &&
11770       Base.get() == E->getBase())
11771     return E;
11772 
11773   // FIXME: Bad source location
11774   SourceLocation FakeOperatorLoc =
11775       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11776   return getDerived().RebuildExtVectorElementExpr(
11777       Base.get(), FakeOperatorLoc, E->isArrow(), E->getAccessorLoc(),
11778       E->getAccessor());
11779 }
11780 
11781 template<typename Derived>
11782 ExprResult
11783 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11784   if (InitListExpr *Syntactic = E->getSyntacticForm())
11785     E = Syntactic;
11786 
11787   bool InitChanged = false;
11788 
11789   EnterExpressionEvaluationContext Context(
11790       getSema(), EnterExpressionEvaluationContext::InitList);
11791 
11792   SmallVector<Expr*, 4> Inits;
11793   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11794                                   Inits, &InitChanged))
11795     return ExprError();
11796 
11797   if (!getDerived().AlwaysRebuild() && !InitChanged) {
11798     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11799     // in some cases. We can't reuse it in general, because the syntactic and
11800     // semantic forms are linked, and we can't know that semantic form will
11801     // match even if the syntactic form does.
11802   }
11803 
11804   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11805                                       E->getRBraceLoc());
11806 }
11807 
11808 template<typename Derived>
11809 ExprResult
11810 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11811   Designation Desig;
11812 
11813   // transform the initializer value
11814   ExprResult Init = getDerived().TransformExpr(E->getInit());
11815   if (Init.isInvalid())
11816     return ExprError();
11817 
11818   // transform the designators.
11819   SmallVector<Expr*, 4> ArrayExprs;
11820   bool ExprChanged = false;
11821   for (const DesignatedInitExpr::Designator &D : E->designators()) {
11822     if (D.isFieldDesignator()) {
11823       if (D.getFieldDecl()) {
11824         FieldDecl *Field = cast_or_null<FieldDecl>(
11825             getDerived().TransformDecl(D.getFieldLoc(), D.getFieldDecl()));
11826         if (Field != D.getFieldDecl())
11827           // Rebuild the expression when the transformed FieldDecl is
11828           // different to the already assigned FieldDecl.
11829           ExprChanged = true;
11830         if (Field->isAnonymousStructOrUnion())
11831           continue;
11832       } else {
11833         // Ensure that the designator expression is rebuilt when there isn't
11834         // a resolved FieldDecl in the designator as we don't want to assign
11835         // a FieldDecl to a pattern designator that will be instantiated again.
11836         ExprChanged = true;
11837       }
11838       Desig.AddDesignator(Designator::CreateFieldDesignator(
11839           D.getFieldName(), D.getDotLoc(), D.getFieldLoc()));
11840       continue;
11841     }
11842 
11843     if (D.isArrayDesignator()) {
11844       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11845       if (Index.isInvalid())
11846         return ExprError();
11847 
11848       Desig.AddDesignator(
11849           Designator::CreateArrayDesignator(Index.get(), D.getLBracketLoc()));
11850 
11851       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11852       ArrayExprs.push_back(Index.get());
11853       continue;
11854     }
11855 
11856     assert(D.isArrayRangeDesignator() && "New kind of designator?");
11857     ExprResult Start
11858       = getDerived().TransformExpr(E->getArrayRangeStart(D));
11859     if (Start.isInvalid())
11860       return ExprError();
11861 
11862     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11863     if (End.isInvalid())
11864       return ExprError();
11865 
11866     Desig.AddDesignator(Designator::CreateArrayRangeDesignator(
11867         Start.get(), End.get(), D.getLBracketLoc(), D.getEllipsisLoc()));
11868 
11869     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11870                   End.get() != E->getArrayRangeEnd(D);
11871 
11872     ArrayExprs.push_back(Start.get());
11873     ArrayExprs.push_back(End.get());
11874   }
11875 
11876   if (!getDerived().AlwaysRebuild() &&
11877       Init.get() == E->getInit() &&
11878       !ExprChanged)
11879     return E;
11880 
11881   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11882                                                 E->getEqualOrColonLoc(),
11883                                                 E->usesGNUSyntax(), Init.get());
11884 }
11885 
11886 // Seems that if TransformInitListExpr() only works on the syntactic form of an
11887 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11888 template<typename Derived>
11889 ExprResult
11890 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11891     DesignatedInitUpdateExpr *E) {
11892   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
11893                    "initializer");
11894   return ExprError();
11895 }
11896 
11897 template<typename Derived>
11898 ExprResult
11899 TreeTransform<Derived>::TransformNoInitExpr(
11900     NoInitExpr *E) {
11901   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
11902   return ExprError();
11903 }
11904 
11905 template<typename Derived>
11906 ExprResult
11907 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11908   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
11909   return ExprError();
11910 }
11911 
11912 template<typename Derived>
11913 ExprResult
11914 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11915   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
11916   return ExprError();
11917 }
11918 
11919 template<typename Derived>
11920 ExprResult
11921 TreeTransform<Derived>::TransformImplicitValueInitExpr(
11922                                                      ImplicitValueInitExpr *E) {
11923   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11924 
11925   // FIXME: Will we ever have proper type location here? Will we actually
11926   // need to transform the type?
11927   QualType T = getDerived().TransformType(E->getType());
11928   if (T.isNull())
11929     return ExprError();
11930 
11931   if (!getDerived().AlwaysRebuild() &&
11932       T == E->getType())
11933     return E;
11934 
11935   return getDerived().RebuildImplicitValueInitExpr(T);
11936 }
11937 
11938 template<typename Derived>
11939 ExprResult
11940 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11941   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11942   if (!TInfo)
11943     return ExprError();
11944 
11945   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11946   if (SubExpr.isInvalid())
11947     return ExprError();
11948 
11949   if (!getDerived().AlwaysRebuild() &&
11950       TInfo == E->getWrittenTypeInfo() &&
11951       SubExpr.get() == E->getSubExpr())
11952     return E;
11953 
11954   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11955                                        TInfo, E->getRParenLoc());
11956 }
11957 
11958 template<typename Derived>
11959 ExprResult
11960 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11961   bool ArgumentChanged = false;
11962   SmallVector<Expr*, 4> Inits;
11963   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11964                      &ArgumentChanged))
11965     return ExprError();
11966 
11967   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11968                                            Inits,
11969                                            E->getRParenLoc());
11970 }
11971 
11972 /// Transform an address-of-label expression.
11973 ///
11974 /// By default, the transformation of an address-of-label expression always
11975 /// rebuilds the expression, so that the label identifier can be resolved to
11976 /// the corresponding label statement by semantic analysis.
11977 template<typename Derived>
11978 ExprResult
11979 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11980   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11981                                         E->getLabel());
11982   if (!LD)
11983     return ExprError();
11984 
11985   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11986                                            cast<LabelDecl>(LD));
11987 }
11988 
11989 template<typename Derived>
11990 ExprResult
11991 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11992   SemaRef.ActOnStartStmtExpr();
11993   StmtResult SubStmt
11994     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11995   if (SubStmt.isInvalid()) {
11996     SemaRef.ActOnStmtExprError();
11997     return ExprError();
11998   }
11999 
12000   unsigned OldDepth = E->getTemplateDepth();
12001   unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
12002 
12003   if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
12004       SubStmt.get() == E->getSubStmt()) {
12005     // Calling this an 'error' is unintuitive, but it does the right thing.
12006     SemaRef.ActOnStmtExprError();
12007     return SemaRef.MaybeBindToTemporary(E);
12008   }
12009 
12010   return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
12011                                       E->getRParenLoc(), NewDepth);
12012 }
12013 
12014 template<typename Derived>
12015 ExprResult
12016 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
12017   ExprResult Cond = getDerived().TransformExpr(E->getCond());
12018   if (Cond.isInvalid())
12019     return ExprError();
12020 
12021   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
12022   if (LHS.isInvalid())
12023     return ExprError();
12024 
12025   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
12026   if (RHS.isInvalid())
12027     return ExprError();
12028 
12029   if (!getDerived().AlwaysRebuild() &&
12030       Cond.get() == E->getCond() &&
12031       LHS.get() == E->getLHS() &&
12032       RHS.get() == E->getRHS())
12033     return E;
12034 
12035   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
12036                                         Cond.get(), LHS.get(), RHS.get(),
12037                                         E->getRParenLoc());
12038 }
12039 
12040 template<typename Derived>
12041 ExprResult
12042 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
12043   return E;
12044 }
12045 
12046 template<typename Derived>
12047 ExprResult
12048 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
12049   switch (E->getOperator()) {
12050   case OO_New:
12051   case OO_Delete:
12052   case OO_Array_New:
12053   case OO_Array_Delete:
12054     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
12055 
12056   case OO_Subscript:
12057   case OO_Call: {
12058     // This is a call to an object's operator().
12059     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
12060 
12061     // Transform the object itself.
12062     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
12063     if (Object.isInvalid())
12064       return ExprError();
12065 
12066     // FIXME: Poor location information
12067     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
12068         static_cast<Expr *>(Object.get())->getEndLoc());
12069 
12070     // Transform the call arguments.
12071     SmallVector<Expr*, 8> Args;
12072     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
12073                                     Args))
12074       return ExprError();
12075 
12076     if (E->getOperator() == OO_Subscript)
12077       return getDerived().RebuildCxxSubscriptExpr(Object.get(), FakeLParenLoc,
12078                                                   Args, E->getEndLoc());
12079 
12080     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
12081                                         E->getEndLoc());
12082   }
12083 
12084 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
12085   case OO_##Name:                                                              \
12086     break;
12087 
12088 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
12089 #include "clang/Basic/OperatorKinds.def"
12090 
12091   case OO_Conditional:
12092     llvm_unreachable("conditional operator is not actually overloadable");
12093 
12094   case OO_None:
12095   case NUM_OVERLOADED_OPERATORS:
12096     llvm_unreachable("not an overloaded operator?");
12097   }
12098 
12099   ExprResult First;
12100   if (E->getOperator() == OO_Amp)
12101     First = getDerived().TransformAddressOfOperand(E->getArg(0));
12102   else
12103     First = getDerived().TransformExpr(E->getArg(0));
12104   if (First.isInvalid())
12105     return ExprError();
12106 
12107   ExprResult Second;
12108   if (E->getNumArgs() == 2) {
12109     Second =
12110         getDerived().TransformInitializer(E->getArg(1), /*NotCopyInit=*/false);
12111     if (Second.isInvalid())
12112       return ExprError();
12113   }
12114 
12115   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
12116   FPOptionsOverride NewOverrides(E->getFPFeatures());
12117   getSema().CurFPFeatures =
12118       NewOverrides.applyOverrides(getSema().getLangOpts());
12119   getSema().FpPragmaStack.CurrentValue = NewOverrides;
12120 
12121   Expr *Callee = E->getCallee();
12122   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
12123     LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12124                    Sema::LookupOrdinaryName);
12125     if (getDerived().TransformOverloadExprDecls(ULE, ULE->requiresADL(), R))
12126       return ExprError();
12127 
12128     return getDerived().RebuildCXXOperatorCallExpr(
12129         E->getOperator(), E->getOperatorLoc(), Callee->getBeginLoc(),
12130         ULE->requiresADL(), R.asUnresolvedSet(), First.get(), Second.get());
12131   }
12132 
12133   UnresolvedSet<1> Functions;
12134   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
12135     Callee = ICE->getSubExprAsWritten();
12136   NamedDecl *DR = cast<DeclRefExpr>(Callee)->getDecl();
12137   ValueDecl *VD = cast_or_null<ValueDecl>(
12138       getDerived().TransformDecl(DR->getLocation(), DR));
12139   if (!VD)
12140     return ExprError();
12141 
12142   if (!isa<CXXMethodDecl>(VD))
12143     Functions.addDecl(VD);
12144 
12145   return getDerived().RebuildCXXOperatorCallExpr(
12146       E->getOperator(), E->getOperatorLoc(), Callee->getBeginLoc(),
12147       /*RequiresADL=*/false, Functions, First.get(), Second.get());
12148 }
12149 
12150 template<typename Derived>
12151 ExprResult
12152 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
12153   return getDerived().TransformCallExpr(E);
12154 }
12155 
12156 template <typename Derived>
12157 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
12158   bool NeedRebuildFunc = SourceLocExpr::MayBeDependent(E->getIdentKind()) &&
12159                          getSema().CurContext != E->getParentContext();
12160 
12161   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
12162     return E;
12163 
12164   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
12165                                            E->getBeginLoc(), E->getEndLoc(),
12166                                            getSema().CurContext);
12167 }
12168 
12169 template<typename Derived>
12170 ExprResult
12171 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
12172   // Transform the callee.
12173   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
12174   if (Callee.isInvalid())
12175     return ExprError();
12176 
12177   // Transform exec config.
12178   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
12179   if (EC.isInvalid())
12180     return ExprError();
12181 
12182   // Transform arguments.
12183   bool ArgChanged = false;
12184   SmallVector<Expr*, 8> Args;
12185   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12186                                   &ArgChanged))
12187     return ExprError();
12188 
12189   if (!getDerived().AlwaysRebuild() &&
12190       Callee.get() == E->getCallee() &&
12191       !ArgChanged)
12192     return SemaRef.MaybeBindToTemporary(E);
12193 
12194   // FIXME: Wrong source location information for the '('.
12195   SourceLocation FakeLParenLoc
12196     = ((Expr *)Callee.get())->getSourceRange().getBegin();
12197   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
12198                                       Args,
12199                                       E->getRParenLoc(), EC.get());
12200 }
12201 
12202 template<typename Derived>
12203 ExprResult
12204 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
12205   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
12206   if (!Type)
12207     return ExprError();
12208 
12209   ExprResult SubExpr
12210     = getDerived().TransformExpr(E->getSubExprAsWritten());
12211   if (SubExpr.isInvalid())
12212     return ExprError();
12213 
12214   if (!getDerived().AlwaysRebuild() &&
12215       Type == E->getTypeInfoAsWritten() &&
12216       SubExpr.get() == E->getSubExpr())
12217     return E;
12218   return getDerived().RebuildCXXNamedCastExpr(
12219       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
12220       Type, E->getAngleBrackets().getEnd(),
12221       // FIXME. this should be '(' location
12222       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
12223 }
12224 
12225 template<typename Derived>
12226 ExprResult
12227 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
12228   TypeSourceInfo *TSI =
12229       getDerived().TransformType(BCE->getTypeInfoAsWritten());
12230   if (!TSI)
12231     return ExprError();
12232 
12233   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
12234   if (Sub.isInvalid())
12235     return ExprError();
12236 
12237   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
12238                                                 Sub.get(), BCE->getEndLoc());
12239 }
12240 
12241 template<typename Derived>
12242 ExprResult
12243 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
12244   return getDerived().TransformCXXNamedCastExpr(E);
12245 }
12246 
12247 template<typename Derived>
12248 ExprResult
12249 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
12250   return getDerived().TransformCXXNamedCastExpr(E);
12251 }
12252 
12253 template<typename Derived>
12254 ExprResult
12255 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
12256                                                       CXXReinterpretCastExpr *E) {
12257   return getDerived().TransformCXXNamedCastExpr(E);
12258 }
12259 
12260 template<typename Derived>
12261 ExprResult
12262 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
12263   return getDerived().TransformCXXNamedCastExpr(E);
12264 }
12265 
12266 template<typename Derived>
12267 ExprResult
12268 TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
12269   return getDerived().TransformCXXNamedCastExpr(E);
12270 }
12271 
12272 template<typename Derived>
12273 ExprResult
12274 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
12275                                                      CXXFunctionalCastExpr *E) {
12276   TypeSourceInfo *Type =
12277       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
12278   if (!Type)
12279     return ExprError();
12280 
12281   ExprResult SubExpr
12282     = getDerived().TransformExpr(E->getSubExprAsWritten());
12283   if (SubExpr.isInvalid())
12284     return ExprError();
12285 
12286   if (!getDerived().AlwaysRebuild() &&
12287       Type == E->getTypeInfoAsWritten() &&
12288       SubExpr.get() == E->getSubExpr())
12289     return E;
12290 
12291   return getDerived().RebuildCXXFunctionalCastExpr(Type,
12292                                                    E->getLParenLoc(),
12293                                                    SubExpr.get(),
12294                                                    E->getRParenLoc(),
12295                                                    E->isListInitialization());
12296 }
12297 
12298 template<typename Derived>
12299 ExprResult
12300 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
12301   if (E->isTypeOperand()) {
12302     TypeSourceInfo *TInfo
12303       = getDerived().TransformType(E->getTypeOperandSourceInfo());
12304     if (!TInfo)
12305       return ExprError();
12306 
12307     if (!getDerived().AlwaysRebuild() &&
12308         TInfo == E->getTypeOperandSourceInfo())
12309       return E;
12310 
12311     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12312                                              TInfo, E->getEndLoc());
12313   }
12314 
12315   // Typeid's operand is an unevaluated context, unless it's a polymorphic
12316   // type.  We must not unilaterally enter unevaluated context here, as then
12317   // semantic processing can re-transform an already transformed operand.
12318   Expr *Op = E->getExprOperand();
12319   auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
12320   if (E->isGLValue())
12321     if (auto *RecordT = Op->getType()->getAs<RecordType>())
12322       if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
12323         EvalCtx = SemaRef.ExprEvalContexts.back().Context;
12324 
12325   EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
12326                                                Sema::ReuseLambdaContextDecl);
12327 
12328   ExprResult SubExpr = getDerived().TransformExpr(Op);
12329   if (SubExpr.isInvalid())
12330     return ExprError();
12331 
12332   if (!getDerived().AlwaysRebuild() &&
12333       SubExpr.get() == E->getExprOperand())
12334     return E;
12335 
12336   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12337                                            SubExpr.get(), E->getEndLoc());
12338 }
12339 
12340 template<typename Derived>
12341 ExprResult
12342 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
12343   if (E->isTypeOperand()) {
12344     TypeSourceInfo *TInfo
12345       = getDerived().TransformType(E->getTypeOperandSourceInfo());
12346     if (!TInfo)
12347       return ExprError();
12348 
12349     if (!getDerived().AlwaysRebuild() &&
12350         TInfo == E->getTypeOperandSourceInfo())
12351       return E;
12352 
12353     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12354                                              TInfo, E->getEndLoc());
12355   }
12356 
12357   EnterExpressionEvaluationContext Unevaluated(
12358       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12359 
12360   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
12361   if (SubExpr.isInvalid())
12362     return ExprError();
12363 
12364   if (!getDerived().AlwaysRebuild() &&
12365       SubExpr.get() == E->getExprOperand())
12366     return E;
12367 
12368   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12369                                            SubExpr.get(), E->getEndLoc());
12370 }
12371 
12372 template<typename Derived>
12373 ExprResult
12374 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
12375   return E;
12376 }
12377 
12378 template<typename Derived>
12379 ExprResult
12380 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
12381                                                      CXXNullPtrLiteralExpr *E) {
12382   return E;
12383 }
12384 
12385 template<typename Derived>
12386 ExprResult
12387 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
12388 
12389   // In lambdas, the qualifiers of the type depends of where in
12390   // the call operator `this` appear, and we do not have a good way to
12391   // rebuild this information, so we transform the type.
12392   //
12393   // In other contexts, the type of `this` may be overrided
12394   // for type deduction, so we need to recompute it.
12395   QualType T = getSema().getCurLambda() ?
12396                    getDerived().TransformType(E->getType())
12397                  : getSema().getCurrentThisType();
12398 
12399   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
12400     // Mark it referenced in the new context regardless.
12401     // FIXME: this is a bit instantiation-specific.
12402     getSema().MarkThisReferenced(E);
12403     return E;
12404   }
12405 
12406   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
12407 }
12408 
12409 template<typename Derived>
12410 ExprResult
12411 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
12412   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12413   if (SubExpr.isInvalid())
12414     return ExprError();
12415 
12416   if (!getDerived().AlwaysRebuild() &&
12417       SubExpr.get() == E->getSubExpr())
12418     return E;
12419 
12420   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
12421                                           E->isThrownVariableInScope());
12422 }
12423 
12424 template<typename Derived>
12425 ExprResult
12426 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12427   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
12428       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
12429   if (!Param)
12430     return ExprError();
12431 
12432   ExprResult InitRes;
12433   if (E->hasRewrittenInit()) {
12434     InitRes = getDerived().TransformExpr(E->getRewrittenExpr());
12435     if (InitRes.isInvalid())
12436       return ExprError();
12437   }
12438 
12439   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
12440       E->getUsedContext() == SemaRef.CurContext &&
12441       InitRes.get() == E->getRewrittenExpr())
12442     return E;
12443 
12444   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param,
12445                                                InitRes.get());
12446 }
12447 
12448 template<typename Derived>
12449 ExprResult
12450 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
12451   FieldDecl *Field = cast_or_null<FieldDecl>(
12452       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
12453   if (!Field)
12454     return ExprError();
12455 
12456   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
12457       E->getUsedContext() == SemaRef.CurContext)
12458     return E;
12459 
12460   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
12461 }
12462 
12463 template<typename Derived>
12464 ExprResult
12465 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
12466                                                     CXXScalarValueInitExpr *E) {
12467   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
12468   if (!T)
12469     return ExprError();
12470 
12471   if (!getDerived().AlwaysRebuild() &&
12472       T == E->getTypeSourceInfo())
12473     return E;
12474 
12475   return getDerived().RebuildCXXScalarValueInitExpr(T,
12476                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
12477                                                     E->getRParenLoc());
12478 }
12479 
12480 template<typename Derived>
12481 ExprResult
12482 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
12483   // Transform the type that we're allocating
12484   TypeSourceInfo *AllocTypeInfo =
12485       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
12486   if (!AllocTypeInfo)
12487     return ExprError();
12488 
12489   // Transform the size of the array we're allocating (if any).
12490   std::optional<Expr *> ArraySize;
12491   if (E->isArray()) {
12492     ExprResult NewArraySize;
12493     if (std::optional<Expr *> OldArraySize = E->getArraySize()) {
12494       NewArraySize = getDerived().TransformExpr(*OldArraySize);
12495       if (NewArraySize.isInvalid())
12496         return ExprError();
12497     }
12498     ArraySize = NewArraySize.get();
12499   }
12500 
12501   // Transform the placement arguments (if any).
12502   bool ArgumentChanged = false;
12503   SmallVector<Expr*, 8> PlacementArgs;
12504   if (getDerived().TransformExprs(E->getPlacementArgs(),
12505                                   E->getNumPlacementArgs(), true,
12506                                   PlacementArgs, &ArgumentChanged))
12507     return ExprError();
12508 
12509   // Transform the initializer (if any).
12510   Expr *OldInit = E->getInitializer();
12511   ExprResult NewInit;
12512   if (OldInit)
12513     NewInit = getDerived().TransformInitializer(OldInit, true);
12514   if (NewInit.isInvalid())
12515     return ExprError();
12516 
12517   // Transform new operator and delete operator.
12518   FunctionDecl *OperatorNew = nullptr;
12519   if (E->getOperatorNew()) {
12520     OperatorNew = cast_or_null<FunctionDecl>(
12521         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
12522     if (!OperatorNew)
12523       return ExprError();
12524   }
12525 
12526   FunctionDecl *OperatorDelete = nullptr;
12527   if (E->getOperatorDelete()) {
12528     OperatorDelete = cast_or_null<FunctionDecl>(
12529         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12530     if (!OperatorDelete)
12531       return ExprError();
12532   }
12533 
12534   if (!getDerived().AlwaysRebuild() &&
12535       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
12536       ArraySize == E->getArraySize() &&
12537       NewInit.get() == OldInit &&
12538       OperatorNew == E->getOperatorNew() &&
12539       OperatorDelete == E->getOperatorDelete() &&
12540       !ArgumentChanged) {
12541     // Mark any declarations we need as referenced.
12542     // FIXME: instantiation-specific.
12543     if (OperatorNew)
12544       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
12545     if (OperatorDelete)
12546       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12547 
12548     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
12549       QualType ElementType
12550         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
12551       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
12552         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
12553         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
12554           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
12555         }
12556       }
12557     }
12558 
12559     return E;
12560   }
12561 
12562   QualType AllocType = AllocTypeInfo->getType();
12563   if (!ArraySize) {
12564     // If no array size was specified, but the new expression was
12565     // instantiated with an array type (e.g., "new T" where T is
12566     // instantiated with "int[4]"), extract the outer bound from the
12567     // array type as our array size. We do this with constant and
12568     // dependently-sized array types.
12569     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
12570     if (!ArrayT) {
12571       // Do nothing
12572     } else if (const ConstantArrayType *ConsArrayT
12573                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
12574       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
12575                                          SemaRef.Context.getSizeType(),
12576                                          /*FIXME:*/ E->getBeginLoc());
12577       AllocType = ConsArrayT->getElementType();
12578     } else if (const DependentSizedArrayType *DepArrayT
12579                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
12580       if (DepArrayT->getSizeExpr()) {
12581         ArraySize = DepArrayT->getSizeExpr();
12582         AllocType = DepArrayT->getElementType();
12583       }
12584     }
12585   }
12586 
12587   return getDerived().RebuildCXXNewExpr(
12588       E->getBeginLoc(), E->isGlobalNew(),
12589       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
12590       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
12591       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
12592 }
12593 
12594 template<typename Derived>
12595 ExprResult
12596 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
12597   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
12598   if (Operand.isInvalid())
12599     return ExprError();
12600 
12601   // Transform the delete operator, if known.
12602   FunctionDecl *OperatorDelete = nullptr;
12603   if (E->getOperatorDelete()) {
12604     OperatorDelete = cast_or_null<FunctionDecl>(
12605         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12606     if (!OperatorDelete)
12607       return ExprError();
12608   }
12609 
12610   if (!getDerived().AlwaysRebuild() &&
12611       Operand.get() == E->getArgument() &&
12612       OperatorDelete == E->getOperatorDelete()) {
12613     // Mark any declarations we need as referenced.
12614     // FIXME: instantiation-specific.
12615     if (OperatorDelete)
12616       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12617 
12618     if (!E->getArgument()->isTypeDependent()) {
12619       QualType Destroyed = SemaRef.Context.getBaseElementType(
12620                                                          E->getDestroyedType());
12621       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12622         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12623         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12624                                        SemaRef.LookupDestructor(Record));
12625       }
12626     }
12627 
12628     return E;
12629   }
12630 
12631   return getDerived().RebuildCXXDeleteExpr(
12632       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
12633 }
12634 
12635 template<typename Derived>
12636 ExprResult
12637 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
12638                                                      CXXPseudoDestructorExpr *E) {
12639   ExprResult Base = getDerived().TransformExpr(E->getBase());
12640   if (Base.isInvalid())
12641     return ExprError();
12642 
12643   ParsedType ObjectTypePtr;
12644   bool MayBePseudoDestructor = false;
12645   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12646                                               E->getOperatorLoc(),
12647                                         E->isArrow()? tok::arrow : tok::period,
12648                                               ObjectTypePtr,
12649                                               MayBePseudoDestructor);
12650   if (Base.isInvalid())
12651     return ExprError();
12652 
12653   QualType ObjectType = ObjectTypePtr.get();
12654   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
12655   if (QualifierLoc) {
12656     QualifierLoc
12657       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
12658     if (!QualifierLoc)
12659       return ExprError();
12660   }
12661   CXXScopeSpec SS;
12662   SS.Adopt(QualifierLoc);
12663 
12664   PseudoDestructorTypeStorage Destroyed;
12665   if (E->getDestroyedTypeInfo()) {
12666     TypeSourceInfo *DestroyedTypeInfo
12667       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
12668                                                 ObjectType, nullptr, SS);
12669     if (!DestroyedTypeInfo)
12670       return ExprError();
12671     Destroyed = DestroyedTypeInfo;
12672   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
12673     // We aren't likely to be able to resolve the identifier down to a type
12674     // now anyway, so just retain the identifier.
12675     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
12676                                             E->getDestroyedTypeLoc());
12677   } else {
12678     // Look for a destructor known with the given name.
12679     ParsedType T = SemaRef.getDestructorName(
12680         *E->getDestroyedTypeIdentifier(), E->getDestroyedTypeLoc(),
12681         /*Scope=*/nullptr, SS, ObjectTypePtr, false);
12682     if (!T)
12683       return ExprError();
12684 
12685     Destroyed
12686       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
12687                                                  E->getDestroyedTypeLoc());
12688   }
12689 
12690   TypeSourceInfo *ScopeTypeInfo = nullptr;
12691   if (E->getScopeTypeInfo()) {
12692     CXXScopeSpec EmptySS;
12693     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12694                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12695     if (!ScopeTypeInfo)
12696       return ExprError();
12697   }
12698 
12699   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12700                                                      E->getOperatorLoc(),
12701                                                      E->isArrow(),
12702                                                      SS,
12703                                                      ScopeTypeInfo,
12704                                                      E->getColonColonLoc(),
12705                                                      E->getTildeLoc(),
12706                                                      Destroyed);
12707 }
12708 
12709 template <typename Derived>
12710 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12711                                                         bool RequiresADL,
12712                                                         LookupResult &R) {
12713   // Transform all the decls.
12714   bool AllEmptyPacks = true;
12715   for (auto *OldD : Old->decls()) {
12716     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12717     if (!InstD) {
12718       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12719       // This can happen because of dependent hiding.
12720       if (isa<UsingShadowDecl>(OldD))
12721         continue;
12722       else {
12723         R.clear();
12724         return true;
12725       }
12726     }
12727 
12728     // Expand using pack declarations.
12729     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12730     ArrayRef<NamedDecl*> Decls = SingleDecl;
12731     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12732       Decls = UPD->expansions();
12733 
12734     // Expand using declarations.
12735     for (auto *D : Decls) {
12736       if (auto *UD = dyn_cast<UsingDecl>(D)) {
12737         for (auto *SD : UD->shadows())
12738           R.addDecl(SD);
12739       } else {
12740         R.addDecl(D);
12741       }
12742     }
12743 
12744     AllEmptyPacks &= Decls.empty();
12745   };
12746 
12747   // C++ [temp.res]/8.4.2:
12748   //   The program is ill-formed, no diagnostic required, if [...] lookup for
12749   //   a name in the template definition found a using-declaration, but the
12750   //   lookup in the corresponding scope in the instantiation odoes not find
12751   //   any declarations because the using-declaration was a pack expansion and
12752   //   the corresponding pack is empty
12753   if (AllEmptyPacks && !RequiresADL) {
12754     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12755         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12756     return true;
12757   }
12758 
12759   // Resolve a kind, but don't do any further analysis.  If it's
12760   // ambiguous, the callee needs to deal with it.
12761   R.resolveKind();
12762   return false;
12763 }
12764 
12765 template<typename Derived>
12766 ExprResult
12767 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12768                                                   UnresolvedLookupExpr *Old) {
12769   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12770                  Sema::LookupOrdinaryName);
12771 
12772   // Transform the declaration set.
12773   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12774     return ExprError();
12775 
12776   // Rebuild the nested-name qualifier, if present.
12777   CXXScopeSpec SS;
12778   if (Old->getQualifierLoc()) {
12779     NestedNameSpecifierLoc QualifierLoc
12780       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12781     if (!QualifierLoc)
12782       return ExprError();
12783 
12784     SS.Adopt(QualifierLoc);
12785   }
12786 
12787   if (Old->getNamingClass()) {
12788     CXXRecordDecl *NamingClass
12789       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12790                                                             Old->getNameLoc(),
12791                                                         Old->getNamingClass()));
12792     if (!NamingClass) {
12793       R.clear();
12794       return ExprError();
12795     }
12796 
12797     R.setNamingClass(NamingClass);
12798   }
12799 
12800   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12801 
12802   // If we have neither explicit template arguments, nor the template keyword,
12803   // it's a normal declaration name or member reference.
12804   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12805     NamedDecl *D = R.getAsSingle<NamedDecl>();
12806     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12807     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12808     // give a good diagnostic.
12809     if (D && D->isCXXInstanceMember()) {
12810       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12811                                                      /*TemplateArgs=*/nullptr,
12812                                                      /*Scope=*/nullptr);
12813     }
12814 
12815     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12816   }
12817 
12818   // If we have template arguments, rebuild them, then rebuild the
12819   // templateid expression.
12820   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12821   if (Old->hasExplicitTemplateArgs() &&
12822       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12823                                               Old->getNumTemplateArgs(),
12824                                               TransArgs)) {
12825     R.clear();
12826     return ExprError();
12827   }
12828 
12829   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12830                                             Old->requiresADL(), &TransArgs);
12831 }
12832 
12833 template<typename Derived>
12834 ExprResult
12835 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12836   bool ArgChanged = false;
12837   SmallVector<TypeSourceInfo *, 4> Args;
12838   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12839     TypeSourceInfo *From = E->getArg(I);
12840     TypeLoc FromTL = From->getTypeLoc();
12841     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12842       TypeLocBuilder TLB;
12843       TLB.reserve(FromTL.getFullDataSize());
12844       QualType To = getDerived().TransformType(TLB, FromTL);
12845       if (To.isNull())
12846         return ExprError();
12847 
12848       if (To == From->getType())
12849         Args.push_back(From);
12850       else {
12851         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12852         ArgChanged = true;
12853       }
12854       continue;
12855     }
12856 
12857     ArgChanged = true;
12858 
12859     // We have a pack expansion. Instantiate it.
12860     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12861     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12862     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12863     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12864 
12865     // Determine whether the set of unexpanded parameter packs can and should
12866     // be expanded.
12867     bool Expand = true;
12868     bool RetainExpansion = false;
12869     std::optional<unsigned> OrigNumExpansions =
12870         ExpansionTL.getTypePtr()->getNumExpansions();
12871     std::optional<unsigned> NumExpansions = OrigNumExpansions;
12872     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12873                                              PatternTL.getSourceRange(),
12874                                              Unexpanded,
12875                                              Expand, RetainExpansion,
12876                                              NumExpansions))
12877       return ExprError();
12878 
12879     if (!Expand) {
12880       // The transform has determined that we should perform a simple
12881       // transformation on the pack expansion, producing another pack
12882       // expansion.
12883       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12884 
12885       TypeLocBuilder TLB;
12886       TLB.reserve(From->getTypeLoc().getFullDataSize());
12887 
12888       QualType To = getDerived().TransformType(TLB, PatternTL);
12889       if (To.isNull())
12890         return ExprError();
12891 
12892       To = getDerived().RebuildPackExpansionType(To,
12893                                                  PatternTL.getSourceRange(),
12894                                                  ExpansionTL.getEllipsisLoc(),
12895                                                  NumExpansions);
12896       if (To.isNull())
12897         return ExprError();
12898 
12899       PackExpansionTypeLoc ToExpansionTL
12900         = TLB.push<PackExpansionTypeLoc>(To);
12901       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12902       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12903       continue;
12904     }
12905 
12906     // Expand the pack expansion by substituting for each argument in the
12907     // pack(s).
12908     for (unsigned I = 0; I != *NumExpansions; ++I) {
12909       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12910       TypeLocBuilder TLB;
12911       TLB.reserve(PatternTL.getFullDataSize());
12912       QualType To = getDerived().TransformType(TLB, PatternTL);
12913       if (To.isNull())
12914         return ExprError();
12915 
12916       if (To->containsUnexpandedParameterPack()) {
12917         To = getDerived().RebuildPackExpansionType(To,
12918                                                    PatternTL.getSourceRange(),
12919                                                    ExpansionTL.getEllipsisLoc(),
12920                                                    NumExpansions);
12921         if (To.isNull())
12922           return ExprError();
12923 
12924         PackExpansionTypeLoc ToExpansionTL
12925           = TLB.push<PackExpansionTypeLoc>(To);
12926         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12927       }
12928 
12929       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12930     }
12931 
12932     if (!RetainExpansion)
12933       continue;
12934 
12935     // If we're supposed to retain a pack expansion, do so by temporarily
12936     // forgetting the partially-substituted parameter pack.
12937     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12938 
12939     TypeLocBuilder TLB;
12940     TLB.reserve(From->getTypeLoc().getFullDataSize());
12941 
12942     QualType To = getDerived().TransformType(TLB, PatternTL);
12943     if (To.isNull())
12944       return ExprError();
12945 
12946     To = getDerived().RebuildPackExpansionType(To,
12947                                                PatternTL.getSourceRange(),
12948                                                ExpansionTL.getEllipsisLoc(),
12949                                                NumExpansions);
12950     if (To.isNull())
12951       return ExprError();
12952 
12953     PackExpansionTypeLoc ToExpansionTL
12954       = TLB.push<PackExpansionTypeLoc>(To);
12955     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12956     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12957   }
12958 
12959   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12960     return E;
12961 
12962   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12963                                        E->getEndLoc());
12964 }
12965 
12966 template<typename Derived>
12967 ExprResult
12968 TreeTransform<Derived>::TransformConceptSpecializationExpr(
12969                                                  ConceptSpecializationExpr *E) {
12970   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12971   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12972   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12973                                               Old->NumTemplateArgs, TransArgs))
12974     return ExprError();
12975 
12976   return getDerived().RebuildConceptSpecializationExpr(
12977       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12978       E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12979       &TransArgs);
12980 }
12981 
12982 template<typename Derived>
12983 ExprResult
12984 TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12985   SmallVector<ParmVarDecl*, 4> TransParams;
12986   SmallVector<QualType, 4> TransParamTypes;
12987   Sema::ExtParameterInfoBuilder ExtParamInfos;
12988 
12989   // C++2a [expr.prim.req]p2
12990   // Expressions appearing within a requirement-body are unevaluated operands.
12991   EnterExpressionEvaluationContext Ctx(
12992       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
12993       Sema::ReuseLambdaContextDecl);
12994 
12995   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12996       getSema().Context, getSema().CurContext,
12997       E->getBody()->getBeginLoc());
12998 
12999   Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
13000 
13001   ExprResult TypeParamResult = getDerived().TransformRequiresTypeParams(
13002       E->getRequiresKWLoc(), E->getRBraceLoc(), E, Body,
13003       E->getLocalParameters(), TransParamTypes, TransParams, ExtParamInfos);
13004 
13005   for (ParmVarDecl *Param : TransParams)
13006     if (Param)
13007       Param->setDeclContext(Body);
13008 
13009   // On failure to transform, TransformRequiresTypeParams returns an expression
13010   // in the event that the transformation of the type params failed in some way.
13011   // It is expected that this will result in a 'not satisfied' Requires clause
13012   // when instantiating.
13013   if (!TypeParamResult.isUnset())
13014     return TypeParamResult;
13015 
13016   SmallVector<concepts::Requirement *, 4> TransReqs;
13017   if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
13018                                                      TransReqs))
13019     return ExprError();
13020 
13021   for (concepts::Requirement *Req : TransReqs) {
13022     if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
13023       if (ER->getReturnTypeRequirement().isTypeConstraint()) {
13024         ER->getReturnTypeRequirement()
13025                 .getTypeConstraintTemplateParameterList()->getParam(0)
13026                 ->setDeclContext(Body);
13027       }
13028     }
13029   }
13030 
13031   return getDerived().RebuildRequiresExpr(
13032       E->getRequiresKWLoc(), Body, E->getLParenLoc(), TransParams,
13033       E->getRParenLoc(), TransReqs, E->getRBraceLoc());
13034 }
13035 
13036 template<typename Derived>
13037 bool TreeTransform<Derived>::TransformRequiresExprRequirements(
13038     ArrayRef<concepts::Requirement *> Reqs,
13039     SmallVectorImpl<concepts::Requirement *> &Transformed) {
13040   for (concepts::Requirement *Req : Reqs) {
13041     concepts::Requirement *TransReq = nullptr;
13042     if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
13043       TransReq = getDerived().TransformTypeRequirement(TypeReq);
13044     else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
13045       TransReq = getDerived().TransformExprRequirement(ExprReq);
13046     else
13047       TransReq = getDerived().TransformNestedRequirement(
13048                      cast<concepts::NestedRequirement>(Req));
13049     if (!TransReq)
13050       return true;
13051     Transformed.push_back(TransReq);
13052   }
13053   return false;
13054 }
13055 
13056 template<typename Derived>
13057 concepts::TypeRequirement *
13058 TreeTransform<Derived>::TransformTypeRequirement(
13059     concepts::TypeRequirement *Req) {
13060   if (Req->isSubstitutionFailure()) {
13061     if (getDerived().AlwaysRebuild())
13062       return getDerived().RebuildTypeRequirement(
13063               Req->getSubstitutionDiagnostic());
13064     return Req;
13065   }
13066   TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
13067   if (!TransType)
13068     return nullptr;
13069   return getDerived().RebuildTypeRequirement(TransType);
13070 }
13071 
13072 template<typename Derived>
13073 concepts::ExprRequirement *
13074 TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
13075   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
13076   if (Req->isExprSubstitutionFailure())
13077     TransExpr = Req->getExprSubstitutionDiagnostic();
13078   else {
13079     ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
13080     if (TransExprRes.isUsable() && TransExprRes.get()->hasPlaceholderType())
13081       TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
13082     if (TransExprRes.isInvalid())
13083       return nullptr;
13084     TransExpr = TransExprRes.get();
13085   }
13086 
13087   std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
13088   const auto &RetReq = Req->getReturnTypeRequirement();
13089   if (RetReq.isEmpty())
13090     TransRetReq.emplace();
13091   else if (RetReq.isSubstitutionFailure())
13092     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
13093   else if (RetReq.isTypeConstraint()) {
13094     TemplateParameterList *OrigTPL =
13095         RetReq.getTypeConstraintTemplateParameterList();
13096     TemplateParameterList *TPL =
13097         getDerived().TransformTemplateParameterList(OrigTPL);
13098     if (!TPL)
13099       return nullptr;
13100     TransRetReq.emplace(TPL);
13101   }
13102   assert(TransRetReq && "All code paths leading here must set TransRetReq");
13103   if (Expr *E = TransExpr.dyn_cast<Expr *>())
13104     return getDerived().RebuildExprRequirement(E, Req->isSimple(),
13105                                                Req->getNoexceptLoc(),
13106                                                std::move(*TransRetReq));
13107   return getDerived().RebuildExprRequirement(
13108       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
13109       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
13110 }
13111 
13112 template<typename Derived>
13113 concepts::NestedRequirement *
13114 TreeTransform<Derived>::TransformNestedRequirement(
13115     concepts::NestedRequirement *Req) {
13116   if (Req->hasInvalidConstraint()) {
13117     if (getDerived().AlwaysRebuild())
13118       return getDerived().RebuildNestedRequirement(
13119           Req->getInvalidConstraintEntity(), Req->getConstraintSatisfaction());
13120     return Req;
13121   }
13122   ExprResult TransConstraint =
13123       getDerived().TransformExpr(Req->getConstraintExpr());
13124   if (TransConstraint.isInvalid())
13125     return nullptr;
13126   return getDerived().RebuildNestedRequirement(TransConstraint.get());
13127 }
13128 
13129 template<typename Derived>
13130 ExprResult
13131 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
13132   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
13133   if (!T)
13134     return ExprError();
13135 
13136   if (!getDerived().AlwaysRebuild() &&
13137       T == E->getQueriedTypeSourceInfo())
13138     return E;
13139 
13140   ExprResult SubExpr;
13141   {
13142     EnterExpressionEvaluationContext Unevaluated(
13143         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13144     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
13145     if (SubExpr.isInvalid())
13146       return ExprError();
13147 
13148     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
13149       return E;
13150   }
13151 
13152   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
13153                                             SubExpr.get(), E->getEndLoc());
13154 }
13155 
13156 template<typename Derived>
13157 ExprResult
13158 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
13159   ExprResult SubExpr;
13160   {
13161     EnterExpressionEvaluationContext Unevaluated(
13162         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13163     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
13164     if (SubExpr.isInvalid())
13165       return ExprError();
13166 
13167     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
13168       return E;
13169   }
13170 
13171   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
13172                                              SubExpr.get(), E->getEndLoc());
13173 }
13174 
13175 template <typename Derived>
13176 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
13177     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
13178     TypeSourceInfo **RecoveryTSI) {
13179   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
13180       DRE, AddrTaken, RecoveryTSI);
13181 
13182   // Propagate both errors and recovered types, which return ExprEmpty.
13183   if (!NewDRE.isUsable())
13184     return NewDRE;
13185 
13186   // We got an expr, wrap it up in parens.
13187   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
13188     return PE;
13189   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
13190                                        PE->getRParen());
13191 }
13192 
13193 template <typename Derived>
13194 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13195     DependentScopeDeclRefExpr *E) {
13196   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
13197                                             nullptr);
13198 }
13199 
13200 template <typename Derived>
13201 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13202     DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
13203     TypeSourceInfo **RecoveryTSI) {
13204   assert(E->getQualifierLoc());
13205   NestedNameSpecifierLoc QualifierLoc =
13206       getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
13207   if (!QualifierLoc)
13208     return ExprError();
13209   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13210 
13211   // TODO: If this is a conversion-function-id, verify that the
13212   // destination type name (if present) resolves the same way after
13213   // instantiation as it did in the local scope.
13214 
13215   DeclarationNameInfo NameInfo =
13216       getDerived().TransformDeclarationNameInfo(E->getNameInfo());
13217   if (!NameInfo.getName())
13218     return ExprError();
13219 
13220   if (!E->hasExplicitTemplateArgs()) {
13221     if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
13222         // Note: it is sufficient to compare the Name component of NameInfo:
13223         // if name has not changed, DNLoc has not changed either.
13224         NameInfo.getName() == E->getDeclName())
13225       return E;
13226 
13227     return getDerived().RebuildDependentScopeDeclRefExpr(
13228         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
13229         IsAddressOfOperand, RecoveryTSI);
13230   }
13231 
13232   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13233   if (getDerived().TransformTemplateArguments(
13234           E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
13235     return ExprError();
13236 
13237   return getDerived().RebuildDependentScopeDeclRefExpr(
13238       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
13239       RecoveryTSI);
13240 }
13241 
13242 template<typename Derived>
13243 ExprResult
13244 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
13245   // CXXConstructExprs other than for list-initialization and
13246   // CXXTemporaryObjectExpr are always implicit, so when we have
13247   // a 1-argument construction we just transform that argument.
13248   if (getDerived().AllowSkippingCXXConstructExpr() &&
13249       ((E->getNumArgs() == 1 ||
13250         (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
13251        (!getDerived().DropCallArgument(E->getArg(0))) &&
13252        !E->isListInitialization()))
13253     return getDerived().TransformInitializer(E->getArg(0),
13254                                              /*DirectInit*/ false);
13255 
13256   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
13257 
13258   QualType T = getDerived().TransformType(E->getType());
13259   if (T.isNull())
13260     return ExprError();
13261 
13262   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13263       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13264   if (!Constructor)
13265     return ExprError();
13266 
13267   bool ArgumentChanged = false;
13268   SmallVector<Expr*, 8> Args;
13269   {
13270     EnterExpressionEvaluationContext Context(
13271         getSema(), EnterExpressionEvaluationContext::InitList,
13272         E->isListInitialization());
13273     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13274                                     &ArgumentChanged))
13275       return ExprError();
13276   }
13277 
13278   if (!getDerived().AlwaysRebuild() &&
13279       T == E->getType() &&
13280       Constructor == E->getConstructor() &&
13281       !ArgumentChanged) {
13282     // Mark the constructor as referenced.
13283     // FIXME: Instantiation-specific
13284     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13285     return E;
13286   }
13287 
13288   return getDerived().RebuildCXXConstructExpr(
13289       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
13290       E->hadMultipleCandidates(), E->isListInitialization(),
13291       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
13292       E->getConstructionKind(), E->getParenOrBraceRange());
13293 }
13294 
13295 template<typename Derived>
13296 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
13297     CXXInheritedCtorInitExpr *E) {
13298   QualType T = getDerived().TransformType(E->getType());
13299   if (T.isNull())
13300     return ExprError();
13301 
13302   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13303       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13304   if (!Constructor)
13305     return ExprError();
13306 
13307   if (!getDerived().AlwaysRebuild() &&
13308       T == E->getType() &&
13309       Constructor == E->getConstructor()) {
13310     // Mark the constructor as referenced.
13311     // FIXME: Instantiation-specific
13312     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13313     return E;
13314   }
13315 
13316   return getDerived().RebuildCXXInheritedCtorInitExpr(
13317       T, E->getLocation(), Constructor,
13318       E->constructsVBase(), E->inheritedFromVBase());
13319 }
13320 
13321 /// Transform a C++ temporary-binding expression.
13322 ///
13323 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
13324 /// transform the subexpression and return that.
13325 template<typename Derived>
13326 ExprResult
13327 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13328   if (auto *Dtor = E->getTemporary()->getDestructor())
13329     SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
13330                                    const_cast<CXXDestructorDecl *>(Dtor));
13331   return getDerived().TransformExpr(E->getSubExpr());
13332 }
13333 
13334 /// Transform a C++ expression that contains cleanups that should
13335 /// be run after the expression is evaluated.
13336 ///
13337 /// Since ExprWithCleanups nodes are implicitly generated, we
13338 /// just transform the subexpression and return that.
13339 template<typename Derived>
13340 ExprResult
13341 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
13342   return getDerived().TransformExpr(E->getSubExpr());
13343 }
13344 
13345 template<typename Derived>
13346 ExprResult
13347 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
13348                                                     CXXTemporaryObjectExpr *E) {
13349   TypeSourceInfo *T =
13350       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13351   if (!T)
13352     return ExprError();
13353 
13354   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13355       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13356   if (!Constructor)
13357     return ExprError();
13358 
13359   bool ArgumentChanged = false;
13360   SmallVector<Expr*, 8> Args;
13361   Args.reserve(E->getNumArgs());
13362   {
13363     EnterExpressionEvaluationContext Context(
13364         getSema(), EnterExpressionEvaluationContext::InitList,
13365         E->isListInitialization());
13366     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13367                        &ArgumentChanged))
13368       return ExprError();
13369   }
13370 
13371   if (!getDerived().AlwaysRebuild() &&
13372       T == E->getTypeSourceInfo() &&
13373       Constructor == E->getConstructor() &&
13374       !ArgumentChanged) {
13375     // FIXME: Instantiation-specific
13376     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13377     return SemaRef.MaybeBindToTemporary(E);
13378   }
13379 
13380   // FIXME: We should just pass E->isListInitialization(), but we're not
13381   // prepared to handle list-initialization without a child InitListExpr.
13382   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
13383   return getDerived().RebuildCXXTemporaryObjectExpr(
13384       T, LParenLoc, Args, E->getEndLoc(),
13385       /*ListInitialization=*/LParenLoc.isInvalid());
13386 }
13387 
13388 template<typename Derived>
13389 ExprResult
13390 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
13391   // Transform any init-capture expressions before entering the scope of the
13392   // lambda body, because they are not semantically within that scope.
13393   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
13394   struct TransformedInitCapture {
13395     // The location of the ... if the result is retaining a pack expansion.
13396     SourceLocation EllipsisLoc;
13397     // Zero or more expansions of the init-capture.
13398     SmallVector<InitCaptureInfoTy, 4> Expansions;
13399   };
13400   SmallVector<TransformedInitCapture, 4> InitCaptures;
13401   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
13402   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13403                                     CEnd = E->capture_end();
13404        C != CEnd; ++C) {
13405     if (!E->isInitCapture(C))
13406       continue;
13407 
13408     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
13409     auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13410 
13411     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
13412                                 std::optional<unsigned> NumExpansions) {
13413       ExprResult NewExprInitResult = getDerived().TransformInitializer(
13414           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
13415 
13416       if (NewExprInitResult.isInvalid()) {
13417         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
13418         return;
13419       }
13420       Expr *NewExprInit = NewExprInitResult.get();
13421 
13422       QualType NewInitCaptureType =
13423           getSema().buildLambdaInitCaptureInitialization(
13424               C->getLocation(), C->getCaptureKind() == LCK_ByRef,
13425               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
13426               cast<VarDecl>(C->getCapturedVar())->getInitStyle() !=
13427                   VarDecl::CInit,
13428               NewExprInit);
13429       Result.Expansions.push_back(
13430           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
13431     };
13432 
13433     // If this is an init-capture pack, consider expanding the pack now.
13434     if (OldVD->isParameterPack()) {
13435       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
13436                                              ->getTypeLoc()
13437                                              .castAs<PackExpansionTypeLoc>();
13438       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13439       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
13440 
13441       // Determine whether the set of unexpanded parameter packs can and should
13442       // be expanded.
13443       bool Expand = true;
13444       bool RetainExpansion = false;
13445       std::optional<unsigned> OrigNumExpansions =
13446           ExpansionTL.getTypePtr()->getNumExpansions();
13447       std::optional<unsigned> NumExpansions = OrigNumExpansions;
13448       if (getDerived().TryExpandParameterPacks(
13449               ExpansionTL.getEllipsisLoc(),
13450               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
13451               RetainExpansion, NumExpansions))
13452         return ExprError();
13453       if (Expand) {
13454         for (unsigned I = 0; I != *NumExpansions; ++I) {
13455           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13456           SubstInitCapture(SourceLocation(), std::nullopt);
13457         }
13458       }
13459       if (!Expand || RetainExpansion) {
13460         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13461         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
13462         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
13463       }
13464     } else {
13465       SubstInitCapture(SourceLocation(), std::nullopt);
13466     }
13467   }
13468 
13469   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
13470   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
13471 
13472   // Create the local class that will describe the lambda.
13473 
13474   // FIXME: DependencyKind below is wrong when substituting inside a templated
13475   // context that isn't a DeclContext (such as a variable template), or when
13476   // substituting an unevaluated lambda inside of a function's parameter's type
13477   // - as parameter types are not instantiated from within a function's DC. We
13478   // use evaluation contexts to distinguish the function parameter case.
13479   CXXRecordDecl::LambdaDependencyKind DependencyKind =
13480       CXXRecordDecl::LDK_Unknown;
13481   if ((getSema().isUnevaluatedContext() ||
13482        getSema().isConstantEvaluatedContext()) &&
13483       (getSema().CurContext->isFileContext() ||
13484        !getSema().CurContext->getParent()->isDependentContext()))
13485     DependencyKind = CXXRecordDecl::LDK_NeverDependent;
13486 
13487   CXXRecordDecl *OldClass = E->getLambdaClass();
13488   CXXRecordDecl *Class = getSema().createLambdaClosureType(
13489       E->getIntroducerRange(), /*Info=*/nullptr, DependencyKind,
13490       E->getCaptureDefault());
13491   getDerived().transformedLocalDecl(OldClass, {Class});
13492 
13493   CXXMethodDecl *NewCallOperator =
13494       getSema().CreateLambdaCallOperator(E->getIntroducerRange(), Class);
13495   NewCallOperator->setLexicalDeclContext(getSema().CurContext);
13496 
13497   // Enter the scope of the lambda.
13498   getSema().buildLambdaScope(LSI, NewCallOperator, E->getIntroducerRange(),
13499                              E->getCaptureDefault(), E->getCaptureDefaultLoc(),
13500                              E->hasExplicitParameters(), E->isMutable());
13501 
13502   // Introduce the context of the call operator.
13503   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
13504                                  /*NewThisContext*/false);
13505 
13506   bool Invalid = false;
13507 
13508   // Transform captures.
13509   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13510                                  CEnd = E->capture_end();
13511        C != CEnd; ++C) {
13512     // When we hit the first implicit capture, tell Sema that we've finished
13513     // the list of explicit captures.
13514     if (C->isImplicit())
13515       break;
13516 
13517     // Capturing 'this' is trivial.
13518     if (C->capturesThis()) {
13519       // If this is a lambda that is part of a default member initialiser
13520       // and which we're instantiating outside the class that 'this' is
13521       // supposed to refer to, adjust the type of 'this' accordingly.
13522       //
13523       // Otherwise, leave the type of 'this' as-is.
13524       Sema::CXXThisScopeRAII ThisScope(
13525           getSema(),
13526           dyn_cast_if_present<CXXRecordDecl>(
13527               getSema().getFunctionLevelDeclContext()),
13528           Qualifiers());
13529       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13530                                     /*BuildAndDiagnose*/ true, nullptr,
13531                                     C->getCaptureKind() == LCK_StarThis);
13532       continue;
13533     }
13534     // Captured expression will be recaptured during captured variables
13535     // rebuilding.
13536     if (C->capturesVLAType())
13537       continue;
13538 
13539     // Rebuild init-captures, including the implied field declaration.
13540     if (E->isInitCapture(C)) {
13541       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
13542 
13543       auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13544       llvm::SmallVector<Decl*, 4> NewVDs;
13545 
13546       for (InitCaptureInfoTy &Info : NewC.Expansions) {
13547         ExprResult Init = Info.first;
13548         QualType InitQualType = Info.second;
13549         if (Init.isInvalid() || InitQualType.isNull()) {
13550           Invalid = true;
13551           break;
13552         }
13553         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
13554             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
13555             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get(),
13556             getSema().CurContext);
13557         if (!NewVD) {
13558           Invalid = true;
13559           break;
13560         }
13561         NewVDs.push_back(NewVD);
13562         getSema().addInitCapture(LSI, NewVD, C->getCaptureKind() == LCK_ByRef);
13563       }
13564 
13565       if (Invalid)
13566         break;
13567 
13568       getDerived().transformedLocalDecl(OldVD, NewVDs);
13569       continue;
13570     }
13571 
13572     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13573 
13574     // Determine the capture kind for Sema.
13575     Sema::TryCaptureKind Kind
13576       = C->isImplicit()? Sema::TryCapture_Implicit
13577                        : C->getCaptureKind() == LCK_ByCopy
13578                            ? Sema::TryCapture_ExplicitByVal
13579                            : Sema::TryCapture_ExplicitByRef;
13580     SourceLocation EllipsisLoc;
13581     if (C->isPackExpansion()) {
13582       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
13583       bool ShouldExpand = false;
13584       bool RetainExpansion = false;
13585       std::optional<unsigned> NumExpansions;
13586       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
13587                                                C->getLocation(),
13588                                                Unexpanded,
13589                                                ShouldExpand, RetainExpansion,
13590                                                NumExpansions)) {
13591         Invalid = true;
13592         continue;
13593       }
13594 
13595       if (ShouldExpand) {
13596         // The transform has determined that we should perform an expansion;
13597         // transform and capture each of the arguments.
13598         // expansion of the pattern. Do so.
13599         auto *Pack = cast<VarDecl>(C->getCapturedVar());
13600         for (unsigned I = 0; I != *NumExpansions; ++I) {
13601           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13602           VarDecl *CapturedVar
13603             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13604                                                                Pack));
13605           if (!CapturedVar) {
13606             Invalid = true;
13607             continue;
13608           }
13609 
13610           // Capture the transformed variable.
13611           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
13612         }
13613 
13614         // FIXME: Retain a pack expansion if RetainExpansion is true.
13615 
13616         continue;
13617       }
13618 
13619       EllipsisLoc = C->getEllipsisLoc();
13620     }
13621 
13622     // Transform the captured variable.
13623     auto *CapturedVar = cast_or_null<ValueDecl>(
13624         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13625     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
13626       Invalid = true;
13627       continue;
13628     }
13629 
13630     // Capture the transformed variable.
13631     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
13632                                  EllipsisLoc);
13633   }
13634   getSema().finishLambdaExplicitCaptures(LSI);
13635 
13636   // Transform the template parameters, and add them to the current
13637   // instantiation scope. The null case is handled correctly.
13638   auto TPL = getDerived().TransformTemplateParameterList(
13639       E->getTemplateParameterList());
13640   LSI->GLTemplateParameterList = TPL;
13641   if (TPL)
13642     getSema().AddTemplateParametersToLambdaCallOperator(NewCallOperator, Class,
13643                                                         TPL);
13644 
13645   // Transform the type of the original lambda's call operator.
13646   // The transformation MUST be done in the CurrentInstantiationScope since
13647   // it introduces a mapping of the original to the newly created
13648   // transformed parameters.
13649   TypeSourceInfo *NewCallOpTSI = nullptr;
13650   {
13651     auto OldCallOpTypeLoc =
13652         E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
13653 
13654     auto TransformFunctionProtoTypeLoc =
13655         [this](TypeLocBuilder &TLB, FunctionProtoTypeLoc FPTL) -> QualType {
13656       SmallVector<QualType, 4> ExceptionStorage;
13657       return this->TransformFunctionProtoType(
13658           TLB, FPTL, nullptr, Qualifiers(),
13659           [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
13660             return TransformExceptionSpec(FPTL.getBeginLoc(), ESI,
13661                                           ExceptionStorage, Changed);
13662           });
13663     };
13664 
13665     QualType NewCallOpType;
13666     TypeLocBuilder NewCallOpTLBuilder;
13667 
13668     if (auto ATL = OldCallOpTypeLoc.getAs<AttributedTypeLoc>()) {
13669       NewCallOpType = this->TransformAttributedType(
13670           NewCallOpTLBuilder, ATL,
13671           [&](TypeLocBuilder &TLB, TypeLoc TL) -> QualType {
13672             return TransformFunctionProtoTypeLoc(
13673                 TLB, TL.castAs<FunctionProtoTypeLoc>());
13674           });
13675     } else {
13676       auto FPTL = OldCallOpTypeLoc.castAs<FunctionProtoTypeLoc>();
13677       NewCallOpType = TransformFunctionProtoTypeLoc(NewCallOpTLBuilder, FPTL);
13678     }
13679 
13680     if (NewCallOpType.isNull())
13681       return ExprError();
13682     NewCallOpTSI =
13683         NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context, NewCallOpType);
13684   }
13685 
13686   ArrayRef<ParmVarDecl *> Params;
13687   if (auto ATL = NewCallOpTSI->getTypeLoc().getAs<AttributedTypeLoc>()) {
13688     Params = ATL.getModifiedLoc().castAs<FunctionProtoTypeLoc>().getParams();
13689   } else {
13690     auto FPTL = NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
13691     Params = FPTL.getParams();
13692   }
13693 
13694   getSema().CompleteLambdaCallOperator(
13695       NewCallOperator, E->getCallOperator()->getLocation(),
13696       E->getCallOperator()->getInnerLocStart(),
13697       E->getCallOperator()->getTrailingRequiresClause(), NewCallOpTSI,
13698       E->getCallOperator()->getConstexprKind(),
13699       E->getCallOperator()->getStorageClass(), Params,
13700       E->hasExplicitResultType());
13701 
13702   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
13703   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
13704 
13705   {
13706     // Number the lambda for linkage purposes if necessary.
13707     Sema::ContextRAII ManglingContext(getSema(), Class->getDeclContext());
13708 
13709     std::optional<CXXRecordDecl::LambdaNumbering> Numbering;
13710     if (getDerived().ReplacingOriginal()) {
13711       Numbering = OldClass->getLambdaNumbering();
13712     }
13713 
13714     getSema().handleLambdaNumbering(Class, NewCallOperator, Numbering);
13715   }
13716 
13717   // FIXME: Sema's lambda-building mechanism expects us to push an expression
13718   // evaluation context even if we're not transforming the function body.
13719   getSema().PushExpressionEvaluationContext(
13720       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13721 
13722   Sema::CodeSynthesisContext C;
13723   C.Kind = clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution;
13724   C.PointOfInstantiation = E->getBody()->getBeginLoc();
13725   getSema().pushCodeSynthesisContext(C);
13726 
13727   // Instantiate the body of the lambda expression.
13728   StmtResult Body =
13729       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
13730 
13731   getSema().popCodeSynthesisContext();
13732 
13733   // ActOnLambda* will pop the function scope for us.
13734   FuncScopeCleanup.disable();
13735 
13736   if (Body.isInvalid()) {
13737     SavedContext.pop();
13738     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
13739                                /*IsInstantiation=*/true);
13740     return ExprError();
13741   }
13742 
13743   // Copy the LSI before ActOnFinishFunctionBody removes it.
13744   // FIXME: This is dumb. Store the lambda information somewhere that outlives
13745   // the call operator.
13746   auto LSICopy = *LSI;
13747   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
13748                                     /*IsInstantiation*/ true);
13749   SavedContext.pop();
13750 
13751   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13752                                    &LSICopy);
13753 }
13754 
13755 template<typename Derived>
13756 StmtResult
13757 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13758   return TransformStmt(S);
13759 }
13760 
13761 template<typename Derived>
13762 StmtResult
13763 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13764   // Transform captures.
13765   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13766                                  CEnd = E->capture_end();
13767        C != CEnd; ++C) {
13768     // When we hit the first implicit capture, tell Sema that we've finished
13769     // the list of explicit captures.
13770     if (!C->isImplicit())
13771       continue;
13772 
13773     // Capturing 'this' is trivial.
13774     if (C->capturesThis()) {
13775       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13776                                     /*BuildAndDiagnose*/ true, nullptr,
13777                                     C->getCaptureKind() == LCK_StarThis);
13778       continue;
13779     }
13780     // Captured expression will be recaptured during captured variables
13781     // rebuilding.
13782     if (C->capturesVLAType())
13783       continue;
13784 
13785     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13786     assert(!E->isInitCapture(C) && "implicit init-capture?");
13787 
13788     // Transform the captured variable.
13789     VarDecl *CapturedVar = cast_or_null<VarDecl>(
13790         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13791     if (!CapturedVar || CapturedVar->isInvalidDecl())
13792       return StmtError();
13793 
13794     // Capture the transformed variable.
13795     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13796   }
13797 
13798   return S;
13799 }
13800 
13801 template<typename Derived>
13802 ExprResult
13803 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13804                                                   CXXUnresolvedConstructExpr *E) {
13805   TypeSourceInfo *T =
13806       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13807   if (!T)
13808     return ExprError();
13809 
13810   bool ArgumentChanged = false;
13811   SmallVector<Expr*, 8> Args;
13812   Args.reserve(E->getNumArgs());
13813   {
13814     EnterExpressionEvaluationContext Context(
13815         getSema(), EnterExpressionEvaluationContext::InitList,
13816         E->isListInitialization());
13817     if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13818                                     &ArgumentChanged))
13819       return ExprError();
13820   }
13821 
13822   if (!getDerived().AlwaysRebuild() &&
13823       T == E->getTypeSourceInfo() &&
13824       !ArgumentChanged)
13825     return E;
13826 
13827   // FIXME: we're faking the locations of the commas
13828   return getDerived().RebuildCXXUnresolvedConstructExpr(
13829       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13830 }
13831 
13832 template<typename Derived>
13833 ExprResult
13834 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13835                                              CXXDependentScopeMemberExpr *E) {
13836   // Transform the base of the expression.
13837   ExprResult Base((Expr*) nullptr);
13838   Expr *OldBase;
13839   QualType BaseType;
13840   QualType ObjectType;
13841   if (!E->isImplicitAccess()) {
13842     OldBase = E->getBase();
13843     Base = getDerived().TransformExpr(OldBase);
13844     if (Base.isInvalid())
13845       return ExprError();
13846 
13847     // Start the member reference and compute the object's type.
13848     ParsedType ObjectTy;
13849     bool MayBePseudoDestructor = false;
13850     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13851                                                 E->getOperatorLoc(),
13852                                       E->isArrow()? tok::arrow : tok::period,
13853                                                 ObjectTy,
13854                                                 MayBePseudoDestructor);
13855     if (Base.isInvalid())
13856       return ExprError();
13857 
13858     ObjectType = ObjectTy.get();
13859     BaseType = ((Expr*) Base.get())->getType();
13860   } else {
13861     OldBase = nullptr;
13862     BaseType = getDerived().TransformType(E->getBaseType());
13863     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13864   }
13865 
13866   // Transform the first part of the nested-name-specifier that qualifies
13867   // the member name.
13868   NamedDecl *FirstQualifierInScope
13869     = getDerived().TransformFirstQualifierInScope(
13870                                             E->getFirstQualifierFoundInScope(),
13871                                             E->getQualifierLoc().getBeginLoc());
13872 
13873   NestedNameSpecifierLoc QualifierLoc;
13874   if (E->getQualifier()) {
13875     QualifierLoc
13876       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13877                                                      ObjectType,
13878                                                      FirstQualifierInScope);
13879     if (!QualifierLoc)
13880       return ExprError();
13881   }
13882 
13883   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13884 
13885   // TODO: If this is a conversion-function-id, verify that the
13886   // destination type name (if present) resolves the same way after
13887   // instantiation as it did in the local scope.
13888 
13889   DeclarationNameInfo NameInfo
13890     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13891   if (!NameInfo.getName())
13892     return ExprError();
13893 
13894   if (!E->hasExplicitTemplateArgs()) {
13895     // This is a reference to a member without an explicitly-specified
13896     // template argument list. Optimize for this common case.
13897     if (!getDerived().AlwaysRebuild() &&
13898         Base.get() == OldBase &&
13899         BaseType == E->getBaseType() &&
13900         QualifierLoc == E->getQualifierLoc() &&
13901         NameInfo.getName() == E->getMember() &&
13902         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13903       return E;
13904 
13905     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13906                                                        BaseType,
13907                                                        E->isArrow(),
13908                                                        E->getOperatorLoc(),
13909                                                        QualifierLoc,
13910                                                        TemplateKWLoc,
13911                                                        FirstQualifierInScope,
13912                                                        NameInfo,
13913                                                        /*TemplateArgs*/nullptr);
13914   }
13915 
13916   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13917   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13918                                               E->getNumTemplateArgs(),
13919                                               TransArgs))
13920     return ExprError();
13921 
13922   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13923                                                      BaseType,
13924                                                      E->isArrow(),
13925                                                      E->getOperatorLoc(),
13926                                                      QualifierLoc,
13927                                                      TemplateKWLoc,
13928                                                      FirstQualifierInScope,
13929                                                      NameInfo,
13930                                                      &TransArgs);
13931 }
13932 
13933 template <typename Derived>
13934 ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13935     UnresolvedMemberExpr *Old) {
13936   // Transform the base of the expression.
13937   ExprResult Base((Expr *)nullptr);
13938   QualType BaseType;
13939   if (!Old->isImplicitAccess()) {
13940     Base = getDerived().TransformExpr(Old->getBase());
13941     if (Base.isInvalid())
13942       return ExprError();
13943     Base =
13944         getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13945     if (Base.isInvalid())
13946       return ExprError();
13947     BaseType = Base.get()->getType();
13948   } else {
13949     BaseType = getDerived().TransformType(Old->getBaseType());
13950   }
13951 
13952   NestedNameSpecifierLoc QualifierLoc;
13953   if (Old->getQualifierLoc()) {
13954     QualifierLoc =
13955         getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13956     if (!QualifierLoc)
13957       return ExprError();
13958   }
13959 
13960   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13961 
13962   LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13963 
13964   // Transform the declaration set.
13965   if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13966     return ExprError();
13967 
13968   // Determine the naming class.
13969   if (Old->getNamingClass()) {
13970     CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13971         getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13972     if (!NamingClass)
13973       return ExprError();
13974 
13975     R.setNamingClass(NamingClass);
13976   }
13977 
13978   TemplateArgumentListInfo TransArgs;
13979   if (Old->hasExplicitTemplateArgs()) {
13980     TransArgs.setLAngleLoc(Old->getLAngleLoc());
13981     TransArgs.setRAngleLoc(Old->getRAngleLoc());
13982     if (getDerived().TransformTemplateArguments(
13983             Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13984       return ExprError();
13985   }
13986 
13987   // FIXME: to do this check properly, we will need to preserve the
13988   // first-qualifier-in-scope here, just in case we had a dependent
13989   // base (and therefore couldn't do the check) and a
13990   // nested-name-qualifier (and therefore could do the lookup).
13991   NamedDecl *FirstQualifierInScope = nullptr;
13992 
13993   return getDerived().RebuildUnresolvedMemberExpr(
13994       Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13995       TemplateKWLoc, FirstQualifierInScope, R,
13996       (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13997 }
13998 
13999 template<typename Derived>
14000 ExprResult
14001 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
14002   EnterExpressionEvaluationContext Unevaluated(
14003       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
14004   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
14005   if (SubExpr.isInvalid())
14006     return ExprError();
14007 
14008   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
14009     return E;
14010 
14011   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
14012 }
14013 
14014 template<typename Derived>
14015 ExprResult
14016 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
14017   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
14018   if (Pattern.isInvalid())
14019     return ExprError();
14020 
14021   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
14022     return E;
14023 
14024   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
14025                                            E->getNumExpansions());
14026 }
14027 
14028 template<typename Derived>
14029 ExprResult
14030 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
14031   // If E is not value-dependent, then nothing will change when we transform it.
14032   // Note: This is an instantiation-centric view.
14033   if (!E->isValueDependent())
14034     return E;
14035 
14036   EnterExpressionEvaluationContext Unevaluated(
14037       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
14038 
14039   ArrayRef<TemplateArgument> PackArgs;
14040   TemplateArgument ArgStorage;
14041 
14042   // Find the argument list to transform.
14043   if (E->isPartiallySubstituted()) {
14044     PackArgs = E->getPartialArguments();
14045   } else if (E->isValueDependent()) {
14046     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
14047     bool ShouldExpand = false;
14048     bool RetainExpansion = false;
14049     std::optional<unsigned> NumExpansions;
14050     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
14051                                              Unexpanded,
14052                                              ShouldExpand, RetainExpansion,
14053                                              NumExpansions))
14054       return ExprError();
14055 
14056     // If we need to expand the pack, build a template argument from it and
14057     // expand that.
14058     if (ShouldExpand) {
14059       auto *Pack = E->getPack();
14060       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
14061         ArgStorage = getSema().Context.getPackExpansionType(
14062             getSema().Context.getTypeDeclType(TTPD), std::nullopt);
14063       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
14064         ArgStorage = TemplateArgument(TemplateName(TTPD), std::nullopt);
14065       } else {
14066         auto *VD = cast<ValueDecl>(Pack);
14067         ExprResult DRE = getSema().BuildDeclRefExpr(
14068             VD, VD->getType().getNonLValueExprType(getSema().Context),
14069             VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
14070             E->getPackLoc());
14071         if (DRE.isInvalid())
14072           return ExprError();
14073         ArgStorage = new (getSema().Context)
14074             PackExpansionExpr(getSema().Context.DependentTy, DRE.get(),
14075                               E->getPackLoc(), std::nullopt);
14076       }
14077       PackArgs = ArgStorage;
14078     }
14079   }
14080 
14081   // If we're not expanding the pack, just transform the decl.
14082   if (!PackArgs.size()) {
14083     auto *Pack = cast_or_null<NamedDecl>(
14084         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
14085     if (!Pack)
14086       return ExprError();
14087     return getDerived().RebuildSizeOfPackExpr(
14088         E->getOperatorLoc(), Pack, E->getPackLoc(), E->getRParenLoc(),
14089         std::nullopt, std::nullopt);
14090   }
14091 
14092   // Try to compute the result without performing a partial substitution.
14093   std::optional<unsigned> Result = 0;
14094   for (const TemplateArgument &Arg : PackArgs) {
14095     if (!Arg.isPackExpansion()) {
14096       Result = *Result + 1;
14097       continue;
14098     }
14099 
14100     TemplateArgumentLoc ArgLoc;
14101     InventTemplateArgumentLoc(Arg, ArgLoc);
14102 
14103     // Find the pattern of the pack expansion.
14104     SourceLocation Ellipsis;
14105     std::optional<unsigned> OrigNumExpansions;
14106     TemplateArgumentLoc Pattern =
14107         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
14108                                                           OrigNumExpansions);
14109 
14110     // Substitute under the pack expansion. Do not expand the pack (yet).
14111     TemplateArgumentLoc OutPattern;
14112     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14113     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
14114                                                /*Uneval*/ true))
14115       return true;
14116 
14117     // See if we can determine the number of arguments from the result.
14118     std::optional<unsigned> NumExpansions =
14119         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
14120     if (!NumExpansions) {
14121       // No: we must be in an alias template expansion, and we're going to need
14122       // to actually expand the packs.
14123       Result = std::nullopt;
14124       break;
14125     }
14126 
14127     Result = *Result + *NumExpansions;
14128   }
14129 
14130   // Common case: we could determine the number of expansions without
14131   // substituting.
14132   if (Result)
14133     return getDerived().RebuildSizeOfPackExpr(
14134         E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
14135         *Result, std::nullopt);
14136 
14137   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
14138                                                E->getPackLoc());
14139   {
14140     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
14141     typedef TemplateArgumentLocInventIterator<
14142         Derived, const TemplateArgument*> PackLocIterator;
14143     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
14144                                    PackLocIterator(*this, PackArgs.end()),
14145                                    TransformedPackArgs, /*Uneval*/true))
14146       return ExprError();
14147   }
14148 
14149   // Check whether we managed to fully-expand the pack.
14150   // FIXME: Is it possible for us to do so and not hit the early exit path?
14151   SmallVector<TemplateArgument, 8> Args;
14152   bool PartialSubstitution = false;
14153   for (auto &Loc : TransformedPackArgs.arguments()) {
14154     Args.push_back(Loc.getArgument());
14155     if (Loc.getArgument().isPackExpansion())
14156       PartialSubstitution = true;
14157   }
14158 
14159   if (PartialSubstitution)
14160     return getDerived().RebuildSizeOfPackExpr(
14161         E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
14162         std::nullopt, Args);
14163 
14164   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
14165                                             E->getPackLoc(), E->getRParenLoc(),
14166                                             Args.size(), std::nullopt);
14167 }
14168 
14169 template<typename Derived>
14170 ExprResult
14171 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
14172                                           SubstNonTypeTemplateParmPackExpr *E) {
14173   // Default behavior is to do nothing with this transformation.
14174   return E;
14175 }
14176 
14177 template<typename Derived>
14178 ExprResult
14179 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
14180                                           SubstNonTypeTemplateParmExpr *E) {
14181   // Default behavior is to do nothing with this transformation.
14182   return E;
14183 }
14184 
14185 template<typename Derived>
14186 ExprResult
14187 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
14188   // Default behavior is to do nothing with this transformation.
14189   return E;
14190 }
14191 
14192 template<typename Derived>
14193 ExprResult
14194 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
14195                                                   MaterializeTemporaryExpr *E) {
14196   return getDerived().TransformExpr(E->getSubExpr());
14197 }
14198 
14199 template<typename Derived>
14200 ExprResult
14201 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
14202   UnresolvedLookupExpr *Callee = nullptr;
14203   if (Expr *OldCallee = E->getCallee()) {
14204     ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
14205     if (CalleeResult.isInvalid())
14206       return ExprError();
14207     Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
14208   }
14209 
14210   Expr *Pattern = E->getPattern();
14211 
14212   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14213   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
14214   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
14215 
14216   // Determine whether the set of unexpanded parameter packs can and should
14217   // be expanded.
14218   bool Expand = true;
14219   bool RetainExpansion = false;
14220   std::optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
14221                           NumExpansions = OrigNumExpansions;
14222   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
14223                                            Pattern->getSourceRange(),
14224                                            Unexpanded,
14225                                            Expand, RetainExpansion,
14226                                            NumExpansions))
14227     return true;
14228 
14229   if (!Expand) {
14230     // Do not expand any packs here, just transform and rebuild a fold
14231     // expression.
14232     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14233 
14234     ExprResult LHS =
14235         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
14236     if (LHS.isInvalid())
14237       return true;
14238 
14239     ExprResult RHS =
14240         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
14241     if (RHS.isInvalid())
14242       return true;
14243 
14244     if (!getDerived().AlwaysRebuild() &&
14245         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
14246       return E;
14247 
14248     return getDerived().RebuildCXXFoldExpr(
14249         Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
14250         E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
14251   }
14252 
14253   // Formally a fold expression expands to nested parenthesized expressions.
14254   // Enforce this limit to avoid creating trees so deep we can't safely traverse
14255   // them.
14256   if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
14257     SemaRef.Diag(E->getEllipsisLoc(),
14258                  clang::diag::err_fold_expression_limit_exceeded)
14259         << *NumExpansions << SemaRef.getLangOpts().BracketDepth
14260         << E->getSourceRange();
14261     SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
14262     return ExprError();
14263   }
14264 
14265   // The transform has determined that we should perform an elementwise
14266   // expansion of the pattern. Do so.
14267   ExprResult Result = getDerived().TransformExpr(E->getInit());
14268   if (Result.isInvalid())
14269     return true;
14270   bool LeftFold = E->isLeftFold();
14271 
14272   // If we're retaining an expansion for a right fold, it is the innermost
14273   // component and takes the init (if any).
14274   if (!LeftFold && RetainExpansion) {
14275     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14276 
14277     ExprResult Out = getDerived().TransformExpr(Pattern);
14278     if (Out.isInvalid())
14279       return true;
14280 
14281     Result = getDerived().RebuildCXXFoldExpr(
14282         Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
14283         E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
14284     if (Result.isInvalid())
14285       return true;
14286   }
14287 
14288   for (unsigned I = 0; I != *NumExpansions; ++I) {
14289     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
14290         getSema(), LeftFold ? I : *NumExpansions - I - 1);
14291     ExprResult Out = getDerived().TransformExpr(Pattern);
14292     if (Out.isInvalid())
14293       return true;
14294 
14295     if (Out.get()->containsUnexpandedParameterPack()) {
14296       // We still have a pack; retain a pack expansion for this slice.
14297       Result = getDerived().RebuildCXXFoldExpr(
14298           Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
14299           E->getOperator(), E->getEllipsisLoc(),
14300           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
14301           OrigNumExpansions);
14302     } else if (Result.isUsable()) {
14303       // We've got down to a single element; build a binary operator.
14304       Expr *LHS = LeftFold ? Result.get() : Out.get();
14305       Expr *RHS = LeftFold ? Out.get() : Result.get();
14306       if (Callee) {
14307         UnresolvedSet<16> Functions;
14308         Functions.append(Callee->decls_begin(), Callee->decls_end());
14309         Result = getDerived().RebuildCXXOperatorCallExpr(
14310             BinaryOperator::getOverloadedOperator(E->getOperator()),
14311             E->getEllipsisLoc(), Callee->getBeginLoc(), Callee->requiresADL(),
14312             Functions, LHS, RHS);
14313       } else {
14314         Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
14315                                                     E->getOperator(), LHS, RHS);
14316       }
14317     } else
14318       Result = Out;
14319 
14320     if (Result.isInvalid())
14321       return true;
14322   }
14323 
14324   // If we're retaining an expansion for a left fold, it is the outermost
14325   // component and takes the complete expansion so far as its init (if any).
14326   if (LeftFold && RetainExpansion) {
14327     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14328 
14329     ExprResult Out = getDerived().TransformExpr(Pattern);
14330     if (Out.isInvalid())
14331       return true;
14332 
14333     Result = getDerived().RebuildCXXFoldExpr(
14334         Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
14335         E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
14336     if (Result.isInvalid())
14337       return true;
14338   }
14339 
14340   // If we had no init and an empty pack, and we're not retaining an expansion,
14341   // then produce a fallback value or error.
14342   if (Result.isUnset())
14343     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
14344                                                 E->getOperator());
14345 
14346   return Result;
14347 }
14348 
14349 template <typename Derived>
14350 ExprResult
14351 TreeTransform<Derived>::TransformCXXParenListInitExpr(CXXParenListInitExpr *E) {
14352   SmallVector<Expr *, 4> TransformedInits;
14353   ArrayRef<Expr *> InitExprs = E->getInitExprs();
14354   if (TransformExprs(InitExprs.data(), InitExprs.size(), true,
14355                      TransformedInits))
14356     return ExprError();
14357 
14358   return getDerived().RebuildParenListExpr(E->getBeginLoc(), TransformedInits,
14359                                            E->getEndLoc());
14360 }
14361 
14362 template<typename Derived>
14363 ExprResult
14364 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
14365     CXXStdInitializerListExpr *E) {
14366   return getDerived().TransformExpr(E->getSubExpr());
14367 }
14368 
14369 template<typename Derived>
14370 ExprResult
14371 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
14372   return SemaRef.MaybeBindToTemporary(E);
14373 }
14374 
14375 template<typename Derived>
14376 ExprResult
14377 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
14378   return E;
14379 }
14380 
14381 template<typename Derived>
14382 ExprResult
14383 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
14384   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
14385   if (SubExpr.isInvalid())
14386     return ExprError();
14387 
14388   if (!getDerived().AlwaysRebuild() &&
14389       SubExpr.get() == E->getSubExpr())
14390     return E;
14391 
14392   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
14393 }
14394 
14395 template<typename Derived>
14396 ExprResult
14397 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
14398   // Transform each of the elements.
14399   SmallVector<Expr *, 8> Elements;
14400   bool ArgChanged = false;
14401   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
14402                                   /*IsCall=*/false, Elements, &ArgChanged))
14403     return ExprError();
14404 
14405   if (!getDerived().AlwaysRebuild() && !ArgChanged)
14406     return SemaRef.MaybeBindToTemporary(E);
14407 
14408   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
14409                                               Elements.data(),
14410                                               Elements.size());
14411 }
14412 
14413 template<typename Derived>
14414 ExprResult
14415 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
14416                                                     ObjCDictionaryLiteral *E) {
14417   // Transform each of the elements.
14418   SmallVector<ObjCDictionaryElement, 8> Elements;
14419   bool ArgChanged = false;
14420   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
14421     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
14422 
14423     if (OrigElement.isPackExpansion()) {
14424       // This key/value element is a pack expansion.
14425       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14426       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
14427       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
14428       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
14429 
14430       // Determine whether the set of unexpanded parameter packs can
14431       // and should be expanded.
14432       bool Expand = true;
14433       bool RetainExpansion = false;
14434       std::optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
14435       std::optional<unsigned> NumExpansions = OrigNumExpansions;
14436       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
14437                                OrigElement.Value->getEndLoc());
14438       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
14439                                                PatternRange, Unexpanded, Expand,
14440                                                RetainExpansion, NumExpansions))
14441         return ExprError();
14442 
14443       if (!Expand) {
14444         // The transform has determined that we should perform a simple
14445         // transformation on the pack expansion, producing another pack
14446         // expansion.
14447         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14448         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14449         if (Key.isInvalid())
14450           return ExprError();
14451 
14452         if (Key.get() != OrigElement.Key)
14453           ArgChanged = true;
14454 
14455         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14456         if (Value.isInvalid())
14457           return ExprError();
14458 
14459         if (Value.get() != OrigElement.Value)
14460           ArgChanged = true;
14461 
14462         ObjCDictionaryElement Expansion = {
14463           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
14464         };
14465         Elements.push_back(Expansion);
14466         continue;
14467       }
14468 
14469       // Record right away that the argument was changed.  This needs
14470       // to happen even if the array expands to nothing.
14471       ArgChanged = true;
14472 
14473       // The transform has determined that we should perform an elementwise
14474       // expansion of the pattern. Do so.
14475       for (unsigned I = 0; I != *NumExpansions; ++I) {
14476         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
14477         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14478         if (Key.isInvalid())
14479           return ExprError();
14480 
14481         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14482         if (Value.isInvalid())
14483           return ExprError();
14484 
14485         ObjCDictionaryElement Element = {
14486           Key.get(), Value.get(), SourceLocation(), NumExpansions
14487         };
14488 
14489         // If any unexpanded parameter packs remain, we still have a
14490         // pack expansion.
14491         // FIXME: Can this really happen?
14492         if (Key.get()->containsUnexpandedParameterPack() ||
14493             Value.get()->containsUnexpandedParameterPack())
14494           Element.EllipsisLoc = OrigElement.EllipsisLoc;
14495 
14496         Elements.push_back(Element);
14497       }
14498 
14499       // FIXME: Retain a pack expansion if RetainExpansion is true.
14500 
14501       // We've finished with this pack expansion.
14502       continue;
14503     }
14504 
14505     // Transform and check key.
14506     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14507     if (Key.isInvalid())
14508       return ExprError();
14509 
14510     if (Key.get() != OrigElement.Key)
14511       ArgChanged = true;
14512 
14513     // Transform and check value.
14514     ExprResult Value
14515       = getDerived().TransformExpr(OrigElement.Value);
14516     if (Value.isInvalid())
14517       return ExprError();
14518 
14519     if (Value.get() != OrigElement.Value)
14520       ArgChanged = true;
14521 
14522     ObjCDictionaryElement Element = {Key.get(), Value.get(), SourceLocation(),
14523                                      std::nullopt};
14524     Elements.push_back(Element);
14525   }
14526 
14527   if (!getDerived().AlwaysRebuild() && !ArgChanged)
14528     return SemaRef.MaybeBindToTemporary(E);
14529 
14530   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
14531                                                    Elements);
14532 }
14533 
14534 template<typename Derived>
14535 ExprResult
14536 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
14537   TypeSourceInfo *EncodedTypeInfo
14538     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
14539   if (!EncodedTypeInfo)
14540     return ExprError();
14541 
14542   if (!getDerived().AlwaysRebuild() &&
14543       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
14544     return E;
14545 
14546   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
14547                                             EncodedTypeInfo,
14548                                             E->getRParenLoc());
14549 }
14550 
14551 template<typename Derived>
14552 ExprResult TreeTransform<Derived>::
14553 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
14554   // This is a kind of implicit conversion, and it needs to get dropped
14555   // and recomputed for the same general reasons that ImplicitCastExprs
14556   // do, as well a more specific one: this expression is only valid when
14557   // it appears *immediately* as an argument expression.
14558   return getDerived().TransformExpr(E->getSubExpr());
14559 }
14560 
14561 template<typename Derived>
14562 ExprResult TreeTransform<Derived>::
14563 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
14564   TypeSourceInfo *TSInfo
14565     = getDerived().TransformType(E->getTypeInfoAsWritten());
14566   if (!TSInfo)
14567     return ExprError();
14568 
14569   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
14570   if (Result.isInvalid())
14571     return ExprError();
14572 
14573   if (!getDerived().AlwaysRebuild() &&
14574       TSInfo == E->getTypeInfoAsWritten() &&
14575       Result.get() == E->getSubExpr())
14576     return E;
14577 
14578   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
14579                                       E->getBridgeKeywordLoc(), TSInfo,
14580                                       Result.get());
14581 }
14582 
14583 template <typename Derived>
14584 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
14585     ObjCAvailabilityCheckExpr *E) {
14586   return E;
14587 }
14588 
14589 template<typename Derived>
14590 ExprResult
14591 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
14592   // Transform arguments.
14593   bool ArgChanged = false;
14594   SmallVector<Expr*, 8> Args;
14595   Args.reserve(E->getNumArgs());
14596   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
14597                                   &ArgChanged))
14598     return ExprError();
14599 
14600   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
14601     // Class message: transform the receiver type.
14602     TypeSourceInfo *ReceiverTypeInfo
14603       = getDerived().TransformType(E->getClassReceiverTypeInfo());
14604     if (!ReceiverTypeInfo)
14605       return ExprError();
14606 
14607     // If nothing changed, just retain the existing message send.
14608     if (!getDerived().AlwaysRebuild() &&
14609         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
14610       return SemaRef.MaybeBindToTemporary(E);
14611 
14612     // Build a new class message send.
14613     SmallVector<SourceLocation, 16> SelLocs;
14614     E->getSelectorLocs(SelLocs);
14615     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
14616                                                E->getSelector(),
14617                                                SelLocs,
14618                                                E->getMethodDecl(),
14619                                                E->getLeftLoc(),
14620                                                Args,
14621                                                E->getRightLoc());
14622   }
14623   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
14624            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14625     if (!E->getMethodDecl())
14626       return ExprError();
14627 
14628     // Build a new class message send to 'super'.
14629     SmallVector<SourceLocation, 16> SelLocs;
14630     E->getSelectorLocs(SelLocs);
14631     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
14632                                                E->getSelector(),
14633                                                SelLocs,
14634                                                E->getReceiverType(),
14635                                                E->getMethodDecl(),
14636                                                E->getLeftLoc(),
14637                                                Args,
14638                                                E->getRightLoc());
14639   }
14640 
14641   // Instance message: transform the receiver
14642   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
14643          "Only class and instance messages may be instantiated");
14644   ExprResult Receiver
14645     = getDerived().TransformExpr(E->getInstanceReceiver());
14646   if (Receiver.isInvalid())
14647     return ExprError();
14648 
14649   // If nothing changed, just retain the existing message send.
14650   if (!getDerived().AlwaysRebuild() &&
14651       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
14652     return SemaRef.MaybeBindToTemporary(E);
14653 
14654   // Build a new instance message send.
14655   SmallVector<SourceLocation, 16> SelLocs;
14656   E->getSelectorLocs(SelLocs);
14657   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
14658                                              E->getSelector(),
14659                                              SelLocs,
14660                                              E->getMethodDecl(),
14661                                              E->getLeftLoc(),
14662                                              Args,
14663                                              E->getRightLoc());
14664 }
14665 
14666 template<typename Derived>
14667 ExprResult
14668 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
14669   return E;
14670 }
14671 
14672 template<typename Derived>
14673 ExprResult
14674 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
14675   return E;
14676 }
14677 
14678 template<typename Derived>
14679 ExprResult
14680 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
14681   // Transform the base expression.
14682   ExprResult Base = getDerived().TransformExpr(E->getBase());
14683   if (Base.isInvalid())
14684     return ExprError();
14685 
14686   // We don't need to transform the ivar; it will never change.
14687 
14688   // If nothing changed, just retain the existing expression.
14689   if (!getDerived().AlwaysRebuild() &&
14690       Base.get() == E->getBase())
14691     return E;
14692 
14693   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
14694                                              E->getLocation(),
14695                                              E->isArrow(), E->isFreeIvar());
14696 }
14697 
14698 template<typename Derived>
14699 ExprResult
14700 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
14701   // 'super' and types never change. Property never changes. Just
14702   // retain the existing expression.
14703   if (!E->isObjectReceiver())
14704     return E;
14705 
14706   // Transform the base expression.
14707   ExprResult Base = getDerived().TransformExpr(E->getBase());
14708   if (Base.isInvalid())
14709     return ExprError();
14710 
14711   // We don't need to transform the property; it will never change.
14712 
14713   // If nothing changed, just retain the existing expression.
14714   if (!getDerived().AlwaysRebuild() &&
14715       Base.get() == E->getBase())
14716     return E;
14717 
14718   if (E->isExplicitProperty())
14719     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14720                                                    E->getExplicitProperty(),
14721                                                    E->getLocation());
14722 
14723   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14724                                                  SemaRef.Context.PseudoObjectTy,
14725                                                  E->getImplicitPropertyGetter(),
14726                                                  E->getImplicitPropertySetter(),
14727                                                  E->getLocation());
14728 }
14729 
14730 template<typename Derived>
14731 ExprResult
14732 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
14733   // Transform the base expression.
14734   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
14735   if (Base.isInvalid())
14736     return ExprError();
14737 
14738   // Transform the key expression.
14739   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
14740   if (Key.isInvalid())
14741     return ExprError();
14742 
14743   // If nothing changed, just retain the existing expression.
14744   if (!getDerived().AlwaysRebuild() &&
14745       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
14746     return E;
14747 
14748   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
14749                                                   Base.get(), Key.get(),
14750                                                   E->getAtIndexMethodDecl(),
14751                                                   E->setAtIndexMethodDecl());
14752 }
14753 
14754 template<typename Derived>
14755 ExprResult
14756 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
14757   // Transform the base expression.
14758   ExprResult Base = getDerived().TransformExpr(E->getBase());
14759   if (Base.isInvalid())
14760     return ExprError();
14761 
14762   // If nothing changed, just retain the existing expression.
14763   if (!getDerived().AlwaysRebuild() &&
14764       Base.get() == E->getBase())
14765     return E;
14766 
14767   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14768                                          E->getOpLoc(),
14769                                          E->isArrow());
14770 }
14771 
14772 template<typename Derived>
14773 ExprResult
14774 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14775   bool ArgumentChanged = false;
14776   SmallVector<Expr*, 8> SubExprs;
14777   SubExprs.reserve(E->getNumSubExprs());
14778   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14779                                   SubExprs, &ArgumentChanged))
14780     return ExprError();
14781 
14782   if (!getDerived().AlwaysRebuild() &&
14783       !ArgumentChanged)
14784     return E;
14785 
14786   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14787                                                SubExprs,
14788                                                E->getRParenLoc());
14789 }
14790 
14791 template<typename Derived>
14792 ExprResult
14793 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14794   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14795   if (SrcExpr.isInvalid())
14796     return ExprError();
14797 
14798   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14799   if (!Type)
14800     return ExprError();
14801 
14802   if (!getDerived().AlwaysRebuild() &&
14803       Type == E->getTypeSourceInfo() &&
14804       SrcExpr.get() == E->getSrcExpr())
14805     return E;
14806 
14807   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14808                                                SrcExpr.get(), Type,
14809                                                E->getRParenLoc());
14810 }
14811 
14812 template<typename Derived>
14813 ExprResult
14814 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14815   BlockDecl *oldBlock = E->getBlockDecl();
14816 
14817   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14818   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14819 
14820   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14821   blockScope->TheDecl->setBlockMissingReturnType(
14822                          oldBlock->blockMissingReturnType());
14823 
14824   SmallVector<ParmVarDecl*, 4> params;
14825   SmallVector<QualType, 4> paramTypes;
14826 
14827   const FunctionProtoType *exprFunctionType = E->getFunctionType();
14828 
14829   // Parameter substitution.
14830   Sema::ExtParameterInfoBuilder extParamInfos;
14831   if (getDerived().TransformFunctionTypeParams(
14832           E->getCaretLocation(), oldBlock->parameters(), nullptr,
14833           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14834           extParamInfos)) {
14835     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14836     return ExprError();
14837   }
14838 
14839   QualType exprResultType =
14840       getDerived().TransformType(exprFunctionType->getReturnType());
14841 
14842   auto epi = exprFunctionType->getExtProtoInfo();
14843   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14844 
14845   QualType functionType =
14846     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14847   blockScope->FunctionType = functionType;
14848 
14849   // Set the parameters on the block decl.
14850   if (!params.empty())
14851     blockScope->TheDecl->setParams(params);
14852 
14853   if (!oldBlock->blockMissingReturnType()) {
14854     blockScope->HasImplicitReturnType = false;
14855     blockScope->ReturnType = exprResultType;
14856   }
14857 
14858   // Transform the body
14859   StmtResult body = getDerived().TransformStmt(E->getBody());
14860   if (body.isInvalid()) {
14861     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14862     return ExprError();
14863   }
14864 
14865 #ifndef NDEBUG
14866   // In builds with assertions, make sure that we captured everything we
14867   // captured before.
14868   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14869     for (const auto &I : oldBlock->captures()) {
14870       VarDecl *oldCapture = I.getVariable();
14871 
14872       // Ignore parameter packs.
14873       if (oldCapture->isParameterPack())
14874         continue;
14875 
14876       VarDecl *newCapture =
14877         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14878                                                  oldCapture));
14879       assert(blockScope->CaptureMap.count(newCapture));
14880     }
14881 
14882     // The this pointer may not be captured by the instantiated block, even when
14883     // it's captured by the original block, if the expression causing the
14884     // capture is in the discarded branch of a constexpr if statement.
14885     assert((!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) &&
14886            "this pointer isn't captured in the old block");
14887   }
14888 #endif
14889 
14890   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14891                                     /*Scope=*/nullptr);
14892 }
14893 
14894 template<typename Derived>
14895 ExprResult
14896 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14897   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14898   if (SrcExpr.isInvalid())
14899     return ExprError();
14900 
14901   QualType Type = getDerived().TransformType(E->getType());
14902 
14903   return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14904                                  E->getRParenLoc());
14905 }
14906 
14907 template<typename Derived>
14908 ExprResult
14909 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14910   bool ArgumentChanged = false;
14911   SmallVector<Expr*, 8> SubExprs;
14912   SubExprs.reserve(E->getNumSubExprs());
14913   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14914                                   SubExprs, &ArgumentChanged))
14915     return ExprError();
14916 
14917   if (!getDerived().AlwaysRebuild() &&
14918       !ArgumentChanged)
14919     return E;
14920 
14921   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14922                                         E->getOp(), E->getRParenLoc());
14923 }
14924 
14925 //===----------------------------------------------------------------------===//
14926 // Type reconstruction
14927 //===----------------------------------------------------------------------===//
14928 
14929 template<typename Derived>
14930 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14931                                                     SourceLocation Star) {
14932   return SemaRef.BuildPointerType(PointeeType, Star,
14933                                   getDerived().getBaseEntity());
14934 }
14935 
14936 template<typename Derived>
14937 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14938                                                          SourceLocation Star) {
14939   return SemaRef.BuildBlockPointerType(PointeeType, Star,
14940                                        getDerived().getBaseEntity());
14941 }
14942 
14943 template<typename Derived>
14944 QualType
14945 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14946                                              bool WrittenAsLValue,
14947                                              SourceLocation Sigil) {
14948   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14949                                     Sigil, getDerived().getBaseEntity());
14950 }
14951 
14952 template<typename Derived>
14953 QualType
14954 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14955                                                  QualType ClassType,
14956                                                  SourceLocation Sigil) {
14957   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14958                                         getDerived().getBaseEntity());
14959 }
14960 
14961 template<typename Derived>
14962 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14963            const ObjCTypeParamDecl *Decl,
14964            SourceLocation ProtocolLAngleLoc,
14965            ArrayRef<ObjCProtocolDecl *> Protocols,
14966            ArrayRef<SourceLocation> ProtocolLocs,
14967            SourceLocation ProtocolRAngleLoc) {
14968   return SemaRef.BuildObjCTypeParamType(Decl,
14969                                         ProtocolLAngleLoc, Protocols,
14970                                         ProtocolLocs, ProtocolRAngleLoc,
14971                                         /*FailOnError=*/true);
14972 }
14973 
14974 template<typename Derived>
14975 QualType TreeTransform<Derived>::RebuildObjCObjectType(
14976            QualType BaseType,
14977            SourceLocation Loc,
14978            SourceLocation TypeArgsLAngleLoc,
14979            ArrayRef<TypeSourceInfo *> TypeArgs,
14980            SourceLocation TypeArgsRAngleLoc,
14981            SourceLocation ProtocolLAngleLoc,
14982            ArrayRef<ObjCProtocolDecl *> Protocols,
14983            ArrayRef<SourceLocation> ProtocolLocs,
14984            SourceLocation ProtocolRAngleLoc) {
14985   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc, TypeArgs,
14986                                      TypeArgsRAngleLoc, ProtocolLAngleLoc,
14987                                      Protocols, ProtocolLocs, ProtocolRAngleLoc,
14988                                      /*FailOnError=*/true,
14989                                      /*Rebuilding=*/true);
14990 }
14991 
14992 template<typename Derived>
14993 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14994            QualType PointeeType,
14995            SourceLocation Star) {
14996   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14997 }
14998 
14999 template <typename Derived>
15000 QualType TreeTransform<Derived>::RebuildArrayType(
15001     QualType ElementType, ArraySizeModifier SizeMod, const llvm::APInt *Size,
15002     Expr *SizeExpr, unsigned IndexTypeQuals, SourceRange BracketsRange) {
15003   if (SizeExpr || !Size)
15004     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
15005                                   IndexTypeQuals, BracketsRange,
15006                                   getDerived().getBaseEntity());
15007 
15008   QualType Types[] = {
15009     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
15010     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
15011     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
15012   };
15013   QualType SizeType;
15014   for (const auto &T : Types)
15015     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(T)) {
15016       SizeType = T;
15017       break;
15018     }
15019 
15020   // Note that we can return a VariableArrayType here in the case where
15021   // the element type was a dependent VariableArrayType.
15022   IntegerLiteral *ArraySize
15023       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
15024                                /*FIXME*/BracketsRange.getBegin());
15025   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
15026                                 IndexTypeQuals, BracketsRange,
15027                                 getDerived().getBaseEntity());
15028 }
15029 
15030 template <typename Derived>
15031 QualType TreeTransform<Derived>::RebuildConstantArrayType(
15032     QualType ElementType, ArraySizeModifier SizeMod, const llvm::APInt &Size,
15033     Expr *SizeExpr, unsigned IndexTypeQuals, SourceRange BracketsRange) {
15034   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
15035                                         IndexTypeQuals, BracketsRange);
15036 }
15037 
15038 template <typename Derived>
15039 QualType TreeTransform<Derived>::RebuildIncompleteArrayType(
15040     QualType ElementType, ArraySizeModifier SizeMod, unsigned IndexTypeQuals,
15041     SourceRange BracketsRange) {
15042   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
15043                                        IndexTypeQuals, BracketsRange);
15044 }
15045 
15046 template <typename Derived>
15047 QualType TreeTransform<Derived>::RebuildVariableArrayType(
15048     QualType ElementType, ArraySizeModifier SizeMod, Expr *SizeExpr,
15049     unsigned IndexTypeQuals, SourceRange BracketsRange) {
15050   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
15051                                        SizeExpr,
15052                                        IndexTypeQuals, BracketsRange);
15053 }
15054 
15055 template <typename Derived>
15056 QualType TreeTransform<Derived>::RebuildDependentSizedArrayType(
15057     QualType ElementType, ArraySizeModifier SizeMod, Expr *SizeExpr,
15058     unsigned IndexTypeQuals, SourceRange BracketsRange) {
15059   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
15060                                        SizeExpr,
15061                                        IndexTypeQuals, BracketsRange);
15062 }
15063 
15064 template <typename Derived>
15065 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
15066     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
15067   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
15068                                           AttributeLoc);
15069 }
15070 
15071 template <typename Derived>
15072 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
15073                                                    unsigned NumElements,
15074                                                    VectorKind VecKind) {
15075   // FIXME: semantic checking!
15076   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
15077 }
15078 
15079 template <typename Derived>
15080 QualType TreeTransform<Derived>::RebuildDependentVectorType(
15081     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
15082     VectorKind VecKind) {
15083   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
15084 }
15085 
15086 template<typename Derived>
15087 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
15088                                                       unsigned NumElements,
15089                                                  SourceLocation AttributeLoc) {
15090   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
15091                           NumElements, true);
15092   IntegerLiteral *VectorSize
15093     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
15094                              AttributeLoc);
15095   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
15096 }
15097 
15098 template<typename Derived>
15099 QualType
15100 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
15101                                                            Expr *SizeExpr,
15102                                                   SourceLocation AttributeLoc) {
15103   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
15104 }
15105 
15106 template <typename Derived>
15107 QualType TreeTransform<Derived>::RebuildConstantMatrixType(
15108     QualType ElementType, unsigned NumRows, unsigned NumColumns) {
15109   return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
15110                                                NumColumns);
15111 }
15112 
15113 template <typename Derived>
15114 QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
15115     QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
15116     SourceLocation AttributeLoc) {
15117   return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
15118                                  AttributeLoc);
15119 }
15120 
15121 template<typename Derived>
15122 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
15123     QualType T,
15124     MutableArrayRef<QualType> ParamTypes,
15125     const FunctionProtoType::ExtProtoInfo &EPI) {
15126   return SemaRef.BuildFunctionType(T, ParamTypes,
15127                                    getDerived().getBaseLocation(),
15128                                    getDerived().getBaseEntity(),
15129                                    EPI);
15130 }
15131 
15132 template<typename Derived>
15133 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
15134   return SemaRef.Context.getFunctionNoProtoType(T);
15135 }
15136 
15137 template<typename Derived>
15138 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
15139                                                             Decl *D) {
15140   assert(D && "no decl found");
15141   if (D->isInvalidDecl()) return QualType();
15142 
15143   // FIXME: Doesn't account for ObjCInterfaceDecl!
15144   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
15145     // A valid resolved using typename pack expansion decl can have multiple
15146     // UsingDecls, but they must each have exactly one type, and it must be
15147     // the same type in every case. But we must have at least one expansion!
15148     if (UPD->expansions().empty()) {
15149       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
15150           << UPD->isCXXClassMember() << UPD;
15151       return QualType();
15152     }
15153 
15154     // We might still have some unresolved types. Try to pick a resolved type
15155     // if we can. The final instantiation will check that the remaining
15156     // unresolved types instantiate to the type we pick.
15157     QualType FallbackT;
15158     QualType T;
15159     for (auto *E : UPD->expansions()) {
15160       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
15161       if (ThisT.isNull())
15162         continue;
15163       else if (ThisT->getAs<UnresolvedUsingType>())
15164         FallbackT = ThisT;
15165       else if (T.isNull())
15166         T = ThisT;
15167       else
15168         assert(getSema().Context.hasSameType(ThisT, T) &&
15169                "mismatched resolved types in using pack expansion");
15170     }
15171     return T.isNull() ? FallbackT : T;
15172   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
15173     assert(Using->hasTypename() &&
15174            "UnresolvedUsingTypenameDecl transformed to non-typename using");
15175 
15176     // A valid resolved using typename decl points to exactly one type decl.
15177     assert(++Using->shadow_begin() == Using->shadow_end());
15178 
15179     UsingShadowDecl *Shadow = *Using->shadow_begin();
15180     if (SemaRef.DiagnoseUseOfDecl(Shadow->getTargetDecl(), Loc))
15181       return QualType();
15182     return SemaRef.Context.getUsingType(
15183         Shadow, SemaRef.Context.getTypeDeclType(
15184                     cast<TypeDecl>(Shadow->getTargetDecl())));
15185   } else {
15186     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
15187            "UnresolvedUsingTypenameDecl transformed to non-using decl");
15188     return SemaRef.Context.getTypeDeclType(
15189         cast<UnresolvedUsingTypenameDecl>(D));
15190   }
15191 }
15192 
15193 template <typename Derived>
15194 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E, SourceLocation,
15195                                                        TypeOfKind Kind) {
15196   return SemaRef.BuildTypeofExprType(E, Kind);
15197 }
15198 
15199 template<typename Derived>
15200 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying,
15201                                                    TypeOfKind Kind) {
15202   return SemaRef.Context.getTypeOfType(Underlying, Kind);
15203 }
15204 
15205 template <typename Derived>
15206 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E, SourceLocation) {
15207   return SemaRef.BuildDecltypeType(E);
15208 }
15209 
15210 template<typename Derived>
15211 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
15212                                             UnaryTransformType::UTTKind UKind,
15213                                             SourceLocation Loc) {
15214   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
15215 }
15216 
15217 template<typename Derived>
15218 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
15219                                                       TemplateName Template,
15220                                              SourceLocation TemplateNameLoc,
15221                                      TemplateArgumentListInfo &TemplateArgs) {
15222   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
15223 }
15224 
15225 template<typename Derived>
15226 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
15227                                                    SourceLocation KWLoc) {
15228   return SemaRef.BuildAtomicType(ValueType, KWLoc);
15229 }
15230 
15231 template<typename Derived>
15232 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
15233                                                  SourceLocation KWLoc,
15234                                                  bool isReadPipe) {
15235   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
15236                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
15237 }
15238 
15239 template <typename Derived>
15240 QualType TreeTransform<Derived>::RebuildBitIntType(bool IsUnsigned,
15241                                                    unsigned NumBits,
15242                                                    SourceLocation Loc) {
15243   llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
15244                         NumBits, true);
15245   IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
15246                                                 SemaRef.Context.IntTy, Loc);
15247   return SemaRef.BuildBitIntType(IsUnsigned, Bits, Loc);
15248 }
15249 
15250 template <typename Derived>
15251 QualType TreeTransform<Derived>::RebuildDependentBitIntType(
15252     bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
15253   return SemaRef.BuildBitIntType(IsUnsigned, NumBitsExpr, Loc);
15254 }
15255 
15256 template<typename Derived>
15257 TemplateName
15258 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15259                                             bool TemplateKW,
15260                                             TemplateDecl *Template) {
15261   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
15262                                                   TemplateName(Template));
15263 }
15264 
15265 template<typename Derived>
15266 TemplateName
15267 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15268                                             SourceLocation TemplateKWLoc,
15269                                             const IdentifierInfo &Name,
15270                                             SourceLocation NameLoc,
15271                                             QualType ObjectType,
15272                                             NamedDecl *FirstQualifierInScope,
15273                                             bool AllowInjectedClassName) {
15274   UnqualifiedId TemplateName;
15275   TemplateName.setIdentifier(&Name, NameLoc);
15276   Sema::TemplateTy Template;
15277   getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
15278                               TemplateName, ParsedType::make(ObjectType),
15279                               /*EnteringContext=*/false, Template,
15280                               AllowInjectedClassName);
15281   return Template.get();
15282 }
15283 
15284 template<typename Derived>
15285 TemplateName
15286 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15287                                             SourceLocation TemplateKWLoc,
15288                                             OverloadedOperatorKind Operator,
15289                                             SourceLocation NameLoc,
15290                                             QualType ObjectType,
15291                                             bool AllowInjectedClassName) {
15292   UnqualifiedId Name;
15293   // FIXME: Bogus location information.
15294   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
15295   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
15296   Sema::TemplateTy Template;
15297   getSema().ActOnTemplateName(
15298       /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
15299       /*EnteringContext=*/false, Template, AllowInjectedClassName);
15300   return Template.get();
15301 }
15302 
15303 template <typename Derived>
15304 ExprResult TreeTransform<Derived>::RebuildCXXOperatorCallExpr(
15305     OverloadedOperatorKind Op, SourceLocation OpLoc, SourceLocation CalleeLoc,
15306     bool RequiresADL, const UnresolvedSetImpl &Functions, Expr *First,
15307     Expr *Second) {
15308   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
15309 
15310   if (First->getObjectKind() == OK_ObjCProperty) {
15311     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15312     if (BinaryOperator::isAssignmentOp(Opc))
15313       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
15314                                                  First, Second);
15315     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
15316     if (Result.isInvalid())
15317       return ExprError();
15318     First = Result.get();
15319   }
15320 
15321   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
15322     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
15323     if (Result.isInvalid())
15324       return ExprError();
15325     Second = Result.get();
15326   }
15327 
15328   // Determine whether this should be a builtin operation.
15329   if (Op == OO_Subscript) {
15330     if (!First->getType()->isOverloadableType() &&
15331         !Second->getType()->isOverloadableType())
15332       return getSema().CreateBuiltinArraySubscriptExpr(First, CalleeLoc, Second,
15333                                                        OpLoc);
15334   } else if (Op == OO_Arrow) {
15335     // It is possible that the type refers to a RecoveryExpr created earlier
15336     // in the tree transformation.
15337     if (First->getType()->isDependentType())
15338       return ExprError();
15339     // -> is never a builtin operation.
15340     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
15341   } else if (Second == nullptr || isPostIncDec) {
15342     if (!First->getType()->isOverloadableType() ||
15343         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
15344       // The argument is not of overloadable type, or this is an expression
15345       // of the form &Class::member, so try to create a built-in unary
15346       // operation.
15347       UnaryOperatorKind Opc
15348         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15349 
15350       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
15351     }
15352   } else {
15353     if (!First->getType()->isOverloadableType() &&
15354         !Second->getType()->isOverloadableType()) {
15355       // Neither of the arguments is an overloadable type, so try to
15356       // create a built-in binary operation.
15357       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15358       ExprResult Result
15359         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
15360       if (Result.isInvalid())
15361         return ExprError();
15362 
15363       return Result;
15364     }
15365   }
15366 
15367   // Add any functions found via argument-dependent lookup.
15368   Expr *Args[2] = { First, Second };
15369   unsigned NumArgs = 1 + (Second != nullptr);
15370 
15371   // Create the overloaded operator invocation for unary operators.
15372   if (NumArgs == 1 || isPostIncDec) {
15373     UnaryOperatorKind Opc
15374       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15375     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
15376                                            RequiresADL);
15377   }
15378 
15379   // Create the overloaded operator invocation for binary operators.
15380   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15381   ExprResult Result = SemaRef.CreateOverloadedBinOp(
15382       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
15383   if (Result.isInvalid())
15384     return ExprError();
15385 
15386   return Result;
15387 }
15388 
15389 template<typename Derived>
15390 ExprResult
15391 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
15392                                                      SourceLocation OperatorLoc,
15393                                                        bool isArrow,
15394                                                        CXXScopeSpec &SS,
15395                                                      TypeSourceInfo *ScopeType,
15396                                                        SourceLocation CCLoc,
15397                                                        SourceLocation TildeLoc,
15398                                         PseudoDestructorTypeStorage Destroyed) {
15399   QualType BaseType = Base->getType();
15400   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
15401       (!isArrow && !BaseType->getAs<RecordType>()) ||
15402       (isArrow && BaseType->getAs<PointerType>() &&
15403        !BaseType->castAs<PointerType>()->getPointeeType()
15404                                               ->template getAs<RecordType>())){
15405     // This pseudo-destructor expression is still a pseudo-destructor.
15406     return SemaRef.BuildPseudoDestructorExpr(
15407         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
15408         CCLoc, TildeLoc, Destroyed);
15409   }
15410 
15411   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
15412   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
15413                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
15414   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
15415   NameInfo.setNamedTypeInfo(DestroyedType);
15416 
15417   // The scope type is now known to be a valid nested name specifier
15418   // component. Tack it on to the end of the nested name specifier.
15419   if (ScopeType) {
15420     if (!ScopeType->getType()->getAs<TagType>()) {
15421       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
15422                      diag::err_expected_class_or_namespace)
15423           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
15424       return ExprError();
15425     }
15426     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
15427               CCLoc);
15428   }
15429 
15430   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
15431   return getSema().BuildMemberReferenceExpr(Base, BaseType,
15432                                             OperatorLoc, isArrow,
15433                                             SS, TemplateKWLoc,
15434                                             /*FIXME: FirstQualifier*/ nullptr,
15435                                             NameInfo,
15436                                             /*TemplateArgs*/ nullptr,
15437                                             /*S*/nullptr);
15438 }
15439 
15440 template<typename Derived>
15441 StmtResult
15442 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
15443   SourceLocation Loc = S->getBeginLoc();
15444   CapturedDecl *CD = S->getCapturedDecl();
15445   unsigned NumParams = CD->getNumParams();
15446   unsigned ContextParamPos = CD->getContextParamPosition();
15447   SmallVector<Sema::CapturedParamNameType, 4> Params;
15448   for (unsigned I = 0; I < NumParams; ++I) {
15449     if (I != ContextParamPos) {
15450       Params.push_back(
15451              std::make_pair(
15452                   CD->getParam(I)->getName(),
15453                   getDerived().TransformType(CD->getParam(I)->getType())));
15454     } else {
15455       Params.push_back(std::make_pair(StringRef(), QualType()));
15456     }
15457   }
15458   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
15459                                      S->getCapturedRegionKind(), Params);
15460   StmtResult Body;
15461   {
15462     Sema::CompoundScopeRAII CompoundScope(getSema());
15463     Body = getDerived().TransformStmt(S->getCapturedStmt());
15464   }
15465 
15466   if (Body.isInvalid()) {
15467     getSema().ActOnCapturedRegionError();
15468     return StmtError();
15469   }
15470 
15471   return getSema().ActOnCapturedRegionEnd(Body.get());
15472 }
15473 
15474 } // end namespace clang
15475 
15476 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15477