Home | History | Annotate | Download | only in Sema
      1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //===----------------------------------------------------------------------===//
      8 //
      9 //  This file implements a semantic tree transformation that takes a given
     10 //  AST and rebuilds it, possibly transforming some nodes in the process.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
     15 #define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
     16 
     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/ExprObjC.h"
     24 #include "clang/AST/ExprOpenMP.h"
     25 #include "clang/AST/Stmt.h"
     26 #include "clang/AST/StmtCXX.h"
     27 #include "clang/AST/StmtObjC.h"
     28 #include "clang/AST/StmtOpenMP.h"
     29 #include "clang/Sema/Designator.h"
     30 #include "clang/Sema/Lookup.h"
     31 #include "clang/Sema/Ownership.h"
     32 #include "clang/Sema/ParsedTemplate.h"
     33 #include "clang/Sema/ScopeInfo.h"
     34 #include "clang/Sema/SemaDiagnostic.h"
     35 #include "clang/Sema/SemaInternal.h"
     36 #include "llvm/ADT/ArrayRef.h"
     37 #include "llvm/Support/ErrorHandling.h"
     38 #include <algorithm>
     39 
     40 namespace clang {
     41 using namespace sema;
     42 
     43 /// \brief A semantic tree transformation that allows one to transform one
     44 /// abstract syntax tree into another.
     45 ///
     46 /// A new tree transformation is defined by creating a new subclass \c X of
     47 /// \c TreeTransform<X> and then overriding certain operations to provide
     48 /// behavior specific to that transformation. For example, template
     49 /// instantiation is implemented as a tree transformation where the
     50 /// transformation of TemplateTypeParmType nodes involves substituting the
     51 /// template arguments for their corresponding template parameters; a similar
     52 /// transformation is performed for non-type template parameters and
     53 /// template template parameters.
     54 ///
     55 /// This tree-transformation template uses static polymorphism to allow
     56 /// subclasses to customize any of its operations. Thus, a subclass can
     57 /// override any of the transformation or rebuild operators by providing an
     58 /// operation with the same signature as the default implementation. The
     59 /// overridding function should not be virtual.
     60 ///
     61 /// Semantic tree transformations are split into two stages, either of which
     62 /// can be replaced by a subclass. The "transform" step transforms an AST node
     63 /// or the parts of an AST node using the various transformation functions,
     64 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
     65 /// node of the appropriate kind from the pieces. The default transformation
     66 /// routines recursively transform the operands to composite AST nodes (e.g.,
     67 /// the pointee type of a PointerType node) and, if any of those operand nodes
     68 /// were changed by the transformation, invokes the rebuild operation to create
     69 /// a new AST node.
     70 ///
     71 /// Subclasses can customize the transformation at various levels. The
     72 /// most coarse-grained transformations involve replacing TransformType(),
     73 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
     74 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
     75 /// new implementations.
     76 ///
     77 /// For more fine-grained transformations, subclasses can replace any of the
     78 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
     79 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
     80 /// replacing TransformTemplateTypeParmType() allows template instantiation
     81 /// to substitute template arguments for their corresponding template
     82 /// parameters. Additionally, subclasses can override the \c RebuildXXX
     83 /// functions to control how AST nodes are rebuilt when their operands change.
     84 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
     85 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
     86 /// be able to use more efficient rebuild steps.
     87 ///
     88 /// There are a handful of other functions that can be overridden, allowing one
     89 /// to avoid traversing nodes that don't need any transformation
     90 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
     91 /// operands have not changed (\c AlwaysRebuild()), and customize the
     92 /// default locations and entity names used for type-checking
     93 /// (\c getBaseLocation(), \c getBaseEntity()).
     94 template<typename Derived>
     95 class TreeTransform {
     96   /// \brief Private RAII object that helps us forget and then re-remember
     97   /// the template argument corresponding to a partially-substituted parameter
     98   /// pack.
     99   class ForgetPartiallySubstitutedPackRAII {
    100     Derived &Self;
    101     TemplateArgument Old;
    102 
    103   public:
    104     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
    105       Old = Self.ForgetPartiallySubstitutedPack();
    106     }
    107 
    108     ~ForgetPartiallySubstitutedPackRAII() {
    109       Self.RememberPartiallySubstitutedPack(Old);
    110     }
    111   };
    112 
    113 protected:
    114   Sema &SemaRef;
    115 
    116   /// \brief The set of local declarations that have been transformed, for
    117   /// cases where we are forced to build new declarations within the transformer
    118   /// rather than in the subclass (e.g., lambda closure types).
    119   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
    120 
    121 public:
    122   /// \brief Initializes a new tree transformer.
    123   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
    124 
    125   /// \brief Retrieves a reference to the derived class.
    126   Derived &getDerived() { return static_cast<Derived&>(*this); }
    127 
    128   /// \brief Retrieves a reference to the derived class.
    129   const Derived &getDerived() const {
    130     return static_cast<const Derived&>(*this);
    131   }
    132 
    133   static inline ExprResult Owned(Expr *E) { return E; }
    134   static inline StmtResult Owned(Stmt *S) { return S; }
    135 
    136   /// \brief Retrieves a reference to the semantic analysis object used for
    137   /// this tree transform.
    138   Sema &getSema() const { return SemaRef; }
    139 
    140   /// \brief Whether the transformation should always rebuild AST nodes, even
    141   /// if none of the children have changed.
    142   ///
    143   /// Subclasses may override this function to specify when the transformation
    144   /// should rebuild all AST nodes.
    145   ///
    146   /// We must always rebuild all AST nodes when performing variadic template
    147   /// pack expansion, in order to avoid violating the AST invariant that each
    148   /// statement node appears at most once in its containing declaration.
    149   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
    150 
    151   /// \brief Returns the location of the entity being transformed, if that
    152   /// information was not available elsewhere in the AST.
    153   ///
    154   /// By default, returns no source-location information. Subclasses can
    155   /// provide an alternative implementation that provides better location
    156   /// information.
    157   SourceLocation getBaseLocation() { return SourceLocation(); }
    158 
    159   /// \brief Returns the name of the entity being transformed, if that
    160   /// information was not available elsewhere in the AST.
    161   ///
    162   /// By default, returns an empty name. Subclasses can provide an alternative
    163   /// implementation with a more precise name.
    164   DeclarationName getBaseEntity() { return DeclarationName(); }
    165 
    166   /// \brief Sets the "base" location and entity when that
    167   /// information is known based on another transformation.
    168   ///
    169   /// By default, the source location and entity are ignored. Subclasses can
    170   /// override this function to provide a customized implementation.
    171   void setBase(SourceLocation Loc, DeclarationName Entity) { }
    172 
    173   /// \brief RAII object that temporarily sets the base location and entity
    174   /// used for reporting diagnostics in types.
    175   class TemporaryBase {
    176     TreeTransform &Self;
    177     SourceLocation OldLocation;
    178     DeclarationName OldEntity;
    179 
    180   public:
    181     TemporaryBase(TreeTransform &Self, SourceLocation Location,
    182                   DeclarationName Entity) : Self(Self) {
    183       OldLocation = Self.getDerived().getBaseLocation();
    184       OldEntity = Self.getDerived().getBaseEntity();
    185 
    186       if (Location.isValid())
    187         Self.getDerived().setBase(Location, Entity);
    188     }
    189 
    190     ~TemporaryBase() {
    191       Self.getDerived().setBase(OldLocation, OldEntity);
    192     }
    193   };
    194 
    195   /// \brief Determine whether the given type \p T has already been
    196   /// transformed.
    197   ///
    198   /// Subclasses can provide an alternative implementation of this routine
    199   /// to short-circuit evaluation when it is known that a given type will
    200   /// not change. For example, template instantiation need not traverse
    201   /// non-dependent types.
    202   bool AlreadyTransformed(QualType T) {
    203     return T.isNull();
    204   }
    205 
    206   /// \brief Determine whether the given call argument should be dropped, e.g.,
    207   /// because it is a default argument.
    208   ///
    209   /// Subclasses can provide an alternative implementation of this routine to
    210   /// determine which kinds of call arguments get dropped. By default,
    211   /// CXXDefaultArgument nodes are dropped (prior to transformation).
    212   bool DropCallArgument(Expr *E) {
    213     return E->isDefaultArgument();
    214   }
    215 
    216   /// \brief Determine whether we should expand a pack expansion with the
    217   /// given set of parameter packs into separate arguments by repeatedly
    218   /// transforming the pattern.
    219   ///
    220   /// By default, the transformer never tries to expand pack expansions.
    221   /// Subclasses can override this routine to provide different behavior.
    222   ///
    223   /// \param EllipsisLoc The location of the ellipsis that identifies the
    224   /// pack expansion.
    225   ///
    226   /// \param PatternRange The source range that covers the entire pattern of
    227   /// the pack expansion.
    228   ///
    229   /// \param Unexpanded The set of unexpanded parameter packs within the
    230   /// pattern.
    231   ///
    232   /// \param ShouldExpand Will be set to \c true if the transformer should
    233   /// expand the corresponding pack expansions into separate arguments. When
    234   /// set, \c NumExpansions must also be set.
    235   ///
    236   /// \param RetainExpansion Whether the caller should add an unexpanded
    237   /// pack expansion after all of the expanded arguments. This is used
    238   /// when extending explicitly-specified template argument packs per
    239   /// C++0x [temp.arg.explicit]p9.
    240   ///
    241   /// \param NumExpansions The number of separate arguments that will be in
    242   /// the expanded form of the corresponding pack expansion. This is both an
    243   /// input and an output parameter, which can be set by the caller if the
    244   /// number of expansions is known a priori (e.g., due to a prior substitution)
    245   /// and will be set by the callee when the number of expansions is known.
    246   /// The callee must set this value when \c ShouldExpand is \c true; it may
    247   /// set this value in other cases.
    248   ///
    249   /// \returns true if an error occurred (e.g., because the parameter packs
    250   /// are to be instantiated with arguments of different lengths), false
    251   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
    252   /// must be set.
    253   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
    254                                SourceRange PatternRange,
    255                                ArrayRef<UnexpandedParameterPack> Unexpanded,
    256                                bool &ShouldExpand,
    257                                bool &RetainExpansion,
    258                                Optional<unsigned> &NumExpansions) {
    259     ShouldExpand = false;
    260     return false;
    261   }
    262 
    263   /// \brief "Forget" about the partially-substituted pack template argument,
    264   /// when performing an instantiation that must preserve the parameter pack
    265   /// use.
    266   ///
    267   /// This routine is meant to be overridden by the template instantiator.
    268   TemplateArgument ForgetPartiallySubstitutedPack() {
    269     return TemplateArgument();
    270   }
    271 
    272   /// \brief "Remember" the partially-substituted pack template argument
    273   /// after performing an instantiation that must preserve the parameter pack
    274   /// use.
    275   ///
    276   /// This routine is meant to be overridden by the template instantiator.
    277   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
    278 
    279   /// \brief Note to the derived class when a function parameter pack is
    280   /// being expanded.
    281   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
    282 
    283   /// \brief Transforms the given type into another type.
    284   ///
    285   /// By default, this routine transforms a type by creating a
    286   /// TypeSourceInfo for it and delegating to the appropriate
    287   /// function.  This is expensive, but we don't mind, because
    288   /// this method is deprecated anyway;  all users should be
    289   /// switched to storing TypeSourceInfos.
    290   ///
    291   /// \returns the transformed type.
    292   QualType TransformType(QualType T);
    293 
    294   /// \brief Transforms the given type-with-location into a new
    295   /// type-with-location.
    296   ///
    297   /// By default, this routine transforms a type by delegating to the
    298   /// appropriate TransformXXXType to build a new type.  Subclasses
    299   /// may override this function (to take over all type
    300   /// transformations) or some set of the TransformXXXType functions
    301   /// to alter the transformation.
    302   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
    303 
    304   /// \brief Transform the given type-with-location into a new
    305   /// type, collecting location information in the given builder
    306   /// as necessary.
    307   ///
    308   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
    309 
    310   /// \brief Transform the given statement.
    311   ///
    312   /// By default, this routine transforms a statement by delegating to the
    313   /// appropriate TransformXXXStmt function to transform a specific kind of
    314   /// statement or the TransformExpr() function to transform an expression.
    315   /// Subclasses may override this function to transform statements using some
    316   /// other mechanism.
    317   ///
    318   /// \returns the transformed statement.
    319   StmtResult TransformStmt(Stmt *S);
    320 
    321   /// \brief Transform the given statement.
    322   ///
    323   /// By default, this routine transforms a statement by delegating to the
    324   /// appropriate TransformOMPXXXClause function to transform a specific kind
    325   /// of clause. Subclasses may override this function to transform statements
    326   /// using some other mechanism.
    327   ///
    328   /// \returns the transformed OpenMP clause.
    329   OMPClause *TransformOMPClause(OMPClause *S);
    330 
    331   /// \brief Transform the given attribute.
    332   ///
    333   /// By default, this routine transforms a statement by delegating to the
    334   /// appropriate TransformXXXAttr function to transform a specific kind
    335   /// of attribute. Subclasses may override this function to transform
    336   /// attributed statements using some other mechanism.
    337   ///
    338   /// \returns the transformed attribute
    339   const Attr *TransformAttr(const Attr *S);
    340 
    341 /// \brief Transform the specified attribute.
    342 ///
    343 /// Subclasses should override the transformation of attributes with a pragma
    344 /// spelling to transform expressions stored within the attribute.
    345 ///
    346 /// \returns the transformed attribute.
    347 #define ATTR(X)
    348 #define PRAGMA_SPELLING_ATTR(X)                                                \
    349   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
    350 #include "clang/Basic/AttrList.inc"
    351 
    352   /// \brief Transform the given expression.
    353   ///
    354   /// By default, this routine transforms an expression by delegating to the
    355   /// appropriate TransformXXXExpr function to build a new expression.
    356   /// Subclasses may override this function to transform expressions using some
    357   /// other mechanism.
    358   ///
    359   /// \returns the transformed expression.
    360   ExprResult TransformExpr(Expr *E);
    361 
    362   /// \brief Transform the given initializer.
    363   ///
    364   /// By default, this routine transforms an initializer by stripping off the
    365   /// semantic nodes added by initialization, then passing the result to
    366   /// TransformExpr or TransformExprs.
    367   ///
    368   /// \returns the transformed initializer.
    369   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
    370 
    371   /// \brief Transform the given list of expressions.
    372   ///
    373   /// This routine transforms a list of expressions by invoking
    374   /// \c TransformExpr() for each subexpression. However, it also provides
    375   /// support for variadic templates by expanding any pack expansions (if the
    376   /// derived class permits such expansion) along the way. When pack expansions
    377   /// are present, the number of outputs may not equal the number of inputs.
    378   ///
    379   /// \param Inputs The set of expressions to be transformed.
    380   ///
    381   /// \param NumInputs The number of expressions in \c Inputs.
    382   ///
    383   /// \param IsCall If \c true, then this transform is being performed on
    384   /// function-call arguments, and any arguments that should be dropped, will
    385   /// be.
    386   ///
    387   /// \param Outputs The transformed input expressions will be added to this
    388   /// vector.
    389   ///
    390   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
    391   /// due to transformation.
    392   ///
    393   /// \returns true if an error occurred, false otherwise.
    394   bool TransformExprs(Expr **Inputs, unsigned NumInputs, bool IsCall,
    395                       SmallVectorImpl<Expr *> &Outputs,
    396                       bool *ArgChanged = nullptr);
    397 
    398   /// \brief Transform the given declaration, which is referenced from a type
    399   /// or expression.
    400   ///
    401   /// By default, acts as the identity function on declarations, unless the
    402   /// transformer has had to transform the declaration itself. Subclasses
    403   /// may override this function to provide alternate behavior.
    404   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
    405     llvm::DenseMap<Decl *, Decl *>::iterator Known
    406       = TransformedLocalDecls.find(D);
    407     if (Known != TransformedLocalDecls.end())
    408       return Known->second;
    409 
    410     return D;
    411   }
    412 
    413   /// \brief Transform the attributes associated with the given declaration and
    414   /// place them on the new declaration.
    415   ///
    416   /// By default, this operation does nothing. Subclasses may override this
    417   /// behavior to transform attributes.
    418   void transformAttrs(Decl *Old, Decl *New) { }
    419 
    420   /// \brief Note that a local declaration has been transformed by this
    421   /// transformer.
    422   ///
    423   /// Local declarations are typically transformed via a call to
    424   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
    425   /// the transformer itself has to transform the declarations. This routine
    426   /// can be overridden by a subclass that keeps track of such mappings.
    427   void transformedLocalDecl(Decl *Old, Decl *New) {
    428     TransformedLocalDecls[Old] = New;
    429   }
    430 
    431   /// \brief Transform the definition of the given declaration.
    432   ///
    433   /// By default, invokes TransformDecl() to transform the declaration.
    434   /// Subclasses may override this function to provide alternate behavior.
    435   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
    436     return getDerived().TransformDecl(Loc, D);
    437   }
    438 
    439   /// \brief Transform the given declaration, which was the first part of a
    440   /// nested-name-specifier in a member access expression.
    441   ///
    442   /// This specific declaration transformation only applies to the first
    443   /// identifier in a nested-name-specifier of a member access expression, e.g.,
    444   /// the \c T in \c x->T::member
    445   ///
    446   /// By default, invokes TransformDecl() to transform the declaration.
    447   /// Subclasses may override this function to provide alternate behavior.
    448   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
    449     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
    450   }
    451 
    452   /// \brief Transform the given nested-name-specifier with source-location
    453   /// information.
    454   ///
    455   /// By default, transforms all of the types and declarations within the
    456   /// nested-name-specifier. Subclasses may override this function to provide
    457   /// alternate behavior.
    458   NestedNameSpecifierLoc
    459   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
    460                                   QualType ObjectType = QualType(),
    461                                   NamedDecl *FirstQualifierInScope = nullptr);
    462 
    463   /// \brief Transform the given declaration name.
    464   ///
    465   /// By default, transforms the types of conversion function, constructor,
    466   /// and destructor names and then (if needed) rebuilds the declaration name.
    467   /// Identifiers and selectors are returned unmodified. Sublcasses may
    468   /// override this function to provide alternate behavior.
    469   DeclarationNameInfo
    470   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
    471 
    472   /// \brief Transform the given template name.
    473   ///
    474   /// \param SS The nested-name-specifier that qualifies the template
    475   /// name. This nested-name-specifier must already have been transformed.
    476   ///
    477   /// \param Name The template name to transform.
    478   ///
    479   /// \param NameLoc The source location of the template name.
    480   ///
    481   /// \param ObjectType If we're translating a template name within a member
    482   /// access expression, this is the type of the object whose member template
    483   /// is being referenced.
    484   ///
    485   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
    486   /// also refers to a name within the current (lexical) scope, this is the
    487   /// declaration it refers to.
    488   ///
    489   /// By default, transforms the template name by transforming the declarations
    490   /// and nested-name-specifiers that occur within the template name.
    491   /// Subclasses may override this function to provide alternate behavior.
    492   TemplateName
    493   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
    494                         SourceLocation NameLoc,
    495                         QualType ObjectType = QualType(),
    496                         NamedDecl *FirstQualifierInScope = nullptr);
    497 
    498   /// \brief Transform the given template argument.
    499   ///
    500   /// By default, this operation transforms the type, expression, or
    501   /// declaration stored within the template argument and constructs a
    502   /// new template argument from the transformed result. Subclasses may
    503   /// override this function to provide alternate behavior.
    504   ///
    505   /// Returns true if there was an error.
    506   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
    507                                  TemplateArgumentLoc &Output,
    508                                  bool Uneval = false);
    509 
    510   /// \brief Transform the given set of template arguments.
    511   ///
    512   /// By default, this operation transforms all of the template arguments
    513   /// in the input set using \c TransformTemplateArgument(), and appends
    514   /// the transformed arguments to the output list.
    515   ///
    516   /// Note that this overload of \c TransformTemplateArguments() is merely
    517   /// a convenience function. Subclasses that wish to override this behavior
    518   /// should override the iterator-based member template version.
    519   ///
    520   /// \param Inputs The set of template arguments to be transformed.
    521   ///
    522   /// \param NumInputs The number of template arguments in \p Inputs.
    523   ///
    524   /// \param Outputs The set of transformed template arguments output by this
    525   /// routine.
    526   ///
    527   /// Returns true if an error occurred.
    528   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
    529                                   unsigned NumInputs,
    530                                   TemplateArgumentListInfo &Outputs,
    531                                   bool Uneval = false) {
    532     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
    533                                       Uneval);
    534   }
    535 
    536   /// \brief Transform the given set of template arguments.
    537   ///
    538   /// By default, this operation transforms all of the template arguments
    539   /// in the input set using \c TransformTemplateArgument(), and appends
    540   /// the transformed arguments to the output list.
    541   ///
    542   /// \param First An iterator to the first template argument.
    543   ///
    544   /// \param Last An iterator one step past the last template argument.
    545   ///
    546   /// \param Outputs The set of transformed template arguments output by this
    547   /// routine.
    548   ///
    549   /// Returns true if an error occurred.
    550   template<typename InputIterator>
    551   bool TransformTemplateArguments(InputIterator First,
    552                                   InputIterator Last,
    553                                   TemplateArgumentListInfo &Outputs,
    554                                   bool Uneval = false);
    555 
    556   /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
    557   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
    558                                  TemplateArgumentLoc &ArgLoc);
    559 
    560   /// \brief Fakes up a TypeSourceInfo for a type.
    561   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
    562     return SemaRef.Context.getTrivialTypeSourceInfo(T,
    563                        getDerived().getBaseLocation());
    564   }
    565 
    566 #define ABSTRACT_TYPELOC(CLASS, PARENT)
    567 #define TYPELOC(CLASS, PARENT)                                   \
    568   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
    569 #include "clang/AST/TypeLocNodes.def"
    570 
    571   template<typename Fn>
    572   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
    573                                       FunctionProtoTypeLoc TL,
    574                                       CXXRecordDecl *ThisContext,
    575                                       unsigned ThisTypeQuals,
    576                                       Fn TransformExceptionSpec);
    577 
    578   bool TransformExceptionSpec(SourceLocation Loc,
    579                               FunctionProtoType::ExceptionSpecInfo &ESI,
    580                               SmallVectorImpl<QualType> &Exceptions,
    581                               bool &Changed);
    582 
    583   StmtResult TransformSEHHandler(Stmt *Handler);
    584 
    585   QualType
    586   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
    587                                       TemplateSpecializationTypeLoc TL,
    588                                       TemplateName Template);
    589 
    590   QualType
    591   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
    592                                       DependentTemplateSpecializationTypeLoc TL,
    593                                                TemplateName Template,
    594                                                CXXScopeSpec &SS);
    595 
    596   QualType TransformDependentTemplateSpecializationType(
    597       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
    598       NestedNameSpecifierLoc QualifierLoc);
    599 
    600   /// \brief Transforms the parameters of a function type into the
    601   /// given vectors.
    602   ///
    603   /// The result vectors should be kept in sync; null entries in the
    604   /// variables vector are acceptable.
    605   ///
    606   /// Return true on error.
    607   bool TransformFunctionTypeParams(SourceLocation Loc,
    608                                    ParmVarDecl **Params, unsigned NumParams,
    609                                    const QualType *ParamTypes,
    610                                    SmallVectorImpl<QualType> &PTypes,
    611                                    SmallVectorImpl<ParmVarDecl*> *PVars);
    612 
    613   /// \brief Transforms a single function-type parameter.  Return null
    614   /// on error.
    615   ///
    616   /// \param indexAdjustment - A number to add to the parameter's
    617   ///   scope index;  can be negative
    618   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
    619                                           int indexAdjustment,
    620                                           Optional<unsigned> NumExpansions,
    621                                           bool ExpectParameterPack);
    622 
    623   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
    624 
    625   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
    626   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
    627 
    628   TemplateParameterList *TransformTemplateParameterList(
    629         TemplateParameterList *TPL) {
    630     return TPL;
    631   }
    632 
    633   ExprResult TransformAddressOfOperand(Expr *E);
    634 
    635   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
    636                                                 bool IsAddressOfOperand,
    637                                                 TypeSourceInfo **RecoveryTSI);
    638 
    639   ExprResult TransformParenDependentScopeDeclRefExpr(
    640       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
    641       TypeSourceInfo **RecoveryTSI);
    642 
    643   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
    644 
    645 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
    646 // amount of stack usage with clang.
    647 #define STMT(Node, Parent)                        \
    648   LLVM_ATTRIBUTE_NOINLINE \
    649   StmtResult Transform##Node(Node *S);
    650 #define EXPR(Node, Parent)                        \
    651   LLVM_ATTRIBUTE_NOINLINE \
    652   ExprResult Transform##Node(Node *E);
    653 #define ABSTRACT_STMT(Stmt)
    654 #include "clang/AST/StmtNodes.inc"
    655 
    656 #define OPENMP_CLAUSE(Name, Class)                        \
    657   LLVM_ATTRIBUTE_NOINLINE \
    658   OMPClause *Transform ## Class(Class *S);
    659 #include "clang/Basic/OpenMPKinds.def"
    660 
    661   /// \brief Build a new pointer type given its pointee type.
    662   ///
    663   /// By default, performs semantic analysis when building the pointer type.
    664   /// Subclasses may override this routine to provide different behavior.
    665   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
    666 
    667   /// \brief Build a new block pointer type given its pointee type.
    668   ///
    669   /// By default, performs semantic analysis when building the block pointer
    670   /// type. Subclasses may override this routine to provide different behavior.
    671   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
    672 
    673   /// \brief Build a new reference type given the type it references.
    674   ///
    675   /// By default, performs semantic analysis when building the
    676   /// reference type. Subclasses may override this routine to provide
    677   /// different behavior.
    678   ///
    679   /// \param LValue whether the type was written with an lvalue sigil
    680   /// or an rvalue sigil.
    681   QualType RebuildReferenceType(QualType ReferentType,
    682                                 bool LValue,
    683                                 SourceLocation Sigil);
    684 
    685   /// \brief Build a new member pointer type given the pointee type and the
    686   /// class type it refers into.
    687   ///
    688   /// By default, performs semantic analysis when building the member pointer
    689   /// type. Subclasses may override this routine to provide different behavior.
    690   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
    691                                     SourceLocation Sigil);
    692 
    693   /// \brief Build an Objective-C object type.
    694   ///
    695   /// By default, performs semantic analysis when building the object type.
    696   /// Subclasses may override this routine to provide different behavior.
    697   QualType RebuildObjCObjectType(QualType BaseType,
    698                                  SourceLocation Loc,
    699                                  SourceLocation TypeArgsLAngleLoc,
    700                                  ArrayRef<TypeSourceInfo *> TypeArgs,
    701                                  SourceLocation TypeArgsRAngleLoc,
    702                                  SourceLocation ProtocolLAngleLoc,
    703                                  ArrayRef<ObjCProtocolDecl *> Protocols,
    704                                  ArrayRef<SourceLocation> ProtocolLocs,
    705                                  SourceLocation ProtocolRAngleLoc);
    706 
    707   /// \brief Build a new Objective-C object pointer type given the pointee type.
    708   ///
    709   /// By default, directly builds the pointer type, with no additional semantic
    710   /// analysis.
    711   QualType RebuildObjCObjectPointerType(QualType PointeeType,
    712                                         SourceLocation Star);
    713 
    714   /// \brief Build a new array type given the element type, size
    715   /// modifier, size of the array (if known), size expression, and index type
    716   /// qualifiers.
    717   ///
    718   /// By default, performs semantic analysis when building the array type.
    719   /// Subclasses may override this routine to provide different behavior.
    720   /// Also by default, all of the other Rebuild*Array
    721   QualType RebuildArrayType(QualType ElementType,
    722                             ArrayType::ArraySizeModifier SizeMod,
    723                             const llvm::APInt *Size,
    724                             Expr *SizeExpr,
    725                             unsigned IndexTypeQuals,
    726                             SourceRange BracketsRange);
    727 
    728   /// \brief Build a new constant array type given the element type, size
    729   /// modifier, (known) size of the array, and index type qualifiers.
    730   ///
    731   /// By default, performs semantic analysis when building the array type.
    732   /// Subclasses may override this routine to provide different behavior.
    733   QualType RebuildConstantArrayType(QualType ElementType,
    734                                     ArrayType::ArraySizeModifier SizeMod,
    735                                     const llvm::APInt &Size,
    736                                     unsigned IndexTypeQuals,
    737                                     SourceRange BracketsRange);
    738 
    739   /// \brief Build a new incomplete array type given the element type, size
    740   /// modifier, and index type qualifiers.
    741   ///
    742   /// By default, performs semantic analysis when building the array type.
    743   /// Subclasses may override this routine to provide different behavior.
    744   QualType RebuildIncompleteArrayType(QualType ElementType,
    745                                       ArrayType::ArraySizeModifier SizeMod,
    746                                       unsigned IndexTypeQuals,
    747                                       SourceRange BracketsRange);
    748 
    749   /// \brief Build a new variable-length array type given the element type,
    750   /// size modifier, size expression, and index type qualifiers.
    751   ///
    752   /// By default, performs semantic analysis when building the array type.
    753   /// Subclasses may override this routine to provide different behavior.
    754   QualType RebuildVariableArrayType(QualType ElementType,
    755                                     ArrayType::ArraySizeModifier SizeMod,
    756                                     Expr *SizeExpr,
    757                                     unsigned IndexTypeQuals,
    758                                     SourceRange BracketsRange);
    759 
    760   /// \brief Build a new dependent-sized array type given the element type,
    761   /// size modifier, size expression, and index type qualifiers.
    762   ///
    763   /// By default, performs semantic analysis when building the array type.
    764   /// Subclasses may override this routine to provide different behavior.
    765   QualType RebuildDependentSizedArrayType(QualType ElementType,
    766                                           ArrayType::ArraySizeModifier SizeMod,
    767                                           Expr *SizeExpr,
    768                                           unsigned IndexTypeQuals,
    769                                           SourceRange BracketsRange);
    770 
    771   /// \brief Build a new vector type given the element type and
    772   /// number of elements.
    773   ///
    774   /// By default, performs semantic analysis when building the vector type.
    775   /// Subclasses may override this routine to provide different behavior.
    776   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
    777                              VectorType::VectorKind VecKind);
    778 
    779   /// \brief Build a new extended vector type given the element type and
    780   /// number of elements.
    781   ///
    782   /// By default, performs semantic analysis when building the vector type.
    783   /// Subclasses may override this routine to provide different behavior.
    784   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
    785                                 SourceLocation AttributeLoc);
    786 
    787   /// \brief Build a new potentially dependently-sized extended vector type
    788   /// given the element type and number of elements.
    789   ///
    790   /// By default, performs semantic analysis when building the vector type.
    791   /// Subclasses may override this routine to provide different behavior.
    792   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
    793                                               Expr *SizeExpr,
    794                                               SourceLocation AttributeLoc);
    795 
    796   /// \brief Build a new function type.
    797   ///
    798   /// By default, performs semantic analysis when building the function type.
    799   /// Subclasses may override this routine to provide different behavior.
    800   QualType RebuildFunctionProtoType(QualType T,
    801                                     MutableArrayRef<QualType> ParamTypes,
    802                                     const FunctionProtoType::ExtProtoInfo &EPI);
    803 
    804   /// \brief Build a new unprototyped function type.
    805   QualType RebuildFunctionNoProtoType(QualType ResultType);
    806 
    807   /// \brief Rebuild an unresolved typename type, given the decl that
    808   /// the UnresolvedUsingTypenameDecl was transformed to.
    809   QualType RebuildUnresolvedUsingType(Decl *D);
    810 
    811   /// \brief Build a new typedef type.
    812   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
    813     return SemaRef.Context.getTypeDeclType(Typedef);
    814   }
    815 
    816   /// \brief Build a new class/struct/union type.
    817   QualType RebuildRecordType(RecordDecl *Record) {
    818     return SemaRef.Context.getTypeDeclType(Record);
    819   }
    820 
    821   /// \brief Build a new Enum type.
    822   QualType RebuildEnumType(EnumDecl *Enum) {
    823     return SemaRef.Context.getTypeDeclType(Enum);
    824   }
    825 
    826   /// \brief Build a new typeof(expr) type.
    827   ///
    828   /// By default, performs semantic analysis when building the typeof type.
    829   /// Subclasses may override this routine to provide different behavior.
    830   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
    831 
    832   /// \brief Build a new typeof(type) type.
    833   ///
    834   /// By default, builds a new TypeOfType with the given underlying type.
    835   QualType RebuildTypeOfType(QualType Underlying);
    836 
    837   /// \brief Build a new unary transform type.
    838   QualType RebuildUnaryTransformType(QualType BaseType,
    839                                      UnaryTransformType::UTTKind UKind,
    840                                      SourceLocation Loc);
    841 
    842   /// \brief Build a new C++11 decltype type.
    843   ///
    844   /// By default, performs semantic analysis when building the decltype type.
    845   /// Subclasses may override this routine to provide different behavior.
    846   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
    847 
    848   /// \brief Build a new C++11 auto type.
    849   ///
    850   /// By default, builds a new AutoType with the given deduced type.
    851   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
    852     // Note, IsDependent is always false here: we implicitly convert an 'auto'
    853     // which has been deduced to a dependent type into an undeduced 'auto', so
    854     // that we'll retry deduction after the transformation.
    855     return SemaRef.Context.getAutoType(Deduced, Keyword,
    856                                        /*IsDependent*/ false);
    857   }
    858 
    859   /// \brief Build a new template specialization type.
    860   ///
    861   /// By default, performs semantic analysis when building the template
    862   /// specialization type. Subclasses may override this routine to provide
    863   /// different behavior.
    864   QualType RebuildTemplateSpecializationType(TemplateName Template,
    865                                              SourceLocation TemplateLoc,
    866                                              TemplateArgumentListInfo &Args);
    867 
    868   /// \brief Build a new parenthesized type.
    869   ///
    870   /// By default, builds a new ParenType type from the inner type.
    871   /// Subclasses may override this routine to provide different behavior.
    872   QualType RebuildParenType(QualType InnerType) {
    873     return SemaRef.Context.getParenType(InnerType);
    874   }
    875 
    876   /// \brief Build a new qualified name type.
    877   ///
    878   /// By default, builds a new ElaboratedType type from the keyword,
    879   /// the nested-name-specifier and the named type.
    880   /// Subclasses may override this routine to provide different behavior.
    881   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
    882                                  ElaboratedTypeKeyword Keyword,
    883                                  NestedNameSpecifierLoc QualifierLoc,
    884                                  QualType Named) {
    885     return SemaRef.Context.getElaboratedType(Keyword,
    886                                          QualifierLoc.getNestedNameSpecifier(),
    887                                              Named);
    888   }
    889 
    890   /// \brief Build a new typename type that refers to a template-id.
    891   ///
    892   /// By default, builds a new DependentNameType type from the
    893   /// nested-name-specifier and the given type. Subclasses may override
    894   /// this routine to provide different behavior.
    895   QualType RebuildDependentTemplateSpecializationType(
    896                                           ElaboratedTypeKeyword Keyword,
    897                                           NestedNameSpecifierLoc QualifierLoc,
    898                                           const IdentifierInfo *Name,
    899                                           SourceLocation NameLoc,
    900                                           TemplateArgumentListInfo &Args) {
    901     // Rebuild the template name.
    902     // TODO: avoid TemplateName abstraction
    903     CXXScopeSpec SS;
    904     SS.Adopt(QualifierLoc);
    905     TemplateName InstName
    906       = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(),
    907                                          nullptr);
    908 
    909     if (InstName.isNull())
    910       return QualType();
    911 
    912     // If it's still dependent, make a dependent specialization.
    913     if (InstName.getAsDependentTemplateName())
    914       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
    915                                           QualifierLoc.getNestedNameSpecifier(),
    916                                                                     Name,
    917                                                                     Args);
    918 
    919     // Otherwise, make an elaborated type wrapping a non-dependent
    920     // specialization.
    921     QualType T =
    922     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
    923     if (T.isNull()) return QualType();
    924 
    925     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
    926       return T;
    927 
    928     return SemaRef.Context.getElaboratedType(Keyword,
    929                                        QualifierLoc.getNestedNameSpecifier(),
    930                                              T);
    931   }
    932 
    933   /// \brief Build a new typename type that refers to an identifier.
    934   ///
    935   /// By default, performs semantic analysis when building the typename type
    936   /// (or elaborated type). Subclasses may override this routine to provide
    937   /// different behavior.
    938   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
    939                                     SourceLocation KeywordLoc,
    940                                     NestedNameSpecifierLoc QualifierLoc,
    941                                     const IdentifierInfo *Id,
    942                                     SourceLocation IdLoc) {
    943     CXXScopeSpec SS;
    944     SS.Adopt(QualifierLoc);
    945 
    946     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
    947       // If the name is still dependent, just build a new dependent name type.
    948       if (!SemaRef.computeDeclContext(SS))
    949         return SemaRef.Context.getDependentNameType(Keyword,
    950                                           QualifierLoc.getNestedNameSpecifier(),
    951                                                     Id);
    952     }
    953 
    954     if (Keyword == ETK_None || Keyword == ETK_Typename)
    955       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
    956                                        *Id, IdLoc);
    957 
    958     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
    959 
    960     // We had a dependent elaborated-type-specifier that has been transformed
    961     // into a non-dependent elaborated-type-specifier. Find the tag we're
    962     // referring to.
    963     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
    964     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
    965     if (!DC)
    966       return QualType();
    967 
    968     if (SemaRef.RequireCompleteDeclContext(SS, DC))
    969       return QualType();
    970 
    971     TagDecl *Tag = nullptr;
    972     SemaRef.LookupQualifiedName(Result, DC);
    973     switch (Result.getResultKind()) {
    974       case LookupResult::NotFound:
    975       case LookupResult::NotFoundInCurrentInstantiation:
    976         break;
    977 
    978       case LookupResult::Found:
    979         Tag = Result.getAsSingle<TagDecl>();
    980         break;
    981 
    982       case LookupResult::FoundOverloaded:
    983       case LookupResult::FoundUnresolvedValue:
    984         llvm_unreachable("Tag lookup cannot find non-tags");
    985 
    986       case LookupResult::Ambiguous:
    987         // Let the LookupResult structure handle ambiguities.
    988         return QualType();
    989     }
    990 
    991     if (!Tag) {
    992       // Check where the name exists but isn't a tag type and use that to emit
    993       // better diagnostics.
    994       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
    995       SemaRef.LookupQualifiedName(Result, DC);
    996       switch (Result.getResultKind()) {
    997         case LookupResult::Found:
    998         case LookupResult::FoundOverloaded:
    999         case LookupResult::FoundUnresolvedValue: {
   1000           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
   1001           unsigned Kind = 0;
   1002           if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
   1003           else if (isa<TypeAliasDecl>(SomeDecl)) Kind = 2;
   1004           else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 3;
   1005           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
   1006           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
   1007           break;
   1008         }
   1009         default:
   1010           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
   1011               << Kind << Id << DC << QualifierLoc.getSourceRange();
   1012           break;
   1013       }
   1014       return QualType();
   1015     }
   1016 
   1017     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
   1018                                               IdLoc, Id)) {
   1019       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
   1020       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
   1021       return QualType();
   1022     }
   1023 
   1024     // Build the elaborated-type-specifier type.
   1025     QualType T = SemaRef.Context.getTypeDeclType(Tag);
   1026     return SemaRef.Context.getElaboratedType(Keyword,
   1027                                          QualifierLoc.getNestedNameSpecifier(),
   1028                                              T);
   1029   }
   1030 
   1031   /// \brief Build a new pack expansion type.
   1032   ///
   1033   /// By default, builds a new PackExpansionType type from the given pattern.
   1034   /// Subclasses may override this routine to provide different behavior.
   1035   QualType RebuildPackExpansionType(QualType Pattern,
   1036                                     SourceRange PatternRange,
   1037                                     SourceLocation EllipsisLoc,
   1038                                     Optional<unsigned> NumExpansions) {
   1039     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
   1040                                         NumExpansions);
   1041   }
   1042 
   1043   /// \brief Build a new atomic type given its value type.
   1044   ///
   1045   /// By default, performs semantic analysis when building the atomic type.
   1046   /// Subclasses may override this routine to provide different behavior.
   1047   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
   1048 
   1049   /// \brief Build a new template name given a nested name specifier, a flag
   1050   /// indicating whether the "template" keyword was provided, and the template
   1051   /// that the template name refers to.
   1052   ///
   1053   /// By default, builds the new template name directly. Subclasses may override
   1054   /// this routine to provide different behavior.
   1055   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
   1056                                    bool TemplateKW,
   1057                                    TemplateDecl *Template);
   1058 
   1059   /// \brief Build a new template name given a nested name specifier and the
   1060   /// name that is referred to as a template.
   1061   ///
   1062   /// By default, performs semantic analysis to determine whether the name can
   1063   /// be resolved to a specific template, then builds the appropriate kind of
   1064   /// template name. Subclasses may override this routine to provide different
   1065   /// behavior.
   1066   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
   1067                                    const IdentifierInfo &Name,
   1068                                    SourceLocation NameLoc,
   1069                                    QualType ObjectType,
   1070                                    NamedDecl *FirstQualifierInScope);
   1071 
   1072   /// \brief Build a new template name given a nested name specifier and the
   1073   /// overloaded operator name that is referred to as a template.
   1074   ///
   1075   /// By default, performs semantic analysis to determine whether the name can
   1076   /// be resolved to a specific template, then builds the appropriate kind of
   1077   /// template name. Subclasses may override this routine to provide different
   1078   /// behavior.
   1079   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
   1080                                    OverloadedOperatorKind Operator,
   1081                                    SourceLocation NameLoc,
   1082                                    QualType ObjectType);
   1083 
   1084   /// \brief Build a new template name given a template template parameter pack
   1085   /// and the
   1086   ///
   1087   /// By default, performs semantic analysis to determine whether the name can
   1088   /// be resolved to a specific template, then builds the appropriate kind of
   1089   /// template name. Subclasses may override this routine to provide different
   1090   /// behavior.
   1091   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
   1092                                    const TemplateArgument &ArgPack) {
   1093     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
   1094   }
   1095 
   1096   /// \brief Build a new compound statement.
   1097   ///
   1098   /// By default, performs semantic analysis to build the new statement.
   1099   /// Subclasses may override this routine to provide different behavior.
   1100   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
   1101                                        MultiStmtArg Statements,
   1102                                        SourceLocation RBraceLoc,
   1103                                        bool IsStmtExpr) {
   1104     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
   1105                                        IsStmtExpr);
   1106   }
   1107 
   1108   /// \brief Build a new case statement.
   1109   ///
   1110   /// By default, performs semantic analysis to build the new statement.
   1111   /// Subclasses may override this routine to provide different behavior.
   1112   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
   1113                                    Expr *LHS,
   1114                                    SourceLocation EllipsisLoc,
   1115                                    Expr *RHS,
   1116                                    SourceLocation ColonLoc) {
   1117     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
   1118                                    ColonLoc);
   1119   }
   1120 
   1121   /// \brief Attach the body to a new case statement.
   1122   ///
   1123   /// By default, performs semantic analysis to build the new statement.
   1124   /// Subclasses may override this routine to provide different behavior.
   1125   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
   1126     getSema().ActOnCaseStmtBody(S, Body);
   1127     return S;
   1128   }
   1129 
   1130   /// \brief Build a new default statement.
   1131   ///
   1132   /// By default, performs semantic analysis to build the new statement.
   1133   /// Subclasses may override this routine to provide different behavior.
   1134   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
   1135                                       SourceLocation ColonLoc,
   1136                                       Stmt *SubStmt) {
   1137     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
   1138                                       /*CurScope=*/nullptr);
   1139   }
   1140 
   1141   /// \brief Build a new label statement.
   1142   ///
   1143   /// By default, performs semantic analysis to build the new statement.
   1144   /// Subclasses may override this routine to provide different behavior.
   1145   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
   1146                               SourceLocation ColonLoc, Stmt *SubStmt) {
   1147     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
   1148   }
   1149 
   1150   /// \brief Build a new label statement.
   1151   ///
   1152   /// By default, performs semantic analysis to build the new statement.
   1153   /// Subclasses may override this routine to provide different behavior.
   1154   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
   1155                                    ArrayRef<const Attr*> Attrs,
   1156                                    Stmt *SubStmt) {
   1157     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
   1158   }
   1159 
   1160   /// \brief Build a new "if" statement.
   1161   ///
   1162   /// By default, performs semantic analysis to build the new statement.
   1163   /// Subclasses may override this routine to provide different behavior.
   1164   StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
   1165                            VarDecl *CondVar, Stmt *Then,
   1166                            SourceLocation ElseLoc, Stmt *Else) {
   1167     return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
   1168   }
   1169 
   1170   /// \brief Start building a new switch statement.
   1171   ///
   1172   /// By default, performs semantic analysis to build the new statement.
   1173   /// Subclasses may override this routine to provide different behavior.
   1174   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
   1175                                     Expr *Cond, VarDecl *CondVar) {
   1176     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
   1177                                             CondVar);
   1178   }
   1179 
   1180   /// \brief Attach the body to the switch statement.
   1181   ///
   1182   /// By default, performs semantic analysis to build the new statement.
   1183   /// Subclasses may override this routine to provide different behavior.
   1184   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
   1185                                    Stmt *Switch, Stmt *Body) {
   1186     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
   1187   }
   1188 
   1189   /// \brief Build a new while statement.
   1190   ///
   1191   /// By default, performs semantic analysis to build the new statement.
   1192   /// Subclasses may override this routine to provide different behavior.
   1193   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, Sema::FullExprArg Cond,
   1194                               VarDecl *CondVar, Stmt *Body) {
   1195     return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
   1196   }
   1197 
   1198   /// \brief Build a new do-while statement.
   1199   ///
   1200   /// By default, performs semantic analysis to build the new statement.
   1201   /// Subclasses may override this routine to provide different behavior.
   1202   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
   1203                            SourceLocation WhileLoc, SourceLocation LParenLoc,
   1204                            Expr *Cond, SourceLocation RParenLoc) {
   1205     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
   1206                                  Cond, RParenLoc);
   1207   }
   1208 
   1209   /// \brief Build a new for statement.
   1210   ///
   1211   /// By default, performs semantic analysis to build the new statement.
   1212   /// Subclasses may override this routine to provide different behavior.
   1213   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
   1214                             Stmt *Init, Sema::FullExprArg Cond,
   1215                             VarDecl *CondVar, Sema::FullExprArg Inc,
   1216                             SourceLocation RParenLoc, Stmt *Body) {
   1217     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
   1218                                   CondVar, Inc, RParenLoc, Body);
   1219   }
   1220 
   1221   /// \brief Build a new goto statement.
   1222   ///
   1223   /// By default, performs semantic analysis to build the new statement.
   1224   /// Subclasses may override this routine to provide different behavior.
   1225   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
   1226                              LabelDecl *Label) {
   1227     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
   1228   }
   1229 
   1230   /// \brief Build a new indirect goto statement.
   1231   ///
   1232   /// By default, performs semantic analysis to build the new statement.
   1233   /// Subclasses may override this routine to provide different behavior.
   1234   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
   1235                                      SourceLocation StarLoc,
   1236                                      Expr *Target) {
   1237     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
   1238   }
   1239 
   1240   /// \brief Build a new return statement.
   1241   ///
   1242   /// By default, performs semantic analysis to build the new statement.
   1243   /// Subclasses may override this routine to provide different behavior.
   1244   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
   1245     return getSema().BuildReturnStmt(ReturnLoc, Result);
   1246   }
   1247 
   1248   /// \brief Build a new declaration statement.
   1249   ///
   1250   /// By default, performs semantic analysis to build the new statement.
   1251   /// Subclasses may override this routine to provide different behavior.
   1252   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
   1253                              SourceLocation StartLoc, SourceLocation EndLoc) {
   1254     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
   1255     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
   1256   }
   1257 
   1258   /// \brief Build a new inline asm statement.
   1259   ///
   1260   /// By default, performs semantic analysis to build the new statement.
   1261   /// Subclasses may override this routine to provide different behavior.
   1262   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
   1263                                bool IsVolatile, unsigned NumOutputs,
   1264                                unsigned NumInputs, IdentifierInfo **Names,
   1265                                MultiExprArg Constraints, MultiExprArg Exprs,
   1266                                Expr *AsmString, MultiExprArg Clobbers,
   1267                                SourceLocation RParenLoc) {
   1268     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
   1269                                      NumInputs, Names, Constraints, Exprs,
   1270                                      AsmString, Clobbers, RParenLoc);
   1271   }
   1272 
   1273   /// \brief Build a new MS style inline asm statement.
   1274   ///
   1275   /// By default, performs semantic analysis to build the new statement.
   1276   /// Subclasses may override this routine to provide different behavior.
   1277   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
   1278                               ArrayRef<Token> AsmToks,
   1279                               StringRef AsmString,
   1280                               unsigned NumOutputs, unsigned NumInputs,
   1281                               ArrayRef<StringRef> Constraints,
   1282                               ArrayRef<StringRef> Clobbers,
   1283                               ArrayRef<Expr*> Exprs,
   1284                               SourceLocation EndLoc) {
   1285     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
   1286                                     NumOutputs, NumInputs,
   1287                                     Constraints, Clobbers, Exprs, EndLoc);
   1288   }
   1289 
   1290   /// \brief Build a new co_return statement.
   1291   ///
   1292   /// By default, performs semantic analysis to build the new statement.
   1293   /// Subclasses may override this routine to provide different behavior.
   1294   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result) {
   1295     return getSema().BuildCoreturnStmt(CoreturnLoc, Result);
   1296   }
   1297 
   1298   /// \brief Build a new co_await expression.
   1299   ///
   1300   /// By default, performs semantic analysis to build the new expression.
   1301   /// Subclasses may override this routine to provide different behavior.
   1302   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result) {
   1303     return getSema().BuildCoawaitExpr(CoawaitLoc, Result);
   1304   }
   1305 
   1306   /// \brief Build a new co_yield expression.
   1307   ///
   1308   /// By default, performs semantic analysis to build the new expression.
   1309   /// Subclasses may override this routine to provide different behavior.
   1310   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
   1311     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
   1312   }
   1313 
   1314   /// \brief Build a new Objective-C \@try statement.
   1315   ///
   1316   /// By default, performs semantic analysis to build the new statement.
   1317   /// Subclasses may override this routine to provide different behavior.
   1318   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
   1319                                         Stmt *TryBody,
   1320                                         MultiStmtArg CatchStmts,
   1321                                         Stmt *Finally) {
   1322     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
   1323                                         Finally);
   1324   }
   1325 
   1326   /// \brief Rebuild an Objective-C exception declaration.
   1327   ///
   1328   /// By default, performs semantic analysis to build the new declaration.
   1329   /// Subclasses may override this routine to provide different behavior.
   1330   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
   1331                                     TypeSourceInfo *TInfo, QualType T) {
   1332     return getSema().BuildObjCExceptionDecl(TInfo, T,
   1333                                             ExceptionDecl->getInnerLocStart(),
   1334                                             ExceptionDecl->getLocation(),
   1335                                             ExceptionDecl->getIdentifier());
   1336   }
   1337 
   1338   /// \brief Build a new Objective-C \@catch statement.
   1339   ///
   1340   /// By default, performs semantic analysis to build the new statement.
   1341   /// Subclasses may override this routine to provide different behavior.
   1342   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
   1343                                           SourceLocation RParenLoc,
   1344                                           VarDecl *Var,
   1345                                           Stmt *Body) {
   1346     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
   1347                                           Var, Body);
   1348   }
   1349 
   1350   /// \brief Build a new Objective-C \@finally statement.
   1351   ///
   1352   /// By default, performs semantic analysis to build the new statement.
   1353   /// Subclasses may override this routine to provide different behavior.
   1354   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
   1355                                             Stmt *Body) {
   1356     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
   1357   }
   1358 
   1359   /// \brief Build a new Objective-C \@throw statement.
   1360   ///
   1361   /// By default, performs semantic analysis to build the new statement.
   1362   /// Subclasses may override this routine to provide different behavior.
   1363   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
   1364                                           Expr *Operand) {
   1365     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
   1366   }
   1367 
   1368   /// \brief Build a new OpenMP executable directive.
   1369   ///
   1370   /// By default, performs semantic analysis to build the new statement.
   1371   /// Subclasses may override this routine to provide different behavior.
   1372   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
   1373                                            DeclarationNameInfo DirName,
   1374                                            OpenMPDirectiveKind CancelRegion,
   1375                                            ArrayRef<OMPClause *> Clauses,
   1376                                            Stmt *AStmt, SourceLocation StartLoc,
   1377                                            SourceLocation EndLoc) {
   1378     return getSema().ActOnOpenMPExecutableDirective(
   1379         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
   1380   }
   1381 
   1382   /// \brief Build a new OpenMP 'if' clause.
   1383   ///
   1384   /// By default, performs semantic analysis to build the new OpenMP clause.
   1385   /// Subclasses may override this routine to provide different behavior.
   1386   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
   1387                                 Expr *Condition, SourceLocation StartLoc,
   1388                                 SourceLocation LParenLoc,
   1389                                 SourceLocation NameModifierLoc,
   1390                                 SourceLocation ColonLoc,
   1391                                 SourceLocation EndLoc) {
   1392     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
   1393                                          LParenLoc, NameModifierLoc, ColonLoc,
   1394                                          EndLoc);
   1395   }
   1396 
   1397   /// \brief Build a new OpenMP 'final' clause.
   1398   ///
   1399   /// By default, performs semantic analysis to build the new OpenMP clause.
   1400   /// Subclasses may override this routine to provide different behavior.
   1401   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
   1402                                    SourceLocation LParenLoc,
   1403                                    SourceLocation EndLoc) {
   1404     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
   1405                                             EndLoc);
   1406   }
   1407 
   1408   /// \brief Build a new OpenMP 'num_threads' clause.
   1409   ///
   1410   /// By default, performs semantic analysis to build the new OpenMP clause.
   1411   /// Subclasses may override this routine to provide different behavior.
   1412   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
   1413                                         SourceLocation StartLoc,
   1414                                         SourceLocation LParenLoc,
   1415                                         SourceLocation EndLoc) {
   1416     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
   1417                                                  LParenLoc, EndLoc);
   1418   }
   1419 
   1420   /// \brief Build a new OpenMP 'safelen' clause.
   1421   ///
   1422   /// By default, performs semantic analysis to build the new OpenMP clause.
   1423   /// Subclasses may override this routine to provide different behavior.
   1424   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
   1425                                      SourceLocation LParenLoc,
   1426                                      SourceLocation EndLoc) {
   1427     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
   1428   }
   1429 
   1430   /// \brief Build a new OpenMP 'simdlen' clause.
   1431   ///
   1432   /// By default, performs semantic analysis to build the new OpenMP clause.
   1433   /// Subclasses may override this routine to provide different behavior.
   1434   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
   1435                                      SourceLocation LParenLoc,
   1436                                      SourceLocation EndLoc) {
   1437     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
   1438   }
   1439 
   1440   /// \brief Build a new OpenMP 'collapse' clause.
   1441   ///
   1442   /// By default, performs semantic analysis to build the new OpenMP clause.
   1443   /// Subclasses may override this routine to provide different behavior.
   1444   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
   1445                                       SourceLocation LParenLoc,
   1446                                       SourceLocation EndLoc) {
   1447     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
   1448                                                EndLoc);
   1449   }
   1450 
   1451   /// \brief Build a new OpenMP 'default' clause.
   1452   ///
   1453   /// By default, performs semantic analysis to build the new OpenMP clause.
   1454   /// Subclasses may override this routine to provide different behavior.
   1455   OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
   1456                                      SourceLocation KindKwLoc,
   1457                                      SourceLocation StartLoc,
   1458                                      SourceLocation LParenLoc,
   1459                                      SourceLocation EndLoc) {
   1460     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
   1461                                               StartLoc, LParenLoc, EndLoc);
   1462   }
   1463 
   1464   /// \brief Build a new OpenMP 'proc_bind' clause.
   1465   ///
   1466   /// By default, performs semantic analysis to build the new OpenMP clause.
   1467   /// Subclasses may override this routine to provide different behavior.
   1468   OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
   1469                                       SourceLocation KindKwLoc,
   1470                                       SourceLocation StartLoc,
   1471                                       SourceLocation LParenLoc,
   1472                                       SourceLocation EndLoc) {
   1473     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
   1474                                                StartLoc, LParenLoc, EndLoc);
   1475   }
   1476 
   1477   /// \brief Build a new OpenMP 'schedule' clause.
   1478   ///
   1479   /// By default, performs semantic analysis to build the new OpenMP clause.
   1480   /// Subclasses may override this routine to provide different behavior.
   1481   OMPClause *RebuildOMPScheduleClause(OpenMPScheduleClauseKind Kind,
   1482                                       Expr *ChunkSize,
   1483                                       SourceLocation StartLoc,
   1484                                       SourceLocation LParenLoc,
   1485                                       SourceLocation KindLoc,
   1486                                       SourceLocation CommaLoc,
   1487                                       SourceLocation EndLoc) {
   1488     return getSema().ActOnOpenMPScheduleClause(
   1489         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
   1490   }
   1491 
   1492   /// \brief Build a new OpenMP 'ordered' clause.
   1493   ///
   1494   /// By default, performs semantic analysis to build the new OpenMP clause.
   1495   /// Subclasses may override this routine to provide different behavior.
   1496   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
   1497                                      SourceLocation EndLoc,
   1498                                      SourceLocation LParenLoc, Expr *Num) {
   1499     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
   1500   }
   1501 
   1502   /// \brief Build a new OpenMP 'private' clause.
   1503   ///
   1504   /// By default, performs semantic analysis to build the new OpenMP clause.
   1505   /// Subclasses may override this routine to provide different behavior.
   1506   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
   1507                                      SourceLocation StartLoc,
   1508                                      SourceLocation LParenLoc,
   1509                                      SourceLocation EndLoc) {
   1510     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
   1511                                               EndLoc);
   1512   }
   1513 
   1514   /// \brief Build a new OpenMP 'firstprivate' clause.
   1515   ///
   1516   /// By default, performs semantic analysis to build the new OpenMP clause.
   1517   /// Subclasses may override this routine to provide different behavior.
   1518   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
   1519                                           SourceLocation StartLoc,
   1520                                           SourceLocation LParenLoc,
   1521                                           SourceLocation EndLoc) {
   1522     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
   1523                                                    EndLoc);
   1524   }
   1525 
   1526   /// \brief Build a new OpenMP 'lastprivate' clause.
   1527   ///
   1528   /// By default, performs semantic analysis to build the new OpenMP clause.
   1529   /// Subclasses may override this routine to provide different behavior.
   1530   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
   1531                                          SourceLocation StartLoc,
   1532                                          SourceLocation LParenLoc,
   1533                                          SourceLocation EndLoc) {
   1534     return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
   1535                                                   EndLoc);
   1536   }
   1537 
   1538   /// \brief Build a new OpenMP 'shared' clause.
   1539   ///
   1540   /// By default, performs semantic analysis to build the new OpenMP clause.
   1541   /// Subclasses may override this routine to provide different behavior.
   1542   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
   1543                                     SourceLocation StartLoc,
   1544                                     SourceLocation LParenLoc,
   1545                                     SourceLocation EndLoc) {
   1546     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
   1547                                              EndLoc);
   1548   }
   1549 
   1550   /// \brief Build a new OpenMP 'reduction' clause.
   1551   ///
   1552   /// By default, performs semantic analysis to build the new statement.
   1553   /// Subclasses may override this routine to provide different behavior.
   1554   OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
   1555                                        SourceLocation StartLoc,
   1556                                        SourceLocation LParenLoc,
   1557                                        SourceLocation ColonLoc,
   1558                                        SourceLocation EndLoc,
   1559                                        CXXScopeSpec &ReductionIdScopeSpec,
   1560                                        const DeclarationNameInfo &ReductionId) {
   1561     return getSema().ActOnOpenMPReductionClause(
   1562         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
   1563         ReductionId);
   1564   }
   1565 
   1566   /// \brief Build a new OpenMP 'linear' clause.
   1567   ///
   1568   /// By default, performs semantic analysis to build the new OpenMP clause.
   1569   /// Subclasses may override this routine to provide different behavior.
   1570   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
   1571                                     SourceLocation StartLoc,
   1572                                     SourceLocation LParenLoc,
   1573                                     OpenMPLinearClauseKind Modifier,
   1574                                     SourceLocation ModifierLoc,
   1575                                     SourceLocation ColonLoc,
   1576                                     SourceLocation EndLoc) {
   1577     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
   1578                                              Modifier, ModifierLoc, ColonLoc,
   1579                                              EndLoc);
   1580   }
   1581 
   1582   /// \brief Build a new OpenMP 'aligned' clause.
   1583   ///
   1584   /// By default, performs semantic analysis to build the new OpenMP clause.
   1585   /// Subclasses may override this routine to provide different behavior.
   1586   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
   1587                                      SourceLocation StartLoc,
   1588                                      SourceLocation LParenLoc,
   1589                                      SourceLocation ColonLoc,
   1590                                      SourceLocation EndLoc) {
   1591     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
   1592                                               LParenLoc, ColonLoc, EndLoc);
   1593   }
   1594 
   1595   /// \brief Build a new OpenMP 'copyin' clause.
   1596   ///
   1597   /// By default, performs semantic analysis to build the new OpenMP clause.
   1598   /// Subclasses may override this routine to provide different behavior.
   1599   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
   1600                                     SourceLocation StartLoc,
   1601                                     SourceLocation LParenLoc,
   1602                                     SourceLocation EndLoc) {
   1603     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
   1604                                              EndLoc);
   1605   }
   1606 
   1607   /// \brief Build a new OpenMP 'copyprivate' clause.
   1608   ///
   1609   /// By default, performs semantic analysis to build the new OpenMP clause.
   1610   /// Subclasses may override this routine to provide different behavior.
   1611   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
   1612                                          SourceLocation StartLoc,
   1613                                          SourceLocation LParenLoc,
   1614                                          SourceLocation EndLoc) {
   1615     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
   1616                                                   EndLoc);
   1617   }
   1618 
   1619   /// \brief Build a new OpenMP 'flush' pseudo clause.
   1620   ///
   1621   /// By default, performs semantic analysis to build the new OpenMP clause.
   1622   /// Subclasses may override this routine to provide different behavior.
   1623   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
   1624                                    SourceLocation StartLoc,
   1625                                    SourceLocation LParenLoc,
   1626                                    SourceLocation EndLoc) {
   1627     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
   1628                                             EndLoc);
   1629   }
   1630 
   1631   /// \brief Build a new OpenMP 'depend' pseudo clause.
   1632   ///
   1633   /// By default, performs semantic analysis to build the new OpenMP clause.
   1634   /// Subclasses may override this routine to provide different behavior.
   1635   OMPClause *
   1636   RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
   1637                          SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
   1638                          SourceLocation StartLoc, SourceLocation LParenLoc,
   1639                          SourceLocation EndLoc) {
   1640     return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
   1641                                              StartLoc, LParenLoc, EndLoc);
   1642   }
   1643 
   1644   /// \brief Build a new OpenMP 'device' clause.
   1645   ///
   1646   /// By default, performs semantic analysis to build the new statement.
   1647   /// Subclasses may override this routine to provide different behavior.
   1648   OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
   1649                                     SourceLocation LParenLoc,
   1650                                     SourceLocation EndLoc) {
   1651     return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
   1652                                              EndLoc);
   1653   }
   1654 
   1655   /// \brief Build a new OpenMP 'map' clause.
   1656   ///
   1657   /// By default, performs semantic analysis to build the new OpenMP clause.
   1658   /// Subclasses may override this routine to provide different behavior.
   1659   OMPClause *RebuildOMPMapClause(
   1660       OpenMPMapClauseKind MapTypeModifier, OpenMPMapClauseKind MapType,
   1661       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
   1662       SourceLocation StartLoc, SourceLocation LParenLoc,
   1663       SourceLocation EndLoc) {
   1664     return getSema().ActOnOpenMPMapClause(MapTypeModifier, MapType, MapLoc,
   1665                                           ColonLoc, VarList,StartLoc,
   1666                                           LParenLoc, EndLoc);
   1667   }
   1668 
   1669   /// \brief Build a new OpenMP 'num_teams' clause.
   1670   ///
   1671   /// By default, performs semantic analysis to build the new statement.
   1672   /// Subclasses may override this routine to provide different behavior.
   1673   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
   1674                                       SourceLocation LParenLoc,
   1675                                       SourceLocation EndLoc) {
   1676     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
   1677                                                EndLoc);
   1678   }
   1679 
   1680   /// \brief Build a new OpenMP 'thread_limit' clause.
   1681   ///
   1682   /// By default, performs semantic analysis to build the new statement.
   1683   /// Subclasses may override this routine to provide different behavior.
   1684   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
   1685                                          SourceLocation StartLoc,
   1686                                          SourceLocation LParenLoc,
   1687                                          SourceLocation EndLoc) {
   1688     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
   1689                                                   LParenLoc, EndLoc);
   1690   }
   1691 
   1692   /// \brief Build a new OpenMP 'priority' clause.
   1693   ///
   1694   /// By default, performs semantic analysis to build the new statement.
   1695   /// Subclasses may override this routine to provide different behavior.
   1696   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
   1697                                       SourceLocation LParenLoc,
   1698                                       SourceLocation EndLoc) {
   1699     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
   1700                                                EndLoc);
   1701   }
   1702 
   1703   /// \brief Build a new OpenMP 'grainsize' clause.
   1704   ///
   1705   /// By default, performs semantic analysis to build the new statement.
   1706   /// Subclasses may override this routine to provide different behavior.
   1707   OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
   1708                                        SourceLocation LParenLoc,
   1709                                        SourceLocation EndLoc) {
   1710     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
   1711                                                 EndLoc);
   1712   }
   1713 
   1714   /// \brief Build a new OpenMP 'num_tasks' clause.
   1715   ///
   1716   /// By default, performs semantic analysis to build the new statement.
   1717   /// Subclasses may override this routine to provide different behavior.
   1718   OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
   1719                                       SourceLocation LParenLoc,
   1720                                       SourceLocation EndLoc) {
   1721     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
   1722                                                EndLoc);
   1723   }
   1724 
   1725   /// \brief Build a new OpenMP 'hint' clause.
   1726   ///
   1727   /// By default, performs semantic analysis to build the new statement.
   1728   /// Subclasses may override this routine to provide different behavior.
   1729   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
   1730                                   SourceLocation LParenLoc,
   1731                                   SourceLocation EndLoc) {
   1732     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
   1733   }
   1734 
   1735   /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
   1736   ///
   1737   /// By default, performs semantic analysis to build the new statement.
   1738   /// Subclasses may override this routine to provide different behavior.
   1739   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
   1740                                               Expr *object) {
   1741     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
   1742   }
   1743 
   1744   /// \brief Build a new Objective-C \@synchronized statement.
   1745   ///
   1746   /// By default, performs semantic analysis to build the new statement.
   1747   /// Subclasses may override this routine to provide different behavior.
   1748   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
   1749                                            Expr *Object, Stmt *Body) {
   1750     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
   1751   }
   1752 
   1753   /// \brief Build a new Objective-C \@autoreleasepool statement.
   1754   ///
   1755   /// By default, performs semantic analysis to build the new statement.
   1756   /// Subclasses may override this routine to provide different behavior.
   1757   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
   1758                                             Stmt *Body) {
   1759     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
   1760   }
   1761 
   1762   /// \brief Build a new Objective-C fast enumeration statement.
   1763   ///
   1764   /// By default, performs semantic analysis to build the new statement.
   1765   /// Subclasses may override this routine to provide different behavior.
   1766   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
   1767                                           Stmt *Element,
   1768                                           Expr *Collection,
   1769                                           SourceLocation RParenLoc,
   1770                                           Stmt *Body) {
   1771     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
   1772                                                 Element,
   1773                                                 Collection,
   1774                                                 RParenLoc);
   1775     if (ForEachStmt.isInvalid())
   1776       return StmtError();
   1777 
   1778     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
   1779   }
   1780 
   1781   /// \brief Build a new C++ exception declaration.
   1782   ///
   1783   /// By default, performs semantic analysis to build the new decaration.
   1784   /// Subclasses may override this routine to provide different behavior.
   1785   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
   1786                                 TypeSourceInfo *Declarator,
   1787                                 SourceLocation StartLoc,
   1788                                 SourceLocation IdLoc,
   1789                                 IdentifierInfo *Id) {
   1790     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
   1791                                                        StartLoc, IdLoc, Id);
   1792     if (Var)
   1793       getSema().CurContext->addDecl(Var);
   1794     return Var;
   1795   }
   1796 
   1797   /// \brief Build a new C++ catch statement.
   1798   ///
   1799   /// By default, performs semantic analysis to build the new statement.
   1800   /// Subclasses may override this routine to provide different behavior.
   1801   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
   1802                                  VarDecl *ExceptionDecl,
   1803                                  Stmt *Handler) {
   1804     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
   1805                                                       Handler));
   1806   }
   1807 
   1808   /// \brief Build a new C++ try statement.
   1809   ///
   1810   /// By default, performs semantic analysis to build the new statement.
   1811   /// Subclasses may override this routine to provide different behavior.
   1812   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
   1813                                ArrayRef<Stmt *> Handlers) {
   1814     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
   1815   }
   1816 
   1817   /// \brief Build a new C++0x range-based for statement.
   1818   ///
   1819   /// By default, performs semantic analysis to build the new statement.
   1820   /// Subclasses may override this routine to provide different behavior.
   1821   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
   1822                                     SourceLocation CoawaitLoc,
   1823                                     SourceLocation ColonLoc,
   1824                                     Stmt *Range, Stmt *BeginEnd,
   1825                                     Expr *Cond, Expr *Inc,
   1826                                     Stmt *LoopVar,
   1827                                     SourceLocation RParenLoc) {
   1828     // If we've just learned that the range is actually an Objective-C
   1829     // collection, treat this as an Objective-C fast enumeration loop.
   1830     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
   1831       if (RangeStmt->isSingleDecl()) {
   1832         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
   1833           if (RangeVar->isInvalidDecl())
   1834             return StmtError();
   1835 
   1836           Expr *RangeExpr = RangeVar->getInit();
   1837           if (!RangeExpr->isTypeDependent() &&
   1838               RangeExpr->getType()->isObjCObjectPointerType())
   1839             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
   1840                                                         RParenLoc);
   1841         }
   1842       }
   1843     }
   1844 
   1845     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc,
   1846                                           Range, BeginEnd,
   1847                                           Cond, Inc, LoopVar, RParenLoc,
   1848                                           Sema::BFRK_Rebuild);
   1849   }
   1850 
   1851   /// \brief Build a new C++0x range-based for statement.
   1852   ///
   1853   /// By default, performs semantic analysis to build the new statement.
   1854   /// Subclasses may override this routine to provide different behavior.
   1855   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
   1856                                           bool IsIfExists,
   1857                                           NestedNameSpecifierLoc QualifierLoc,
   1858                                           DeclarationNameInfo NameInfo,
   1859                                           Stmt *Nested) {
   1860     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
   1861                                                 QualifierLoc, NameInfo, Nested);
   1862   }
   1863 
   1864   /// \brief Attach body to a C++0x range-based for statement.
   1865   ///
   1866   /// By default, performs semantic analysis to finish the new statement.
   1867   /// Subclasses may override this routine to provide different behavior.
   1868   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
   1869     return getSema().FinishCXXForRangeStmt(ForRange, Body);
   1870   }
   1871 
   1872   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
   1873                                Stmt *TryBlock, Stmt *Handler) {
   1874     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
   1875   }
   1876 
   1877   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
   1878                                   Stmt *Block) {
   1879     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
   1880   }
   1881 
   1882   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
   1883     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
   1884   }
   1885 
   1886   /// \brief Build a new predefined expression.
   1887   ///
   1888   /// By default, performs semantic analysis to build the new expression.
   1889   /// Subclasses may override this routine to provide different behavior.
   1890   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
   1891                                    PredefinedExpr::IdentType IT) {
   1892     return getSema().BuildPredefinedExpr(Loc, IT);
   1893   }
   1894 
   1895   /// \brief Build a new expression that references a declaration.
   1896   ///
   1897   /// By default, performs semantic analysis to build the new expression.
   1898   /// Subclasses may override this routine to provide different behavior.
   1899   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
   1900                                         LookupResult &R,
   1901                                         bool RequiresADL) {
   1902     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
   1903   }
   1904 
   1905 
   1906   /// \brief Build a new expression that references a declaration.
   1907   ///
   1908   /// By default, performs semantic analysis to build the new expression.
   1909   /// Subclasses may override this routine to provide different behavior.
   1910   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
   1911                                 ValueDecl *VD,
   1912                                 const DeclarationNameInfo &NameInfo,
   1913                                 TemplateArgumentListInfo *TemplateArgs) {
   1914     CXXScopeSpec SS;
   1915     SS.Adopt(QualifierLoc);
   1916 
   1917     // FIXME: loses template args.
   1918 
   1919     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
   1920   }
   1921 
   1922   /// \brief Build a new expression in parentheses.
   1923   ///
   1924   /// By default, performs semantic analysis to build the new expression.
   1925   /// Subclasses may override this routine to provide different behavior.
   1926   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
   1927                                     SourceLocation RParen) {
   1928     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
   1929   }
   1930 
   1931   /// \brief Build a new pseudo-destructor expression.
   1932   ///
   1933   /// By default, performs semantic analysis to build the new expression.
   1934   /// Subclasses may override this routine to provide different behavior.
   1935   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
   1936                                             SourceLocation OperatorLoc,
   1937                                             bool isArrow,
   1938                                             CXXScopeSpec &SS,
   1939                                             TypeSourceInfo *ScopeType,
   1940                                             SourceLocation CCLoc,
   1941                                             SourceLocation TildeLoc,
   1942                                         PseudoDestructorTypeStorage Destroyed);
   1943 
   1944   /// \brief Build a new unary operator expression.
   1945   ///
   1946   /// By default, performs semantic analysis to build the new expression.
   1947   /// Subclasses may override this routine to provide different behavior.
   1948   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
   1949                                         UnaryOperatorKind Opc,
   1950                                         Expr *SubExpr) {
   1951     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
   1952   }
   1953 
   1954   /// \brief Build a new builtin offsetof expression.
   1955   ///
   1956   /// By default, performs semantic analysis to build the new expression.
   1957   /// Subclasses may override this routine to provide different behavior.
   1958   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
   1959                                  TypeSourceInfo *Type,
   1960                                  ArrayRef<Sema::OffsetOfComponent> Components,
   1961                                  SourceLocation RParenLoc) {
   1962     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
   1963                                           RParenLoc);
   1964   }
   1965 
   1966   /// \brief Build a new sizeof, alignof or vec_step expression with a
   1967   /// type argument.
   1968   ///
   1969   /// By default, performs semantic analysis to build the new expression.
   1970   /// Subclasses may override this routine to provide different behavior.
   1971   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
   1972                                          SourceLocation OpLoc,
   1973                                          UnaryExprOrTypeTrait ExprKind,
   1974                                          SourceRange R) {
   1975     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
   1976   }
   1977 
   1978   /// \brief Build a new sizeof, alignof or vec step expression with an
   1979   /// expression argument.
   1980   ///
   1981   /// By default, performs semantic analysis to build the new expression.
   1982   /// Subclasses may override this routine to provide different behavior.
   1983   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
   1984                                          UnaryExprOrTypeTrait ExprKind,
   1985                                          SourceRange R) {
   1986     ExprResult Result
   1987       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
   1988     if (Result.isInvalid())
   1989       return ExprError();
   1990 
   1991     return Result;
   1992   }
   1993 
   1994   /// \brief Build a new array subscript expression.
   1995   ///
   1996   /// By default, performs semantic analysis to build the new expression.
   1997   /// Subclasses may override this routine to provide different behavior.
   1998   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
   1999                                              SourceLocation LBracketLoc,
   2000                                              Expr *RHS,
   2001                                              SourceLocation RBracketLoc) {
   2002     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
   2003                                              LBracketLoc, RHS,
   2004                                              RBracketLoc);
   2005   }
   2006 
   2007   /// \brief Build a new array section expression.
   2008   ///
   2009   /// By default, performs semantic analysis to build the new expression.
   2010   /// Subclasses may override this routine to provide different behavior.
   2011   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
   2012                                         Expr *LowerBound,
   2013                                         SourceLocation ColonLoc, Expr *Length,
   2014                                         SourceLocation RBracketLoc) {
   2015     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
   2016                                               ColonLoc, Length, RBracketLoc);
   2017   }
   2018 
   2019   /// \brief Build a new call expression.
   2020   ///
   2021   /// By default, performs semantic analysis to build the new expression.
   2022   /// Subclasses may override this routine to provide different behavior.
   2023   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
   2024                                    MultiExprArg Args,
   2025                                    SourceLocation RParenLoc,
   2026                                    Expr *ExecConfig = nullptr) {
   2027     return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
   2028                                    Args, RParenLoc, ExecConfig);
   2029   }
   2030 
   2031   /// \brief Build a new member access expression.
   2032   ///
   2033   /// By default, performs semantic analysis to build the new expression.
   2034   /// Subclasses may override this routine to provide different behavior.
   2035   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
   2036                                bool isArrow,
   2037                                NestedNameSpecifierLoc QualifierLoc,
   2038                                SourceLocation TemplateKWLoc,
   2039                                const DeclarationNameInfo &MemberNameInfo,
   2040                                ValueDecl *Member,
   2041                                NamedDecl *FoundDecl,
   2042                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
   2043                                NamedDecl *FirstQualifierInScope) {
   2044     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
   2045                                                                       isArrow);
   2046     if (!Member->getDeclName()) {
   2047       // We have a reference to an unnamed field.  This is always the
   2048       // base of an anonymous struct/union member access, i.e. the
   2049       // field is always of record type.
   2050       assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
   2051       assert(Member->getType()->isRecordType() &&
   2052              "unnamed member not of record type?");
   2053 
   2054       BaseResult =
   2055         getSema().PerformObjectMemberConversion(BaseResult.get(),
   2056                                                 QualifierLoc.getNestedNameSpecifier(),
   2057                                                 FoundDecl, Member);
   2058       if (BaseResult.isInvalid())
   2059         return ExprError();
   2060       Base = BaseResult.get();
   2061       ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
   2062       MemberExpr *ME = new (getSema().Context)
   2063           MemberExpr(Base, isArrow, OpLoc, Member, MemberNameInfo,
   2064                      cast<FieldDecl>(Member)->getType(), VK, OK_Ordinary);
   2065       return ME;
   2066     }
   2067 
   2068     CXXScopeSpec SS;
   2069     SS.Adopt(QualifierLoc);
   2070 
   2071     Base = BaseResult.get();
   2072     QualType BaseType = Base->getType();
   2073 
   2074     // FIXME: this involves duplicating earlier analysis in a lot of
   2075     // cases; we should avoid this when possible.
   2076     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
   2077     R.addDecl(FoundDecl);
   2078     R.resolveKind();
   2079 
   2080     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
   2081                                               SS, TemplateKWLoc,
   2082                                               FirstQualifierInScope,
   2083                                               R, ExplicitTemplateArgs,
   2084                                               /*S*/nullptr);
   2085   }
   2086 
   2087   /// \brief Build a new binary operator expression.
   2088   ///
   2089   /// By default, performs semantic analysis to build the new expression.
   2090   /// Subclasses may override this routine to provide different behavior.
   2091   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
   2092                                          BinaryOperatorKind Opc,
   2093                                          Expr *LHS, Expr *RHS) {
   2094     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
   2095   }
   2096 
   2097   /// \brief Build a new conditional operator expression.
   2098   ///
   2099   /// By default, performs semantic analysis to build the new expression.
   2100   /// Subclasses may override this routine to provide different behavior.
   2101   ExprResult RebuildConditionalOperator(Expr *Cond,
   2102                                         SourceLocation QuestionLoc,
   2103                                         Expr *LHS,
   2104                                         SourceLocation ColonLoc,
   2105                                         Expr *RHS) {
   2106     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
   2107                                         LHS, RHS);
   2108   }
   2109 
   2110   /// \brief Build a new C-style cast expression.
   2111   ///
   2112   /// By default, performs semantic analysis to build the new expression.
   2113   /// Subclasses may override this routine to provide different behavior.
   2114   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
   2115                                          TypeSourceInfo *TInfo,
   2116                                          SourceLocation RParenLoc,
   2117                                          Expr *SubExpr) {
   2118     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
   2119                                          SubExpr);
   2120   }
   2121 
   2122   /// \brief Build a new compound literal expression.
   2123   ///
   2124   /// By default, performs semantic analysis to build the new expression.
   2125   /// Subclasses may override this routine to provide different behavior.
   2126   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
   2127                                               TypeSourceInfo *TInfo,
   2128                                               SourceLocation RParenLoc,
   2129                                               Expr *Init) {
   2130     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
   2131                                               Init);
   2132   }
   2133 
   2134   /// \brief Build a new extended vector element access expression.
   2135   ///
   2136   /// By default, performs semantic analysis to build the new expression.
   2137   /// Subclasses may override this routine to provide different behavior.
   2138   ExprResult RebuildExtVectorElementExpr(Expr *Base,
   2139                                                SourceLocation OpLoc,
   2140                                                SourceLocation AccessorLoc,
   2141                                                IdentifierInfo &Accessor) {
   2142 
   2143     CXXScopeSpec SS;
   2144     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
   2145     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
   2146                                               OpLoc, /*IsArrow*/ false,
   2147                                               SS, SourceLocation(),
   2148                                               /*FirstQualifierInScope*/ nullptr,
   2149                                               NameInfo,
   2150                                               /* TemplateArgs */ nullptr,
   2151                                               /*S*/ nullptr);
   2152   }
   2153 
   2154   /// \brief Build a new initializer list expression.
   2155   ///
   2156   /// By default, performs semantic analysis to build the new expression.
   2157   /// Subclasses may override this routine to provide different behavior.
   2158   ExprResult RebuildInitList(SourceLocation LBraceLoc,
   2159                              MultiExprArg Inits,
   2160                              SourceLocation RBraceLoc,
   2161                              QualType ResultTy) {
   2162     ExprResult Result
   2163       = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
   2164     if (Result.isInvalid() || ResultTy->isDependentType())
   2165       return Result;
   2166 
   2167     // Patch in the result type we were given, which may have been computed
   2168     // when the initial InitListExpr was built.
   2169     InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
   2170     ILE->setType(ResultTy);
   2171     return Result;
   2172   }
   2173 
   2174   /// \brief Build a new designated initializer expression.
   2175   ///
   2176   /// By default, performs semantic analysis to build the new expression.
   2177   /// Subclasses may override this routine to provide different behavior.
   2178   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
   2179                                              MultiExprArg ArrayExprs,
   2180                                              SourceLocation EqualOrColonLoc,
   2181                                              bool GNUSyntax,
   2182                                              Expr *Init) {
   2183     ExprResult Result
   2184       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
   2185                                            Init);
   2186     if (Result.isInvalid())
   2187       return ExprError();
   2188 
   2189     return Result;
   2190   }
   2191 
   2192   /// \brief Build a new value-initialized expression.
   2193   ///
   2194   /// By default, builds the implicit value initialization without performing
   2195   /// any semantic analysis. Subclasses may override this routine to provide
   2196   /// different behavior.
   2197   ExprResult RebuildImplicitValueInitExpr(QualType T) {
   2198     return new (SemaRef.Context) ImplicitValueInitExpr(T);
   2199   }
   2200 
   2201   /// \brief Build a new \c va_arg expression.
   2202   ///
   2203   /// By default, performs semantic analysis to build the new expression.
   2204   /// Subclasses may override this routine to provide different behavior.
   2205   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
   2206                                     Expr *SubExpr, TypeSourceInfo *TInfo,
   2207                                     SourceLocation RParenLoc) {
   2208     return getSema().BuildVAArgExpr(BuiltinLoc,
   2209                                     SubExpr, TInfo,
   2210                                     RParenLoc);
   2211   }
   2212 
   2213   /// \brief Build a new expression list in parentheses.
   2214   ///
   2215   /// By default, performs semantic analysis to build the new expression.
   2216   /// Subclasses may override this routine to provide different behavior.
   2217   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
   2218                                   MultiExprArg SubExprs,
   2219                                   SourceLocation RParenLoc) {
   2220     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
   2221   }
   2222 
   2223   /// \brief Build a new address-of-label expression.
   2224   ///
   2225   /// By default, performs semantic analysis, using the name of the label
   2226   /// rather than attempting to map the label statement itself.
   2227   /// Subclasses may override this routine to provide different behavior.
   2228   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
   2229                                   SourceLocation LabelLoc, LabelDecl *Label) {
   2230     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
   2231   }
   2232 
   2233   /// \brief Build a new GNU statement expression.
   2234   ///
   2235   /// By default, performs semantic analysis to build the new expression.
   2236   /// Subclasses may override this routine to provide different behavior.
   2237   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
   2238                                    Stmt *SubStmt,
   2239                                    SourceLocation RParenLoc) {
   2240     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
   2241   }
   2242 
   2243   /// \brief Build a new __builtin_choose_expr expression.
   2244   ///
   2245   /// By default, performs semantic analysis to build the new expression.
   2246   /// Subclasses may override this routine to provide different behavior.
   2247   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
   2248                                      Expr *Cond, Expr *LHS, Expr *RHS,
   2249                                      SourceLocation RParenLoc) {
   2250     return SemaRef.ActOnChooseExpr(BuiltinLoc,
   2251                                    Cond, LHS, RHS,
   2252                                    RParenLoc);
   2253   }
   2254 
   2255   /// \brief Build a new generic selection expression.
   2256   ///
   2257   /// By default, performs semantic analysis to build the new expression.
   2258   /// Subclasses may override this routine to provide different behavior.
   2259   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
   2260                                          SourceLocation DefaultLoc,
   2261                                          SourceLocation RParenLoc,
   2262                                          Expr *ControllingExpr,
   2263                                          ArrayRef<TypeSourceInfo *> Types,
   2264                                          ArrayRef<Expr *> Exprs) {
   2265     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
   2266                                                 ControllingExpr, Types, Exprs);
   2267   }
   2268 
   2269   /// \brief Build a new overloaded operator call expression.
   2270   ///
   2271   /// By default, performs semantic analysis to build the new expression.
   2272   /// The semantic analysis provides the behavior of template instantiation,
   2273   /// copying with transformations that turn what looks like an overloaded
   2274   /// operator call into a use of a builtin operator, performing
   2275   /// argument-dependent lookup, etc. Subclasses may override this routine to
   2276   /// provide different behavior.
   2277   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
   2278                                               SourceLocation OpLoc,
   2279                                               Expr *Callee,
   2280                                               Expr *First,
   2281                                               Expr *Second);
   2282 
   2283   /// \brief Build a new C++ "named" cast expression, such as static_cast or
   2284   /// reinterpret_cast.
   2285   ///
   2286   /// By default, this routine dispatches to one of the more-specific routines
   2287   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
   2288   /// Subclasses may override this routine to provide different behavior.
   2289   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
   2290                                            Stmt::StmtClass Class,
   2291                                            SourceLocation LAngleLoc,
   2292                                            TypeSourceInfo *TInfo,
   2293                                            SourceLocation RAngleLoc,
   2294                                            SourceLocation LParenLoc,
   2295                                            Expr *SubExpr,
   2296                                            SourceLocation RParenLoc) {
   2297     switch (Class) {
   2298     case Stmt::CXXStaticCastExprClass:
   2299       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
   2300                                                    RAngleLoc, LParenLoc,
   2301                                                    SubExpr, RParenLoc);
   2302 
   2303     case Stmt::CXXDynamicCastExprClass:
   2304       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
   2305                                                     RAngleLoc, LParenLoc,
   2306                                                     SubExpr, RParenLoc);
   2307 
   2308     case Stmt::CXXReinterpretCastExprClass:
   2309       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
   2310                                                         RAngleLoc, LParenLoc,
   2311                                                         SubExpr,
   2312                                                         RParenLoc);
   2313 
   2314     case Stmt::CXXConstCastExprClass:
   2315       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
   2316                                                    RAngleLoc, LParenLoc,
   2317                                                    SubExpr, RParenLoc);
   2318 
   2319     default:
   2320       llvm_unreachable("Invalid C++ named cast");
   2321     }
   2322   }
   2323 
   2324   /// \brief Build a new C++ static_cast expression.
   2325   ///
   2326   /// By default, performs semantic analysis to build the new expression.
   2327   /// Subclasses may override this routine to provide different behavior.
   2328   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
   2329                                             SourceLocation LAngleLoc,
   2330                                             TypeSourceInfo *TInfo,
   2331                                             SourceLocation RAngleLoc,
   2332                                             SourceLocation LParenLoc,
   2333                                             Expr *SubExpr,
   2334                                             SourceLocation RParenLoc) {
   2335     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
   2336                                        TInfo, SubExpr,
   2337                                        SourceRange(LAngleLoc, RAngleLoc),
   2338                                        SourceRange(LParenLoc, RParenLoc));
   2339   }
   2340 
   2341   /// \brief Build a new C++ dynamic_cast expression.
   2342   ///
   2343   /// By default, performs semantic analysis to build the new expression.
   2344   /// Subclasses may override this routine to provide different behavior.
   2345   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
   2346                                              SourceLocation LAngleLoc,
   2347                                              TypeSourceInfo *TInfo,
   2348                                              SourceLocation RAngleLoc,
   2349                                              SourceLocation LParenLoc,
   2350                                              Expr *SubExpr,
   2351                                              SourceLocation RParenLoc) {
   2352     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
   2353                                        TInfo, SubExpr,
   2354                                        SourceRange(LAngleLoc, RAngleLoc),
   2355                                        SourceRange(LParenLoc, RParenLoc));
   2356   }
   2357 
   2358   /// \brief Build a new C++ reinterpret_cast expression.
   2359   ///
   2360   /// By default, performs semantic analysis to build the new expression.
   2361   /// Subclasses may override this routine to provide different behavior.
   2362   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
   2363                                                  SourceLocation LAngleLoc,
   2364                                                  TypeSourceInfo *TInfo,
   2365                                                  SourceLocation RAngleLoc,
   2366                                                  SourceLocation LParenLoc,
   2367                                                  Expr *SubExpr,
   2368                                                  SourceLocation RParenLoc) {
   2369     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
   2370                                        TInfo, SubExpr,
   2371                                        SourceRange(LAngleLoc, RAngleLoc),
   2372                                        SourceRange(LParenLoc, RParenLoc));
   2373   }
   2374 
   2375   /// \brief Build a new C++ const_cast expression.
   2376   ///
   2377   /// By default, performs semantic analysis to build the new expression.
   2378   /// Subclasses may override this routine to provide different behavior.
   2379   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
   2380                                            SourceLocation LAngleLoc,
   2381                                            TypeSourceInfo *TInfo,
   2382                                            SourceLocation RAngleLoc,
   2383                                            SourceLocation LParenLoc,
   2384                                            Expr *SubExpr,
   2385                                            SourceLocation RParenLoc) {
   2386     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
   2387                                        TInfo, SubExpr,
   2388                                        SourceRange(LAngleLoc, RAngleLoc),
   2389                                        SourceRange(LParenLoc, RParenLoc));
   2390   }
   2391 
   2392   /// \brief Build a new C++ functional-style cast expression.
   2393   ///
   2394   /// By default, performs semantic analysis to build the new expression.
   2395   /// Subclasses may override this routine to provide different behavior.
   2396   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
   2397                                           SourceLocation LParenLoc,
   2398                                           Expr *Sub,
   2399                                           SourceLocation RParenLoc) {
   2400     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
   2401                                                MultiExprArg(&Sub, 1),
   2402                                                RParenLoc);
   2403   }
   2404 
   2405   /// \brief Build a new C++ typeid(type) expression.
   2406   ///
   2407   /// By default, performs semantic analysis to build the new expression.
   2408   /// Subclasses may override this routine to provide different behavior.
   2409   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
   2410                                         SourceLocation TypeidLoc,
   2411                                         TypeSourceInfo *Operand,
   2412                                         SourceLocation RParenLoc) {
   2413     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
   2414                                     RParenLoc);
   2415   }
   2416 
   2417 
   2418   /// \brief Build a new C++ typeid(expr) expression.
   2419   ///
   2420   /// By default, performs semantic analysis to build the new expression.
   2421   /// Subclasses may override this routine to provide different behavior.
   2422   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
   2423                                         SourceLocation TypeidLoc,
   2424                                         Expr *Operand,
   2425                                         SourceLocation RParenLoc) {
   2426     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
   2427                                     RParenLoc);
   2428   }
   2429 
   2430   /// \brief Build a new C++ __uuidof(type) expression.
   2431   ///
   2432   /// By default, performs semantic analysis to build the new expression.
   2433   /// Subclasses may override this routine to provide different behavior.
   2434   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
   2435                                         SourceLocation TypeidLoc,
   2436                                         TypeSourceInfo *Operand,
   2437                                         SourceLocation RParenLoc) {
   2438     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
   2439                                     RParenLoc);
   2440   }
   2441 
   2442   /// \brief Build a new C++ __uuidof(expr) expression.
   2443   ///
   2444   /// By default, performs semantic analysis to build the new expression.
   2445   /// Subclasses may override this routine to provide different behavior.
   2446   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
   2447                                         SourceLocation TypeidLoc,
   2448                                         Expr *Operand,
   2449                                         SourceLocation RParenLoc) {
   2450     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
   2451                                     RParenLoc);
   2452   }
   2453 
   2454   /// \brief Build a new C++ "this" expression.
   2455   ///
   2456   /// By default, builds a new "this" expression without performing any
   2457   /// semantic analysis. Subclasses may override this routine to provide
   2458   /// different behavior.
   2459   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
   2460                                 QualType ThisType,
   2461                                 bool isImplicit) {
   2462     getSema().CheckCXXThisCapture(ThisLoc);
   2463     return new (getSema().Context) CXXThisExpr(ThisLoc, ThisType, isImplicit);
   2464   }
   2465 
   2466   /// \brief Build a new C++ throw expression.
   2467   ///
   2468   /// By default, performs semantic analysis to build the new expression.
   2469   /// Subclasses may override this routine to provide different behavior.
   2470   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
   2471                                  bool IsThrownVariableInScope) {
   2472     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
   2473   }
   2474 
   2475   /// \brief Build a new C++ default-argument expression.
   2476   ///
   2477   /// By default, builds a new default-argument expression, which does not
   2478   /// require any semantic analysis. Subclasses may override this routine to
   2479   /// provide different behavior.
   2480   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
   2481                                             ParmVarDecl *Param) {
   2482     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param);
   2483   }
   2484 
   2485   /// \brief Build a new C++11 default-initialization expression.
   2486   ///
   2487   /// By default, builds a new default field initialization expression, which
   2488   /// does not require any semantic analysis. Subclasses may override this
   2489   /// routine to provide different behavior.
   2490   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
   2491                                        FieldDecl *Field) {
   2492     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field);
   2493   }
   2494 
   2495   /// \brief Build a new C++ zero-initialization expression.
   2496   ///
   2497   /// By default, performs semantic analysis to build the new expression.
   2498   /// Subclasses may override this routine to provide different behavior.
   2499   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
   2500                                            SourceLocation LParenLoc,
   2501                                            SourceLocation RParenLoc) {
   2502     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
   2503                                                None, RParenLoc);
   2504   }
   2505 
   2506   /// \brief Build a new C++ "new" expression.
   2507   ///
   2508   /// By default, performs semantic analysis to build the new expression.
   2509   /// Subclasses may override this routine to provide different behavior.
   2510   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
   2511                                bool UseGlobal,
   2512                                SourceLocation PlacementLParen,
   2513                                MultiExprArg PlacementArgs,
   2514                                SourceLocation PlacementRParen,
   2515                                SourceRange TypeIdParens,
   2516                                QualType AllocatedType,
   2517                                TypeSourceInfo *AllocatedTypeInfo,
   2518                                Expr *ArraySize,
   2519                                SourceRange DirectInitRange,
   2520                                Expr *Initializer) {
   2521     return getSema().BuildCXXNew(StartLoc, UseGlobal,
   2522                                  PlacementLParen,
   2523                                  PlacementArgs,
   2524                                  PlacementRParen,
   2525                                  TypeIdParens,
   2526                                  AllocatedType,
   2527                                  AllocatedTypeInfo,
   2528                                  ArraySize,
   2529                                  DirectInitRange,
   2530                                  Initializer);
   2531   }
   2532 
   2533   /// \brief Build a new C++ "delete" expression.
   2534   ///
   2535   /// By default, performs semantic analysis to build the new expression.
   2536   /// Subclasses may override this routine to provide different behavior.
   2537   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
   2538                                         bool IsGlobalDelete,
   2539                                         bool IsArrayForm,
   2540                                         Expr *Operand) {
   2541     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
   2542                                     Operand);
   2543   }
   2544 
   2545   /// \brief Build a new type trait expression.
   2546   ///
   2547   /// By default, performs semantic analysis to build the new expression.
   2548   /// Subclasses may override this routine to provide different behavior.
   2549   ExprResult RebuildTypeTrait(TypeTrait Trait,
   2550                               SourceLocation StartLoc,
   2551                               ArrayRef<TypeSourceInfo *> Args,
   2552                               SourceLocation RParenLoc) {
   2553     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
   2554   }
   2555 
   2556   /// \brief Build a new array type trait expression.
   2557   ///
   2558   /// By default, performs semantic analysis to build the new expression.
   2559   /// Subclasses may override this routine to provide different behavior.
   2560   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
   2561                                    SourceLocation StartLoc,
   2562                                    TypeSourceInfo *TSInfo,
   2563                                    Expr *DimExpr,
   2564                                    SourceLocation RParenLoc) {
   2565     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
   2566   }
   2567 
   2568   /// \brief Build a new expression trait expression.
   2569   ///
   2570   /// By default, performs semantic analysis to build the new expression.
   2571   /// Subclasses may override this routine to provide different behavior.
   2572   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
   2573                                    SourceLocation StartLoc,
   2574                                    Expr *Queried,
   2575                                    SourceLocation RParenLoc) {
   2576     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
   2577   }
   2578 
   2579   /// \brief Build a new (previously unresolved) declaration reference
   2580   /// expression.
   2581   ///
   2582   /// By default, performs semantic analysis to build the new expression.
   2583   /// Subclasses may override this routine to provide different behavior.
   2584   ExprResult RebuildDependentScopeDeclRefExpr(
   2585                                           NestedNameSpecifierLoc QualifierLoc,
   2586                                           SourceLocation TemplateKWLoc,
   2587                                        const DeclarationNameInfo &NameInfo,
   2588                               const TemplateArgumentListInfo *TemplateArgs,
   2589                                           bool IsAddressOfOperand,
   2590                                           TypeSourceInfo **RecoveryTSI) {
   2591     CXXScopeSpec SS;
   2592     SS.Adopt(QualifierLoc);
   2593 
   2594     if (TemplateArgs || TemplateKWLoc.isValid())
   2595       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
   2596                                                     TemplateArgs);
   2597 
   2598     return getSema().BuildQualifiedDeclarationNameExpr(
   2599         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
   2600   }
   2601 
   2602   /// \brief Build a new template-id expression.
   2603   ///
   2604   /// By default, performs semantic analysis to build the new expression.
   2605   /// Subclasses may override this routine to provide different behavior.
   2606   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
   2607                                    SourceLocation TemplateKWLoc,
   2608                                    LookupResult &R,
   2609                                    bool RequiresADL,
   2610                               const TemplateArgumentListInfo *TemplateArgs) {
   2611     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
   2612                                          TemplateArgs);
   2613   }
   2614 
   2615   /// \brief Build a new object-construction expression.
   2616   ///
   2617   /// By default, performs semantic analysis to build the new expression.
   2618   /// Subclasses may override this routine to provide different behavior.
   2619   ExprResult RebuildCXXConstructExpr(QualType T,
   2620                                      SourceLocation Loc,
   2621                                      CXXConstructorDecl *Constructor,
   2622                                      bool IsElidable,
   2623                                      MultiExprArg Args,
   2624                                      bool HadMultipleCandidates,
   2625                                      bool ListInitialization,
   2626                                      bool StdInitListInitialization,
   2627                                      bool RequiresZeroInit,
   2628                              CXXConstructExpr::ConstructionKind ConstructKind,
   2629                                      SourceRange ParenRange) {
   2630     SmallVector<Expr*, 8> ConvertedArgs;
   2631     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
   2632                                           ConvertedArgs))
   2633       return ExprError();
   2634 
   2635     return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
   2636                                            ConvertedArgs,
   2637                                            HadMultipleCandidates,
   2638                                            ListInitialization,
   2639                                            StdInitListInitialization,
   2640                                            RequiresZeroInit, ConstructKind,
   2641                                            ParenRange);
   2642   }
   2643 
   2644   /// \brief Build a new object-construction expression.
   2645   ///
   2646   /// By default, performs semantic analysis to build the new expression.
   2647   /// Subclasses may override this routine to provide different behavior.
   2648   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
   2649                                            SourceLocation LParenLoc,
   2650                                            MultiExprArg Args,
   2651                                            SourceLocation RParenLoc) {
   2652     return getSema().BuildCXXTypeConstructExpr(TSInfo,
   2653                                                LParenLoc,
   2654                                                Args,
   2655                                                RParenLoc);
   2656   }
   2657 
   2658   /// \brief Build a new object-construction expression.
   2659   ///
   2660   /// By default, performs semantic analysis to build the new expression.
   2661   /// Subclasses may override this routine to provide different behavior.
   2662   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
   2663                                                SourceLocation LParenLoc,
   2664                                                MultiExprArg Args,
   2665                                                SourceLocation RParenLoc) {
   2666     return getSema().BuildCXXTypeConstructExpr(TSInfo,
   2667                                                LParenLoc,
   2668                                                Args,
   2669                                                RParenLoc);
   2670   }
   2671 
   2672   /// \brief Build a new member reference expression.
   2673   ///
   2674   /// By default, performs semantic analysis to build the new expression.
   2675   /// Subclasses may override this routine to provide different behavior.
   2676   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
   2677                                                 QualType BaseType,
   2678                                                 bool IsArrow,
   2679                                                 SourceLocation OperatorLoc,
   2680                                           NestedNameSpecifierLoc QualifierLoc,
   2681                                                 SourceLocation TemplateKWLoc,
   2682                                             NamedDecl *FirstQualifierInScope,
   2683                                    const DeclarationNameInfo &MemberNameInfo,
   2684                               const TemplateArgumentListInfo *TemplateArgs) {
   2685     CXXScopeSpec SS;
   2686     SS.Adopt(QualifierLoc);
   2687 
   2688     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
   2689                                             OperatorLoc, IsArrow,
   2690                                             SS, TemplateKWLoc,
   2691                                             FirstQualifierInScope,
   2692                                             MemberNameInfo,
   2693                                             TemplateArgs, /*S*/nullptr);
   2694   }
   2695 
   2696   /// \brief Build a new member reference expression.
   2697   ///
   2698   /// By default, performs semantic analysis to build the new expression.
   2699   /// Subclasses may override this routine to provide different behavior.
   2700   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
   2701                                          SourceLocation OperatorLoc,
   2702                                          bool IsArrow,
   2703                                          NestedNameSpecifierLoc QualifierLoc,
   2704                                          SourceLocation TemplateKWLoc,
   2705                                          NamedDecl *FirstQualifierInScope,
   2706                                          LookupResult &R,
   2707                                 const TemplateArgumentListInfo *TemplateArgs) {
   2708     CXXScopeSpec SS;
   2709     SS.Adopt(QualifierLoc);
   2710 
   2711     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
   2712                                             OperatorLoc, IsArrow,
   2713                                             SS, TemplateKWLoc,
   2714                                             FirstQualifierInScope,
   2715                                             R, TemplateArgs, /*S*/nullptr);
   2716   }
   2717 
   2718   /// \brief Build a new noexcept expression.
   2719   ///
   2720   /// By default, performs semantic analysis to build the new expression.
   2721   /// Subclasses may override this routine to provide different behavior.
   2722   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
   2723     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
   2724   }
   2725 
   2726   /// \brief Build a new expression to compute the length of a parameter pack.
   2727   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
   2728                                    NamedDecl *Pack,
   2729                                    SourceLocation PackLoc,
   2730                                    SourceLocation RParenLoc,
   2731                                    Optional<unsigned> Length,
   2732                                    ArrayRef<TemplateArgument> PartialArgs) {
   2733     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
   2734                                   RParenLoc, Length, PartialArgs);
   2735   }
   2736 
   2737   /// \brief Build a new Objective-C boxed expression.
   2738   ///
   2739   /// By default, performs semantic analysis to build the new expression.
   2740   /// Subclasses may override this routine to provide different behavior.
   2741   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
   2742     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
   2743   }
   2744 
   2745   /// \brief Build a new Objective-C array literal.
   2746   ///
   2747   /// By default, performs semantic analysis to build the new expression.
   2748   /// Subclasses may override this routine to provide different behavior.
   2749   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
   2750                                      Expr **Elements, unsigned NumElements) {
   2751     return getSema().BuildObjCArrayLiteral(Range,
   2752                                            MultiExprArg(Elements, NumElements));
   2753   }
   2754 
   2755   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
   2756                                          Expr *Base, Expr *Key,
   2757                                          ObjCMethodDecl *getterMethod,
   2758                                          ObjCMethodDecl *setterMethod) {
   2759     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
   2760                                                    getterMethod, setterMethod);
   2761   }
   2762 
   2763   /// \brief Build a new Objective-C dictionary literal.
   2764   ///
   2765   /// By default, performs semantic analysis to build the new expression.
   2766   /// Subclasses may override this routine to provide different behavior.
   2767   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
   2768                                           ObjCDictionaryElement *Elements,
   2769                                           unsigned NumElements) {
   2770     return getSema().BuildObjCDictionaryLiteral(Range, Elements, NumElements);
   2771   }
   2772 
   2773   /// \brief Build a new Objective-C \@encode expression.
   2774   ///
   2775   /// By default, performs semantic analysis to build the new expression.
   2776   /// Subclasses may override this routine to provide different behavior.
   2777   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
   2778                                          TypeSourceInfo *EncodeTypeInfo,
   2779                                          SourceLocation RParenLoc) {
   2780     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
   2781   }
   2782 
   2783   /// \brief Build a new Objective-C class message.
   2784   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
   2785                                           Selector Sel,
   2786                                           ArrayRef<SourceLocation> SelectorLocs,
   2787                                           ObjCMethodDecl *Method,
   2788                                           SourceLocation LBracLoc,
   2789                                           MultiExprArg Args,
   2790                                           SourceLocation RBracLoc) {
   2791     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
   2792                                      ReceiverTypeInfo->getType(),
   2793                                      /*SuperLoc=*/SourceLocation(),
   2794                                      Sel, Method, LBracLoc, SelectorLocs,
   2795                                      RBracLoc, Args);
   2796   }
   2797 
   2798   /// \brief Build a new Objective-C instance message.
   2799   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
   2800                                           Selector Sel,
   2801                                           ArrayRef<SourceLocation> SelectorLocs,
   2802                                           ObjCMethodDecl *Method,
   2803                                           SourceLocation LBracLoc,
   2804                                           MultiExprArg Args,
   2805                                           SourceLocation RBracLoc) {
   2806     return SemaRef.BuildInstanceMessage(Receiver,
   2807                                         Receiver->getType(),
   2808                                         /*SuperLoc=*/SourceLocation(),
   2809                                         Sel, Method, LBracLoc, SelectorLocs,
   2810                                         RBracLoc, Args);
   2811   }
   2812 
   2813   /// \brief Build a new Objective-C instance/class message to 'super'.
   2814   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
   2815                                     Selector Sel,
   2816                                     ArrayRef<SourceLocation> SelectorLocs,
   2817                                     QualType SuperType,
   2818                                     ObjCMethodDecl *Method,
   2819                                     SourceLocation LBracLoc,
   2820                                     MultiExprArg Args,
   2821                                     SourceLocation RBracLoc) {
   2822     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
   2823                                           SuperType,
   2824                                           SuperLoc,
   2825                                           Sel, Method, LBracLoc, SelectorLocs,
   2826                                           RBracLoc, Args)
   2827                                       : SemaRef.BuildClassMessage(nullptr,
   2828                                           SuperType,
   2829                                           SuperLoc,
   2830                                           Sel, Method, LBracLoc, SelectorLocs,
   2831                                           RBracLoc, Args);
   2832 
   2833 
   2834   }
   2835 
   2836   /// \brief Build a new Objective-C ivar reference expression.
   2837   ///
   2838   /// By default, performs semantic analysis to build the new expression.
   2839   /// Subclasses may override this routine to provide different behavior.
   2840   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
   2841                                           SourceLocation IvarLoc,
   2842                                           bool IsArrow, bool IsFreeIvar) {
   2843     // FIXME: We lose track of the IsFreeIvar bit.
   2844     CXXScopeSpec SS;
   2845     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
   2846     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
   2847                                               /*FIXME:*/IvarLoc, IsArrow,
   2848                                               SS, SourceLocation(),
   2849                                               /*FirstQualifierInScope=*/nullptr,
   2850                                               NameInfo,
   2851                                               /*TemplateArgs=*/nullptr,
   2852                                               /*S=*/nullptr);
   2853   }
   2854 
   2855   /// \brief Build a new Objective-C property reference expression.
   2856   ///
   2857   /// By default, performs semantic analysis to build the new expression.
   2858   /// Subclasses may override this routine to provide different behavior.
   2859   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
   2860                                         ObjCPropertyDecl *Property,
   2861                                         SourceLocation PropertyLoc) {
   2862     CXXScopeSpec SS;
   2863     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
   2864     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
   2865                                               /*FIXME:*/PropertyLoc,
   2866                                               /*IsArrow=*/false,
   2867                                               SS, SourceLocation(),
   2868                                               /*FirstQualifierInScope=*/nullptr,
   2869                                               NameInfo,
   2870                                               /*TemplateArgs=*/nullptr,
   2871                                               /*S=*/nullptr);
   2872   }
   2873 
   2874   /// \brief Build a new Objective-C property reference expression.
   2875   ///
   2876   /// By default, performs semantic analysis to build the new expression.
   2877   /// Subclasses may override this routine to provide different behavior.
   2878   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
   2879                                         ObjCMethodDecl *Getter,
   2880                                         ObjCMethodDecl *Setter,
   2881                                         SourceLocation PropertyLoc) {
   2882     // Since these expressions can only be value-dependent, we do not
   2883     // need to perform semantic analysis again.
   2884     return Owned(
   2885       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
   2886                                                   VK_LValue, OK_ObjCProperty,
   2887                                                   PropertyLoc, Base));
   2888   }
   2889 
   2890   /// \brief Build a new Objective-C "isa" expression.
   2891   ///
   2892   /// By default, performs semantic analysis to build the new expression.
   2893   /// Subclasses may override this routine to provide different behavior.
   2894   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
   2895                                 SourceLocation OpLoc, bool IsArrow) {
   2896     CXXScopeSpec SS;
   2897     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
   2898     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
   2899                                               OpLoc, IsArrow,
   2900                                               SS, SourceLocation(),
   2901                                               /*FirstQualifierInScope=*/nullptr,
   2902                                               NameInfo,
   2903                                               /*TemplateArgs=*/nullptr,
   2904                                               /*S=*/nullptr);
   2905   }
   2906 
   2907   /// \brief Build a new shuffle vector expression.
   2908   ///
   2909   /// By default, performs semantic analysis to build the new expression.
   2910   /// Subclasses may override this routine to provide different behavior.
   2911   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
   2912                                       MultiExprArg SubExprs,
   2913                                       SourceLocation RParenLoc) {
   2914     // Find the declaration for __builtin_shufflevector
   2915     const IdentifierInfo &Name
   2916       = SemaRef.Context.Idents.get("__builtin_shufflevector");
   2917     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
   2918     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
   2919     assert(!Lookup.empty() && "No __builtin_shufflevector?");
   2920 
   2921     // Build a reference to the __builtin_shufflevector builtin
   2922     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
   2923     Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
   2924                                                   SemaRef.Context.BuiltinFnTy,
   2925                                                   VK_RValue, BuiltinLoc);
   2926     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
   2927     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
   2928                                        CK_BuiltinFnToFnPtr).get();
   2929 
   2930     // Build the CallExpr
   2931     ExprResult TheCall = new (SemaRef.Context) CallExpr(
   2932         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
   2933         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
   2934 
   2935     // Type-check the __builtin_shufflevector expression.
   2936     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
   2937   }
   2938 
   2939   /// \brief Build a new convert vector expression.
   2940   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
   2941                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
   2942                                       SourceLocation RParenLoc) {
   2943     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
   2944                                          BuiltinLoc, RParenLoc);
   2945   }
   2946 
   2947   /// \brief Build a new template argument pack expansion.
   2948   ///
   2949   /// By default, performs semantic analysis to build a new pack expansion
   2950   /// for a template argument. Subclasses may override this routine to provide
   2951   /// different behavior.
   2952   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
   2953                                            SourceLocation EllipsisLoc,
   2954                                            Optional<unsigned> NumExpansions) {
   2955     switch (Pattern.getArgument().getKind()) {
   2956     case TemplateArgument::Expression: {
   2957       ExprResult Result
   2958         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
   2959                                        EllipsisLoc, NumExpansions);
   2960       if (Result.isInvalid())
   2961         return TemplateArgumentLoc();
   2962 
   2963       return TemplateArgumentLoc(Result.get(), Result.get());
   2964     }
   2965 
   2966     case TemplateArgument::Template:
   2967       return TemplateArgumentLoc(TemplateArgument(
   2968                                           Pattern.getArgument().getAsTemplate(),
   2969                                                   NumExpansions),
   2970                                  Pattern.getTemplateQualifierLoc(),
   2971                                  Pattern.getTemplateNameLoc(),
   2972                                  EllipsisLoc);
   2973 
   2974     case TemplateArgument::Null:
   2975     case TemplateArgument::Integral:
   2976     case TemplateArgument::Declaration:
   2977     case TemplateArgument::Pack:
   2978     case TemplateArgument::TemplateExpansion:
   2979     case TemplateArgument::NullPtr:
   2980       llvm_unreachable("Pack expansion pattern has no parameter packs");
   2981 
   2982     case TemplateArgument::Type:
   2983       if (TypeSourceInfo *Expansion
   2984             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
   2985                                            EllipsisLoc,
   2986                                            NumExpansions))
   2987         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
   2988                                    Expansion);
   2989       break;
   2990     }
   2991 
   2992     return TemplateArgumentLoc();
   2993   }
   2994 
   2995   /// \brief Build a new expression pack expansion.
   2996   ///
   2997   /// By default, performs semantic analysis to build a new pack expansion
   2998   /// for an expression. Subclasses may override this routine to provide
   2999   /// different behavior.
   3000   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
   3001                                   Optional<unsigned> NumExpansions) {
   3002     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
   3003   }
   3004 
   3005   /// \brief Build a new C++1z fold-expression.
   3006   ///
   3007   /// By default, performs semantic analysis in order to build a new fold
   3008   /// expression.
   3009   ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
   3010                                 BinaryOperatorKind Operator,
   3011                                 SourceLocation EllipsisLoc, Expr *RHS,
   3012                                 SourceLocation RParenLoc) {
   3013     return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
   3014                                       RHS, RParenLoc);
   3015   }
   3016 
   3017   /// \brief Build an empty C++1z fold-expression with the given operator.
   3018   ///
   3019   /// By default, produces the fallback value for the fold-expression, or
   3020   /// produce an error if there is no fallback value.
   3021   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
   3022                                      BinaryOperatorKind Operator) {
   3023     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
   3024   }
   3025 
   3026   /// \brief Build a new atomic operation expression.
   3027   ///
   3028   /// By default, performs semantic analysis to build the new expression.
   3029   /// Subclasses may override this routine to provide different behavior.
   3030   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
   3031                                MultiExprArg SubExprs,
   3032                                QualType RetTy,
   3033                                AtomicExpr::AtomicOp Op,
   3034                                SourceLocation RParenLoc) {
   3035     // Just create the expression; there is not any interesting semantic
   3036     // analysis here because we can't actually build an AtomicExpr until
   3037     // we are sure it is semantically sound.
   3038     return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
   3039                                             RParenLoc);
   3040   }
   3041 
   3042 private:
   3043   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
   3044                                      QualType ObjectType,
   3045                                      NamedDecl *FirstQualifierInScope,
   3046                                      CXXScopeSpec &SS);
   3047 
   3048   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
   3049                                              QualType ObjectType,
   3050                                              NamedDecl *FirstQualifierInScope,
   3051                                              CXXScopeSpec &SS);
   3052 
   3053   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
   3054                                             NamedDecl *FirstQualifierInScope,
   3055                                             CXXScopeSpec &SS);
   3056 };
   3057 
   3058 template<typename Derived>
   3059 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
   3060   if (!S)
   3061     return S;
   3062 
   3063   switch (S->getStmtClass()) {
   3064   case Stmt::NoStmtClass: break;
   3065 
   3066   // Transform individual statement nodes
   3067 #define STMT(Node, Parent)                                              \
   3068   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
   3069 #define ABSTRACT_STMT(Node)
   3070 #define EXPR(Node, Parent)
   3071 #include "clang/AST/StmtNodes.inc"
   3072 
   3073   // Transform expressions by calling TransformExpr.
   3074 #define STMT(Node, Parent)
   3075 #define ABSTRACT_STMT(Stmt)
   3076 #define EXPR(Node, Parent) case Stmt::Node##Class:
   3077 #include "clang/AST/StmtNodes.inc"
   3078     {
   3079       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
   3080       if (E.isInvalid())
   3081         return StmtError();
   3082 
   3083       return getSema().ActOnExprStmt(E);
   3084     }
   3085   }
   3086 
   3087   return S;
   3088 }
   3089 
   3090 template<typename Derived>
   3091 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
   3092   if (!S)
   3093     return S;
   3094 
   3095   switch (S->getClauseKind()) {
   3096   default: break;
   3097   // Transform individual clause nodes
   3098 #define OPENMP_CLAUSE(Name, Class)                                             \
   3099   case OMPC_ ## Name :                                                         \
   3100     return getDerived().Transform ## Class(cast<Class>(S));
   3101 #include "clang/Basic/OpenMPKinds.def"
   3102   }
   3103 
   3104   return S;
   3105 }
   3106 
   3107 
   3108 template<typename Derived>
   3109 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
   3110   if (!E)
   3111     return E;
   3112 
   3113   switch (E->getStmtClass()) {
   3114     case Stmt::NoStmtClass: break;
   3115 #define STMT(Node, Parent) case Stmt::Node##Class: break;
   3116 #define ABSTRACT_STMT(Stmt)
   3117 #define EXPR(Node, Parent)                                              \
   3118     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
   3119 #include "clang/AST/StmtNodes.inc"
   3120   }
   3121 
   3122   return E;
   3123 }
   3124 
   3125 template<typename Derived>
   3126 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
   3127                                                         bool NotCopyInit) {
   3128   // Initializers are instantiated like expressions, except that various outer
   3129   // layers are stripped.
   3130   if (!Init)
   3131     return Init;
   3132 
   3133   if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
   3134     Init = ExprTemp->getSubExpr();
   3135 
   3136   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
   3137     Init = MTE->GetTemporaryExpr();
   3138 
   3139   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
   3140     Init = Binder->getSubExpr();
   3141 
   3142   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
   3143     Init = ICE->getSubExprAsWritten();
   3144 
   3145   if (CXXStdInitializerListExpr *ILE =
   3146           dyn_cast<CXXStdInitializerListExpr>(Init))
   3147     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
   3148 
   3149   // If this is copy-initialization, we only need to reconstruct
   3150   // InitListExprs. Other forms of copy-initialization will be a no-op if
   3151   // the initializer is already the right type.
   3152   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
   3153   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
   3154     return getDerived().TransformExpr(Init);
   3155 
   3156   // Revert value-initialization back to empty parens.
   3157   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
   3158     SourceRange Parens = VIE->getSourceRange();
   3159     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
   3160                                              Parens.getEnd());
   3161   }
   3162 
   3163   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
   3164   if (isa<ImplicitValueInitExpr>(Init))
   3165     return getDerived().RebuildParenListExpr(SourceLocation(), None,
   3166                                              SourceLocation());
   3167 
   3168   // Revert initialization by constructor back to a parenthesized or braced list
   3169   // of expressions. Any other form of initializer can just be reused directly.
   3170   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
   3171     return getDerived().TransformExpr(Init);
   3172 
   3173   // If the initialization implicitly converted an initializer list to a
   3174   // std::initializer_list object, unwrap the std::initializer_list too.
   3175   if (Construct && Construct->isStdInitListInitialization())
   3176     return TransformInitializer(Construct->getArg(0), NotCopyInit);
   3177 
   3178   SmallVector<Expr*, 8> NewArgs;
   3179   bool ArgChanged = false;
   3180   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
   3181                                   /*IsCall*/true, NewArgs, &ArgChanged))
   3182     return ExprError();
   3183 
   3184   // If this was list initialization, revert to list form.
   3185   if (Construct->isListInitialization())
   3186     return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
   3187                                         Construct->getLocEnd(),
   3188                                         Construct->getType());
   3189 
   3190   // Build a ParenListExpr to represent anything else.
   3191   SourceRange Parens = Construct->getParenOrBraceRange();
   3192   if (Parens.isInvalid()) {
   3193     // This was a variable declaration's initialization for which no initializer
   3194     // was specified.
   3195     assert(NewArgs.empty() &&
   3196            "no parens or braces but have direct init with arguments?");
   3197     return ExprEmpty();
   3198   }
   3199   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
   3200                                            Parens.getEnd());
   3201 }
   3202 
   3203 template<typename Derived>
   3204 bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
   3205                                             unsigned NumInputs,
   3206                                             bool IsCall,
   3207                                       SmallVectorImpl<Expr *> &Outputs,
   3208                                             bool *ArgChanged) {
   3209   for (unsigned I = 0; I != NumInputs; ++I) {
   3210     // If requested, drop call arguments that need to be dropped.
   3211     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
   3212       if (ArgChanged)
   3213         *ArgChanged = true;
   3214 
   3215       break;
   3216     }
   3217 
   3218     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
   3219       Expr *Pattern = Expansion->getPattern();
   3220 
   3221       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   3222       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   3223       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   3224 
   3225       // Determine whether the set of unexpanded parameter packs can and should
   3226       // be expanded.
   3227       bool Expand = true;
   3228       bool RetainExpansion = false;
   3229       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
   3230       Optional<unsigned> NumExpansions = OrigNumExpansions;
   3231       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
   3232                                                Pattern->getSourceRange(),
   3233                                                Unexpanded,
   3234                                                Expand, RetainExpansion,
   3235                                                NumExpansions))
   3236         return true;
   3237 
   3238       if (!Expand) {
   3239         // The transform has determined that we should perform a simple
   3240         // transformation on the pack expansion, producing another pack
   3241         // expansion.
   3242         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   3243         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
   3244         if (OutPattern.isInvalid())
   3245           return true;
   3246 
   3247         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
   3248                                                 Expansion->getEllipsisLoc(),
   3249                                                            NumExpansions);
   3250         if (Out.isInvalid())
   3251           return true;
   3252 
   3253         if (ArgChanged)
   3254           *ArgChanged = true;
   3255         Outputs.push_back(Out.get());
   3256         continue;
   3257       }
   3258 
   3259       // Record right away that the argument was changed.  This needs
   3260       // to happen even if the array expands to nothing.
   3261       if (ArgChanged) *ArgChanged = true;
   3262 
   3263       // The transform has determined that we should perform an elementwise
   3264       // expansion of the pattern. Do so.
   3265       for (unsigned I = 0; I != *NumExpansions; ++I) {
   3266         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   3267         ExprResult Out = getDerived().TransformExpr(Pattern);
   3268         if (Out.isInvalid())
   3269           return true;
   3270 
   3271         // FIXME: Can this happen? We should not try to expand the pack
   3272         // in this case.
   3273         if (Out.get()->containsUnexpandedParameterPack()) {
   3274           Out = getDerived().RebuildPackExpansion(
   3275               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
   3276           if (Out.isInvalid())
   3277             return true;
   3278         }
   3279 
   3280         Outputs.push_back(Out.get());
   3281       }
   3282 
   3283       // If we're supposed to retain a pack expansion, do so by temporarily
   3284       // forgetting the partially-substituted parameter pack.
   3285       if (RetainExpansion) {
   3286         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   3287 
   3288         ExprResult Out = getDerived().TransformExpr(Pattern);
   3289         if (Out.isInvalid())
   3290           return true;
   3291 
   3292         Out = getDerived().RebuildPackExpansion(
   3293             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
   3294         if (Out.isInvalid())
   3295           return true;
   3296 
   3297         Outputs.push_back(Out.get());
   3298       }
   3299 
   3300       continue;
   3301     }
   3302 
   3303     ExprResult Result =
   3304       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
   3305              : getDerived().TransformExpr(Inputs[I]);
   3306     if (Result.isInvalid())
   3307       return true;
   3308 
   3309     if (Result.get() != Inputs[I] && ArgChanged)
   3310       *ArgChanged = true;
   3311 
   3312     Outputs.push_back(Result.get());
   3313   }
   3314 
   3315   return false;
   3316 }
   3317 
   3318 template<typename Derived>
   3319 NestedNameSpecifierLoc
   3320 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
   3321                                                     NestedNameSpecifierLoc NNS,
   3322                                                      QualType ObjectType,
   3323                                              NamedDecl *FirstQualifierInScope) {
   3324   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
   3325   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
   3326        Qualifier = Qualifier.getPrefix())
   3327     Qualifiers.push_back(Qualifier);
   3328 
   3329   CXXScopeSpec SS;
   3330   while (!Qualifiers.empty()) {
   3331     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
   3332     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
   3333 
   3334     switch (QNNS->getKind()) {
   3335     case NestedNameSpecifier::Identifier:
   3336       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr,
   3337                                               *QNNS->getAsIdentifier(),
   3338                                               Q.getLocalBeginLoc(),
   3339                                               Q.getLocalEndLoc(),
   3340                                               ObjectType, false, SS,
   3341                                               FirstQualifierInScope, false))
   3342         return NestedNameSpecifierLoc();
   3343 
   3344       break;
   3345 
   3346     case NestedNameSpecifier::Namespace: {
   3347       NamespaceDecl *NS
   3348         = cast_or_null<NamespaceDecl>(
   3349                                     getDerived().TransformDecl(
   3350                                                           Q.getLocalBeginLoc(),
   3351                                                        QNNS->getAsNamespace()));
   3352       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
   3353       break;
   3354     }
   3355 
   3356     case NestedNameSpecifier::NamespaceAlias: {
   3357       NamespaceAliasDecl *Alias
   3358         = cast_or_null<NamespaceAliasDecl>(
   3359                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
   3360                                                  QNNS->getAsNamespaceAlias()));
   3361       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
   3362                 Q.getLocalEndLoc());
   3363       break;
   3364     }
   3365 
   3366     case NestedNameSpecifier::Global:
   3367       // There is no meaningful transformation that one could perform on the
   3368       // global scope.
   3369       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
   3370       break;
   3371 
   3372     case NestedNameSpecifier::Super: {
   3373       CXXRecordDecl *RD =
   3374           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
   3375               SourceLocation(), QNNS->getAsRecordDecl()));
   3376       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
   3377       break;
   3378     }
   3379 
   3380     case NestedNameSpecifier::TypeSpecWithTemplate:
   3381     case NestedNameSpecifier::TypeSpec: {
   3382       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
   3383                                               FirstQualifierInScope, SS);
   3384 
   3385       if (!TL)
   3386         return NestedNameSpecifierLoc();
   3387 
   3388       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
   3389           (SemaRef.getLangOpts().CPlusPlus11 &&
   3390            TL.getType()->isEnumeralType())) {
   3391         assert(!TL.getType().hasLocalQualifiers() &&
   3392                "Can't get cv-qualifiers here");
   3393         if (TL.getType()->isEnumeralType())
   3394           SemaRef.Diag(TL.getBeginLoc(),
   3395                        diag::warn_cxx98_compat_enum_nested_name_spec);
   3396         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
   3397                   Q.getLocalEndLoc());
   3398         break;
   3399       }
   3400       // If the nested-name-specifier is an invalid type def, don't emit an
   3401       // error because a previous error should have already been emitted.
   3402       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
   3403       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
   3404         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
   3405           << TL.getType() << SS.getRange();
   3406       }
   3407       return NestedNameSpecifierLoc();
   3408     }
   3409     }
   3410 
   3411     // The qualifier-in-scope and object type only apply to the leftmost entity.
   3412     FirstQualifierInScope = nullptr;
   3413     ObjectType = QualType();
   3414   }
   3415 
   3416   // Don't rebuild the nested-name-specifier if we don't have to.
   3417   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
   3418       !getDerived().AlwaysRebuild())
   3419     return NNS;
   3420 
   3421   // If we can re-use the source-location data from the original
   3422   // nested-name-specifier, do so.
   3423   if (SS.location_size() == NNS.getDataLength() &&
   3424       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
   3425     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
   3426 
   3427   // Allocate new nested-name-specifier location information.
   3428   return SS.getWithLocInContext(SemaRef.Context);
   3429 }
   3430 
   3431 template<typename Derived>
   3432 DeclarationNameInfo
   3433 TreeTransform<Derived>
   3434 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
   3435   DeclarationName Name = NameInfo.getName();
   3436   if (!Name)
   3437     return DeclarationNameInfo();
   3438 
   3439   switch (Name.getNameKind()) {
   3440   case DeclarationName::Identifier:
   3441   case DeclarationName::ObjCZeroArgSelector:
   3442   case DeclarationName::ObjCOneArgSelector:
   3443   case DeclarationName::ObjCMultiArgSelector:
   3444   case DeclarationName::CXXOperatorName:
   3445   case DeclarationName::CXXLiteralOperatorName:
   3446   case DeclarationName::CXXUsingDirective:
   3447     return NameInfo;
   3448 
   3449   case DeclarationName::CXXConstructorName:
   3450   case DeclarationName::CXXDestructorName:
   3451   case DeclarationName::CXXConversionFunctionName: {
   3452     TypeSourceInfo *NewTInfo;
   3453     CanQualType NewCanTy;
   3454     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
   3455       NewTInfo = getDerived().TransformType(OldTInfo);
   3456       if (!NewTInfo)
   3457         return DeclarationNameInfo();
   3458       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
   3459     }
   3460     else {
   3461       NewTInfo = nullptr;
   3462       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
   3463       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
   3464       if (NewT.isNull())
   3465         return DeclarationNameInfo();
   3466       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
   3467     }
   3468 
   3469     DeclarationName NewName
   3470       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
   3471                                                            NewCanTy);
   3472     DeclarationNameInfo NewNameInfo(NameInfo);
   3473     NewNameInfo.setName(NewName);
   3474     NewNameInfo.setNamedTypeInfo(NewTInfo);
   3475     return NewNameInfo;
   3476   }
   3477   }
   3478 
   3479   llvm_unreachable("Unknown name kind.");
   3480 }
   3481 
   3482 template<typename Derived>
   3483 TemplateName
   3484 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
   3485                                               TemplateName Name,
   3486                                               SourceLocation NameLoc,
   3487                                               QualType ObjectType,
   3488                                               NamedDecl *FirstQualifierInScope) {
   3489   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
   3490     TemplateDecl *Template = QTN->getTemplateDecl();
   3491     assert(Template && "qualified template name must refer to a template");
   3492 
   3493     TemplateDecl *TransTemplate
   3494       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
   3495                                                               Template));
   3496     if (!TransTemplate)
   3497       return TemplateName();
   3498 
   3499     if (!getDerived().AlwaysRebuild() &&
   3500         SS.getScopeRep() == QTN->getQualifier() &&
   3501         TransTemplate == Template)
   3502       return Name;
   3503 
   3504     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
   3505                                             TransTemplate);
   3506   }
   3507 
   3508   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
   3509     if (SS.getScopeRep()) {
   3510       // These apply to the scope specifier, not the template.
   3511       ObjectType = QualType();
   3512       FirstQualifierInScope = nullptr;
   3513     }
   3514 
   3515     if (!getDerived().AlwaysRebuild() &&
   3516         SS.getScopeRep() == DTN->getQualifier() &&
   3517         ObjectType.isNull())
   3518       return Name;
   3519 
   3520     if (DTN->isIdentifier()) {
   3521       return getDerived().RebuildTemplateName(SS,
   3522                                               *DTN->getIdentifier(),
   3523                                               NameLoc,
   3524                                               ObjectType,
   3525                                               FirstQualifierInScope);
   3526     }
   3527 
   3528     return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
   3529                                             ObjectType);
   3530   }
   3531 
   3532   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
   3533     TemplateDecl *TransTemplate
   3534       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
   3535                                                               Template));
   3536     if (!TransTemplate)
   3537       return TemplateName();
   3538 
   3539     if (!getDerived().AlwaysRebuild() &&
   3540         TransTemplate == Template)
   3541       return Name;
   3542 
   3543     return TemplateName(TransTemplate);
   3544   }
   3545 
   3546   if (SubstTemplateTemplateParmPackStorage *SubstPack
   3547       = Name.getAsSubstTemplateTemplateParmPack()) {
   3548     TemplateTemplateParmDecl *TransParam
   3549     = cast_or_null<TemplateTemplateParmDecl>(
   3550             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
   3551     if (!TransParam)
   3552       return TemplateName();
   3553 
   3554     if (!getDerived().AlwaysRebuild() &&
   3555         TransParam == SubstPack->getParameterPack())
   3556       return Name;
   3557 
   3558     return getDerived().RebuildTemplateName(TransParam,
   3559                                             SubstPack->getArgumentPack());
   3560   }
   3561 
   3562   // These should be getting filtered out before they reach the AST.
   3563   llvm_unreachable("overloaded function decl survived to here");
   3564 }
   3565 
   3566 template<typename Derived>
   3567 void TreeTransform<Derived>::InventTemplateArgumentLoc(
   3568                                          const TemplateArgument &Arg,
   3569                                          TemplateArgumentLoc &Output) {
   3570   SourceLocation Loc = getDerived().getBaseLocation();
   3571   switch (Arg.getKind()) {
   3572   case TemplateArgument::Null:
   3573     llvm_unreachable("null template argument in TreeTransform");
   3574     break;
   3575 
   3576   case TemplateArgument::Type:
   3577     Output = TemplateArgumentLoc(Arg,
   3578                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
   3579 
   3580     break;
   3581 
   3582   case TemplateArgument::Template:
   3583   case TemplateArgument::TemplateExpansion: {
   3584     NestedNameSpecifierLocBuilder Builder;
   3585     TemplateName Template = Arg.getAsTemplate();
   3586     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
   3587       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
   3588     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
   3589       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
   3590 
   3591     if (Arg.getKind() == TemplateArgument::Template)
   3592       Output = TemplateArgumentLoc(Arg,
   3593                                    Builder.getWithLocInContext(SemaRef.Context),
   3594                                    Loc);
   3595     else
   3596       Output = TemplateArgumentLoc(Arg,
   3597                                    Builder.getWithLocInContext(SemaRef.Context),
   3598                                    Loc, Loc);
   3599 
   3600     break;
   3601   }
   3602 
   3603   case TemplateArgument::Expression:
   3604     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
   3605     break;
   3606 
   3607   case TemplateArgument::Declaration:
   3608   case TemplateArgument::Integral:
   3609   case TemplateArgument::Pack:
   3610   case TemplateArgument::NullPtr:
   3611     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
   3612     break;
   3613   }
   3614 }
   3615 
   3616 template<typename Derived>
   3617 bool TreeTransform<Derived>::TransformTemplateArgument(
   3618                                          const TemplateArgumentLoc &Input,
   3619                                          TemplateArgumentLoc &Output, bool Uneval) {
   3620   const TemplateArgument &Arg = Input.getArgument();
   3621   switch (Arg.getKind()) {
   3622   case TemplateArgument::Null:
   3623   case TemplateArgument::Integral:
   3624   case TemplateArgument::Pack:
   3625   case TemplateArgument::Declaration:
   3626   case TemplateArgument::NullPtr:
   3627     llvm_unreachable("Unexpected TemplateArgument");
   3628 
   3629   case TemplateArgument::Type: {
   3630     TypeSourceInfo *DI = Input.getTypeSourceInfo();
   3631     if (!DI)
   3632       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
   3633 
   3634     DI = getDerived().TransformType(DI);
   3635     if (!DI) return true;
   3636 
   3637     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
   3638     return false;
   3639   }
   3640 
   3641   case TemplateArgument::Template: {
   3642     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
   3643     if (QualifierLoc) {
   3644       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
   3645       if (!QualifierLoc)
   3646         return true;
   3647     }
   3648 
   3649     CXXScopeSpec SS;
   3650     SS.Adopt(QualifierLoc);
   3651     TemplateName Template
   3652       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
   3653                                            Input.getTemplateNameLoc());
   3654     if (Template.isNull())
   3655       return true;
   3656 
   3657     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
   3658                                  Input.getTemplateNameLoc());
   3659     return false;
   3660   }
   3661 
   3662   case TemplateArgument::TemplateExpansion:
   3663     llvm_unreachable("Caller should expand pack expansions");
   3664 
   3665   case TemplateArgument::Expression: {
   3666     // Template argument expressions are constant expressions.
   3667     EnterExpressionEvaluationContext Unevaluated(
   3668         getSema(), Uneval ? Sema::Unevaluated : Sema::ConstantEvaluated);
   3669 
   3670     Expr *InputExpr = Input.getSourceExpression();
   3671     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
   3672 
   3673     ExprResult E = getDerived().TransformExpr(InputExpr);
   3674     E = SemaRef.ActOnConstantExpression(E);
   3675     if (E.isInvalid()) return true;
   3676     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
   3677     return false;
   3678   }
   3679   }
   3680 
   3681   // Work around bogus GCC warning
   3682   return true;
   3683 }
   3684 
   3685 /// \brief Iterator adaptor that invents template argument location information
   3686 /// for each of the template arguments in its underlying iterator.
   3687 template<typename Derived, typename InputIterator>
   3688 class TemplateArgumentLocInventIterator {
   3689   TreeTransform<Derived> &Self;
   3690   InputIterator Iter;
   3691 
   3692 public:
   3693   typedef TemplateArgumentLoc value_type;
   3694   typedef TemplateArgumentLoc reference;
   3695   typedef typename std::iterator_traits<InputIterator>::difference_type
   3696     difference_type;
   3697   typedef std::input_iterator_tag iterator_category;
   3698 
   3699   class pointer {
   3700     TemplateArgumentLoc Arg;
   3701 
   3702   public:
   3703     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
   3704 
   3705     const TemplateArgumentLoc *operator->() const { return &Arg; }
   3706   };
   3707 
   3708   TemplateArgumentLocInventIterator() { }
   3709 
   3710   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
   3711                                              InputIterator Iter)
   3712     : Self(Self), Iter(Iter) { }
   3713 
   3714   TemplateArgumentLocInventIterator &operator++() {
   3715     ++Iter;
   3716     return *this;
   3717   }
   3718 
   3719   TemplateArgumentLocInventIterator operator++(int) {
   3720     TemplateArgumentLocInventIterator Old(*this);
   3721     ++(*this);
   3722     return Old;
   3723   }
   3724 
   3725   reference operator*() const {
   3726     TemplateArgumentLoc Result;
   3727     Self.InventTemplateArgumentLoc(*Iter, Result);
   3728     return Result;
   3729   }
   3730 
   3731   pointer operator->() const { return pointer(**this); }
   3732 
   3733   friend bool operator==(const TemplateArgumentLocInventIterator &X,
   3734                          const TemplateArgumentLocInventIterator &Y) {
   3735     return X.Iter == Y.Iter;
   3736   }
   3737 
   3738   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
   3739                          const TemplateArgumentLocInventIterator &Y) {
   3740     return X.Iter != Y.Iter;
   3741   }
   3742 };
   3743 
   3744 template<typename Derived>
   3745 template<typename InputIterator>
   3746 bool TreeTransform<Derived>::TransformTemplateArguments(
   3747     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
   3748     bool Uneval) {
   3749   for (; First != Last; ++First) {
   3750     TemplateArgumentLoc Out;
   3751     TemplateArgumentLoc In = *First;
   3752 
   3753     if (In.getArgument().getKind() == TemplateArgument::Pack) {
   3754       // Unpack argument packs, which we translate them into separate
   3755       // arguments.
   3756       // FIXME: We could do much better if we could guarantee that the
   3757       // TemplateArgumentLocInfo for the pack expansion would be usable for
   3758       // all of the template arguments in the argument pack.
   3759       typedef TemplateArgumentLocInventIterator<Derived,
   3760                                                 TemplateArgument::pack_iterator>
   3761         PackLocIterator;
   3762       if (TransformTemplateArguments(PackLocIterator(*this,
   3763                                                  In.getArgument().pack_begin()),
   3764                                      PackLocIterator(*this,
   3765                                                    In.getArgument().pack_end()),
   3766                                      Outputs, Uneval))
   3767         return true;
   3768 
   3769       continue;
   3770     }
   3771 
   3772     if (In.getArgument().isPackExpansion()) {
   3773       // We have a pack expansion, for which we will be substituting into
   3774       // the pattern.
   3775       SourceLocation Ellipsis;
   3776       Optional<unsigned> OrigNumExpansions;
   3777       TemplateArgumentLoc Pattern
   3778         = getSema().getTemplateArgumentPackExpansionPattern(
   3779               In, Ellipsis, OrigNumExpansions);
   3780 
   3781       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   3782       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   3783       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   3784 
   3785       // Determine whether the set of unexpanded parameter packs can and should
   3786       // be expanded.
   3787       bool Expand = true;
   3788       bool RetainExpansion = false;
   3789       Optional<unsigned> NumExpansions = OrigNumExpansions;
   3790       if (getDerived().TryExpandParameterPacks(Ellipsis,
   3791                                                Pattern.getSourceRange(),
   3792                                                Unexpanded,
   3793                                                Expand,
   3794                                                RetainExpansion,
   3795                                                NumExpansions))
   3796         return true;
   3797 
   3798       if (!Expand) {
   3799         // The transform has determined that we should perform a simple
   3800         // transformation on the pack expansion, producing another pack
   3801         // expansion.
   3802         TemplateArgumentLoc OutPattern;
   3803         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   3804         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
   3805           return true;
   3806 
   3807         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
   3808                                                 NumExpansions);
   3809         if (Out.getArgument().isNull())
   3810           return true;
   3811 
   3812         Outputs.addArgument(Out);
   3813         continue;
   3814       }
   3815 
   3816       // The transform has determined that we should perform an elementwise
   3817       // expansion of the pattern. Do so.
   3818       for (unsigned I = 0; I != *NumExpansions; ++I) {
   3819         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   3820 
   3821         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
   3822           return true;
   3823 
   3824         if (Out.getArgument().containsUnexpandedParameterPack()) {
   3825           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
   3826                                                   OrigNumExpansions);
   3827           if (Out.getArgument().isNull())
   3828             return true;
   3829         }
   3830 
   3831         Outputs.addArgument(Out);
   3832       }
   3833 
   3834       // If we're supposed to retain a pack expansion, do so by temporarily
   3835       // forgetting the partially-substituted parameter pack.
   3836       if (RetainExpansion) {
   3837         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   3838 
   3839         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
   3840           return true;
   3841 
   3842         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
   3843                                                 OrigNumExpansions);
   3844         if (Out.getArgument().isNull())
   3845           return true;
   3846 
   3847         Outputs.addArgument(Out);
   3848       }
   3849 
   3850       continue;
   3851     }
   3852 
   3853     // The simple case:
   3854     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
   3855       return true;
   3856 
   3857     Outputs.addArgument(Out);
   3858   }
   3859 
   3860   return false;
   3861 
   3862 }
   3863 
   3864 //===----------------------------------------------------------------------===//
   3865 // Type transformation
   3866 //===----------------------------------------------------------------------===//
   3867 
   3868 template<typename Derived>
   3869 QualType TreeTransform<Derived>::TransformType(QualType T) {
   3870   if (getDerived().AlreadyTransformed(T))
   3871     return T;
   3872 
   3873   // Temporary workaround.  All of these transformations should
   3874   // eventually turn into transformations on TypeLocs.
   3875   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
   3876                                                 getDerived().getBaseLocation());
   3877 
   3878   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
   3879 
   3880   if (!NewDI)
   3881     return QualType();
   3882 
   3883   return NewDI->getType();
   3884 }
   3885 
   3886 template<typename Derived>
   3887 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
   3888   // Refine the base location to the type's location.
   3889   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
   3890                        getDerived().getBaseEntity());
   3891   if (getDerived().AlreadyTransformed(DI->getType()))
   3892     return DI;
   3893 
   3894   TypeLocBuilder TLB;
   3895 
   3896   TypeLoc TL = DI->getTypeLoc();
   3897   TLB.reserve(TL.getFullDataSize());
   3898 
   3899   QualType Result = getDerived().TransformType(TLB, TL);
   3900   if (Result.isNull())
   3901     return nullptr;
   3902 
   3903   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
   3904 }
   3905 
   3906 template<typename Derived>
   3907 QualType
   3908 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
   3909   switch (T.getTypeLocClass()) {
   3910 #define ABSTRACT_TYPELOC(CLASS, PARENT)
   3911 #define TYPELOC(CLASS, PARENT)                                                 \
   3912   case TypeLoc::CLASS:                                                         \
   3913     return getDerived().Transform##CLASS##Type(TLB,                            \
   3914                                                T.castAs<CLASS##TypeLoc>());
   3915 #include "clang/AST/TypeLocNodes.def"
   3916   }
   3917 
   3918   llvm_unreachable("unhandled type loc!");
   3919 }
   3920 
   3921 /// FIXME: By default, this routine adds type qualifiers only to types
   3922 /// that can have qualifiers, and silently suppresses those qualifiers
   3923 /// that are not permitted (e.g., qualifiers on reference or function
   3924 /// types). This is the right thing for template instantiation, but
   3925 /// probably not for other clients.
   3926 template<typename Derived>
   3927 QualType
   3928 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
   3929                                                QualifiedTypeLoc T) {
   3930   Qualifiers Quals = T.getType().getLocalQualifiers();
   3931 
   3932   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
   3933   if (Result.isNull())
   3934     return QualType();
   3935 
   3936   // Silently suppress qualifiers if the result type can't be qualified.
   3937   // FIXME: this is the right thing for template instantiation, but
   3938   // probably not for other clients.
   3939   if (Result->isFunctionType() || Result->isReferenceType())
   3940     return Result;
   3941 
   3942   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
   3943   // resulting type.
   3944   if (Quals.hasObjCLifetime()) {
   3945     if (!Result->isObjCLifetimeType() && !Result->isDependentType())
   3946       Quals.removeObjCLifetime();
   3947     else if (Result.getObjCLifetime()) {
   3948       // Objective-C ARC:
   3949       //   A lifetime qualifier applied to a substituted template parameter
   3950       //   overrides the lifetime qualifier from the template argument.
   3951       const AutoType *AutoTy;
   3952       if (const SubstTemplateTypeParmType *SubstTypeParam
   3953                                 = dyn_cast<SubstTemplateTypeParmType>(Result)) {
   3954         QualType Replacement = SubstTypeParam->getReplacementType();
   3955         Qualifiers Qs = Replacement.getQualifiers();
   3956         Qs.removeObjCLifetime();
   3957         Replacement
   3958           = SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(),
   3959                                              Qs);
   3960         Result = SemaRef.Context.getSubstTemplateTypeParmType(
   3961                                         SubstTypeParam->getReplacedParameter(),
   3962                                                               Replacement);
   3963         TLB.TypeWasModifiedSafely(Result);
   3964       } else if ((AutoTy = dyn_cast<AutoType>(Result)) && AutoTy->isDeduced()) {
   3965         // 'auto' types behave the same way as template parameters.
   3966         QualType Deduced = AutoTy->getDeducedType();
   3967         Qualifiers Qs = Deduced.getQualifiers();
   3968         Qs.removeObjCLifetime();
   3969         Deduced = SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(),
   3970                                                    Qs);
   3971         Result = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
   3972                                 AutoTy->isDependentType());
   3973         TLB.TypeWasModifiedSafely(Result);
   3974       } else {
   3975         // Otherwise, complain about the addition of a qualifier to an
   3976         // already-qualified type.
   3977         SourceRange R = T.getUnqualifiedLoc().getSourceRange();
   3978         SemaRef.Diag(R.getBegin(), diag::err_attr_objc_ownership_redundant)
   3979           << Result << R;
   3980 
   3981         Quals.removeObjCLifetime();
   3982       }
   3983     }
   3984   }
   3985   if (!Quals.empty()) {
   3986     Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
   3987     // BuildQualifiedType might not add qualifiers if they are invalid.
   3988     if (Result.hasLocalQualifiers())
   3989       TLB.push<QualifiedTypeLoc>(Result);
   3990     // No location information to preserve.
   3991   }
   3992 
   3993   return Result;
   3994 }
   3995 
   3996 template<typename Derived>
   3997 TypeLoc
   3998 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
   3999                                                    QualType ObjectType,
   4000                                                    NamedDecl *UnqualLookup,
   4001                                                    CXXScopeSpec &SS) {
   4002   if (getDerived().AlreadyTransformed(TL.getType()))
   4003     return TL;
   4004 
   4005   TypeSourceInfo *TSI =
   4006       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
   4007   if (TSI)
   4008     return TSI->getTypeLoc();
   4009   return TypeLoc();
   4010 }
   4011 
   4012 template<typename Derived>
   4013 TypeSourceInfo *
   4014 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
   4015                                                    QualType ObjectType,
   4016                                                    NamedDecl *UnqualLookup,
   4017                                                    CXXScopeSpec &SS) {
   4018   if (getDerived().AlreadyTransformed(TSInfo->getType()))
   4019     return TSInfo;
   4020 
   4021   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
   4022                                    UnqualLookup, SS);
   4023 }
   4024 
   4025 template <typename Derived>
   4026 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
   4027     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
   4028     CXXScopeSpec &SS) {
   4029   QualType T = TL.getType();
   4030   assert(!getDerived().AlreadyTransformed(T));
   4031 
   4032   TypeLocBuilder TLB;
   4033   QualType Result;
   4034 
   4035   if (isa<TemplateSpecializationType>(T)) {
   4036     TemplateSpecializationTypeLoc SpecTL =
   4037         TL.castAs<TemplateSpecializationTypeLoc>();
   4038 
   4039     TemplateName Template
   4040     = getDerived().TransformTemplateName(SS,
   4041                                          SpecTL.getTypePtr()->getTemplateName(),
   4042                                          SpecTL.getTemplateNameLoc(),
   4043                                          ObjectType, UnqualLookup);
   4044     if (Template.isNull())
   4045       return nullptr;
   4046 
   4047     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
   4048                                                               Template);
   4049   } else if (isa<DependentTemplateSpecializationType>(T)) {
   4050     DependentTemplateSpecializationTypeLoc SpecTL =
   4051         TL.castAs<DependentTemplateSpecializationTypeLoc>();
   4052 
   4053     TemplateName Template
   4054       = getDerived().RebuildTemplateName(SS,
   4055                                          *SpecTL.getTypePtr()->getIdentifier(),
   4056                                          SpecTL.getTemplateNameLoc(),
   4057                                          ObjectType, UnqualLookup);
   4058     if (Template.isNull())
   4059       return nullptr;
   4060 
   4061     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
   4062                                                                        SpecTL,
   4063                                                                        Template,
   4064                                                                        SS);
   4065   } else {
   4066     // Nothing special needs to be done for these.
   4067     Result = getDerived().TransformType(TLB, TL);
   4068   }
   4069 
   4070   if (Result.isNull())
   4071     return nullptr;
   4072 
   4073   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
   4074 }
   4075 
   4076 template <class TyLoc> static inline
   4077 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
   4078   TyLoc NewT = TLB.push<TyLoc>(T.getType());
   4079   NewT.setNameLoc(T.getNameLoc());
   4080   return T.getType();
   4081 }
   4082 
   4083 template<typename Derived>
   4084 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
   4085                                                       BuiltinTypeLoc T) {
   4086   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
   4087   NewT.setBuiltinLoc(T.getBuiltinLoc());
   4088   if (T.needsExtraLocalData())
   4089     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
   4090   return T.getType();
   4091 }
   4092 
   4093 template<typename Derived>
   4094 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
   4095                                                       ComplexTypeLoc T) {
   4096   // FIXME: recurse?
   4097   return TransformTypeSpecType(TLB, T);
   4098 }
   4099 
   4100 template <typename Derived>
   4101 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
   4102                                                        AdjustedTypeLoc TL) {
   4103   // Adjustments applied during transformation are handled elsewhere.
   4104   return getDerived().TransformType(TLB, TL.getOriginalLoc());
   4105 }
   4106 
   4107 template<typename Derived>
   4108 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
   4109                                                       DecayedTypeLoc TL) {
   4110   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
   4111   if (OriginalType.isNull())
   4112     return QualType();
   4113 
   4114   QualType Result = TL.getType();
   4115   if (getDerived().AlwaysRebuild() ||
   4116       OriginalType != TL.getOriginalLoc().getType())
   4117     Result = SemaRef.Context.getDecayedType(OriginalType);
   4118   TLB.push<DecayedTypeLoc>(Result);
   4119   // Nothing to set for DecayedTypeLoc.
   4120   return Result;
   4121 }
   4122 
   4123 template<typename Derived>
   4124 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
   4125                                                       PointerTypeLoc TL) {
   4126   QualType PointeeType
   4127     = getDerived().TransformType(TLB, TL.getPointeeLoc());
   4128   if (PointeeType.isNull())
   4129     return QualType();
   4130 
   4131   QualType Result = TL.getType();
   4132   if (PointeeType->getAs<ObjCObjectType>()) {
   4133     // A dependent pointer type 'T *' has is being transformed such
   4134     // that an Objective-C class type is being replaced for 'T'. The
   4135     // resulting pointer type is an ObjCObjectPointerType, not a
   4136     // PointerType.
   4137     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
   4138 
   4139     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
   4140     NewT.setStarLoc(TL.getStarLoc());
   4141     return Result;
   4142   }
   4143 
   4144   if (getDerived().AlwaysRebuild() ||
   4145       PointeeType != TL.getPointeeLoc().getType()) {
   4146     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
   4147     if (Result.isNull())
   4148       return QualType();
   4149   }
   4150 
   4151   // Objective-C ARC can add lifetime qualifiers to the type that we're
   4152   // pointing to.
   4153   TLB.TypeWasModifiedSafely(Result->getPointeeType());
   4154 
   4155   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
   4156   NewT.setSigilLoc(TL.getSigilLoc());
   4157   return Result;
   4158 }
   4159 
   4160 template<typename Derived>
   4161 QualType
   4162 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
   4163                                                   BlockPointerTypeLoc TL) {
   4164   QualType PointeeType
   4165     = getDerived().TransformType(TLB, TL.getPointeeLoc());
   4166   if (PointeeType.isNull())
   4167     return QualType();
   4168 
   4169   QualType Result = TL.getType();
   4170   if (getDerived().AlwaysRebuild() ||
   4171       PointeeType != TL.getPointeeLoc().getType()) {
   4172     Result = getDerived().RebuildBlockPointerType(PointeeType,
   4173                                                   TL.getSigilLoc());
   4174     if (Result.isNull())
   4175       return QualType();
   4176   }
   4177 
   4178   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
   4179   NewT.setSigilLoc(TL.getSigilLoc());
   4180   return Result;
   4181 }
   4182 
   4183 /// Transforms a reference type.  Note that somewhat paradoxically we
   4184 /// don't care whether the type itself is an l-value type or an r-value
   4185 /// type;  we only care if the type was *written* as an l-value type
   4186 /// or an r-value type.
   4187 template<typename Derived>
   4188 QualType
   4189 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
   4190                                                ReferenceTypeLoc TL) {
   4191   const ReferenceType *T = TL.getTypePtr();
   4192 
   4193   // Note that this works with the pointee-as-written.
   4194   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
   4195   if (PointeeType.isNull())
   4196     return QualType();
   4197 
   4198   QualType Result = TL.getType();
   4199   if (getDerived().AlwaysRebuild() ||
   4200       PointeeType != T->getPointeeTypeAsWritten()) {
   4201     Result = getDerived().RebuildReferenceType(PointeeType,
   4202                                                T->isSpelledAsLValue(),
   4203                                                TL.getSigilLoc());
   4204     if (Result.isNull())
   4205       return QualType();
   4206   }
   4207 
   4208   // Objective-C ARC can add lifetime qualifiers to the type that we're
   4209   // referring to.
   4210   TLB.TypeWasModifiedSafely(
   4211                      Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
   4212 
   4213   // r-value references can be rebuilt as l-value references.
   4214   ReferenceTypeLoc NewTL;
   4215   if (isa<LValueReferenceType>(Result))
   4216     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
   4217   else
   4218     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
   4219   NewTL.setSigilLoc(TL.getSigilLoc());
   4220 
   4221   return Result;
   4222 }
   4223 
   4224 template<typename Derived>
   4225 QualType
   4226 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
   4227                                                  LValueReferenceTypeLoc TL) {
   4228   return TransformReferenceType(TLB, TL);
   4229 }
   4230 
   4231 template<typename Derived>
   4232 QualType
   4233 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
   4234                                                  RValueReferenceTypeLoc TL) {
   4235   return TransformReferenceType(TLB, TL);
   4236 }
   4237 
   4238 template<typename Derived>
   4239 QualType
   4240 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
   4241                                                    MemberPointerTypeLoc TL) {
   4242   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
   4243   if (PointeeType.isNull())
   4244     return QualType();
   4245 
   4246   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
   4247   TypeSourceInfo *NewClsTInfo = nullptr;
   4248   if (OldClsTInfo) {
   4249     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
   4250     if (!NewClsTInfo)
   4251       return QualType();
   4252   }
   4253 
   4254   const MemberPointerType *T = TL.getTypePtr();
   4255   QualType OldClsType = QualType(T->getClass(), 0);
   4256   QualType NewClsType;
   4257   if (NewClsTInfo)
   4258     NewClsType = NewClsTInfo->getType();
   4259   else {
   4260     NewClsType = getDerived().TransformType(OldClsType);
   4261     if (NewClsType.isNull())
   4262       return QualType();
   4263   }
   4264 
   4265   QualType Result = TL.getType();
   4266   if (getDerived().AlwaysRebuild() ||
   4267       PointeeType != T->getPointeeType() ||
   4268       NewClsType != OldClsType) {
   4269     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
   4270                                                    TL.getStarLoc());
   4271     if (Result.isNull())
   4272       return QualType();
   4273   }
   4274 
   4275   // If we had to adjust the pointee type when building a member pointer, make
   4276   // sure to push TypeLoc info for it.
   4277   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
   4278   if (MPT && PointeeType != MPT->getPointeeType()) {
   4279     assert(isa<AdjustedType>(MPT->getPointeeType()));
   4280     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
   4281   }
   4282 
   4283   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
   4284   NewTL.setSigilLoc(TL.getSigilLoc());
   4285   NewTL.setClassTInfo(NewClsTInfo);
   4286 
   4287   return Result;
   4288 }
   4289 
   4290 template<typename Derived>
   4291 QualType
   4292 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
   4293                                                    ConstantArrayTypeLoc TL) {
   4294   const ConstantArrayType *T = TL.getTypePtr();
   4295   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   4296   if (ElementType.isNull())
   4297     return QualType();
   4298 
   4299   QualType Result = TL.getType();
   4300   if (getDerived().AlwaysRebuild() ||
   4301       ElementType != T->getElementType()) {
   4302     Result = getDerived().RebuildConstantArrayType(ElementType,
   4303                                                    T->getSizeModifier(),
   4304                                                    T->getSize(),
   4305                                              T->getIndexTypeCVRQualifiers(),
   4306                                                    TL.getBracketsRange());
   4307     if (Result.isNull())
   4308       return QualType();
   4309   }
   4310 
   4311   // We might have either a ConstantArrayType or a VariableArrayType now:
   4312   // a ConstantArrayType is allowed to have an element type which is a
   4313   // VariableArrayType if the type is dependent.  Fortunately, all array
   4314   // types have the same location layout.
   4315   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
   4316   NewTL.setLBracketLoc(TL.getLBracketLoc());
   4317   NewTL.setRBracketLoc(TL.getRBracketLoc());
   4318 
   4319   Expr *Size = TL.getSizeExpr();
   4320   if (Size) {
   4321     EnterExpressionEvaluationContext Unevaluated(SemaRef,
   4322                                                  Sema::ConstantEvaluated);
   4323     Size = getDerived().TransformExpr(Size).template getAs<Expr>();
   4324     Size = SemaRef.ActOnConstantExpression(Size).get();
   4325   }
   4326   NewTL.setSizeExpr(Size);
   4327 
   4328   return Result;
   4329 }
   4330 
   4331 template<typename Derived>
   4332 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
   4333                                               TypeLocBuilder &TLB,
   4334                                               IncompleteArrayTypeLoc TL) {
   4335   const IncompleteArrayType *T = TL.getTypePtr();
   4336   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   4337   if (ElementType.isNull())
   4338     return QualType();
   4339 
   4340   QualType Result = TL.getType();
   4341   if (getDerived().AlwaysRebuild() ||
   4342       ElementType != T->getElementType()) {
   4343     Result = getDerived().RebuildIncompleteArrayType(ElementType,
   4344                                                      T->getSizeModifier(),
   4345                                            T->getIndexTypeCVRQualifiers(),
   4346                                                      TL.getBracketsRange());
   4347     if (Result.isNull())
   4348       return QualType();
   4349   }
   4350 
   4351   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
   4352   NewTL.setLBracketLoc(TL.getLBracketLoc());
   4353   NewTL.setRBracketLoc(TL.getRBracketLoc());
   4354   NewTL.setSizeExpr(nullptr);
   4355 
   4356   return Result;
   4357 }
   4358 
   4359 template<typename Derived>
   4360 QualType
   4361 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
   4362                                                    VariableArrayTypeLoc TL) {
   4363   const VariableArrayType *T = TL.getTypePtr();
   4364   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   4365   if (ElementType.isNull())
   4366     return QualType();
   4367 
   4368   ExprResult SizeResult
   4369     = getDerived().TransformExpr(T->getSizeExpr());
   4370   if (SizeResult.isInvalid())
   4371     return QualType();
   4372 
   4373   Expr *Size = SizeResult.get();
   4374 
   4375   QualType Result = TL.getType();
   4376   if (getDerived().AlwaysRebuild() ||
   4377       ElementType != T->getElementType() ||
   4378       Size != T->getSizeExpr()) {
   4379     Result = getDerived().RebuildVariableArrayType(ElementType,
   4380                                                    T->getSizeModifier(),
   4381                                                    Size,
   4382                                              T->getIndexTypeCVRQualifiers(),
   4383                                                    TL.getBracketsRange());
   4384     if (Result.isNull())
   4385       return QualType();
   4386   }
   4387 
   4388   // We might have constant size array now, but fortunately it has the same
   4389   // location layout.
   4390   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
   4391   NewTL.setLBracketLoc(TL.getLBracketLoc());
   4392   NewTL.setRBracketLoc(TL.getRBracketLoc());
   4393   NewTL.setSizeExpr(Size);
   4394 
   4395   return Result;
   4396 }
   4397 
   4398 template<typename Derived>
   4399 QualType
   4400 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
   4401                                              DependentSizedArrayTypeLoc TL) {
   4402   const DependentSizedArrayType *T = TL.getTypePtr();
   4403   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   4404   if (ElementType.isNull())
   4405     return QualType();
   4406 
   4407   // Array bounds are constant expressions.
   4408   EnterExpressionEvaluationContext Unevaluated(SemaRef,
   4409                                                Sema::ConstantEvaluated);
   4410 
   4411   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
   4412   Expr *origSize = TL.getSizeExpr();
   4413   if (!origSize) origSize = T->getSizeExpr();
   4414 
   4415   ExprResult sizeResult
   4416     = getDerived().TransformExpr(origSize);
   4417   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
   4418   if (sizeResult.isInvalid())
   4419     return QualType();
   4420 
   4421   Expr *size = sizeResult.get();
   4422 
   4423   QualType Result = TL.getType();
   4424   if (getDerived().AlwaysRebuild() ||
   4425       ElementType != T->getElementType() ||
   4426       size != origSize) {
   4427     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
   4428                                                          T->getSizeModifier(),
   4429                                                          size,
   4430                                                 T->getIndexTypeCVRQualifiers(),
   4431                                                         TL.getBracketsRange());
   4432     if (Result.isNull())
   4433       return QualType();
   4434   }
   4435 
   4436   // We might have any sort of array type now, but fortunately they
   4437   // all have the same location layout.
   4438   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
   4439   NewTL.setLBracketLoc(TL.getLBracketLoc());
   4440   NewTL.setRBracketLoc(TL.getRBracketLoc());
   4441   NewTL.setSizeExpr(size);
   4442 
   4443   return Result;
   4444 }
   4445 
   4446 template<typename Derived>
   4447 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
   4448                                       TypeLocBuilder &TLB,
   4449                                       DependentSizedExtVectorTypeLoc TL) {
   4450   const DependentSizedExtVectorType *T = TL.getTypePtr();
   4451 
   4452   // FIXME: ext vector locs should be nested
   4453   QualType ElementType = getDerived().TransformType(T->getElementType());
   4454   if (ElementType.isNull())
   4455     return QualType();
   4456 
   4457   // Vector sizes are constant expressions.
   4458   EnterExpressionEvaluationContext Unevaluated(SemaRef,
   4459                                                Sema::ConstantEvaluated);
   4460 
   4461   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
   4462   Size = SemaRef.ActOnConstantExpression(Size);
   4463   if (Size.isInvalid())
   4464     return QualType();
   4465 
   4466   QualType Result = TL.getType();
   4467   if (getDerived().AlwaysRebuild() ||
   4468       ElementType != T->getElementType() ||
   4469       Size.get() != T->getSizeExpr()) {
   4470     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
   4471                                                              Size.get(),
   4472                                                          T->getAttributeLoc());
   4473     if (Result.isNull())
   4474       return QualType();
   4475   }
   4476 
   4477   // Result might be dependent or not.
   4478   if (isa<DependentSizedExtVectorType>(Result)) {
   4479     DependentSizedExtVectorTypeLoc NewTL
   4480       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
   4481     NewTL.setNameLoc(TL.getNameLoc());
   4482   } else {
   4483     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
   4484     NewTL.setNameLoc(TL.getNameLoc());
   4485   }
   4486 
   4487   return Result;
   4488 }
   4489 
   4490 template<typename Derived>
   4491 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
   4492                                                      VectorTypeLoc TL) {
   4493   const VectorType *T = TL.getTypePtr();
   4494   QualType ElementType = getDerived().TransformType(T->getElementType());
   4495   if (ElementType.isNull())
   4496     return QualType();
   4497 
   4498   QualType Result = TL.getType();
   4499   if (getDerived().AlwaysRebuild() ||
   4500       ElementType != T->getElementType()) {
   4501     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
   4502                                             T->getVectorKind());
   4503     if (Result.isNull())
   4504       return QualType();
   4505   }
   4506 
   4507   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
   4508   NewTL.setNameLoc(TL.getNameLoc());
   4509 
   4510   return Result;
   4511 }
   4512 
   4513 template<typename Derived>
   4514 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
   4515                                                         ExtVectorTypeLoc TL) {
   4516   const VectorType *T = TL.getTypePtr();
   4517   QualType ElementType = getDerived().TransformType(T->getElementType());
   4518   if (ElementType.isNull())
   4519     return QualType();
   4520 
   4521   QualType Result = TL.getType();
   4522   if (getDerived().AlwaysRebuild() ||
   4523       ElementType != T->getElementType()) {
   4524     Result = getDerived().RebuildExtVectorType(ElementType,
   4525                                                T->getNumElements(),
   4526                                                /*FIXME*/ SourceLocation());
   4527     if (Result.isNull())
   4528       return QualType();
   4529   }
   4530 
   4531   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
   4532   NewTL.setNameLoc(TL.getNameLoc());
   4533 
   4534   return Result;
   4535 }
   4536 
   4537 template <typename Derived>
   4538 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
   4539     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
   4540     bool ExpectParameterPack) {
   4541   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
   4542   TypeSourceInfo *NewDI = nullptr;
   4543 
   4544   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
   4545     // If we're substituting into a pack expansion type and we know the
   4546     // length we want to expand to, just substitute for the pattern.
   4547     TypeLoc OldTL = OldDI->getTypeLoc();
   4548     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
   4549 
   4550     TypeLocBuilder TLB;
   4551     TypeLoc NewTL = OldDI->getTypeLoc();
   4552     TLB.reserve(NewTL.getFullDataSize());
   4553 
   4554     QualType Result = getDerived().TransformType(TLB,
   4555                                                OldExpansionTL.getPatternLoc());
   4556     if (Result.isNull())
   4557       return nullptr;
   4558 
   4559     Result = RebuildPackExpansionType(Result,
   4560                                 OldExpansionTL.getPatternLoc().getSourceRange(),
   4561                                       OldExpansionTL.getEllipsisLoc(),
   4562                                       NumExpansions);
   4563     if (Result.isNull())
   4564       return nullptr;
   4565 
   4566     PackExpansionTypeLoc NewExpansionTL
   4567       = TLB.push<PackExpansionTypeLoc>(Result);
   4568     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
   4569     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
   4570   } else
   4571     NewDI = getDerived().TransformType(OldDI);
   4572   if (!NewDI)
   4573     return nullptr;
   4574 
   4575   if (NewDI == OldDI && indexAdjustment == 0)
   4576     return OldParm;
   4577 
   4578   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
   4579                                              OldParm->getDeclContext(),
   4580                                              OldParm->getInnerLocStart(),
   4581                                              OldParm->getLocation(),
   4582                                              OldParm->getIdentifier(),
   4583                                              NewDI->getType(),
   4584                                              NewDI,
   4585                                              OldParm->getStorageClass(),
   4586                                              /* DefArg */ nullptr);
   4587   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
   4588                         OldParm->getFunctionScopeIndex() + indexAdjustment);
   4589   return newParm;
   4590 }
   4591 
   4592 template<typename Derived>
   4593 bool TreeTransform<Derived>::
   4594   TransformFunctionTypeParams(SourceLocation Loc,
   4595                               ParmVarDecl **Params, unsigned NumParams,
   4596                               const QualType *ParamTypes,
   4597                               SmallVectorImpl<QualType> &OutParamTypes,
   4598                               SmallVectorImpl<ParmVarDecl*> *PVars) {
   4599   int indexAdjustment = 0;
   4600 
   4601   for (unsigned i = 0; i != NumParams; ++i) {
   4602     if (ParmVarDecl *OldParm = Params[i]) {
   4603       assert(OldParm->getFunctionScopeIndex() == i);
   4604 
   4605       Optional<unsigned> NumExpansions;
   4606       ParmVarDecl *NewParm = nullptr;
   4607       if (OldParm->isParameterPack()) {
   4608         // We have a function parameter pack that may need to be expanded.
   4609         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   4610 
   4611         // Find the parameter packs that could be expanded.
   4612         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
   4613         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
   4614         TypeLoc Pattern = ExpansionTL.getPatternLoc();
   4615         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
   4616         assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
   4617 
   4618         // Determine whether we should expand the parameter packs.
   4619         bool ShouldExpand = false;
   4620         bool RetainExpansion = false;
   4621         Optional<unsigned> OrigNumExpansions =
   4622             ExpansionTL.getTypePtr()->getNumExpansions();
   4623         NumExpansions = OrigNumExpansions;
   4624         if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
   4625                                                  Pattern.getSourceRange(),
   4626                                                  Unexpanded,
   4627                                                  ShouldExpand,
   4628                                                  RetainExpansion,
   4629                                                  NumExpansions)) {
   4630           return true;
   4631         }
   4632 
   4633         if (ShouldExpand) {
   4634           // Expand the function parameter pack into multiple, separate
   4635           // parameters.
   4636           getDerived().ExpandingFunctionParameterPack(OldParm);
   4637           for (unsigned I = 0; I != *NumExpansions; ++I) {
   4638             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   4639             ParmVarDecl *NewParm
   4640               = getDerived().TransformFunctionTypeParam(OldParm,
   4641                                                         indexAdjustment++,
   4642                                                         OrigNumExpansions,
   4643                                                 /*ExpectParameterPack=*/false);
   4644             if (!NewParm)
   4645               return true;
   4646 
   4647             OutParamTypes.push_back(NewParm->getType());
   4648             if (PVars)
   4649               PVars->push_back(NewParm);
   4650           }
   4651 
   4652           // If we're supposed to retain a pack expansion, do so by temporarily
   4653           // forgetting the partially-substituted parameter pack.
   4654           if (RetainExpansion) {
   4655             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   4656             ParmVarDecl *NewParm
   4657               = getDerived().TransformFunctionTypeParam(OldParm,
   4658                                                         indexAdjustment++,
   4659                                                         OrigNumExpansions,
   4660                                                 /*ExpectParameterPack=*/false);
   4661             if (!NewParm)
   4662               return true;
   4663 
   4664             OutParamTypes.push_back(NewParm->getType());
   4665             if (PVars)
   4666               PVars->push_back(NewParm);
   4667           }
   4668 
   4669           // The next parameter should have the same adjustment as the
   4670           // last thing we pushed, but we post-incremented indexAdjustment
   4671           // on every push.  Also, if we push nothing, the adjustment should
   4672           // go down by one.
   4673           indexAdjustment--;
   4674 
   4675           // We're done with the pack expansion.
   4676           continue;
   4677         }
   4678 
   4679         // We'll substitute the parameter now without expanding the pack
   4680         // expansion.
   4681         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   4682         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
   4683                                                           indexAdjustment,
   4684                                                           NumExpansions,
   4685                                                   /*ExpectParameterPack=*/true);
   4686       } else {
   4687         NewParm = getDerived().TransformFunctionTypeParam(
   4688             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
   4689       }
   4690 
   4691       if (!NewParm)
   4692         return true;
   4693 
   4694       OutParamTypes.push_back(NewParm->getType());
   4695       if (PVars)
   4696         PVars->push_back(NewParm);
   4697       continue;
   4698     }
   4699 
   4700     // Deal with the possibility that we don't have a parameter
   4701     // declaration for this parameter.
   4702     QualType OldType = ParamTypes[i];
   4703     bool IsPackExpansion = false;
   4704     Optional<unsigned> NumExpansions;
   4705     QualType NewType;
   4706     if (const PackExpansionType *Expansion
   4707                                        = dyn_cast<PackExpansionType>(OldType)) {
   4708       // We have a function parameter pack that may need to be expanded.
   4709       QualType Pattern = Expansion->getPattern();
   4710       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   4711       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   4712 
   4713       // Determine whether we should expand the parameter packs.
   4714       bool ShouldExpand = false;
   4715       bool RetainExpansion = false;
   4716       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
   4717                                                Unexpanded,
   4718                                                ShouldExpand,
   4719                                                RetainExpansion,
   4720                                                NumExpansions)) {
   4721         return true;
   4722       }
   4723 
   4724       if (ShouldExpand) {
   4725         // Expand the function parameter pack into multiple, separate
   4726         // parameters.
   4727         for (unsigned I = 0; I != *NumExpansions; ++I) {
   4728           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   4729           QualType NewType = getDerived().TransformType(Pattern);
   4730           if (NewType.isNull())
   4731             return true;
   4732 
   4733           OutParamTypes.push_back(NewType);
   4734           if (PVars)
   4735             PVars->push_back(nullptr);
   4736         }
   4737 
   4738         // We're done with the pack expansion.
   4739         continue;
   4740       }
   4741 
   4742       // If we're supposed to retain a pack expansion, do so by temporarily
   4743       // forgetting the partially-substituted parameter pack.
   4744       if (RetainExpansion) {
   4745         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   4746         QualType NewType = getDerived().TransformType(Pattern);
   4747         if (NewType.isNull())
   4748           return true;
   4749 
   4750         OutParamTypes.push_back(NewType);
   4751         if (PVars)
   4752           PVars->push_back(nullptr);
   4753       }
   4754 
   4755       // We'll substitute the parameter now without expanding the pack
   4756       // expansion.
   4757       OldType = Expansion->getPattern();
   4758       IsPackExpansion = true;
   4759       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   4760       NewType = getDerived().TransformType(OldType);
   4761     } else {
   4762       NewType = getDerived().TransformType(OldType);
   4763     }
   4764 
   4765     if (NewType.isNull())
   4766       return true;
   4767 
   4768     if (IsPackExpansion)
   4769       NewType = getSema().Context.getPackExpansionType(NewType,
   4770                                                        NumExpansions);
   4771 
   4772     OutParamTypes.push_back(NewType);
   4773     if (PVars)
   4774       PVars->push_back(nullptr);
   4775   }
   4776 
   4777 #ifndef NDEBUG
   4778   if (PVars) {
   4779     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
   4780       if (ParmVarDecl *parm = (*PVars)[i])
   4781         assert(parm->getFunctionScopeIndex() == i);
   4782   }
   4783 #endif
   4784 
   4785   return false;
   4786 }
   4787 
   4788 template<typename Derived>
   4789 QualType
   4790 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
   4791                                                    FunctionProtoTypeLoc TL) {
   4792   SmallVector<QualType, 4> ExceptionStorage;
   4793   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
   4794   return getDerived().TransformFunctionProtoType(
   4795       TLB, TL, nullptr, 0,
   4796       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
   4797         return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
   4798                                             ExceptionStorage, Changed);
   4799       });
   4800 }
   4801 
   4802 template<typename Derived> template<typename Fn>
   4803 QualType TreeTransform<Derived>::TransformFunctionProtoType(
   4804     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
   4805     unsigned ThisTypeQuals, Fn TransformExceptionSpec) {
   4806   // Transform the parameters and return type.
   4807   //
   4808   // We are required to instantiate the params and return type in source order.
   4809   // When the function has a trailing return type, we instantiate the
   4810   // parameters before the return type,  since the return type can then refer
   4811   // to the parameters themselves (via decltype, sizeof, etc.).
   4812   //
   4813   SmallVector<QualType, 4> ParamTypes;
   4814   SmallVector<ParmVarDecl*, 4> ParamDecls;
   4815   const FunctionProtoType *T = TL.getTypePtr();
   4816 
   4817   QualType ResultType;
   4818 
   4819   if (T->hasTrailingReturn()) {
   4820     if (getDerived().TransformFunctionTypeParams(
   4821             TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
   4822             TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
   4823       return QualType();
   4824 
   4825     {
   4826       // C++11 [expr.prim.general]p3:
   4827       //   If a declaration declares a member function or member function
   4828       //   template of a class X, the expression this is a prvalue of type
   4829       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
   4830       //   and the end of the function-definition, member-declarator, or
   4831       //   declarator.
   4832       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
   4833 
   4834       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
   4835       if (ResultType.isNull())
   4836         return QualType();
   4837     }
   4838   }
   4839   else {
   4840     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
   4841     if (ResultType.isNull())
   4842       return QualType();
   4843 
   4844     if (getDerived().TransformFunctionTypeParams(
   4845             TL.getBeginLoc(), TL.getParmArray(), TL.getNumParams(),
   4846             TL.getTypePtr()->param_type_begin(), ParamTypes, &ParamDecls))
   4847       return QualType();
   4848   }
   4849 
   4850   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
   4851 
   4852   bool EPIChanged = false;
   4853   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
   4854     return QualType();
   4855 
   4856   // FIXME: Need to transform ConsumedParameters for variadic template
   4857   // expansion.
   4858 
   4859   QualType Result = TL.getType();
   4860   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
   4861       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
   4862     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
   4863     if (Result.isNull())
   4864       return QualType();
   4865   }
   4866 
   4867   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
   4868   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
   4869   NewTL.setLParenLoc(TL.getLParenLoc());
   4870   NewTL.setRParenLoc(TL.getRParenLoc());
   4871   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
   4872   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
   4873     NewTL.setParam(i, ParamDecls[i]);
   4874 
   4875   return Result;
   4876 }
   4877 
   4878 template<typename Derived>
   4879 bool TreeTransform<Derived>::TransformExceptionSpec(
   4880     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
   4881     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
   4882   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
   4883 
   4884   // Instantiate a dynamic noexcept expression, if any.
   4885   if (ESI.Type == EST_ComputedNoexcept) {
   4886     EnterExpressionEvaluationContext Unevaluated(getSema(),
   4887                                                  Sema::ConstantEvaluated);
   4888     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
   4889     if (NoexceptExpr.isInvalid())
   4890       return true;
   4891 
   4892     NoexceptExpr = getSema().CheckBooleanCondition(
   4893         NoexceptExpr.get(), NoexceptExpr.get()->getLocStart());
   4894     if (NoexceptExpr.isInvalid())
   4895       return true;
   4896 
   4897     if (!NoexceptExpr.get()->isValueDependent()) {
   4898       NoexceptExpr = getSema().VerifyIntegerConstantExpression(
   4899           NoexceptExpr.get(), nullptr,
   4900           diag::err_noexcept_needs_constant_expression,
   4901           /*AllowFold*/false);
   4902       if (NoexceptExpr.isInvalid())
   4903         return true;
   4904     }
   4905 
   4906     if (ESI.NoexceptExpr != NoexceptExpr.get())
   4907       Changed = true;
   4908     ESI.NoexceptExpr = NoexceptExpr.get();
   4909   }
   4910 
   4911   if (ESI.Type != EST_Dynamic)
   4912     return false;
   4913 
   4914   // Instantiate a dynamic exception specification's type.
   4915   for (QualType T : ESI.Exceptions) {
   4916     if (const PackExpansionType *PackExpansion =
   4917             T->getAs<PackExpansionType>()) {
   4918       Changed = true;
   4919 
   4920       // We have a pack expansion. Instantiate it.
   4921       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   4922       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
   4923                                               Unexpanded);
   4924       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   4925 
   4926       // Determine whether the set of unexpanded parameter packs can and
   4927       // should
   4928       // be expanded.
   4929       bool Expand = false;
   4930       bool RetainExpansion = false;
   4931       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
   4932       // FIXME: Track the location of the ellipsis (and track source location
   4933       // information for the types in the exception specification in general).
   4934       if (getDerived().TryExpandParameterPacks(
   4935               Loc, SourceRange(), Unexpanded, Expand,
   4936               RetainExpansion, NumExpansions))
   4937         return true;
   4938 
   4939       if (!Expand) {
   4940         // We can't expand this pack expansion into separate arguments yet;
   4941         // just substitute into the pattern and create a new pack expansion
   4942         // type.
   4943         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   4944         QualType U = getDerived().TransformType(PackExpansion->getPattern());
   4945         if (U.isNull())
   4946           return true;
   4947 
   4948         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
   4949         Exceptions.push_back(U);
   4950         continue;
   4951       }
   4952 
   4953       // Substitute into the pack expansion pattern for each slice of the
   4954       // pack.
   4955       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
   4956         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
   4957 
   4958         QualType U = getDerived().TransformType(PackExpansion->getPattern());
   4959         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
   4960           return true;
   4961 
   4962         Exceptions.push_back(U);
   4963       }
   4964     } else {
   4965       QualType U = getDerived().TransformType(T);
   4966       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
   4967         return true;
   4968       if (T != U)
   4969         Changed = true;
   4970 
   4971       Exceptions.push_back(U);
   4972     }
   4973   }
   4974 
   4975   ESI.Exceptions = Exceptions;
   4976   return false;
   4977 }
   4978 
   4979 template<typename Derived>
   4980 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
   4981                                                  TypeLocBuilder &TLB,
   4982                                                  FunctionNoProtoTypeLoc TL) {
   4983   const FunctionNoProtoType *T = TL.getTypePtr();
   4984   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
   4985   if (ResultType.isNull())
   4986     return QualType();
   4987 
   4988   QualType Result = TL.getType();
   4989   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
   4990     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
   4991 
   4992   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
   4993   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
   4994   NewTL.setLParenLoc(TL.getLParenLoc());
   4995   NewTL.setRParenLoc(TL.getRParenLoc());
   4996   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
   4997 
   4998   return Result;
   4999 }
   5000 
   5001 template<typename Derived> QualType
   5002 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
   5003                                                  UnresolvedUsingTypeLoc TL) {
   5004   const UnresolvedUsingType *T = TL.getTypePtr();
   5005   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
   5006   if (!D)
   5007     return QualType();
   5008 
   5009   QualType Result = TL.getType();
   5010   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
   5011     Result = getDerived().RebuildUnresolvedUsingType(D);
   5012     if (Result.isNull())
   5013       return QualType();
   5014   }
   5015 
   5016   // We might get an arbitrary type spec type back.  We should at
   5017   // least always get a type spec type, though.
   5018   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
   5019   NewTL.setNameLoc(TL.getNameLoc());
   5020 
   5021   return Result;
   5022 }
   5023 
   5024 template<typename Derived>
   5025 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
   5026                                                       TypedefTypeLoc TL) {
   5027   const TypedefType *T = TL.getTypePtr();
   5028   TypedefNameDecl *Typedef
   5029     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   5030                                                                T->getDecl()));
   5031   if (!Typedef)
   5032     return QualType();
   5033 
   5034   QualType Result = TL.getType();
   5035   if (getDerived().AlwaysRebuild() ||
   5036       Typedef != T->getDecl()) {
   5037     Result = getDerived().RebuildTypedefType(Typedef);
   5038     if (Result.isNull())
   5039       return QualType();
   5040   }
   5041 
   5042   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
   5043   NewTL.setNameLoc(TL.getNameLoc());
   5044 
   5045   return Result;
   5046 }
   5047 
   5048 template<typename Derived>
   5049 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
   5050                                                       TypeOfExprTypeLoc TL) {
   5051   // typeof expressions are not potentially evaluated contexts
   5052   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
   5053                                                Sema::ReuseLambdaContextDecl);
   5054 
   5055   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
   5056   if (E.isInvalid())
   5057     return QualType();
   5058 
   5059   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
   5060   if (E.isInvalid())
   5061     return QualType();
   5062 
   5063   QualType Result = TL.getType();
   5064   if (getDerived().AlwaysRebuild() ||
   5065       E.get() != TL.getUnderlyingExpr()) {
   5066     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
   5067     if (Result.isNull())
   5068       return QualType();
   5069   }
   5070   else E.get();
   5071 
   5072   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
   5073   NewTL.setTypeofLoc(TL.getTypeofLoc());
   5074   NewTL.setLParenLoc(TL.getLParenLoc());
   5075   NewTL.setRParenLoc(TL.getRParenLoc());
   5076 
   5077   return Result;
   5078 }
   5079 
   5080 template<typename Derived>
   5081 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
   5082                                                      TypeOfTypeLoc TL) {
   5083   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
   5084   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
   5085   if (!New_Under_TI)
   5086     return QualType();
   5087 
   5088   QualType Result = TL.getType();
   5089   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
   5090     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
   5091     if (Result.isNull())
   5092       return QualType();
   5093   }
   5094 
   5095   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
   5096   NewTL.setTypeofLoc(TL.getTypeofLoc());
   5097   NewTL.setLParenLoc(TL.getLParenLoc());
   5098   NewTL.setRParenLoc(TL.getRParenLoc());
   5099   NewTL.setUnderlyingTInfo(New_Under_TI);
   5100 
   5101   return Result;
   5102 }
   5103 
   5104 template<typename Derived>
   5105 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
   5106                                                        DecltypeTypeLoc TL) {
   5107   const DecltypeType *T = TL.getTypePtr();
   5108 
   5109   // decltype expressions are not potentially evaluated contexts
   5110   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
   5111                                                nullptr, /*IsDecltype=*/ true);
   5112 
   5113   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
   5114   if (E.isInvalid())
   5115     return QualType();
   5116 
   5117   E = getSema().ActOnDecltypeExpression(E.get());
   5118   if (E.isInvalid())
   5119     return QualType();
   5120 
   5121   QualType Result = TL.getType();
   5122   if (getDerived().AlwaysRebuild() ||
   5123       E.get() != T->getUnderlyingExpr()) {
   5124     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
   5125     if (Result.isNull())
   5126       return QualType();
   5127   }
   5128   else E.get();
   5129 
   5130   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
   5131   NewTL.setNameLoc(TL.getNameLoc());
   5132 
   5133   return Result;
   5134 }
   5135 
   5136 template<typename Derived>
   5137 QualType TreeTransform<Derived>::TransformUnaryTransformType(
   5138                                                             TypeLocBuilder &TLB,
   5139                                                      UnaryTransformTypeLoc TL) {
   5140   QualType Result = TL.getType();
   5141   if (Result->isDependentType()) {
   5142     const UnaryTransformType *T = TL.getTypePtr();
   5143     QualType NewBase =
   5144       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
   5145     Result = getDerived().RebuildUnaryTransformType(NewBase,
   5146                                                     T->getUTTKind(),
   5147                                                     TL.getKWLoc());
   5148     if (Result.isNull())
   5149       return QualType();
   5150   }
   5151 
   5152   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
   5153   NewTL.setKWLoc(TL.getKWLoc());
   5154   NewTL.setParensRange(TL.getParensRange());
   5155   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
   5156   return Result;
   5157 }
   5158 
   5159 template<typename Derived>
   5160 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
   5161                                                    AutoTypeLoc TL) {
   5162   const AutoType *T = TL.getTypePtr();
   5163   QualType OldDeduced = T->getDeducedType();
   5164   QualType NewDeduced;
   5165   if (!OldDeduced.isNull()) {
   5166     NewDeduced = getDerived().TransformType(OldDeduced);
   5167     if (NewDeduced.isNull())
   5168       return QualType();
   5169   }
   5170 
   5171   QualType Result = TL.getType();
   5172   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
   5173       T->isDependentType()) {
   5174     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword());
   5175     if (Result.isNull())
   5176       return QualType();
   5177   }
   5178 
   5179   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
   5180   NewTL.setNameLoc(TL.getNameLoc());
   5181 
   5182   return Result;
   5183 }
   5184 
   5185 template<typename Derived>
   5186 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
   5187                                                      RecordTypeLoc TL) {
   5188   const RecordType *T = TL.getTypePtr();
   5189   RecordDecl *Record
   5190     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   5191                                                           T->getDecl()));
   5192   if (!Record)
   5193     return QualType();
   5194 
   5195   QualType Result = TL.getType();
   5196   if (getDerived().AlwaysRebuild() ||
   5197       Record != T->getDecl()) {
   5198     Result = getDerived().RebuildRecordType(Record);
   5199     if (Result.isNull())
   5200       return QualType();
   5201   }
   5202 
   5203   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
   5204   NewTL.setNameLoc(TL.getNameLoc());
   5205 
   5206   return Result;
   5207 }
   5208 
   5209 template<typename Derived>
   5210 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
   5211                                                    EnumTypeLoc TL) {
   5212   const EnumType *T = TL.getTypePtr();
   5213   EnumDecl *Enum
   5214     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   5215                                                         T->getDecl()));
   5216   if (!Enum)
   5217     return QualType();
   5218 
   5219   QualType Result = TL.getType();
   5220   if (getDerived().AlwaysRebuild() ||
   5221       Enum != T->getDecl()) {
   5222     Result = getDerived().RebuildEnumType(Enum);
   5223     if (Result.isNull())
   5224       return QualType();
   5225   }
   5226 
   5227   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
   5228   NewTL.setNameLoc(TL.getNameLoc());
   5229 
   5230   return Result;
   5231 }
   5232 
   5233 template<typename Derived>
   5234 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
   5235                                          TypeLocBuilder &TLB,
   5236                                          InjectedClassNameTypeLoc TL) {
   5237   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
   5238                                        TL.getTypePtr()->getDecl());
   5239   if (!D) return QualType();
   5240 
   5241   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
   5242   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
   5243   return T;
   5244 }
   5245 
   5246 template<typename Derived>
   5247 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
   5248                                                 TypeLocBuilder &TLB,
   5249                                                 TemplateTypeParmTypeLoc TL) {
   5250   return TransformTypeSpecType(TLB, TL);
   5251 }
   5252 
   5253 template<typename Derived>
   5254 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
   5255                                          TypeLocBuilder &TLB,
   5256                                          SubstTemplateTypeParmTypeLoc TL) {
   5257   const SubstTemplateTypeParmType *T = TL.getTypePtr();
   5258 
   5259   // Substitute into the replacement type, which itself might involve something
   5260   // that needs to be transformed. This only tends to occur with default
   5261   // template arguments of template template parameters.
   5262   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
   5263   QualType Replacement = getDerived().TransformType(T->getReplacementType());
   5264   if (Replacement.isNull())
   5265     return QualType();
   5266 
   5267   // Always canonicalize the replacement type.
   5268   Replacement = SemaRef.Context.getCanonicalType(Replacement);
   5269   QualType Result
   5270     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
   5271                                                    Replacement);
   5272 
   5273   // Propagate type-source information.
   5274   SubstTemplateTypeParmTypeLoc NewTL
   5275     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
   5276   NewTL.setNameLoc(TL.getNameLoc());
   5277   return Result;
   5278 
   5279 }
   5280 
   5281 template<typename Derived>
   5282 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
   5283                                           TypeLocBuilder &TLB,
   5284                                           SubstTemplateTypeParmPackTypeLoc TL) {
   5285   return TransformTypeSpecType(TLB, TL);
   5286 }
   5287 
   5288 template<typename Derived>
   5289 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
   5290                                                         TypeLocBuilder &TLB,
   5291                                            TemplateSpecializationTypeLoc TL) {
   5292   const TemplateSpecializationType *T = TL.getTypePtr();
   5293 
   5294   // The nested-name-specifier never matters in a TemplateSpecializationType,
   5295   // because we can't have a dependent nested-name-specifier anyway.
   5296   CXXScopeSpec SS;
   5297   TemplateName Template
   5298     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
   5299                                          TL.getTemplateNameLoc());
   5300   if (Template.isNull())
   5301     return QualType();
   5302 
   5303   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
   5304 }
   5305 
   5306 template<typename Derived>
   5307 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
   5308                                                      AtomicTypeLoc TL) {
   5309   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
   5310   if (ValueType.isNull())
   5311     return QualType();
   5312 
   5313   QualType Result = TL.getType();
   5314   if (getDerived().AlwaysRebuild() ||
   5315       ValueType != TL.getValueLoc().getType()) {
   5316     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
   5317     if (Result.isNull())
   5318       return QualType();
   5319   }
   5320 
   5321   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
   5322   NewTL.setKWLoc(TL.getKWLoc());
   5323   NewTL.setLParenLoc(TL.getLParenLoc());
   5324   NewTL.setRParenLoc(TL.getRParenLoc());
   5325 
   5326   return Result;
   5327 }
   5328 
   5329   /// \brief Simple iterator that traverses the template arguments in a
   5330   /// container that provides a \c getArgLoc() member function.
   5331   ///
   5332   /// This iterator is intended to be used with the iterator form of
   5333   /// \c TreeTransform<Derived>::TransformTemplateArguments().
   5334   template<typename ArgLocContainer>
   5335   class TemplateArgumentLocContainerIterator {
   5336     ArgLocContainer *Container;
   5337     unsigned Index;
   5338 
   5339   public:
   5340     typedef TemplateArgumentLoc value_type;
   5341     typedef TemplateArgumentLoc reference;
   5342     typedef int difference_type;
   5343     typedef std::input_iterator_tag iterator_category;
   5344 
   5345     class pointer {
   5346       TemplateArgumentLoc Arg;
   5347 
   5348     public:
   5349       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
   5350 
   5351       const TemplateArgumentLoc *operator->() const {
   5352         return &Arg;
   5353       }
   5354     };
   5355 
   5356 
   5357     TemplateArgumentLocContainerIterator() {}
   5358 
   5359     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
   5360                                  unsigned Index)
   5361       : Container(&Container), Index(Index) { }
   5362 
   5363     TemplateArgumentLocContainerIterator &operator++() {
   5364       ++Index;
   5365       return *this;
   5366     }
   5367 
   5368     TemplateArgumentLocContainerIterator operator++(int) {
   5369       TemplateArgumentLocContainerIterator Old(*this);
   5370       ++(*this);
   5371       return Old;
   5372     }
   5373 
   5374     TemplateArgumentLoc operator*() const {
   5375       return Container->getArgLoc(Index);
   5376     }
   5377 
   5378     pointer operator->() const {
   5379       return pointer(Container->getArgLoc(Index));
   5380     }
   5381 
   5382     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
   5383                            const TemplateArgumentLocContainerIterator &Y) {
   5384       return X.Container == Y.Container && X.Index == Y.Index;
   5385     }
   5386 
   5387     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
   5388                            const TemplateArgumentLocContainerIterator &Y) {
   5389       return !(X == Y);
   5390     }
   5391   };
   5392 
   5393 
   5394 template <typename Derived>
   5395 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
   5396                                                         TypeLocBuilder &TLB,
   5397                                            TemplateSpecializationTypeLoc TL,
   5398                                                       TemplateName Template) {
   5399   TemplateArgumentListInfo NewTemplateArgs;
   5400   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   5401   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   5402   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
   5403     ArgIterator;
   5404   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   5405                                               ArgIterator(TL, TL.getNumArgs()),
   5406                                               NewTemplateArgs))
   5407     return QualType();
   5408 
   5409   // FIXME: maybe don't rebuild if all the template arguments are the same.
   5410 
   5411   QualType Result =
   5412     getDerived().RebuildTemplateSpecializationType(Template,
   5413                                                    TL.getTemplateNameLoc(),
   5414                                                    NewTemplateArgs);
   5415 
   5416   if (!Result.isNull()) {
   5417     // Specializations of template template parameters are represented as
   5418     // TemplateSpecializationTypes, and substitution of type alias templates
   5419     // within a dependent context can transform them into
   5420     // DependentTemplateSpecializationTypes.
   5421     if (isa<DependentTemplateSpecializationType>(Result)) {
   5422       DependentTemplateSpecializationTypeLoc NewTL
   5423         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   5424       NewTL.setElaboratedKeywordLoc(SourceLocation());
   5425       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
   5426       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5427       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5428       NewTL.setLAngleLoc(TL.getLAngleLoc());
   5429       NewTL.setRAngleLoc(TL.getRAngleLoc());
   5430       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   5431         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   5432       return Result;
   5433     }
   5434 
   5435     TemplateSpecializationTypeLoc NewTL
   5436       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   5437     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5438     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5439     NewTL.setLAngleLoc(TL.getLAngleLoc());
   5440     NewTL.setRAngleLoc(TL.getRAngleLoc());
   5441     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   5442       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   5443   }
   5444 
   5445   return Result;
   5446 }
   5447 
   5448 template <typename Derived>
   5449 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
   5450                                      TypeLocBuilder &TLB,
   5451                                      DependentTemplateSpecializationTypeLoc TL,
   5452                                      TemplateName Template,
   5453                                      CXXScopeSpec &SS) {
   5454   TemplateArgumentListInfo NewTemplateArgs;
   5455   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   5456   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   5457   typedef TemplateArgumentLocContainerIterator<
   5458             DependentTemplateSpecializationTypeLoc> ArgIterator;
   5459   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   5460                                               ArgIterator(TL, TL.getNumArgs()),
   5461                                               NewTemplateArgs))
   5462     return QualType();
   5463 
   5464   // FIXME: maybe don't rebuild if all the template arguments are the same.
   5465 
   5466   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
   5467     QualType Result
   5468       = getSema().Context.getDependentTemplateSpecializationType(
   5469                                                 TL.getTypePtr()->getKeyword(),
   5470                                                          DTN->getQualifier(),
   5471                                                          DTN->getIdentifier(),
   5472                                                                NewTemplateArgs);
   5473 
   5474     DependentTemplateSpecializationTypeLoc NewTL
   5475       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   5476     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5477     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
   5478     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5479     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5480     NewTL.setLAngleLoc(TL.getLAngleLoc());
   5481     NewTL.setRAngleLoc(TL.getRAngleLoc());
   5482     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   5483       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   5484     return Result;
   5485   }
   5486 
   5487   QualType Result
   5488     = getDerived().RebuildTemplateSpecializationType(Template,
   5489                                                      TL.getTemplateNameLoc(),
   5490                                                      NewTemplateArgs);
   5491 
   5492   if (!Result.isNull()) {
   5493     /// FIXME: Wrap this in an elaborated-type-specifier?
   5494     TemplateSpecializationTypeLoc NewTL
   5495       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   5496     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5497     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5498     NewTL.setLAngleLoc(TL.getLAngleLoc());
   5499     NewTL.setRAngleLoc(TL.getRAngleLoc());
   5500     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   5501       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   5502   }
   5503 
   5504   return Result;
   5505 }
   5506 
   5507 template<typename Derived>
   5508 QualType
   5509 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
   5510                                                 ElaboratedTypeLoc TL) {
   5511   const ElaboratedType *T = TL.getTypePtr();
   5512 
   5513   NestedNameSpecifierLoc QualifierLoc;
   5514   // NOTE: the qualifier in an ElaboratedType is optional.
   5515   if (TL.getQualifierLoc()) {
   5516     QualifierLoc
   5517       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   5518     if (!QualifierLoc)
   5519       return QualType();
   5520   }
   5521 
   5522   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
   5523   if (NamedT.isNull())
   5524     return QualType();
   5525 
   5526   // C++0x [dcl.type.elab]p2:
   5527   //   If the identifier resolves to a typedef-name or the simple-template-id
   5528   //   resolves to an alias template specialization, the
   5529   //   elaborated-type-specifier is ill-formed.
   5530   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
   5531     if (const TemplateSpecializationType *TST =
   5532           NamedT->getAs<TemplateSpecializationType>()) {
   5533       TemplateName Template = TST->getTemplateName();
   5534       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
   5535               Template.getAsTemplateDecl())) {
   5536         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
   5537                      diag::err_tag_reference_non_tag) << 4;
   5538         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
   5539       }
   5540     }
   5541   }
   5542 
   5543   QualType Result = TL.getType();
   5544   if (getDerived().AlwaysRebuild() ||
   5545       QualifierLoc != TL.getQualifierLoc() ||
   5546       NamedT != T->getNamedType()) {
   5547     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
   5548                                                 T->getKeyword(),
   5549                                                 QualifierLoc, NamedT);
   5550     if (Result.isNull())
   5551       return QualType();
   5552   }
   5553 
   5554   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   5555   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5556   NewTL.setQualifierLoc(QualifierLoc);
   5557   return Result;
   5558 }
   5559 
   5560 template<typename Derived>
   5561 QualType TreeTransform<Derived>::TransformAttributedType(
   5562                                                 TypeLocBuilder &TLB,
   5563                                                 AttributedTypeLoc TL) {
   5564   const AttributedType *oldType = TL.getTypePtr();
   5565   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
   5566   if (modifiedType.isNull())
   5567     return QualType();
   5568 
   5569   QualType result = TL.getType();
   5570 
   5571   // FIXME: dependent operand expressions?
   5572   if (getDerived().AlwaysRebuild() ||
   5573       modifiedType != oldType->getModifiedType()) {
   5574     // TODO: this is really lame; we should really be rebuilding the
   5575     // equivalent type from first principles.
   5576     QualType equivalentType
   5577       = getDerived().TransformType(oldType->getEquivalentType());
   5578     if (equivalentType.isNull())
   5579       return QualType();
   5580 
   5581     // Check whether we can add nullability; it is only represented as
   5582     // type sugar, and therefore cannot be diagnosed in any other way.
   5583     if (auto nullability = oldType->getImmediateNullability()) {
   5584       if (!modifiedType->canHaveNullability()) {
   5585         SemaRef.Diag(TL.getAttrNameLoc(), diag::err_nullability_nonpointer)
   5586           << DiagNullabilityKind(*nullability, false) << modifiedType;
   5587         return QualType();
   5588       }
   5589     }
   5590 
   5591     result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
   5592                                                modifiedType,
   5593                                                equivalentType);
   5594   }
   5595 
   5596   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
   5597   newTL.setAttrNameLoc(TL.getAttrNameLoc());
   5598   if (TL.hasAttrOperand())
   5599     newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
   5600   if (TL.hasAttrExprOperand())
   5601     newTL.setAttrExprOperand(TL.getAttrExprOperand());
   5602   else if (TL.hasAttrEnumOperand())
   5603     newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
   5604 
   5605   return result;
   5606 }
   5607 
   5608 template<typename Derived>
   5609 QualType
   5610 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
   5611                                            ParenTypeLoc TL) {
   5612   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
   5613   if (Inner.isNull())
   5614     return QualType();
   5615 
   5616   QualType Result = TL.getType();
   5617   if (getDerived().AlwaysRebuild() ||
   5618       Inner != TL.getInnerLoc().getType()) {
   5619     Result = getDerived().RebuildParenType(Inner);
   5620     if (Result.isNull())
   5621       return QualType();
   5622   }
   5623 
   5624   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
   5625   NewTL.setLParenLoc(TL.getLParenLoc());
   5626   NewTL.setRParenLoc(TL.getRParenLoc());
   5627   return Result;
   5628 }
   5629 
   5630 template<typename Derived>
   5631 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
   5632                                                       DependentNameTypeLoc TL) {
   5633   const DependentNameType *T = TL.getTypePtr();
   5634 
   5635   NestedNameSpecifierLoc QualifierLoc
   5636     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   5637   if (!QualifierLoc)
   5638     return QualType();
   5639 
   5640   QualType Result
   5641     = getDerived().RebuildDependentNameType(T->getKeyword(),
   5642                                             TL.getElaboratedKeywordLoc(),
   5643                                             QualifierLoc,
   5644                                             T->getIdentifier(),
   5645                                             TL.getNameLoc());
   5646   if (Result.isNull())
   5647     return QualType();
   5648 
   5649   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
   5650     QualType NamedT = ElabT->getNamedType();
   5651     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
   5652 
   5653     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   5654     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5655     NewTL.setQualifierLoc(QualifierLoc);
   5656   } else {
   5657     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
   5658     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5659     NewTL.setQualifierLoc(QualifierLoc);
   5660     NewTL.setNameLoc(TL.getNameLoc());
   5661   }
   5662   return Result;
   5663 }
   5664 
   5665 template<typename Derived>
   5666 QualType TreeTransform<Derived>::
   5667           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
   5668                                  DependentTemplateSpecializationTypeLoc TL) {
   5669   NestedNameSpecifierLoc QualifierLoc;
   5670   if (TL.getQualifierLoc()) {
   5671     QualifierLoc
   5672       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   5673     if (!QualifierLoc)
   5674       return QualType();
   5675   }
   5676 
   5677   return getDerived()
   5678            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
   5679 }
   5680 
   5681 template<typename Derived>
   5682 QualType TreeTransform<Derived>::
   5683 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
   5684                                    DependentTemplateSpecializationTypeLoc TL,
   5685                                        NestedNameSpecifierLoc QualifierLoc) {
   5686   const DependentTemplateSpecializationType *T = TL.getTypePtr();
   5687 
   5688   TemplateArgumentListInfo NewTemplateArgs;
   5689   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   5690   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   5691 
   5692   typedef TemplateArgumentLocContainerIterator<
   5693   DependentTemplateSpecializationTypeLoc> ArgIterator;
   5694   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   5695                                               ArgIterator(TL, TL.getNumArgs()),
   5696                                               NewTemplateArgs))
   5697     return QualType();
   5698 
   5699   QualType Result
   5700     = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
   5701                                                               QualifierLoc,
   5702                                                             T->getIdentifier(),
   5703                                                        TL.getTemplateNameLoc(),
   5704                                                             NewTemplateArgs);
   5705   if (Result.isNull())
   5706     return QualType();
   5707 
   5708   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
   5709     QualType NamedT = ElabT->getNamedType();
   5710 
   5711     // Copy information relevant to the template specialization.
   5712     TemplateSpecializationTypeLoc NamedTL
   5713       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
   5714     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5715     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5716     NamedTL.setLAngleLoc(TL.getLAngleLoc());
   5717     NamedTL.setRAngleLoc(TL.getRAngleLoc());
   5718     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   5719       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   5720 
   5721     // Copy information relevant to the elaborated type.
   5722     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   5723     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5724     NewTL.setQualifierLoc(QualifierLoc);
   5725   } else if (isa<DependentTemplateSpecializationType>(Result)) {
   5726     DependentTemplateSpecializationTypeLoc SpecTL
   5727       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   5728     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5729     SpecTL.setQualifierLoc(QualifierLoc);
   5730     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5731     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5732     SpecTL.setLAngleLoc(TL.getLAngleLoc());
   5733     SpecTL.setRAngleLoc(TL.getRAngleLoc());
   5734     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   5735       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   5736   } else {
   5737     TemplateSpecializationTypeLoc SpecTL
   5738       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   5739     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5740     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5741     SpecTL.setLAngleLoc(TL.getLAngleLoc());
   5742     SpecTL.setRAngleLoc(TL.getRAngleLoc());
   5743     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   5744       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   5745   }
   5746   return Result;
   5747 }
   5748 
   5749 template<typename Derived>
   5750 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
   5751                                                       PackExpansionTypeLoc TL) {
   5752   QualType Pattern
   5753     = getDerived().TransformType(TLB, TL.getPatternLoc());
   5754   if (Pattern.isNull())
   5755     return QualType();
   5756 
   5757   QualType Result = TL.getType();
   5758   if (getDerived().AlwaysRebuild() ||
   5759       Pattern != TL.getPatternLoc().getType()) {
   5760     Result = getDerived().RebuildPackExpansionType(Pattern,
   5761                                            TL.getPatternLoc().getSourceRange(),
   5762                                                    TL.getEllipsisLoc(),
   5763                                            TL.getTypePtr()->getNumExpansions());
   5764     if (Result.isNull())
   5765       return QualType();
   5766   }
   5767 
   5768   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
   5769   NewT.setEllipsisLoc(TL.getEllipsisLoc());
   5770   return Result;
   5771 }
   5772 
   5773 template<typename Derived>
   5774 QualType
   5775 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
   5776                                                    ObjCInterfaceTypeLoc TL) {
   5777   // ObjCInterfaceType is never dependent.
   5778   TLB.pushFullCopy(TL);
   5779   return TL.getType();
   5780 }
   5781 
   5782 template<typename Derived>
   5783 QualType
   5784 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
   5785                                                 ObjCObjectTypeLoc TL) {
   5786   // Transform base type.
   5787   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
   5788   if (BaseType.isNull())
   5789     return QualType();
   5790 
   5791   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
   5792 
   5793   // Transform type arguments.
   5794   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
   5795   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
   5796     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
   5797     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
   5798     QualType TypeArg = TypeArgInfo->getType();
   5799     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
   5800       AnyChanged = true;
   5801 
   5802       // We have a pack expansion. Instantiate it.
   5803       const auto *PackExpansion = PackExpansionLoc.getType()
   5804                                     ->castAs<PackExpansionType>();
   5805       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   5806       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
   5807                                               Unexpanded);
   5808       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   5809 
   5810       // Determine whether the set of unexpanded parameter packs can
   5811       // and should be expanded.
   5812       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
   5813       bool Expand = false;
   5814       bool RetainExpansion = false;
   5815       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
   5816       if (getDerived().TryExpandParameterPacks(
   5817             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
   5818             Unexpanded, Expand, RetainExpansion, NumExpansions))
   5819         return QualType();
   5820 
   5821       if (!Expand) {
   5822         // We can't expand this pack expansion into separate arguments yet;
   5823         // just substitute into the pattern and create a new pack expansion
   5824         // type.
   5825         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   5826 
   5827         TypeLocBuilder TypeArgBuilder;
   5828         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
   5829         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
   5830                                                              PatternLoc);
   5831         if (NewPatternType.isNull())
   5832           return QualType();
   5833 
   5834         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
   5835                                       NewPatternType, NumExpansions);
   5836         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
   5837         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
   5838         NewTypeArgInfos.push_back(
   5839           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
   5840         continue;
   5841       }
   5842 
   5843       // Substitute into the pack expansion pattern for each slice of the
   5844       // pack.
   5845       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
   5846         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
   5847 
   5848         TypeLocBuilder TypeArgBuilder;
   5849         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
   5850 
   5851         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
   5852                                                          PatternLoc);
   5853         if (NewTypeArg.isNull())
   5854           return QualType();
   5855 
   5856         NewTypeArgInfos.push_back(
   5857           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
   5858       }
   5859 
   5860       continue;
   5861     }
   5862 
   5863     TypeLocBuilder TypeArgBuilder;
   5864     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
   5865     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
   5866     if (NewTypeArg.isNull())
   5867       return QualType();
   5868 
   5869     // If nothing changed, just keep the old TypeSourceInfo.
   5870     if (NewTypeArg == TypeArg) {
   5871       NewTypeArgInfos.push_back(TypeArgInfo);
   5872       continue;
   5873     }
   5874 
   5875     NewTypeArgInfos.push_back(
   5876       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
   5877     AnyChanged = true;
   5878   }
   5879 
   5880   QualType Result = TL.getType();
   5881   if (getDerived().AlwaysRebuild() || AnyChanged) {
   5882     // Rebuild the type.
   5883     Result = getDerived().RebuildObjCObjectType(
   5884                BaseType,
   5885                TL.getLocStart(),
   5886                TL.getTypeArgsLAngleLoc(),
   5887                NewTypeArgInfos,
   5888                TL.getTypeArgsRAngleLoc(),
   5889                TL.getProtocolLAngleLoc(),
   5890                llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
   5891                                   TL.getNumProtocols()),
   5892                TL.getProtocolLocs(),
   5893                TL.getProtocolRAngleLoc());
   5894 
   5895     if (Result.isNull())
   5896       return QualType();
   5897   }
   5898 
   5899   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
   5900   assert(TL.hasBaseTypeAsWritten() && "Can't be dependent");
   5901   NewT.setHasBaseTypeAsWritten(true);
   5902   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
   5903   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
   5904     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
   5905   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
   5906   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
   5907   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
   5908     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
   5909   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
   5910   return Result;
   5911 }
   5912 
   5913 template<typename Derived>
   5914 QualType
   5915 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
   5916                                                ObjCObjectPointerTypeLoc TL) {
   5917   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
   5918   if (PointeeType.isNull())
   5919     return QualType();
   5920 
   5921   QualType Result = TL.getType();
   5922   if (getDerived().AlwaysRebuild() ||
   5923       PointeeType != TL.getPointeeLoc().getType()) {
   5924     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
   5925                                                        TL.getStarLoc());
   5926     if (Result.isNull())
   5927       return QualType();
   5928   }
   5929 
   5930   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
   5931   NewT.setStarLoc(TL.getStarLoc());
   5932   return Result;
   5933 }
   5934 
   5935 //===----------------------------------------------------------------------===//
   5936 // Statement transformation
   5937 //===----------------------------------------------------------------------===//
   5938 template<typename Derived>
   5939 StmtResult
   5940 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
   5941   return S;
   5942 }
   5943 
   5944 template<typename Derived>
   5945 StmtResult
   5946 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
   5947   return getDerived().TransformCompoundStmt(S, false);
   5948 }
   5949 
   5950 template<typename Derived>
   5951 StmtResult
   5952 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
   5953                                               bool IsStmtExpr) {
   5954   Sema::CompoundScopeRAII CompoundScope(getSema());
   5955 
   5956   bool SubStmtInvalid = false;
   5957   bool SubStmtChanged = false;
   5958   SmallVector<Stmt*, 8> Statements;
   5959   for (auto *B : S->body()) {
   5960     StmtResult Result = getDerived().TransformStmt(B);
   5961     if (Result.isInvalid()) {
   5962       // Immediately fail if this was a DeclStmt, since it's very
   5963       // likely that this will cause problems for future statements.
   5964       if (isa<DeclStmt>(B))
   5965         return StmtError();
   5966 
   5967       // Otherwise, just keep processing substatements and fail later.
   5968       SubStmtInvalid = true;
   5969       continue;
   5970     }
   5971 
   5972     SubStmtChanged = SubStmtChanged || Result.get() != B;
   5973     Statements.push_back(Result.getAs<Stmt>());
   5974   }
   5975 
   5976   if (SubStmtInvalid)
   5977     return StmtError();
   5978 
   5979   if (!getDerived().AlwaysRebuild() &&
   5980       !SubStmtChanged)
   5981     return S;
   5982 
   5983   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
   5984                                           Statements,
   5985                                           S->getRBracLoc(),
   5986                                           IsStmtExpr);
   5987 }
   5988 
   5989 template<typename Derived>
   5990 StmtResult
   5991 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
   5992   ExprResult LHS, RHS;
   5993   {
   5994     EnterExpressionEvaluationContext Unevaluated(SemaRef,
   5995                                                  Sema::ConstantEvaluated);
   5996 
   5997     // Transform the left-hand case value.
   5998     LHS = getDerived().TransformExpr(S->getLHS());
   5999     LHS = SemaRef.ActOnConstantExpression(LHS);
   6000     if (LHS.isInvalid())
   6001       return StmtError();
   6002 
   6003     // Transform the right-hand case value (for the GNU case-range extension).
   6004     RHS = getDerived().TransformExpr(S->getRHS());
   6005     RHS = SemaRef.ActOnConstantExpression(RHS);
   6006     if (RHS.isInvalid())
   6007       return StmtError();
   6008   }
   6009 
   6010   // Build the case statement.
   6011   // Case statements are always rebuilt so that they will attached to their
   6012   // transformed switch statement.
   6013   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
   6014                                                        LHS.get(),
   6015                                                        S->getEllipsisLoc(),
   6016                                                        RHS.get(),
   6017                                                        S->getColonLoc());
   6018   if (Case.isInvalid())
   6019     return StmtError();
   6020 
   6021   // Transform the statement following the case
   6022   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   6023   if (SubStmt.isInvalid())
   6024     return StmtError();
   6025 
   6026   // Attach the body to the case statement
   6027   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
   6028 }
   6029 
   6030 template<typename Derived>
   6031 StmtResult
   6032 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
   6033   // Transform the statement following the default case
   6034   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   6035   if (SubStmt.isInvalid())
   6036     return StmtError();
   6037 
   6038   // Default statements are always rebuilt
   6039   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
   6040                                          SubStmt.get());
   6041 }
   6042 
   6043 template<typename Derived>
   6044 StmtResult
   6045 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
   6046   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   6047   if (SubStmt.isInvalid())
   6048     return StmtError();
   6049 
   6050   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
   6051                                         S->getDecl());
   6052   if (!LD)
   6053     return StmtError();
   6054 
   6055 
   6056   // FIXME: Pass the real colon location in.
   6057   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
   6058                                        cast<LabelDecl>(LD), SourceLocation(),
   6059                                        SubStmt.get());
   6060 }
   6061 
   6062 template <typename Derived>
   6063 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
   6064   if (!R)
   6065     return R;
   6066 
   6067   switch (R->getKind()) {
   6068 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
   6069 #define ATTR(X)
   6070 #define PRAGMA_SPELLING_ATTR(X)                                                \
   6071   case attr::X:                                                                \
   6072     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
   6073 #include "clang/Basic/AttrList.inc"
   6074   default:
   6075     return R;
   6076   }
   6077 }
   6078 
   6079 template <typename Derived>
   6080 StmtResult TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
   6081   bool AttrsChanged = false;
   6082   SmallVector<const Attr *, 1> Attrs;
   6083 
   6084   // Visit attributes and keep track if any are transformed.
   6085   for (const auto *I : S->getAttrs()) {
   6086     const Attr *R = getDerived().TransformAttr(I);
   6087     AttrsChanged |= (I != R);
   6088     Attrs.push_back(R);
   6089   }
   6090 
   6091   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   6092   if (SubStmt.isInvalid())
   6093     return StmtError();
   6094 
   6095   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
   6096     return S;
   6097 
   6098   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
   6099                                             SubStmt.get());
   6100 }
   6101 
   6102 template<typename Derived>
   6103 StmtResult
   6104 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
   6105   // Transform the condition
   6106   ExprResult Cond;
   6107   VarDecl *ConditionVar = nullptr;
   6108   if (S->getConditionVariable()) {
   6109     ConditionVar
   6110       = cast_or_null<VarDecl>(
   6111                    getDerived().TransformDefinition(
   6112                                       S->getConditionVariable()->getLocation(),
   6113                                                     S->getConditionVariable()));
   6114     if (!ConditionVar)
   6115       return StmtError();
   6116   } else {
   6117     Cond = getDerived().TransformExpr(S->getCond());
   6118 
   6119     if (Cond.isInvalid())
   6120       return StmtError();
   6121 
   6122     // Convert the condition to a boolean value.
   6123     if (S->getCond()) {
   6124       ExprResult CondE = getSema().ActOnBooleanCondition(nullptr, S->getIfLoc(),
   6125                                                          Cond.get());
   6126       if (CondE.isInvalid())
   6127         return StmtError();
   6128 
   6129       Cond = CondE.get();
   6130     }
   6131   }
   6132 
   6133   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
   6134   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   6135     return StmtError();
   6136 
   6137   // Transform the "then" branch.
   6138   StmtResult Then = getDerived().TransformStmt(S->getThen());
   6139   if (Then.isInvalid())
   6140     return StmtError();
   6141 
   6142   // Transform the "else" branch.
   6143   StmtResult Else = getDerived().TransformStmt(S->getElse());
   6144   if (Else.isInvalid())
   6145     return StmtError();
   6146 
   6147   if (!getDerived().AlwaysRebuild() &&
   6148       FullCond.get() == S->getCond() &&
   6149       ConditionVar == S->getConditionVariable() &&
   6150       Then.get() == S->getThen() &&
   6151       Else.get() == S->getElse())
   6152     return S;
   6153 
   6154   return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
   6155                                     Then.get(),
   6156                                     S->getElseLoc(), Else.get());
   6157 }
   6158 
   6159 template<typename Derived>
   6160 StmtResult
   6161 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
   6162   // Transform the condition.
   6163   ExprResult Cond;
   6164   VarDecl *ConditionVar = nullptr;
   6165   if (S->getConditionVariable()) {
   6166     ConditionVar
   6167       = cast_or_null<VarDecl>(
   6168                    getDerived().TransformDefinition(
   6169                                       S->getConditionVariable()->getLocation(),
   6170                                                     S->getConditionVariable()));
   6171     if (!ConditionVar)
   6172       return StmtError();
   6173   } else {
   6174     Cond = getDerived().TransformExpr(S->getCond());
   6175 
   6176     if (Cond.isInvalid())
   6177       return StmtError();
   6178   }
   6179 
   6180   // Rebuild the switch statement.
   6181   StmtResult Switch
   6182     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
   6183                                           ConditionVar);
   6184   if (Switch.isInvalid())
   6185     return StmtError();
   6186 
   6187   // Transform the body of the switch statement.
   6188   StmtResult Body = getDerived().TransformStmt(S->getBody());
   6189   if (Body.isInvalid())
   6190     return StmtError();
   6191 
   6192   // Complete the switch statement.
   6193   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
   6194                                             Body.get());
   6195 }
   6196 
   6197 template<typename Derived>
   6198 StmtResult
   6199 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
   6200   // Transform the condition
   6201   ExprResult Cond;
   6202   VarDecl *ConditionVar = nullptr;
   6203   if (S->getConditionVariable()) {
   6204     ConditionVar
   6205       = cast_or_null<VarDecl>(
   6206                    getDerived().TransformDefinition(
   6207                                       S->getConditionVariable()->getLocation(),
   6208                                                     S->getConditionVariable()));
   6209     if (!ConditionVar)
   6210       return StmtError();
   6211   } else {
   6212     Cond = getDerived().TransformExpr(S->getCond());
   6213 
   6214     if (Cond.isInvalid())
   6215       return StmtError();
   6216 
   6217     if (S->getCond()) {
   6218       // Convert the condition to a boolean value.
   6219       ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
   6220                                                          S->getWhileLoc(),
   6221                                                          Cond.get());
   6222       if (CondE.isInvalid())
   6223         return StmtError();
   6224       Cond = CondE;
   6225     }
   6226   }
   6227 
   6228   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
   6229   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   6230     return StmtError();
   6231 
   6232   // Transform the body
   6233   StmtResult Body = getDerived().TransformStmt(S->getBody());
   6234   if (Body.isInvalid())
   6235     return StmtError();
   6236 
   6237   if (!getDerived().AlwaysRebuild() &&
   6238       FullCond.get() == S->getCond() &&
   6239       ConditionVar == S->getConditionVariable() &&
   6240       Body.get() == S->getBody())
   6241     return Owned(S);
   6242 
   6243   return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
   6244                                        ConditionVar, Body.get());
   6245 }
   6246 
   6247 template<typename Derived>
   6248 StmtResult
   6249 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
   6250   // Transform the body
   6251   StmtResult Body = getDerived().TransformStmt(S->getBody());
   6252   if (Body.isInvalid())
   6253     return StmtError();
   6254 
   6255   // Transform the condition
   6256   ExprResult Cond = getDerived().TransformExpr(S->getCond());
   6257   if (Cond.isInvalid())
   6258     return StmtError();
   6259 
   6260   if (!getDerived().AlwaysRebuild() &&
   6261       Cond.get() == S->getCond() &&
   6262       Body.get() == S->getBody())
   6263     return S;
   6264 
   6265   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
   6266                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
   6267                                     S->getRParenLoc());
   6268 }
   6269 
   6270 template<typename Derived>
   6271 StmtResult
   6272 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
   6273   // Transform the initialization statement
   6274   StmtResult Init = getDerived().TransformStmt(S->getInit());
   6275   if (Init.isInvalid())
   6276     return StmtError();
   6277 
   6278   // Transform the condition
   6279   ExprResult Cond;
   6280   VarDecl *ConditionVar = nullptr;
   6281   if (S->getConditionVariable()) {
   6282     ConditionVar
   6283       = cast_or_null<VarDecl>(
   6284                    getDerived().TransformDefinition(
   6285                                       S->getConditionVariable()->getLocation(),
   6286                                                     S->getConditionVariable()));
   6287     if (!ConditionVar)
   6288       return StmtError();
   6289   } else {
   6290     Cond = getDerived().TransformExpr(S->getCond());
   6291 
   6292     if (Cond.isInvalid())
   6293       return StmtError();
   6294 
   6295     if (S->getCond()) {
   6296       // Convert the condition to a boolean value.
   6297       ExprResult CondE = getSema().ActOnBooleanCondition(nullptr,
   6298                                                          S->getForLoc(),
   6299                                                          Cond.get());
   6300       if (CondE.isInvalid())
   6301         return StmtError();
   6302 
   6303       Cond = CondE.get();
   6304     }
   6305   }
   6306 
   6307   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.get()));
   6308   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   6309     return StmtError();
   6310 
   6311   // Transform the increment
   6312   ExprResult Inc = getDerived().TransformExpr(S->getInc());
   6313   if (Inc.isInvalid())
   6314     return StmtError();
   6315 
   6316   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
   6317   if (S->getInc() && !FullInc.get())
   6318     return StmtError();
   6319 
   6320   // Transform the body
   6321   StmtResult Body = getDerived().TransformStmt(S->getBody());
   6322   if (Body.isInvalid())
   6323     return StmtError();
   6324 
   6325   if (!getDerived().AlwaysRebuild() &&
   6326       Init.get() == S->getInit() &&
   6327       FullCond.get() == S->getCond() &&
   6328       Inc.get() == S->getInc() &&
   6329       Body.get() == S->getBody())
   6330     return S;
   6331 
   6332   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
   6333                                      Init.get(), FullCond, ConditionVar,
   6334                                      FullInc, S->getRParenLoc(), Body.get());
   6335 }
   6336 
   6337 template<typename Derived>
   6338 StmtResult
   6339 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
   6340   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
   6341                                         S->getLabel());
   6342   if (!LD)
   6343     return StmtError();
   6344 
   6345   // Goto statements must always be rebuilt, to resolve the label.
   6346   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
   6347                                       cast<LabelDecl>(LD));
   6348 }
   6349 
   6350 template<typename Derived>
   6351 StmtResult
   6352 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
   6353   ExprResult Target = getDerived().TransformExpr(S->getTarget());
   6354   if (Target.isInvalid())
   6355     return StmtError();
   6356   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
   6357 
   6358   if (!getDerived().AlwaysRebuild() &&
   6359       Target.get() == S->getTarget())
   6360     return S;
   6361 
   6362   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
   6363                                               Target.get());
   6364 }
   6365 
   6366 template<typename Derived>
   6367 StmtResult
   6368 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
   6369   return S;
   6370 }
   6371 
   6372 template<typename Derived>
   6373 StmtResult
   6374 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
   6375   return S;
   6376 }
   6377 
   6378 template<typename Derived>
   6379 StmtResult
   6380 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
   6381   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
   6382                                                         /*NotCopyInit*/false);
   6383   if (Result.isInvalid())
   6384     return StmtError();
   6385 
   6386   // FIXME: We always rebuild the return statement because there is no way
   6387   // to tell whether the return type of the function has changed.
   6388   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
   6389 }
   6390 
   6391 template<typename Derived>
   6392 StmtResult
   6393 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
   6394   bool DeclChanged = false;
   6395   SmallVector<Decl *, 4> Decls;
   6396   for (auto *D : S->decls()) {
   6397     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
   6398     if (!Transformed)
   6399       return StmtError();
   6400 
   6401     if (Transformed != D)
   6402       DeclChanged = true;
   6403 
   6404     Decls.push_back(Transformed);
   6405   }
   6406 
   6407   if (!getDerived().AlwaysRebuild() && !DeclChanged)
   6408     return S;
   6409 
   6410   return getDerived().RebuildDeclStmt(Decls, S->getStartLoc(), S->getEndLoc());
   6411 }
   6412 
   6413 template<typename Derived>
   6414 StmtResult
   6415 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
   6416 
   6417   SmallVector<Expr*, 8> Constraints;
   6418   SmallVector<Expr*, 8> Exprs;
   6419   SmallVector<IdentifierInfo *, 4> Names;
   6420 
   6421   ExprResult AsmString;
   6422   SmallVector<Expr*, 8> Clobbers;
   6423 
   6424   bool ExprsChanged = false;
   6425 
   6426   // Go through the outputs.
   6427   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
   6428     Names.push_back(S->getOutputIdentifier(I));
   6429 
   6430     // No need to transform the constraint literal.
   6431     Constraints.push_back(S->getOutputConstraintLiteral(I));
   6432 
   6433     // Transform the output expr.
   6434     Expr *OutputExpr = S->getOutputExpr(I);
   6435     ExprResult Result = getDerived().TransformExpr(OutputExpr);
   6436     if (Result.isInvalid())
   6437       return StmtError();
   6438 
   6439     ExprsChanged |= Result.get() != OutputExpr;
   6440 
   6441     Exprs.push_back(Result.get());
   6442   }
   6443 
   6444   // Go through the inputs.
   6445   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
   6446     Names.push_back(S->getInputIdentifier(I));
   6447 
   6448     // No need to transform the constraint literal.
   6449     Constraints.push_back(S->getInputConstraintLiteral(I));
   6450 
   6451     // Transform the input expr.
   6452     Expr *InputExpr = S->getInputExpr(I);
   6453     ExprResult Result = getDerived().TransformExpr(InputExpr);
   6454     if (Result.isInvalid())
   6455       return StmtError();
   6456 
   6457     ExprsChanged |= Result.get() != InputExpr;
   6458 
   6459     Exprs.push_back(Result.get());
   6460   }
   6461 
   6462   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
   6463     return S;
   6464 
   6465   // Go through the clobbers.
   6466   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
   6467     Clobbers.push_back(S->getClobberStringLiteral(I));
   6468 
   6469   // No need to transform the asm string literal.
   6470   AsmString = S->getAsmString();
   6471   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
   6472                                         S->isVolatile(), S->getNumOutputs(),
   6473                                         S->getNumInputs(), Names.data(),
   6474                                         Constraints, Exprs, AsmString.get(),
   6475                                         Clobbers, S->getRParenLoc());
   6476 }
   6477 
   6478 template<typename Derived>
   6479 StmtResult
   6480 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
   6481   ArrayRef<Token> AsmToks =
   6482     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
   6483 
   6484   bool HadError = false, HadChange = false;
   6485 
   6486   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
   6487   SmallVector<Expr*, 8> TransformedExprs;
   6488   TransformedExprs.reserve(SrcExprs.size());
   6489   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
   6490     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
   6491     if (!Result.isUsable()) {
   6492       HadError = true;
   6493     } else {
   6494       HadChange |= (Result.get() != SrcExprs[i]);
   6495       TransformedExprs.push_back(Result.get());
   6496     }
   6497   }
   6498 
   6499   if (HadError) return StmtError();
   6500   if (!HadChange && !getDerived().AlwaysRebuild())
   6501     return Owned(S);
   6502 
   6503   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
   6504                                        AsmToks, S->getAsmString(),
   6505                                        S->getNumOutputs(), S->getNumInputs(),
   6506                                        S->getAllConstraints(), S->getClobbers(),
   6507                                        TransformedExprs, S->getEndLoc());
   6508 }
   6509 
   6510 // C++ Coroutines TS
   6511 
   6512 template<typename Derived>
   6513 StmtResult
   6514 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
   6515   // The coroutine body should be re-formed by the caller if necessary.
   6516   return getDerived().TransformStmt(S->getBody());
   6517 }
   6518 
   6519 template<typename Derived>
   6520 StmtResult
   6521 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
   6522   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
   6523                                                         /*NotCopyInit*/false);
   6524   if (Result.isInvalid())
   6525     return StmtError();
   6526 
   6527   // Always rebuild; we don't know if this needs to be injected into a new
   6528   // context or if the promise type has changed.
   6529   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get());
   6530 }
   6531 
   6532 template<typename Derived>
   6533 ExprResult
   6534 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
   6535   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
   6536                                                         /*NotCopyInit*/false);
   6537   if (Result.isInvalid())
   6538     return ExprError();
   6539