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 
   6540   // Always rebuild; we don't know if this needs to be injected into a new
   6541   // context or if the promise type has changed.
   6542   return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get());
   6543 }
   6544 
   6545 template<typename Derived>
   6546 ExprResult
   6547 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
   6548   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
   6549                                                         /*NotCopyInit*/false);
   6550   if (Result.isInvalid())
   6551     return ExprError();
   6552 
   6553   // Always rebuild; we don't know if this needs to be injected into a new
   6554   // context or if the promise type has changed.
   6555   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
   6556 }
   6557 
   6558 // Objective-C Statements.
   6559 
   6560 template<typename Derived>
   6561 StmtResult
   6562 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
   6563   // Transform the body of the @try.
   6564   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
   6565   if (TryBody.isInvalid())
   6566     return StmtError();
   6567 
   6568   // Transform the @catch statements (if present).
   6569   bool AnyCatchChanged = false;
   6570   SmallVector<Stmt*, 8> CatchStmts;
   6571   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
   6572     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
   6573     if (Catch.isInvalid())
   6574       return StmtError();
   6575     if (Catch.get() != S->getCatchStmt(I))
   6576       AnyCatchChanged = true;
   6577     CatchStmts.push_back(Catch.get());
   6578   }
   6579 
   6580   // Transform the @finally statement (if present).
   6581   StmtResult Finally;
   6582   if (S->getFinallyStmt()) {
   6583     Finally = getDerived().TransformStmt(S->getFinallyStmt());
   6584     if (Finally.isInvalid())
   6585       return StmtError();
   6586   }
   6587 
   6588   // If nothing changed, just retain this statement.
   6589   if (!getDerived().AlwaysRebuild() &&
   6590       TryBody.get() == S->getTryBody() &&
   6591       !AnyCatchChanged &&
   6592       Finally.get() == S->getFinallyStmt())
   6593     return S;
   6594 
   6595   // Build a new statement.
   6596   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
   6597                                            CatchStmts, Finally.get());
   6598 }
   6599 
   6600 template<typename Derived>
   6601 StmtResult
   6602 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
   6603   // Transform the @catch parameter, if there is one.
   6604   VarDecl *Var = nullptr;
   6605   if (VarDecl *FromVar = S->getCatchParamDecl()) {
   6606     TypeSourceInfo *TSInfo = nullptr;
   6607     if (FromVar->getTypeSourceInfo()) {
   6608       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
   6609       if (!TSInfo)
   6610         return StmtError();
   6611     }
   6612 
   6613     QualType T;
   6614     if (TSInfo)
   6615       T = TSInfo->getType();
   6616     else {
   6617       T = getDerived().TransformType(FromVar->getType());
   6618       if (T.isNull())
   6619         return StmtError();
   6620     }
   6621 
   6622     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
   6623     if (!Var)
   6624       return StmtError();
   6625   }
   6626 
   6627   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
   6628   if (Body.isInvalid())
   6629     return StmtError();
   6630 
   6631   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
   6632                                              S->getRParenLoc(),
   6633                                              Var, Body.get());
   6634 }
   6635 
   6636 template<typename Derived>
   6637 StmtResult
   6638 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
   6639   // Transform the body.
   6640   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
   6641   if (Body.isInvalid())
   6642     return StmtError();
   6643 
   6644   // If nothing changed, just retain this statement.
   6645   if (!getDerived().AlwaysRebuild() &&
   6646       Body.get() == S->getFinallyBody())
   6647     return S;
   6648 
   6649   // Build a new statement.
   6650   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
   6651                                                Body.get());
   6652 }
   6653 
   6654 template<typename Derived>
   6655 StmtResult
   6656 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
   6657   ExprResult Operand;
   6658   if (S->getThrowExpr()) {
   6659     Operand = getDerived().TransformExpr(S->getThrowExpr());
   6660     if (Operand.isInvalid())
   6661       return StmtError();
   6662   }
   6663 
   6664   if (!getDerived().AlwaysRebuild() &&
   6665       Operand.get() == S->getThrowExpr())
   6666     return S;
   6667 
   6668   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
   6669 }
   6670 
   6671 template<typename Derived>
   6672 StmtResult
   6673 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
   6674                                                   ObjCAtSynchronizedStmt *S) {
   6675   // Transform the object we are locking.
   6676   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
   6677   if (Object.isInvalid())
   6678     return StmtError();
   6679   Object =
   6680     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
   6681                                                   Object.get());
   6682   if (Object.isInvalid())
   6683     return StmtError();
   6684 
   6685   // Transform the body.
   6686   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
   6687   if (Body.isInvalid())
   6688     return StmtError();
   6689 
   6690   // If nothing change, just retain the current statement.
   6691   if (!getDerived().AlwaysRebuild() &&
   6692       Object.get() == S->getSynchExpr() &&
   6693       Body.get() == S->getSynchBody())
   6694     return S;
   6695 
   6696   // Build a new statement.
   6697   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
   6698                                                     Object.get(), Body.get());
   6699 }
   6700 
   6701 template<typename Derived>
   6702 StmtResult
   6703 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
   6704                                               ObjCAutoreleasePoolStmt *S) {
   6705   // Transform the body.
   6706   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
   6707   if (Body.isInvalid())
   6708     return StmtError();
   6709 
   6710   // If nothing changed, just retain this statement.
   6711   if (!getDerived().AlwaysRebuild() &&
   6712       Body.get() == S->getSubStmt())
   6713     return S;
   6714 
   6715   // Build a new statement.
   6716   return getDerived().RebuildObjCAutoreleasePoolStmt(
   6717                         S->getAtLoc(), Body.get());
   6718 }
   6719 
   6720 template<typename Derived>
   6721 StmtResult
   6722 TreeTransform<Derived>::TransformObjCForCollectionStmt(
   6723                                                   ObjCForCollectionStmt *S) {
   6724   // Transform the element statement.
   6725   StmtResult Element = getDerived().TransformStmt(S->getElement());
   6726   if (Element.isInvalid())
   6727     return StmtError();
   6728 
   6729   // Transform the collection expression.
   6730   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
   6731   if (Collection.isInvalid())
   6732     return StmtError();
   6733 
   6734   // Transform the body.
   6735   StmtResult Body = getDerived().TransformStmt(S->getBody());
   6736   if (Body.isInvalid())
   6737     return StmtError();
   6738 
   6739   // If nothing changed, just retain this statement.
   6740   if (!getDerived().AlwaysRebuild() &&
   6741       Element.get() == S->getElement() &&
   6742       Collection.get() == S->getCollection() &&
   6743       Body.get() == S->getBody())
   6744     return S;
   6745 
   6746   // Build a new statement.
   6747   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
   6748                                                    Element.get(),
   6749                                                    Collection.get(),
   6750                                                    S->getRParenLoc(),
   6751                                                    Body.get());
   6752 }
   6753 
   6754 template <typename Derived>
   6755 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
   6756   // Transform the exception declaration, if any.
   6757   VarDecl *Var = nullptr;
   6758   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
   6759     TypeSourceInfo *T =
   6760         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
   6761     if (!T)
   6762       return StmtError();
   6763 
   6764     Var = getDerived().RebuildExceptionDecl(
   6765         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
   6766         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
   6767     if (!Var || Var->isInvalidDecl())
   6768       return StmtError();
   6769   }
   6770 
   6771   // Transform the actual exception handler.
   6772   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
   6773   if (Handler.isInvalid())
   6774     return StmtError();
   6775 
   6776   if (!getDerived().AlwaysRebuild() && !Var &&
   6777       Handler.get() == S->getHandlerBlock())
   6778     return S;
   6779 
   6780   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
   6781 }
   6782 
   6783 template <typename Derived>
   6784 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
   6785   // Transform the try block itself.
   6786   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
   6787   if (TryBlock.isInvalid())
   6788     return StmtError();
   6789 
   6790   // Transform the handlers.
   6791   bool HandlerChanged = false;
   6792   SmallVector<Stmt *, 8> Handlers;
   6793   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
   6794     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
   6795     if (Handler.isInvalid())
   6796       return StmtError();
   6797 
   6798     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
   6799     Handlers.push_back(Handler.getAs<Stmt>());
   6800   }
   6801 
   6802   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
   6803       !HandlerChanged)
   6804     return S;
   6805 
   6806   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
   6807                                         Handlers);
   6808 }
   6809 
   6810 template<typename Derived>
   6811 StmtResult
   6812 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
   6813   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
   6814   if (Range.isInvalid())
   6815     return StmtError();
   6816 
   6817   StmtResult BeginEnd = getDerived().TransformStmt(S->getBeginEndStmt());
   6818   if (BeginEnd.isInvalid())
   6819     return StmtError();
   6820 
   6821   ExprResult Cond = getDerived().TransformExpr(S->getCond());
   6822   if (Cond.isInvalid())
   6823     return StmtError();
   6824   if (Cond.get())
   6825     Cond = SemaRef.CheckBooleanCondition(Cond.get(), S->getColonLoc());
   6826   if (Cond.isInvalid())
   6827     return StmtError();
   6828   if (Cond.get())
   6829     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
   6830 
   6831   ExprResult Inc = getDerived().TransformExpr(S->getInc());
   6832   if (Inc.isInvalid())
   6833     return StmtError();
   6834   if (Inc.get())
   6835     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
   6836 
   6837   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
   6838   if (LoopVar.isInvalid())
   6839     return StmtError();
   6840 
   6841   StmtResult NewStmt = S;
   6842   if (getDerived().AlwaysRebuild() ||
   6843       Range.get() != S->getRangeStmt() ||
   6844       BeginEnd.get() != S->getBeginEndStmt() ||
   6845       Cond.get() != S->getCond() ||
   6846       Inc.get() != S->getInc() ||
   6847       LoopVar.get() != S->getLoopVarStmt()) {
   6848     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
   6849                                                   S->getCoawaitLoc(),
   6850                                                   S->getColonLoc(), Range.get(),
   6851                                                   BeginEnd.get(), Cond.get(),
   6852                                                   Inc.get(), LoopVar.get(),
   6853                                                   S->getRParenLoc());
   6854     if (NewStmt.isInvalid())
   6855       return StmtError();
   6856   }
   6857 
   6858   StmtResult Body = getDerived().TransformStmt(S->getBody());
   6859   if (Body.isInvalid())
   6860     return StmtError();
   6861 
   6862   // Body has changed but we didn't rebuild the for-range statement. Rebuild
   6863   // it now so we have a new statement to attach the body to.
   6864   if (Body.get() != S->getBody() && NewStmt.get() == S) {
   6865     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
   6866                                                   S->getCoawaitLoc(),
   6867                                                   S->getColonLoc(), Range.get(),
   6868                                                   BeginEnd.get(), Cond.get(),
   6869                                                   Inc.get(), LoopVar.get(),
   6870                                                   S->getRParenLoc());
   6871     if (NewStmt.isInvalid())
   6872       return StmtError();
   6873   }
   6874 
   6875   if (NewStmt.get() == S)
   6876     return S;
   6877 
   6878   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
   6879 }
   6880 
   6881 template<typename Derived>
   6882 StmtResult
   6883 TreeTransform<Derived>::TransformMSDependentExistsStmt(
   6884                                                     MSDependentExistsStmt *S) {
   6885   // Transform the nested-name-specifier, if any.
   6886   NestedNameSpecifierLoc QualifierLoc;
   6887   if (S->getQualifierLoc()) {
   6888     QualifierLoc
   6889       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
   6890     if (!QualifierLoc)
   6891       return StmtError();
   6892   }
   6893 
   6894   // Transform the declaration name.
   6895   DeclarationNameInfo NameInfo = S->getNameInfo();
   6896   if (NameInfo.getName()) {
   6897     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
   6898     if (!NameInfo.getName())
   6899       return StmtError();
   6900   }
   6901 
   6902   // Check whether anything changed.
   6903   if (!getDerived().AlwaysRebuild() &&
   6904       QualifierLoc == S->getQualifierLoc() &&
   6905       NameInfo.getName() == S->getNameInfo().getName())
   6906     return S;
   6907 
   6908   // Determine whether this name exists, if we can.
   6909   CXXScopeSpec SS;
   6910   SS.Adopt(QualifierLoc);
   6911   bool Dependent = false;
   6912   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
   6913   case Sema::IER_Exists:
   6914     if (S->isIfExists())
   6915       break;
   6916 
   6917     return new (getSema().Context) NullStmt(S->getKeywordLoc());
   6918 
   6919   case Sema::IER_DoesNotExist:
   6920     if (S->isIfNotExists())
   6921       break;
   6922 
   6923     return new (getSema().Context) NullStmt(S->getKeywordLoc());
   6924 
   6925   case Sema::IER_Dependent:
   6926     Dependent = true;
   6927     break;
   6928 
   6929   case Sema::IER_Error:
   6930     return StmtError();
   6931   }
   6932 
   6933   // We need to continue with the instantiation, so do so now.
   6934   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
   6935   if (SubStmt.isInvalid())
   6936     return StmtError();
   6937 
   6938   // If we have resolved the name, just transform to the substatement.
   6939   if (!Dependent)
   6940     return SubStmt;
   6941 
   6942   // The name is still dependent, so build a dependent expression again.
   6943   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
   6944                                                    S->isIfExists(),
   6945                                                    QualifierLoc,
   6946                                                    NameInfo,
   6947                                                    SubStmt.get());
   6948 }
   6949 
   6950 template<typename Derived>
   6951 ExprResult
   6952 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
   6953   NestedNameSpecifierLoc QualifierLoc;
   6954   if (E->getQualifierLoc()) {
   6955     QualifierLoc
   6956     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   6957     if (!QualifierLoc)
   6958       return ExprError();
   6959   }
   6960 
   6961   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
   6962     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
   6963   if (!PD)
   6964     return ExprError();
   6965 
   6966   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
   6967   if (Base.isInvalid())
   6968     return ExprError();
   6969 
   6970   return new (SemaRef.getASTContext())
   6971       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
   6972                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
   6973                         QualifierLoc, E->getMemberLoc());
   6974 }
   6975 
   6976 template <typename Derived>
   6977 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
   6978     MSPropertySubscriptExpr *E) {
   6979   auto BaseRes = getDerived().TransformExpr(E->getBase());
   6980   if (BaseRes.isInvalid())
   6981     return ExprError();
   6982   auto IdxRes = getDerived().TransformExpr(E->getIdx());
   6983   if (IdxRes.isInvalid())
   6984     return ExprError();
   6985 
   6986   if (!getDerived().AlwaysRebuild() &&
   6987       BaseRes.get() == E->getBase() &&
   6988       IdxRes.get() == E->getIdx())
   6989     return E;
   6990 
   6991   return getDerived().RebuildArraySubscriptExpr(
   6992       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
   6993 }
   6994 
   6995 template <typename Derived>
   6996 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
   6997   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
   6998   if (TryBlock.isInvalid())
   6999     return StmtError();
   7000 
   7001   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
   7002   if (Handler.isInvalid())
   7003     return StmtError();
   7004 
   7005   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
   7006       Handler.get() == S->getHandler())
   7007     return S;
   7008 
   7009   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
   7010                                         TryBlock.get(), Handler.get());
   7011 }
   7012 
   7013 template <typename Derived>
   7014 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
   7015   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
   7016   if (Block.isInvalid())
   7017     return StmtError();
   7018 
   7019   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
   7020 }
   7021 
   7022 template <typename Derived>
   7023 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
   7024   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
   7025   if (FilterExpr.isInvalid())
   7026     return StmtError();
   7027 
   7028   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
   7029   if (Block.isInvalid())
   7030     return StmtError();
   7031 
   7032   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
   7033                                            Block.get());
   7034 }
   7035 
   7036 template <typename Derived>
   7037 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
   7038   if (isa<SEHFinallyStmt>(Handler))
   7039     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
   7040   else
   7041     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
   7042 }
   7043 
   7044 template<typename Derived>
   7045 StmtResult
   7046 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
   7047   return S;
   7048 }
   7049 
   7050 //===----------------------------------------------------------------------===//
   7051 // OpenMP directive transformation
   7052 //===----------------------------------------------------------------------===//
   7053 template <typename Derived>
   7054 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
   7055     OMPExecutableDirective *D) {
   7056 
   7057   // Transform the clauses
   7058   llvm::SmallVector<OMPClause *, 16> TClauses;
   7059   ArrayRef<OMPClause *> Clauses = D->clauses();
   7060   TClauses.reserve(Clauses.size());
   7061   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
   7062        I != E; ++I) {
   7063     if (*I) {
   7064       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
   7065       OMPClause *Clause = getDerived().TransformOMPClause(*I);
   7066       getDerived().getSema().EndOpenMPClause();
   7067       if (Clause)
   7068         TClauses.push_back(Clause);
   7069     } else {
   7070       TClauses.push_back(nullptr);
   7071     }
   7072   }
   7073   StmtResult AssociatedStmt;
   7074   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
   7075     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
   7076                                                   /*CurScope=*/nullptr);
   7077     StmtResult Body;
   7078     {
   7079       Sema::CompoundScopeRAII CompoundScope(getSema());
   7080       Body = getDerived().TransformStmt(
   7081           cast<CapturedStmt>(D->getAssociatedStmt())->getCapturedStmt());
   7082     }
   7083     AssociatedStmt =
   7084         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
   7085     if (AssociatedStmt.isInvalid()) {
   7086       return StmtError();
   7087     }
   7088   }
   7089   if (TClauses.size() != Clauses.size()) {
   7090     return StmtError();
   7091   }
   7092 
   7093   // Transform directive name for 'omp critical' directive.
   7094   DeclarationNameInfo DirName;
   7095   if (D->getDirectiveKind() == OMPD_critical) {
   7096     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
   7097     DirName = getDerived().TransformDeclarationNameInfo(DirName);
   7098   }
   7099   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
   7100   if (D->getDirectiveKind() == OMPD_cancellation_point) {
   7101     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
   7102   } else if (D->getDirectiveKind() == OMPD_cancel) {
   7103     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
   7104   }
   7105 
   7106   return getDerived().RebuildOMPExecutableDirective(
   7107       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
   7108       AssociatedStmt.get(), D->getLocStart(), D->getLocEnd());
   7109 }
   7110 
   7111 template <typename Derived>
   7112 StmtResult
   7113 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
   7114   DeclarationNameInfo DirName;
   7115   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
   7116                                              D->getLocStart());
   7117   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7118   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7119   return Res;
   7120 }
   7121 
   7122 template <typename Derived>
   7123 StmtResult
   7124 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
   7125   DeclarationNameInfo DirName;
   7126   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
   7127                                              D->getLocStart());
   7128   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7129   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7130   return Res;
   7131 }
   7132 
   7133 template <typename Derived>
   7134 StmtResult
   7135 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
   7136   DeclarationNameInfo DirName;
   7137   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
   7138                                              D->getLocStart());
   7139   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7140   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7141   return Res;
   7142 }
   7143 
   7144 template <typename Derived>
   7145 StmtResult
   7146 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
   7147   DeclarationNameInfo DirName;
   7148   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
   7149                                              D->getLocStart());
   7150   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7151   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7152   return Res;
   7153 }
   7154 
   7155 template <typename Derived>
   7156 StmtResult
   7157 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
   7158   DeclarationNameInfo DirName;
   7159   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
   7160                                              D->getLocStart());
   7161   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7162   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7163   return Res;
   7164 }
   7165 
   7166 template <typename Derived>
   7167 StmtResult
   7168 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
   7169   DeclarationNameInfo DirName;
   7170   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
   7171                                              D->getLocStart());
   7172   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7173   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7174   return Res;
   7175 }
   7176 
   7177 template <typename Derived>
   7178 StmtResult
   7179 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
   7180   DeclarationNameInfo DirName;
   7181   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
   7182                                              D->getLocStart());
   7183   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7184   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7185   return Res;
   7186 }
   7187 
   7188 template <typename Derived>
   7189 StmtResult
   7190 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
   7191   DeclarationNameInfo DirName;
   7192   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
   7193                                              D->getLocStart());
   7194   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7195   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7196   return Res;
   7197 }
   7198 
   7199 template <typename Derived>
   7200 StmtResult
   7201 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
   7202   getDerived().getSema().StartOpenMPDSABlock(
   7203       OMPD_critical, D->getDirectiveName(), nullptr, D->getLocStart());
   7204   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7205   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7206   return Res;
   7207 }
   7208 
   7209 template <typename Derived>
   7210 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
   7211     OMPParallelForDirective *D) {
   7212   DeclarationNameInfo DirName;
   7213   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
   7214                                              nullptr, D->getLocStart());
   7215   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7216   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7217   return Res;
   7218 }
   7219 
   7220 template <typename Derived>
   7221 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
   7222     OMPParallelForSimdDirective *D) {
   7223   DeclarationNameInfo DirName;
   7224   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
   7225                                              nullptr, D->getLocStart());
   7226   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7227   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7228   return Res;
   7229 }
   7230 
   7231 template <typename Derived>
   7232 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
   7233     OMPParallelSectionsDirective *D) {
   7234   DeclarationNameInfo DirName;
   7235   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
   7236                                              nullptr, D->getLocStart());
   7237   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7238   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7239   return Res;
   7240 }
   7241 
   7242 template <typename Derived>
   7243 StmtResult
   7244 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
   7245   DeclarationNameInfo DirName;
   7246   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
   7247                                              D->getLocStart());
   7248   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7249   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7250   return Res;
   7251 }
   7252 
   7253 template <typename Derived>
   7254 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
   7255     OMPTaskyieldDirective *D) {
   7256   DeclarationNameInfo DirName;
   7257   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
   7258                                              D->getLocStart());
   7259   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7260   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7261   return Res;
   7262 }
   7263 
   7264 template <typename Derived>
   7265 StmtResult
   7266 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
   7267   DeclarationNameInfo DirName;
   7268   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
   7269                                              D->getLocStart());
   7270   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7271   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7272   return Res;
   7273 }
   7274 
   7275 template <typename Derived>
   7276 StmtResult
   7277 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
   7278   DeclarationNameInfo DirName;
   7279   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
   7280                                              D->getLocStart());
   7281   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7282   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7283   return Res;
   7284 }
   7285 
   7286 template <typename Derived>
   7287 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
   7288     OMPTaskgroupDirective *D) {
   7289   DeclarationNameInfo DirName;
   7290   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
   7291                                              D->getLocStart());
   7292   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7293   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7294   return Res;
   7295 }
   7296 
   7297 template <typename Derived>
   7298 StmtResult
   7299 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
   7300   DeclarationNameInfo DirName;
   7301   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
   7302                                              D->getLocStart());
   7303   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7304   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7305   return Res;
   7306 }
   7307 
   7308 template <typename Derived>
   7309 StmtResult
   7310 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
   7311   DeclarationNameInfo DirName;
   7312   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
   7313                                              D->getLocStart());
   7314   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7315   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7316   return Res;
   7317 }
   7318 
   7319 template <typename Derived>
   7320 StmtResult
   7321 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
   7322   DeclarationNameInfo DirName;
   7323   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
   7324                                              D->getLocStart());
   7325   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7326   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7327   return Res;
   7328 }
   7329 
   7330 template <typename Derived>
   7331 StmtResult
   7332 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
   7333   DeclarationNameInfo DirName;
   7334   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
   7335                                              D->getLocStart());
   7336   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7337   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7338   return Res;
   7339 }
   7340 
   7341 template <typename Derived>
   7342 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
   7343     OMPTargetDataDirective *D) {
   7344   DeclarationNameInfo DirName;
   7345   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
   7346                                              D->getLocStart());
   7347   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7348   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7349   return Res;
   7350 }
   7351 
   7352 template <typename Derived>
   7353 StmtResult
   7354 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
   7355   DeclarationNameInfo DirName;
   7356   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
   7357                                              D->getLocStart());
   7358   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7359   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7360   return Res;
   7361 }
   7362 
   7363 template <typename Derived>
   7364 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
   7365     OMPCancellationPointDirective *D) {
   7366   DeclarationNameInfo DirName;
   7367   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
   7368                                              nullptr, D->getLocStart());
   7369   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7370   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7371   return Res;
   7372 }
   7373 
   7374 template <typename Derived>
   7375 StmtResult
   7376 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
   7377   DeclarationNameInfo DirName;
   7378   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
   7379                                              D->getLocStart());
   7380   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7381   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7382   return Res;
   7383 }
   7384 
   7385 template <typename Derived>
   7386 StmtResult
   7387 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
   7388   DeclarationNameInfo DirName;
   7389   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
   7390                                              D->getLocStart());
   7391   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7392   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7393   return Res;
   7394 }
   7395 
   7396 template <typename Derived>
   7397 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
   7398     OMPTaskLoopSimdDirective *D) {
   7399   DeclarationNameInfo DirName;
   7400   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
   7401                                              nullptr, D->getLocStart());
   7402   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7403   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7404   return Res;
   7405 }
   7406 
   7407 template <typename Derived>
   7408 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
   7409     OMPDistributeDirective *D) {
   7410   DeclarationNameInfo DirName;
   7411   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
   7412                                              D->getLocStart());
   7413   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
   7414   getDerived().getSema().EndOpenMPDSABlock(Res.get());
   7415   return Res;
   7416 }
   7417 
   7418 //===----------------------------------------------------------------------===//
   7419 // OpenMP clause transformation
   7420 //===----------------------------------------------------------------------===//
   7421 template <typename Derived>
   7422 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
   7423   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
   7424   if (Cond.isInvalid())
   7425     return nullptr;
   7426   return getDerived().RebuildOMPIfClause(
   7427       C->getNameModifier(), Cond.get(), C->getLocStart(), C->getLParenLoc(),
   7428       C->getNameModifierLoc(), C->getColonLoc(), C->getLocEnd());
   7429 }
   7430 
   7431 template <typename Derived>
   7432 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
   7433   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
   7434   if (Cond.isInvalid())
   7435     return nullptr;
   7436   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getLocStart(),
   7437                                             C->getLParenLoc(), C->getLocEnd());
   7438 }
   7439 
   7440 template <typename Derived>
   7441 OMPClause *
   7442 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
   7443   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
   7444   if (NumThreads.isInvalid())
   7445     return nullptr;
   7446   return getDerived().RebuildOMPNumThreadsClause(
   7447       NumThreads.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7448 }
   7449 
   7450 template <typename Derived>
   7451 OMPClause *
   7452 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
   7453   ExprResult E = getDerived().TransformExpr(C->getSafelen());
   7454   if (E.isInvalid())
   7455     return nullptr;
   7456   return getDerived().RebuildOMPSafelenClause(
   7457       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7458 }
   7459 
   7460 template <typename Derived>
   7461 OMPClause *
   7462 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
   7463   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
   7464   if (E.isInvalid())
   7465     return nullptr;
   7466   return getDerived().RebuildOMPSimdlenClause(
   7467       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7468 }
   7469 
   7470 template <typename Derived>
   7471 OMPClause *
   7472 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
   7473   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
   7474   if (E.isInvalid())
   7475     return nullptr;
   7476   return getDerived().RebuildOMPCollapseClause(
   7477       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7478 }
   7479 
   7480 template <typename Derived>
   7481 OMPClause *
   7482 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
   7483   return getDerived().RebuildOMPDefaultClause(
   7484       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getLocStart(),
   7485       C->getLParenLoc(), C->getLocEnd());
   7486 }
   7487 
   7488 template <typename Derived>
   7489 OMPClause *
   7490 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
   7491   return getDerived().RebuildOMPProcBindClause(
   7492       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getLocStart(),
   7493       C->getLParenLoc(), C->getLocEnd());
   7494 }
   7495 
   7496 template <typename Derived>
   7497 OMPClause *
   7498 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
   7499   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
   7500   if (E.isInvalid())
   7501     return nullptr;
   7502   return getDerived().RebuildOMPScheduleClause(
   7503       C->getScheduleKind(), E.get(), C->getLocStart(), C->getLParenLoc(),
   7504       C->getScheduleKindLoc(), C->getCommaLoc(), C->getLocEnd());
   7505 }
   7506 
   7507 template <typename Derived>
   7508 OMPClause *
   7509 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
   7510   ExprResult E;
   7511   if (auto *Num = C->getNumForLoops()) {
   7512     E = getDerived().TransformExpr(Num);
   7513     if (E.isInvalid())
   7514       return nullptr;
   7515   }
   7516   return getDerived().RebuildOMPOrderedClause(C->getLocStart(), C->getLocEnd(),
   7517                                               C->getLParenLoc(), E.get());
   7518 }
   7519 
   7520 template <typename Derived>
   7521 OMPClause *
   7522 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
   7523   // No need to rebuild this clause, no template-dependent parameters.
   7524   return C;
   7525 }
   7526 
   7527 template <typename Derived>
   7528 OMPClause *
   7529 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
   7530   // No need to rebuild this clause, no template-dependent parameters.
   7531   return C;
   7532 }
   7533 
   7534 template <typename Derived>
   7535 OMPClause *
   7536 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
   7537   // No need to rebuild this clause, no template-dependent parameters.
   7538   return C;
   7539 }
   7540 
   7541 template <typename Derived>
   7542 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
   7543   // No need to rebuild this clause, no template-dependent parameters.
   7544   return C;
   7545 }
   7546 
   7547 template <typename Derived>
   7548 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
   7549   // No need to rebuild this clause, no template-dependent parameters.
   7550   return C;
   7551 }
   7552 
   7553 template <typename Derived>
   7554 OMPClause *
   7555 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
   7556   // No need to rebuild this clause, no template-dependent parameters.
   7557   return C;
   7558 }
   7559 
   7560 template <typename Derived>
   7561 OMPClause *
   7562 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
   7563   // No need to rebuild this clause, no template-dependent parameters.
   7564   return C;
   7565 }
   7566 
   7567 template <typename Derived>
   7568 OMPClause *
   7569 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
   7570   // No need to rebuild this clause, no template-dependent parameters.
   7571   return C;
   7572 }
   7573 
   7574 template <typename Derived>
   7575 OMPClause *
   7576 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
   7577   // No need to rebuild this clause, no template-dependent parameters.
   7578   return C;
   7579 }
   7580 
   7581 template <typename Derived>
   7582 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
   7583   // No need to rebuild this clause, no template-dependent parameters.
   7584   return C;
   7585 }
   7586 
   7587 template <typename Derived>
   7588 OMPClause *
   7589 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
   7590   // No need to rebuild this clause, no template-dependent parameters.
   7591   return C;
   7592 }
   7593 
   7594 template <typename Derived>
   7595 OMPClause *
   7596 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
   7597   llvm::SmallVector<Expr *, 16> Vars;
   7598   Vars.reserve(C->varlist_size());
   7599   for (auto *VE : C->varlists()) {
   7600     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7601     if (EVar.isInvalid())
   7602       return nullptr;
   7603     Vars.push_back(EVar.get());
   7604   }
   7605   return getDerived().RebuildOMPPrivateClause(
   7606       Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7607 }
   7608 
   7609 template <typename Derived>
   7610 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
   7611     OMPFirstprivateClause *C) {
   7612   llvm::SmallVector<Expr *, 16> Vars;
   7613   Vars.reserve(C->varlist_size());
   7614   for (auto *VE : C->varlists()) {
   7615     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7616     if (EVar.isInvalid())
   7617       return nullptr;
   7618     Vars.push_back(EVar.get());
   7619   }
   7620   return getDerived().RebuildOMPFirstprivateClause(
   7621       Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7622 }
   7623 
   7624 template <typename Derived>
   7625 OMPClause *
   7626 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
   7627   llvm::SmallVector<Expr *, 16> Vars;
   7628   Vars.reserve(C->varlist_size());
   7629   for (auto *VE : C->varlists()) {
   7630     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7631     if (EVar.isInvalid())
   7632       return nullptr;
   7633     Vars.push_back(EVar.get());
   7634   }
   7635   return getDerived().RebuildOMPLastprivateClause(
   7636       Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7637 }
   7638 
   7639 template <typename Derived>
   7640 OMPClause *
   7641 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
   7642   llvm::SmallVector<Expr *, 16> Vars;
   7643   Vars.reserve(C->varlist_size());
   7644   for (auto *VE : C->varlists()) {
   7645     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7646     if (EVar.isInvalid())
   7647       return nullptr;
   7648     Vars.push_back(EVar.get());
   7649   }
   7650   return getDerived().RebuildOMPSharedClause(Vars, C->getLocStart(),
   7651                                              C->getLParenLoc(), C->getLocEnd());
   7652 }
   7653 
   7654 template <typename Derived>
   7655 OMPClause *
   7656 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
   7657   llvm::SmallVector<Expr *, 16> Vars;
   7658   Vars.reserve(C->varlist_size());
   7659   for (auto *VE : C->varlists()) {
   7660     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7661     if (EVar.isInvalid())
   7662       return nullptr;
   7663     Vars.push_back(EVar.get());
   7664   }
   7665   CXXScopeSpec ReductionIdScopeSpec;
   7666   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
   7667 
   7668   DeclarationNameInfo NameInfo = C->getNameInfo();
   7669   if (NameInfo.getName()) {
   7670     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
   7671     if (!NameInfo.getName())
   7672       return nullptr;
   7673   }
   7674   return getDerived().RebuildOMPReductionClause(
   7675       Vars, C->getLocStart(), C->getLParenLoc(), C->getColonLoc(),
   7676       C->getLocEnd(), ReductionIdScopeSpec, NameInfo);
   7677 }
   7678 
   7679 template <typename Derived>
   7680 OMPClause *
   7681 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
   7682   llvm::SmallVector<Expr *, 16> Vars;
   7683   Vars.reserve(C->varlist_size());
   7684   for (auto *VE : C->varlists()) {
   7685     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7686     if (EVar.isInvalid())
   7687       return nullptr;
   7688     Vars.push_back(EVar.get());
   7689   }
   7690   ExprResult Step = getDerived().TransformExpr(C->getStep());
   7691   if (Step.isInvalid())
   7692     return nullptr;
   7693   return getDerived().RebuildOMPLinearClause(
   7694       Vars, Step.get(), C->getLocStart(), C->getLParenLoc(), C->getModifier(),
   7695       C->getModifierLoc(), C->getColonLoc(), C->getLocEnd());
   7696 }
   7697 
   7698 template <typename Derived>
   7699 OMPClause *
   7700 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
   7701   llvm::SmallVector<Expr *, 16> Vars;
   7702   Vars.reserve(C->varlist_size());
   7703   for (auto *VE : C->varlists()) {
   7704     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7705     if (EVar.isInvalid())
   7706       return nullptr;
   7707     Vars.push_back(EVar.get());
   7708   }
   7709   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
   7710   if (Alignment.isInvalid())
   7711     return nullptr;
   7712   return getDerived().RebuildOMPAlignedClause(
   7713       Vars, Alignment.get(), C->getLocStart(), C->getLParenLoc(),
   7714       C->getColonLoc(), C->getLocEnd());
   7715 }
   7716 
   7717 template <typename Derived>
   7718 OMPClause *
   7719 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
   7720   llvm::SmallVector<Expr *, 16> Vars;
   7721   Vars.reserve(C->varlist_size());
   7722   for (auto *VE : C->varlists()) {
   7723     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7724     if (EVar.isInvalid())
   7725       return nullptr;
   7726     Vars.push_back(EVar.get());
   7727   }
   7728   return getDerived().RebuildOMPCopyinClause(Vars, C->getLocStart(),
   7729                                              C->getLParenLoc(), C->getLocEnd());
   7730 }
   7731 
   7732 template <typename Derived>
   7733 OMPClause *
   7734 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
   7735   llvm::SmallVector<Expr *, 16> Vars;
   7736   Vars.reserve(C->varlist_size());
   7737   for (auto *VE : C->varlists()) {
   7738     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7739     if (EVar.isInvalid())
   7740       return nullptr;
   7741     Vars.push_back(EVar.get());
   7742   }
   7743   return getDerived().RebuildOMPCopyprivateClause(
   7744       Vars, C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7745 }
   7746 
   7747 template <typename Derived>
   7748 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
   7749   llvm::SmallVector<Expr *, 16> Vars;
   7750   Vars.reserve(C->varlist_size());
   7751   for (auto *VE : C->varlists()) {
   7752     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7753     if (EVar.isInvalid())
   7754       return nullptr;
   7755     Vars.push_back(EVar.get());
   7756   }
   7757   return getDerived().RebuildOMPFlushClause(Vars, C->getLocStart(),
   7758                                             C->getLParenLoc(), C->getLocEnd());
   7759 }
   7760 
   7761 template <typename Derived>
   7762 OMPClause *
   7763 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
   7764   llvm::SmallVector<Expr *, 16> Vars;
   7765   Vars.reserve(C->varlist_size());
   7766   for (auto *VE : C->varlists()) {
   7767     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7768     if (EVar.isInvalid())
   7769       return nullptr;
   7770     Vars.push_back(EVar.get());
   7771   }
   7772   return getDerived().RebuildOMPDependClause(
   7773       C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
   7774       C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7775 }
   7776 
   7777 template <typename Derived>
   7778 OMPClause *
   7779 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
   7780   ExprResult E = getDerived().TransformExpr(C->getDevice());
   7781   if (E.isInvalid())
   7782     return nullptr;
   7783   return getDerived().RebuildOMPDeviceClause(
   7784       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7785 }
   7786 
   7787 template <typename Derived>
   7788 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
   7789   llvm::SmallVector<Expr *, 16> Vars;
   7790   Vars.reserve(C->varlist_size());
   7791   for (auto *VE : C->varlists()) {
   7792     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
   7793     if (EVar.isInvalid())
   7794       return nullptr;
   7795     Vars.push_back(EVar.get());
   7796   }
   7797   return getDerived().RebuildOMPMapClause(
   7798       C->getMapTypeModifier(), C->getMapType(), C->getMapLoc(),
   7799       C->getColonLoc(), Vars, C->getLocStart(), C->getLParenLoc(),
   7800       C->getLocEnd());
   7801 }
   7802 
   7803 template <typename Derived>
   7804 OMPClause *
   7805 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
   7806   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
   7807   if (E.isInvalid())
   7808     return nullptr;
   7809   return getDerived().RebuildOMPNumTeamsClause(
   7810       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7811 }
   7812 
   7813 template <typename Derived>
   7814 OMPClause *
   7815 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
   7816   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
   7817   if (E.isInvalid())
   7818     return nullptr;
   7819   return getDerived().RebuildOMPThreadLimitClause(
   7820       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7821 }
   7822 
   7823 template <typename Derived>
   7824 OMPClause *
   7825 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
   7826   ExprResult E = getDerived().TransformExpr(C->getPriority());
   7827   if (E.isInvalid())
   7828     return nullptr;
   7829   return getDerived().RebuildOMPPriorityClause(
   7830       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7831 }
   7832 
   7833 template <typename Derived>
   7834 OMPClause *
   7835 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
   7836   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
   7837   if (E.isInvalid())
   7838     return nullptr;
   7839   return getDerived().RebuildOMPGrainsizeClause(
   7840       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7841 }
   7842 
   7843 template <typename Derived>
   7844 OMPClause *
   7845 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
   7846   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
   7847   if (E.isInvalid())
   7848     return nullptr;
   7849   return getDerived().RebuildOMPNumTasksClause(
   7850       E.get(), C->getLocStart(), C->getLParenLoc(), C->getLocEnd());
   7851 }
   7852 
   7853 template <typename Derived>
   7854 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
   7855   ExprResult E = getDerived().TransformExpr(C->getHint());
   7856   if (E.isInvalid())
   7857     return nullptr;
   7858   return getDerived().RebuildOMPHintClause(E.get(), C->getLocStart(),
   7859                                            C->getLParenLoc(), C->getLocEnd());
   7860 }
   7861 
   7862 //===----------------------------------------------------------------------===//
   7863 // Expression transformation
   7864 //===----------------------------------------------------------------------===//
   7865 template<typename Derived>
   7866 ExprResult
   7867 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
   7868   if (!E->isTypeDependent())
   7869     return E;
   7870 
   7871   return getDerived().RebuildPredefinedExpr(E->getLocation(),
   7872                                             E->getIdentType());
   7873 }
   7874 
   7875 template<typename Derived>
   7876 ExprResult
   7877 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
   7878   NestedNameSpecifierLoc QualifierLoc;
   7879   if (E->getQualifierLoc()) {
   7880     QualifierLoc
   7881       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   7882     if (!QualifierLoc)
   7883       return ExprError();
   7884   }
   7885 
   7886   ValueDecl *ND
   7887     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
   7888                                                          E->getDecl()));
   7889   if (!ND)
   7890     return ExprError();
   7891 
   7892   DeclarationNameInfo NameInfo = E->getNameInfo();
   7893   if (NameInfo.getName()) {
   7894     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
   7895     if (!NameInfo.getName())
   7896       return ExprError();
   7897   }
   7898 
   7899   if (!getDerived().AlwaysRebuild() &&
   7900       QualifierLoc == E->getQualifierLoc() &&
   7901       ND == E->getDecl() &&
   7902       NameInfo.getName() == E->getDecl()->getDeclName() &&
   7903       !E->hasExplicitTemplateArgs()) {
   7904 
   7905     // Mark it referenced in the new context regardless.
   7906     // FIXME: this is a bit instantiation-specific.
   7907     SemaRef.MarkDeclRefReferenced(E);
   7908 
   7909     return E;
   7910   }
   7911 
   7912   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
   7913   if (E->hasExplicitTemplateArgs()) {
   7914     TemplateArgs = &TransArgs;
   7915     TransArgs.setLAngleLoc(E->getLAngleLoc());
   7916     TransArgs.setRAngleLoc(E->getRAngleLoc());
   7917     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   7918                                                 E->getNumTemplateArgs(),
   7919                                                 TransArgs))
   7920       return ExprError();
   7921   }
   7922 
   7923   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
   7924                                          TemplateArgs);
   7925 }
   7926 
   7927 template<typename Derived>
   7928 ExprResult
   7929 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
   7930   return E;
   7931 }
   7932 
   7933 template<typename Derived>
   7934 ExprResult
   7935 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
   7936   return E;
   7937 }
   7938 
   7939 template<typename Derived>
   7940 ExprResult
   7941 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
   7942   return E;
   7943 }
   7944 
   7945 template<typename Derived>
   7946 ExprResult
   7947 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
   7948   return E;
   7949 }
   7950 
   7951 template<typename Derived>
   7952 ExprResult
   7953 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
   7954   return E;
   7955 }
   7956 
   7957 template<typename Derived>
   7958 ExprResult
   7959 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
   7960   if (FunctionDecl *FD = E->getDirectCallee())
   7961     SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
   7962   return SemaRef.MaybeBindToTemporary(E);
   7963 }
   7964 
   7965 template<typename Derived>
   7966 ExprResult
   7967 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
   7968   ExprResult ControllingExpr =
   7969     getDerived().TransformExpr(E->getControllingExpr());
   7970   if (ControllingExpr.isInvalid())
   7971     return ExprError();
   7972 
   7973   SmallVector<Expr *, 4> AssocExprs;
   7974   SmallVector<TypeSourceInfo *, 4> AssocTypes;
   7975   for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
   7976     TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
   7977     if (TS) {
   7978       TypeSourceInfo *AssocType = getDerived().TransformType(TS);
   7979       if (!AssocType)
   7980         return ExprError();
   7981       AssocTypes.push_back(AssocType);
   7982     } else {
   7983       AssocTypes.push_back(nullptr);
   7984     }
   7985 
   7986     ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
   7987     if (AssocExpr.isInvalid())
   7988       return ExprError();
   7989     AssocExprs.push_back(AssocExpr.get());
   7990   }
   7991 
   7992   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
   7993                                                   E->getDefaultLoc(),
   7994                                                   E->getRParenLoc(),
   7995                                                   ControllingExpr.get(),
   7996                                                   AssocTypes,
   7997                                                   AssocExprs);
   7998 }
   7999 
   8000 template<typename Derived>
   8001 ExprResult
   8002 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
   8003   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   8004   if (SubExpr.isInvalid())
   8005     return ExprError();
   8006 
   8007   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
   8008     return E;
   8009 
   8010   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
   8011                                        E->getRParen());
   8012 }
   8013 
   8014 /// \brief The operand of a unary address-of operator has special rules: it's
   8015 /// allowed to refer to a non-static member of a class even if there's no 'this'
   8016 /// object available.
   8017 template<typename Derived>
   8018 ExprResult
   8019 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
   8020   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
   8021     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
   8022   else
   8023     return getDerived().TransformExpr(E);
   8024 }
   8025 
   8026 template<typename Derived>
   8027 ExprResult
   8028 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
   8029   ExprResult SubExpr;
   8030   if (E->getOpcode() == UO_AddrOf)
   8031     SubExpr = TransformAddressOfOperand(E->getSubExpr());
   8032   else
   8033     SubExpr = TransformExpr(E->getSubExpr());
   8034   if (SubExpr.isInvalid())
   8035     return ExprError();
   8036 
   8037   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
   8038     return E;
   8039 
   8040   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
   8041                                            E->getOpcode(),
   8042                                            SubExpr.get());
   8043 }
   8044 
   8045 template<typename Derived>
   8046 ExprResult
   8047 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
   8048   // Transform the type.
   8049   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
   8050   if (!Type)
   8051     return ExprError();
   8052 
   8053   // Transform all of the components into components similar to what the
   8054   // parser uses.
   8055   // FIXME: It would be slightly more efficient in the non-dependent case to
   8056   // just map FieldDecls, rather than requiring the rebuilder to look for
   8057   // the fields again. However, __builtin_offsetof is rare enough in
   8058   // template code that we don't care.
   8059   bool ExprChanged = false;
   8060   typedef Sema::OffsetOfComponent Component;
   8061   typedef OffsetOfExpr::OffsetOfNode Node;
   8062   SmallVector<Component, 4> Components;
   8063   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
   8064     const Node &ON = E->getComponent(I);
   8065     Component Comp;
   8066     Comp.isBrackets = true;
   8067     Comp.LocStart = ON.getSourceRange().getBegin();
   8068     Comp.LocEnd = ON.getSourceRange().getEnd();
   8069     switch (ON.getKind()) {
   8070     case Node::Array: {
   8071       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
   8072       ExprResult Index = getDerived().TransformExpr(FromIndex);
   8073       if (Index.isInvalid())
   8074         return ExprError();
   8075 
   8076       ExprChanged = ExprChanged || Index.get() != FromIndex;
   8077       Comp.isBrackets = true;
   8078       Comp.U.E = Index.get();
   8079       break;
   8080     }
   8081 
   8082     case Node::Field:
   8083     case Node::Identifier:
   8084       Comp.isBrackets = false;
   8085       Comp.U.IdentInfo = ON.getFieldName();
   8086       if (!Comp.U.IdentInfo)
   8087         continue;
   8088 
   8089       break;
   8090 
   8091     case Node::Base:
   8092       // Will be recomputed during the rebuild.
   8093       continue;
   8094     }
   8095 
   8096     Components.push_back(Comp);
   8097   }
   8098 
   8099   // If nothing changed, retain the existing expression.
   8100   if (!getDerived().AlwaysRebuild() &&
   8101       Type == E->getTypeSourceInfo() &&
   8102       !ExprChanged)
   8103     return E;
   8104 
   8105   // Build a new offsetof expression.
   8106   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
   8107                                           Components, E->getRParenLoc());
   8108 }
   8109 
   8110 template<typename Derived>
   8111 ExprResult
   8112 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
   8113   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
   8114          "opaque value expression requires transformation");
   8115   return E;
   8116 }
   8117 
   8118 template<typename Derived>
   8119 ExprResult
   8120 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
   8121   return E;
   8122 }
   8123 
   8124 template<typename Derived>
   8125 ExprResult
   8126 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
   8127   // Rebuild the syntactic form.  The original syntactic form has
   8128   // opaque-value expressions in it, so strip those away and rebuild
   8129   // the result.  This is a really awful way of doing this, but the
   8130   // better solution (rebuilding the semantic expressions and
   8131   // rebinding OVEs as necessary) doesn't work; we'd need
   8132   // TreeTransform to not strip away implicit conversions.
   8133   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
   8134   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
   8135   if (result.isInvalid()) return ExprError();
   8136 
   8137   // If that gives us a pseudo-object result back, the pseudo-object
   8138   // expression must have been an lvalue-to-rvalue conversion which we
   8139   // should reapply.
   8140   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
   8141     result = SemaRef.checkPseudoObjectRValue(result.get());
   8142 
   8143   return result;
   8144 }
   8145 
   8146 template<typename Derived>
   8147 ExprResult
   8148 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
   8149                                                 UnaryExprOrTypeTraitExpr *E) {
   8150   if (E->isArgumentType()) {
   8151     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
   8152 
   8153     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
   8154     if (!NewT)
   8155       return ExprError();
   8156 
   8157     if (!getDerived().AlwaysRebuild() && OldT == NewT)
   8158       return E;
   8159 
   8160     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
   8161                                                     E->getKind(),
   8162                                                     E->getSourceRange());
   8163   }
   8164 
   8165   // C++0x [expr.sizeof]p1:
   8166   //   The operand is either an expression, which is an unevaluated operand
   8167   //   [...]
   8168   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
   8169                                                Sema::ReuseLambdaContextDecl);
   8170 
   8171   // Try to recover if we have something like sizeof(T::X) where X is a type.
   8172   // Notably, there must be *exactly* one set of parens if X is a type.
   8173   TypeSourceInfo *RecoveryTSI = nullptr;
   8174   ExprResult SubExpr;
   8175   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
   8176   if (auto *DRE =
   8177           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
   8178     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
   8179         PE, DRE, false, &RecoveryTSI);
   8180   else
   8181     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
   8182 
   8183   if (RecoveryTSI) {
   8184     return getDerived().RebuildUnaryExprOrTypeTrait(
   8185         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
   8186   } else if (SubExpr.isInvalid())
   8187     return ExprError();
   8188 
   8189   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
   8190     return E;
   8191 
   8192   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
   8193                                                   E->getOperatorLoc(),
   8194                                                   E->getKind(),
   8195                                                   E->getSourceRange());
   8196 }
   8197 
   8198 template<typename Derived>
   8199 ExprResult
   8200 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
   8201   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   8202   if (LHS.isInvalid())
   8203     return ExprError();
   8204 
   8205   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   8206   if (RHS.isInvalid())
   8207     return ExprError();
   8208 
   8209 
   8210   if (!getDerived().AlwaysRebuild() &&
   8211       LHS.get() == E->getLHS() &&
   8212       RHS.get() == E->getRHS())
   8213     return E;
   8214 
   8215   return getDerived().RebuildArraySubscriptExpr(LHS.get(),
   8216                                            /*FIXME:*/E->getLHS()->getLocStart(),
   8217                                                 RHS.get(),
   8218                                                 E->getRBracketLoc());
   8219 }
   8220 
   8221 template <typename Derived>
   8222 ExprResult
   8223 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
   8224   ExprResult Base = getDerived().TransformExpr(E->getBase());
   8225   if (Base.isInvalid())
   8226     return ExprError();
   8227 
   8228   ExprResult LowerBound;
   8229   if (E->getLowerBound()) {
   8230     LowerBound = getDerived().TransformExpr(E->getLowerBound());
   8231     if (LowerBound.isInvalid())
   8232       return ExprError();
   8233   }
   8234 
   8235   ExprResult Length;
   8236   if (E->getLength()) {
   8237     Length = getDerived().TransformExpr(E->getLength());
   8238     if (Length.isInvalid())
   8239       return ExprError();
   8240   }
   8241 
   8242   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
   8243       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
   8244     return E;
   8245 
   8246   return getDerived().RebuildOMPArraySectionExpr(
   8247       Base.get(), E->getBase()->getLocEnd(), LowerBound.get(), E->getColonLoc(),
   8248       Length.get(), E->getRBracketLoc());
   8249 }
   8250 
   8251 template<typename Derived>
   8252 ExprResult
   8253 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
   8254   // Transform the callee.
   8255   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
   8256   if (Callee.isInvalid())
   8257     return ExprError();
   8258 
   8259   // Transform arguments.
   8260   bool ArgChanged = false;
   8261   SmallVector<Expr*, 8> Args;
   8262   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   8263                                   &ArgChanged))
   8264     return ExprError();
   8265 
   8266   if (!getDerived().AlwaysRebuild() &&
   8267       Callee.get() == E->getCallee() &&
   8268       !ArgChanged)
   8269     return SemaRef.MaybeBindToTemporary(E);
   8270 
   8271   // FIXME: Wrong source location information for the '('.
   8272   SourceLocation FakeLParenLoc
   8273     = ((Expr *)Callee.get())->getSourceRange().getBegin();
   8274   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
   8275                                       Args,
   8276                                       E->getRParenLoc());
   8277 }
   8278 
   8279 template<typename Derived>
   8280 ExprResult
   8281 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
   8282   ExprResult Base = getDerived().TransformExpr(E->getBase());
   8283   if (Base.isInvalid())
   8284     return ExprError();
   8285 
   8286   NestedNameSpecifierLoc QualifierLoc;
   8287   if (E->hasQualifier()) {
   8288     QualifierLoc
   8289       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   8290 
   8291     if (!QualifierLoc)
   8292       return ExprError();
   8293   }
   8294   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
   8295 
   8296   ValueDecl *Member
   8297     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
   8298                                                          E->getMemberDecl()));
   8299   if (!Member)
   8300     return ExprError();
   8301 
   8302   NamedDecl *FoundDecl = E->getFoundDecl();
   8303   if (FoundDecl == E->getMemberDecl()) {
   8304     FoundDecl = Member;
   8305   } else {
   8306     FoundDecl = cast_or_null<NamedDecl>(
   8307                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
   8308     if (!FoundDecl)
   8309       return ExprError();
   8310   }
   8311 
   8312   if (!getDerived().AlwaysRebuild() &&
   8313       Base.get() == E->getBase() &&
   8314       QualifierLoc == E->getQualifierLoc() &&
   8315       Member == E->getMemberDecl() &&
   8316       FoundDecl == E->getFoundDecl() &&
   8317       !E->hasExplicitTemplateArgs()) {
   8318 
   8319     // Mark it referenced in the new context regardless.
   8320     // FIXME: this is a bit instantiation-specific.
   8321     SemaRef.MarkMemberReferenced(E);
   8322 
   8323     return E;
   8324   }
   8325 
   8326   TemplateArgumentListInfo TransArgs;
   8327   if (E->hasExplicitTemplateArgs()) {
   8328     TransArgs.setLAngleLoc(E->getLAngleLoc());
   8329     TransArgs.setRAngleLoc(E->getRAngleLoc());
   8330     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   8331                                                 E->getNumTemplateArgs(),
   8332                                                 TransArgs))
   8333       return ExprError();
   8334   }
   8335 
   8336   // FIXME: Bogus source location for the operator
   8337   SourceLocation FakeOperatorLoc =
   8338       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
   8339 
   8340   // FIXME: to do this check properly, we will need to preserve the
   8341   // first-qualifier-in-scope here, just in case we had a dependent
   8342   // base (and therefore couldn't do the check) and a
   8343   // nested-name-qualifier (and therefore could do the lookup).
   8344   NamedDecl *FirstQualifierInScope = nullptr;
   8345 
   8346   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
   8347                                         E->isArrow(),
   8348                                         QualifierLoc,
   8349                                         TemplateKWLoc,
   8350                                         E->getMemberNameInfo(),
   8351                                         Member,
   8352                                         FoundDecl,
   8353                                         (E->hasExplicitTemplateArgs()
   8354                                            ? &TransArgs : nullptr),
   8355                                         FirstQualifierInScope);
   8356 }
   8357 
   8358 template<typename Derived>
   8359 ExprResult
   8360 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
   8361   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   8362   if (LHS.isInvalid())
   8363     return ExprError();
   8364 
   8365   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   8366   if (RHS.isInvalid())
   8367     return ExprError();
   8368 
   8369   if (!getDerived().AlwaysRebuild() &&
   8370       LHS.get() == E->getLHS() &&
   8371       RHS.get() == E->getRHS())
   8372     return E;
   8373 
   8374   Sema::FPContractStateRAII FPContractState(getSema());
   8375   getSema().FPFeatures.fp_contract = E->isFPContractable();
   8376 
   8377   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
   8378                                             LHS.get(), RHS.get());
   8379 }
   8380 
   8381 template<typename Derived>
   8382 ExprResult
   8383 TreeTransform<Derived>::TransformCompoundAssignOperator(
   8384                                                       CompoundAssignOperator *E) {
   8385   return getDerived().TransformBinaryOperator(E);
   8386 }
   8387 
   8388 template<typename Derived>
   8389 ExprResult TreeTransform<Derived>::
   8390 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
   8391   // Just rebuild the common and RHS expressions and see whether we
   8392   // get any changes.
   8393 
   8394   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
   8395   if (commonExpr.isInvalid())
   8396     return ExprError();
   8397 
   8398   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
   8399   if (rhs.isInvalid())
   8400     return ExprError();
   8401 
   8402   if (!getDerived().AlwaysRebuild() &&
   8403       commonExpr.get() == e->getCommon() &&
   8404       rhs.get() == e->getFalseExpr())
   8405     return e;
   8406 
   8407   return getDerived().RebuildConditionalOperator(commonExpr.get(),
   8408                                                  e->getQuestionLoc(),
   8409                                                  nullptr,
   8410                                                  e->getColonLoc(),
   8411                                                  rhs.get());
   8412 }
   8413 
   8414 template<typename Derived>
   8415 ExprResult
   8416 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
   8417   ExprResult Cond = getDerived().TransformExpr(E->getCond());
   8418   if (Cond.isInvalid())
   8419     return ExprError();
   8420 
   8421   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   8422   if (LHS.isInvalid())
   8423     return ExprError();
   8424 
   8425   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   8426   if (RHS.isInvalid())
   8427     return ExprError();
   8428 
   8429   if (!getDerived().AlwaysRebuild() &&
   8430       Cond.get() == E->getCond() &&
   8431       LHS.get() == E->getLHS() &&
   8432       RHS.get() == E->getRHS())
   8433     return E;
   8434 
   8435   return getDerived().RebuildConditionalOperator(Cond.get(),
   8436                                                  E->getQuestionLoc(),
   8437                                                  LHS.get(),
   8438                                                  E->getColonLoc(),
   8439                                                  RHS.get());
   8440 }
   8441 
   8442 template<typename Derived>
   8443 ExprResult
   8444 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
   8445   // Implicit casts are eliminated during transformation, since they
   8446   // will be recomputed by semantic analysis after transformation.
   8447   return getDerived().TransformExpr(E->getSubExprAsWritten());
   8448 }
   8449 
   8450 template<typename Derived>
   8451 ExprResult
   8452 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
   8453   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
   8454   if (!Type)
   8455     return ExprError();
   8456 
   8457   ExprResult SubExpr
   8458     = getDerived().TransformExpr(E->getSubExprAsWritten());
   8459   if (SubExpr.isInvalid())
   8460     return ExprError();
   8461 
   8462   if (!getDerived().AlwaysRebuild() &&
   8463       Type == E->getTypeInfoAsWritten() &&
   8464       SubExpr.get() == E->getSubExpr())
   8465     return E;
   8466 
   8467   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
   8468                                             Type,
   8469                                             E->getRParenLoc(),
   8470                                             SubExpr.get());
   8471 }
   8472 
   8473 template<typename Derived>
   8474 ExprResult
   8475 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
   8476   TypeSourceInfo *OldT = E->getTypeSourceInfo();
   8477   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
   8478   if (!NewT)
   8479     return ExprError();
   8480 
   8481   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
   8482   if (Init.isInvalid())
   8483     return ExprError();
   8484 
   8485   if (!getDerived().AlwaysRebuild() &&
   8486       OldT == NewT &&
   8487       Init.get() == E->getInitializer())
   8488     return SemaRef.MaybeBindToTemporary(E);
   8489 
   8490   // Note: the expression type doesn't necessarily match the
   8491   // type-as-written, but that's okay, because it should always be
   8492   // derivable from the initializer.
   8493 
   8494   return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
   8495                                    /*FIXME:*/E->getInitializer()->getLocEnd(),
   8496                                                  Init.get());
   8497 }
   8498 
   8499 template<typename Derived>
   8500 ExprResult
   8501 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
   8502   ExprResult Base = getDerived().TransformExpr(E->getBase());
   8503   if (Base.isInvalid())
   8504     return ExprError();
   8505 
   8506   if (!getDerived().AlwaysRebuild() &&
   8507       Base.get() == E->getBase())
   8508     return E;
   8509 
   8510   // FIXME: Bad source location
   8511   SourceLocation FakeOperatorLoc =
   8512       SemaRef.getLocForEndOfToken(E->getBase()->getLocEnd());
   8513   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
   8514                                                   E->getAccessorLoc(),
   8515                                                   E->getAccessor());
   8516 }
   8517 
   8518 template<typename Derived>
   8519 ExprResult
   8520 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
   8521   if (InitListExpr *Syntactic = E->getSyntacticForm())
   8522     E = Syntactic;
   8523 
   8524   bool InitChanged = false;
   8525 
   8526   SmallVector<Expr*, 4> Inits;
   8527   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
   8528                                   Inits, &InitChanged))
   8529     return ExprError();
   8530 
   8531   if (!getDerived().AlwaysRebuild() && !InitChanged) {
   8532     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
   8533     // in some cases. We can't reuse it in general, because the syntactic and
   8534     // semantic forms are linked, and we can't know that semantic form will
   8535     // match even if the syntactic form does.
   8536   }
   8537 
   8538   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
   8539                                       E->getRBraceLoc(), E->getType());
   8540 }
   8541 
   8542 template<typename Derived>
   8543 ExprResult
   8544 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
   8545   Designation Desig;
   8546 
   8547   // transform the initializer value
   8548   ExprResult Init = getDerived().TransformExpr(E->getInit());
   8549   if (Init.isInvalid())
   8550     return ExprError();
   8551 
   8552   // transform the designators.
   8553   SmallVector<Expr*, 4> ArrayExprs;
   8554   bool ExprChanged = false;
   8555   for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
   8556                                              DEnd = E->designators_end();
   8557        D != DEnd; ++D) {
   8558     if (D->isFieldDesignator()) {
   8559       Desig.AddDesignator(Designator::getField(D->getFieldName(),
   8560                                                D->getDotLoc(),
   8561                                                D->getFieldLoc()));
   8562       continue;
   8563     }
   8564 
   8565     if (D->isArrayDesignator()) {
   8566       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
   8567       if (Index.isInvalid())
   8568         return ExprError();
   8569 
   8570       Desig.AddDesignator(Designator::getArray(Index.get(),
   8571                                                D->getLBracketLoc()));
   8572 
   8573       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
   8574       ArrayExprs.push_back(Index.get());
   8575       continue;
   8576     }
   8577 
   8578     assert(D->isArrayRangeDesignator() && "New kind of designator?");
   8579     ExprResult Start
   8580       = getDerived().TransformExpr(E->getArrayRangeStart(*D));
   8581     if (Start.isInvalid())
   8582       return ExprError();
   8583 
   8584     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
   8585     if (End.isInvalid())
   8586       return ExprError();
   8587 
   8588     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
   8589                                                   End.get(),
   8590                                                   D->getLBracketLoc(),
   8591                                                   D->getEllipsisLoc()));
   8592 
   8593     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
   8594       End.get() != E->getArrayRangeEnd(*D);
   8595 
   8596     ArrayExprs.push_back(Start.get());
   8597     ArrayExprs.push_back(End.get());
   8598   }
   8599 
   8600   if (!getDerived().AlwaysRebuild() &&
   8601       Init.get() == E->getInit() &&
   8602       !ExprChanged)
   8603     return E;
   8604 
   8605   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
   8606                                                 E->getEqualOrColonLoc(),
   8607                                                 E->usesGNUSyntax(), Init.get());
   8608 }
   8609 
   8610 // Seems that if TransformInitListExpr() only works on the syntactic form of an
   8611 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
   8612 template<typename Derived>
   8613 ExprResult
   8614 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
   8615     DesignatedInitUpdateExpr *E) {
   8616   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
   8617                    "initializer");
   8618   return ExprError();
   8619 }
   8620 
   8621 template<typename Derived>
   8622 ExprResult
   8623 TreeTransform<Derived>::TransformNoInitExpr(
   8624     NoInitExpr *E) {
   8625   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
   8626   return ExprError();
   8627 }
   8628 
   8629 template<typename Derived>
   8630 ExprResult
   8631 TreeTransform<Derived>::TransformImplicitValueInitExpr(
   8632                                                      ImplicitValueInitExpr *E) {
   8633   TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
   8634 
   8635   // FIXME: Will we ever have proper type location here? Will we actually
   8636   // need to transform the type?
   8637   QualType T = getDerived().TransformType(E->getType());
   8638   if (T.isNull())
   8639     return ExprError();
   8640 
   8641   if (!getDerived().AlwaysRebuild() &&
   8642       T == E->getType())
   8643     return E;
   8644 
   8645   return getDerived().RebuildImplicitValueInitExpr(T);
   8646 }
   8647 
   8648 template<typename Derived>
   8649 ExprResult
   8650 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
   8651   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
   8652   if (!TInfo)
   8653     return ExprError();
   8654 
   8655   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   8656   if (SubExpr.isInvalid())
   8657     return ExprError();
   8658 
   8659   if (!getDerived().AlwaysRebuild() &&
   8660       TInfo == E->getWrittenTypeInfo() &&
   8661       SubExpr.get() == E->getSubExpr())
   8662     return E;
   8663 
   8664   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
   8665                                        TInfo, E->getRParenLoc());
   8666 }
   8667 
   8668 template<typename Derived>
   8669 ExprResult
   8670 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
   8671   bool ArgumentChanged = false;
   8672   SmallVector<Expr*, 4> Inits;
   8673   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
   8674                      &ArgumentChanged))
   8675     return ExprError();
   8676 
   8677   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
   8678                                            Inits,
   8679                                            E->getRParenLoc());
   8680 }
   8681 
   8682 /// \brief Transform an address-of-label expression.
   8683 ///
   8684 /// By default, the transformation of an address-of-label expression always
   8685 /// rebuilds the expression, so that the label identifier can be resolved to
   8686 /// the corresponding label statement by semantic analysis.
   8687 template<typename Derived>
   8688 ExprResult
   8689 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
   8690   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
   8691                                         E->getLabel());
   8692   if (!LD)
   8693     return ExprError();
   8694 
   8695   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
   8696                                            cast<LabelDecl>(LD));
   8697 }
   8698 
   8699 template<typename Derived>
   8700 ExprResult
   8701 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
   8702   SemaRef.ActOnStartStmtExpr();
   8703   StmtResult SubStmt
   8704     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
   8705   if (SubStmt.isInvalid()) {
   8706     SemaRef.ActOnStmtExprError();
   8707     return ExprError();
   8708   }
   8709 
   8710   if (!getDerived().AlwaysRebuild() &&
   8711       SubStmt.get() == E->getSubStmt()) {
   8712     // Calling this an 'error' is unintuitive, but it does the right thing.
   8713     SemaRef.ActOnStmtExprError();
   8714     return SemaRef.MaybeBindToTemporary(E);
   8715   }
   8716 
   8717   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
   8718                                       SubStmt.get(),
   8719                                       E->getRParenLoc());
   8720 }
   8721 
   8722 template<typename Derived>
   8723 ExprResult
   8724 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
   8725   ExprResult Cond = getDerived().TransformExpr(E->getCond());
   8726   if (Cond.isInvalid())
   8727     return ExprError();
   8728 
   8729   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   8730   if (LHS.isInvalid())
   8731     return ExprError();
   8732 
   8733   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   8734   if (RHS.isInvalid())
   8735     return ExprError();
   8736 
   8737   if (!getDerived().AlwaysRebuild() &&
   8738       Cond.get() == E->getCond() &&
   8739       LHS.get() == E->getLHS() &&
   8740       RHS.get() == E->getRHS())
   8741     return E;
   8742 
   8743   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
   8744                                         Cond.get(), LHS.get(), RHS.get(),
   8745                                         E->getRParenLoc());
   8746 }
   8747 
   8748 template<typename Derived>
   8749 ExprResult
   8750 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
   8751   return E;
   8752 }
   8753 
   8754 template<typename Derived>
   8755 ExprResult
   8756 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
   8757   switch (E->getOperator()) {
   8758   case OO_New:
   8759   case OO_Delete:
   8760   case OO_Array_New:
   8761   case OO_Array_Delete:
   8762     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
   8763 
   8764   case OO_Call: {
   8765     // This is a call to an object's operator().
   8766     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
   8767 
   8768     // Transform the object itself.
   8769     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
   8770     if (Object.isInvalid())
   8771       return ExprError();
   8772 
   8773     // FIXME: Poor location information
   8774     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
   8775         static_cast<Expr *>(Object.get())->getLocEnd());
   8776 
   8777     // Transform the call arguments.
   8778     SmallVector<Expr*, 8> Args;
   8779     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
   8780                                     Args))
   8781       return ExprError();
   8782 
   8783     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
   8784                                         Args,
   8785                                         E->getLocEnd());
   8786   }
   8787 
   8788 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
   8789   case OO_##Name:
   8790 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
   8791 #include "clang/Basic/OperatorKinds.def"
   8792   case OO_Subscript:
   8793     // Handled below.
   8794     break;
   8795 
   8796   case OO_Conditional:
   8797     llvm_unreachable("conditional operator is not actually overloadable");
   8798 
   8799   case OO_None:
   8800   case NUM_OVERLOADED_OPERATORS:
   8801     llvm_unreachable("not an overloaded operator?");
   8802   }
   8803 
   8804   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
   8805   if (Callee.isInvalid())
   8806     return ExprError();
   8807 
   8808   ExprResult First;
   8809   if (E->getOperator() == OO_Amp)
   8810     First = getDerived().TransformAddressOfOperand(E->getArg(0));
   8811   else
   8812     First = getDerived().TransformExpr(E->getArg(0));
   8813   if (First.isInvalid())
   8814     return ExprError();
   8815 
   8816   ExprResult Second;
   8817   if (E->getNumArgs() == 2) {
   8818     Second = getDerived().TransformExpr(E->getArg(1));
   8819     if (Second.isInvalid())
   8820       return ExprError();
   8821   }
   8822 
   8823   if (!getDerived().AlwaysRebuild() &&
   8824       Callee.get() == E->getCallee() &&
   8825       First.get() == E->getArg(0) &&
   8826       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
   8827     return SemaRef.MaybeBindToTemporary(E);
   8828 
   8829   Sema::FPContractStateRAII FPContractState(getSema());
   8830   getSema().FPFeatures.fp_contract = E->isFPContractable();
   8831 
   8832   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
   8833                                                  E->getOperatorLoc(),
   8834                                                  Callee.get(),
   8835                                                  First.get(),
   8836                                                  Second.get());
   8837 }
   8838 
   8839 template<typename Derived>
   8840 ExprResult
   8841 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
   8842   return getDerived().TransformCallExpr(E);
   8843 }
   8844 
   8845 template<typename Derived>
   8846 ExprResult
   8847 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
   8848   // Transform the callee.
   8849   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
   8850   if (Callee.isInvalid())
   8851     return ExprError();
   8852 
   8853   // Transform exec config.
   8854   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
   8855   if (EC.isInvalid())
   8856     return ExprError();
   8857 
   8858   // Transform arguments.
   8859   bool ArgChanged = false;
   8860   SmallVector<Expr*, 8> Args;
   8861   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   8862                                   &ArgChanged))
   8863     return ExprError();
   8864 
   8865   if (!getDerived().AlwaysRebuild() &&
   8866       Callee.get() == E->getCallee() &&
   8867       !ArgChanged)
   8868     return SemaRef.MaybeBindToTemporary(E);
   8869 
   8870   // FIXME: Wrong source location information for the '('.
   8871   SourceLocation FakeLParenLoc
   8872     = ((Expr *)Callee.get())->getSourceRange().getBegin();
   8873   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
   8874                                       Args,
   8875                                       E->getRParenLoc(), EC.get());
   8876 }
   8877 
   8878 template<typename Derived>
   8879 ExprResult
   8880 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
   8881   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
   8882   if (!Type)
   8883     return ExprError();
   8884 
   8885   ExprResult SubExpr
   8886     = getDerived().TransformExpr(E->getSubExprAsWritten());
   8887   if (SubExpr.isInvalid())
   8888     return ExprError();
   8889 
   8890   if (!getDerived().AlwaysRebuild() &&
   8891       Type == E->getTypeInfoAsWritten() &&
   8892       SubExpr.get() == E->getSubExpr())
   8893     return E;
   8894   return getDerived().RebuildCXXNamedCastExpr(
   8895       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
   8896       Type, E->getAngleBrackets().getEnd(),
   8897       // FIXME. this should be '(' location
   8898       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
   8899 }
   8900 
   8901 template<typename Derived>
   8902 ExprResult
   8903 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
   8904   return getDerived().TransformCXXNamedCastExpr(E);
   8905 }
   8906 
   8907 template<typename Derived>
   8908 ExprResult
   8909 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
   8910   return getDerived().TransformCXXNamedCastExpr(E);
   8911 }
   8912 
   8913 template<typename Derived>
   8914 ExprResult
   8915 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
   8916                                                       CXXReinterpretCastExpr *E) {
   8917   return getDerived().TransformCXXNamedCastExpr(E);
   8918 }
   8919 
   8920 template<typename Derived>
   8921 ExprResult
   8922 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
   8923   return getDerived().TransformCXXNamedCastExpr(E);
   8924 }
   8925 
   8926 template<typename Derived>
   8927 ExprResult
   8928 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
   8929                                                      CXXFunctionalCastExpr *E) {
   8930   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
   8931   if (!Type)
   8932     return ExprError();
   8933 
   8934   ExprResult SubExpr
   8935     = getDerived().TransformExpr(E->getSubExprAsWritten());
   8936   if (SubExpr.isInvalid())
   8937     return ExprError();
   8938 
   8939   if (!getDerived().AlwaysRebuild() &&
   8940       Type == E->getTypeInfoAsWritten() &&
   8941       SubExpr.get() == E->getSubExpr())
   8942     return E;
   8943 
   8944   return getDerived().RebuildCXXFunctionalCastExpr(Type,
   8945                                                    E->getLParenLoc(),
   8946                                                    SubExpr.get(),
   8947                                                    E->getRParenLoc());
   8948 }
   8949 
   8950 template<typename Derived>
   8951 ExprResult
   8952 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
   8953   if (E->isTypeOperand()) {
   8954     TypeSourceInfo *TInfo
   8955       = getDerived().TransformType(E->getTypeOperandSourceInfo());
   8956     if (!TInfo)
   8957       return ExprError();
   8958 
   8959     if (!getDerived().AlwaysRebuild() &&
   8960         TInfo == E->getTypeOperandSourceInfo())
   8961       return E;
   8962 
   8963     return getDerived().RebuildCXXTypeidExpr(E->getType(),
   8964                                              E->getLocStart(),
   8965                                              TInfo,
   8966                                              E->getLocEnd());
   8967   }
   8968 
   8969   // We don't know whether the subexpression is potentially evaluated until
   8970   // after we perform semantic analysis.  We speculatively assume it is
   8971   // unevaluated; it will get fixed later if the subexpression is in fact
   8972   // potentially evaluated.
   8973   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
   8974                                                Sema::ReuseLambdaContextDecl);
   8975 
   8976   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
   8977   if (SubExpr.isInvalid())
   8978     return ExprError();
   8979 
   8980   if (!getDerived().AlwaysRebuild() &&
   8981       SubExpr.get() == E->getExprOperand())
   8982     return E;
   8983 
   8984   return getDerived().RebuildCXXTypeidExpr(E->getType(),
   8985                                            E->getLocStart(),
   8986                                            SubExpr.get(),
   8987                                            E->getLocEnd());
   8988 }
   8989 
   8990 template<typename Derived>
   8991 ExprResult
   8992 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
   8993   if (E->isTypeOperand()) {
   8994     TypeSourceInfo *TInfo
   8995       = getDerived().TransformType(E->getTypeOperandSourceInfo());
   8996     if (!TInfo)
   8997       return ExprError();
   8998 
   8999     if (!getDerived().AlwaysRebuild() &&
   9000         TInfo == E->getTypeOperandSourceInfo())
   9001       return E;
   9002 
   9003     return getDerived().RebuildCXXUuidofExpr(E->getType(),
   9004                                              E->getLocStart(),
   9005                                              TInfo,
   9006                                              E->getLocEnd());
   9007   }
   9008 
   9009   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   9010 
   9011   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
   9012   if (SubExpr.isInvalid())
   9013     return ExprError();
   9014 
   9015   if (!getDerived().AlwaysRebuild() &&
   9016       SubExpr.get() == E->getExprOperand())
   9017     return E;
   9018 
   9019   return getDerived().RebuildCXXUuidofExpr(E->getType(),
   9020                                            E->getLocStart(),
   9021                                            SubExpr.get(),
   9022                                            E->getLocEnd());
   9023 }
   9024 
   9025 template<typename Derived>
   9026 ExprResult
   9027 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
   9028   return E;
   9029 }
   9030 
   9031 template<typename Derived>
   9032 ExprResult
   9033 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
   9034                                                      CXXNullPtrLiteralExpr *E) {
   9035   return E;
   9036 }
   9037 
   9038 template<typename Derived>
   9039 ExprResult
   9040 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
   9041   QualType T = getSema().getCurrentThisType();
   9042 
   9043   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
   9044     // Make sure that we capture 'this'.
   9045     getSema().CheckCXXThisCapture(E->getLocStart());
   9046     return E;
   9047   }
   9048 
   9049   return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
   9050 }
   9051 
   9052 template<typename Derived>
   9053 ExprResult
   9054 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
   9055   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   9056   if (SubExpr.isInvalid())
   9057     return ExprError();
   9058 
   9059   if (!getDerived().AlwaysRebuild() &&
   9060       SubExpr.get() == E->getSubExpr())
   9061     return E;
   9062 
   9063   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
   9064                                           E->isThrownVariableInScope());
   9065 }
   9066 
   9067 template<typename Derived>
   9068 ExprResult
   9069 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
   9070   ParmVarDecl *Param
   9071     = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
   9072                                                            E->getParam()));
   9073   if (!Param)
   9074     return ExprError();
   9075 
   9076   if (!getDerived().AlwaysRebuild() &&
   9077       Param == E->getParam())
   9078     return E;
   9079 
   9080   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
   9081 }
   9082 
   9083 template<typename Derived>
   9084 ExprResult
   9085 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
   9086   FieldDecl *Field
   9087     = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
   9088                                                          E->getField()));
   9089   if (!Field)
   9090     return ExprError();
   9091 
   9092   if (!getDerived().AlwaysRebuild() && Field == E->getField())
   9093     return E;
   9094 
   9095   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
   9096 }
   9097 
   9098 template<typename Derived>
   9099 ExprResult
   9100 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
   9101                                                     CXXScalarValueInitExpr *E) {
   9102   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
   9103   if (!T)
   9104     return ExprError();
   9105 
   9106   if (!getDerived().AlwaysRebuild() &&
   9107       T == E->getTypeSourceInfo())
   9108     return E;
   9109 
   9110   return getDerived().RebuildCXXScalarValueInitExpr(T,
   9111                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
   9112                                                     E->getRParenLoc());
   9113 }
   9114 
   9115 template<typename Derived>
   9116 ExprResult
   9117 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
   9118   // Transform the type that we're allocating
   9119   TypeSourceInfo *AllocTypeInfo
   9120     = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
   9121   if (!AllocTypeInfo)
   9122     return ExprError();
   9123 
   9124   // Transform the size of the array we're allocating (if any).
   9125   ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
   9126   if (ArraySize.isInvalid())
   9127     return ExprError();
   9128 
   9129   // Transform the placement arguments (if any).
   9130   bool ArgumentChanged = false;
   9131   SmallVector<Expr*, 8> PlacementArgs;
   9132   if (getDerived().TransformExprs(E->getPlacementArgs(),
   9133                                   E->getNumPlacementArgs(), true,
   9134                                   PlacementArgs, &ArgumentChanged))
   9135     return ExprError();
   9136 
   9137   // Transform the initializer (if any).
   9138   Expr *OldInit = E->getInitializer();
   9139   ExprResult NewInit;
   9140   if (OldInit)
   9141     NewInit = getDerived().TransformInitializer(OldInit, true);
   9142   if (NewInit.isInvalid())
   9143     return ExprError();
   9144 
   9145   // Transform new operator and delete operator.
   9146   FunctionDecl *OperatorNew = nullptr;
   9147   if (E->getOperatorNew()) {
   9148     OperatorNew = cast_or_null<FunctionDecl>(
   9149                                  getDerived().TransformDecl(E->getLocStart(),
   9150                                                          E->getOperatorNew()));
   9151     if (!OperatorNew)
   9152       return ExprError();
   9153   }
   9154 
   9155   FunctionDecl *OperatorDelete = nullptr;
   9156   if (E->getOperatorDelete()) {
   9157     OperatorDelete = cast_or_null<FunctionDecl>(
   9158                                    getDerived().TransformDecl(E->getLocStart(),
   9159                                                        E->getOperatorDelete()));
   9160     if (!OperatorDelete)
   9161       return ExprError();
   9162   }
   9163 
   9164   if (!getDerived().AlwaysRebuild() &&
   9165       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
   9166       ArraySize.get() == E->getArraySize() &&
   9167       NewInit.get() == OldInit &&
   9168       OperatorNew == E->getOperatorNew() &&
   9169       OperatorDelete == E->getOperatorDelete() &&
   9170       !ArgumentChanged) {
   9171     // Mark any declarations we need as referenced.
   9172     // FIXME: instantiation-specific.
   9173     if (OperatorNew)
   9174       SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
   9175     if (OperatorDelete)
   9176       SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
   9177 
   9178     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
   9179       QualType ElementType
   9180         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
   9181       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
   9182         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
   9183         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
   9184           SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
   9185         }
   9186       }
   9187     }
   9188 
   9189     return E;
   9190   }
   9191 
   9192   QualType AllocType = AllocTypeInfo->getType();
   9193   if (!ArraySize.get()) {
   9194     // If no array size was specified, but the new expression was
   9195     // instantiated with an array type (e.g., "new T" where T is
   9196     // instantiated with "int[4]"), extract the outer bound from the
   9197     // array type as our array size. We do this with constant and
   9198     // dependently-sized array types.
   9199     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
   9200     if (!ArrayT) {
   9201       // Do nothing
   9202     } else if (const ConstantArrayType *ConsArrayT
   9203                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
   9204       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
   9205                                          SemaRef.Context.getSizeType(),
   9206                                          /*FIXME:*/ E->getLocStart());
   9207       AllocType = ConsArrayT->getElementType();
   9208     } else if (const DependentSizedArrayType *DepArrayT
   9209                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
   9210       if (DepArrayT->getSizeExpr()) {
   9211         ArraySize = DepArrayT->getSizeExpr();
   9212         AllocType = DepArrayT->getElementType();
   9213       }
   9214     }
   9215   }
   9216 
   9217   return getDerived().RebuildCXXNewExpr(E->getLocStart(),
   9218                                         E->isGlobalNew(),
   9219                                         /*FIXME:*/E->getLocStart(),
   9220                                         PlacementArgs,
   9221                                         /*FIXME:*/E->getLocStart(),
   9222                                         E->getTypeIdParens(),
   9223                                         AllocType,
   9224                                         AllocTypeInfo,
   9225                                         ArraySize.get(),
   9226                                         E->getDirectInitRange(),
   9227                                         NewInit.get());
   9228 }
   9229 
   9230 template<typename Derived>
   9231 ExprResult
   9232 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
   9233   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
   9234   if (Operand.isInvalid())
   9235     return ExprError();
   9236 
   9237   // Transform the delete operator, if known.
   9238   FunctionDecl *OperatorDelete = nullptr;
   9239   if (E->getOperatorDelete()) {
   9240     OperatorDelete = cast_or_null<FunctionDecl>(
   9241                                    getDerived().TransformDecl(E->getLocStart(),
   9242                                                        E->getOperatorDelete()));
   9243     if (!OperatorDelete)
   9244       return ExprError();
   9245   }
   9246 
   9247   if (!getDerived().AlwaysRebuild() &&
   9248       Operand.get() == E->getArgument() &&
   9249       OperatorDelete == E->getOperatorDelete()) {
   9250     // Mark any declarations we need as referenced.
   9251     // FIXME: instantiation-specific.
   9252     if (OperatorDelete)
   9253       SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
   9254 
   9255     if (!E->getArgument()->isTypeDependent()) {
   9256       QualType Destroyed = SemaRef.Context.getBaseElementType(
   9257                                                          E->getDestroyedType());
   9258       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
   9259         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
   9260         SemaRef.MarkFunctionReferenced(E->getLocStart(),
   9261                                        SemaRef.LookupDestructor(Record));
   9262       }
   9263     }
   9264 
   9265     return E;
   9266   }
   9267 
   9268   return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
   9269                                            E->isGlobalDelete(),
   9270                                            E->isArrayForm(),
   9271                                            Operand.get());
   9272 }
   9273 
   9274 template<typename Derived>
   9275 ExprResult
   9276 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
   9277                                                      CXXPseudoDestructorExpr *E) {
   9278   ExprResult Base = getDerived().TransformExpr(E->getBase());
   9279   if (Base.isInvalid())
   9280     return ExprError();
   9281 
   9282   ParsedType ObjectTypePtr;
   9283   bool MayBePseudoDestructor = false;
   9284   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
   9285                                               E->getOperatorLoc(),
   9286                                         E->isArrow()? tok::arrow : tok::period,
   9287                                               ObjectTypePtr,
   9288                                               MayBePseudoDestructor);
   9289   if (Base.isInvalid())
   9290     return ExprError();
   9291 
   9292   QualType ObjectType = ObjectTypePtr.get();
   9293   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
   9294   if (QualifierLoc) {
   9295     QualifierLoc
   9296       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
   9297     if (!QualifierLoc)
   9298       return ExprError();
   9299   }
   9300   CXXScopeSpec SS;
   9301   SS.Adopt(QualifierLoc);
   9302 
   9303   PseudoDestructorTypeStorage Destroyed;
   9304   if (E->getDestroyedTypeInfo()) {
   9305     TypeSourceInfo *DestroyedTypeInfo
   9306       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
   9307                                                 ObjectType, nullptr, SS);
   9308     if (!DestroyedTypeInfo)
   9309       return ExprError();
   9310     Destroyed = DestroyedTypeInfo;
   9311   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
   9312     // We aren't likely to be able to resolve the identifier down to a type
   9313     // now anyway, so just retain the identifier.
   9314     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
   9315                                             E->getDestroyedTypeLoc());
   9316   } else {
   9317     // Look for a destructor known with the given name.
   9318     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
   9319                                               *E->getDestroyedTypeIdentifier(),
   9320                                                 E->getDestroyedTypeLoc(),
   9321                                                 /*Scope=*/nullptr,
   9322                                                 SS, ObjectTypePtr,
   9323                                                 false);
   9324     if (!T)
   9325       return ExprError();
   9326 
   9327     Destroyed
   9328       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
   9329                                                  E->getDestroyedTypeLoc());
   9330   }
   9331 
   9332   TypeSourceInfo *ScopeTypeInfo = nullptr;
   9333   if (E->getScopeTypeInfo()) {
   9334     CXXScopeSpec EmptySS;
   9335     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
   9336                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
   9337     if (!ScopeTypeInfo)
   9338       return ExprError();
   9339   }
   9340 
   9341   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
   9342                                                      E->getOperatorLoc(),
   9343                                                      E->isArrow(),
   9344                                                      SS,
   9345                                                      ScopeTypeInfo,
   9346                                                      E->getColonColonLoc(),
   9347                                                      E->getTildeLoc(),
   9348                                                      Destroyed);
   9349 }
   9350 
   9351 template<typename Derived>
   9352 ExprResult
   9353 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
   9354                                                   UnresolvedLookupExpr *Old) {
   9355   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
   9356                  Sema::LookupOrdinaryName);
   9357 
   9358   // Transform all the decls.
   9359   for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
   9360          E = Old->decls_end(); I != E; ++I) {
   9361     NamedDecl *InstD = static_cast<NamedDecl*>(
   9362                                  getDerived().TransformDecl(Old->getNameLoc(),
   9363                                                             *I));
   9364     if (!InstD) {
   9365       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
   9366       // This can happen because of dependent hiding.
   9367       if (isa<UsingShadowDecl>(*I))
   9368         continue;
   9369       else {
   9370         R.clear();
   9371         return ExprError();
   9372       }
   9373     }
   9374 
   9375     // Expand using declarations.
   9376     if (isa<UsingDecl>(InstD)) {
   9377       UsingDecl *UD = cast<UsingDecl>(InstD);
   9378       for (auto *I : UD->shadows())
   9379         R.addDecl(I);
   9380       continue;
   9381     }
   9382 
   9383     R.addDecl(InstD);
   9384   }
   9385 
   9386   // Resolve a kind, but don't do any further analysis.  If it's
   9387   // ambiguous, the callee needs to deal with it.
   9388   R.resolveKind();
   9389 
   9390   // Rebuild the nested-name qualifier, if present.
   9391   CXXScopeSpec SS;
   9392   if (Old->getQualifierLoc()) {
   9393     NestedNameSpecifierLoc QualifierLoc
   9394       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
   9395     if (!QualifierLoc)
   9396       return ExprError();
   9397 
   9398     SS.Adopt(QualifierLoc);
   9399   }
   9400 
   9401   if (Old->getNamingClass()) {
   9402     CXXRecordDecl *NamingClass
   9403       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
   9404                                                             Old->getNameLoc(),
   9405                                                         Old->getNamingClass()));
   9406     if (!NamingClass) {
   9407       R.clear();
   9408       return ExprError();
   9409     }
   9410 
   9411     R.setNamingClass(NamingClass);
   9412   }
   9413 
   9414   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
   9415 
   9416   // If we have neither explicit template arguments, nor the template keyword,
   9417   // it's a normal declaration name or member reference.
   9418   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
   9419     NamedDecl *D = R.getAsSingle<NamedDecl>();
   9420     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
   9421     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
   9422     // give a good diagnostic.
   9423     if (D && D->isCXXInstanceMember()) {
   9424       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
   9425                                                      /*TemplateArgs=*/nullptr,
   9426                                                      /*Scope=*/nullptr);
   9427     }
   9428 
   9429     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
   9430   }
   9431 
   9432   // If we have template arguments, rebuild them, then rebuild the
   9433   // templateid expression.
   9434   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
   9435   if (Old->hasExplicitTemplateArgs() &&
   9436       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
   9437                                               Old->getNumTemplateArgs(),
   9438                                               TransArgs)) {
   9439     R.clear();
   9440     return ExprError();
   9441   }
   9442 
   9443   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
   9444                                             Old->requiresADL(), &TransArgs);
   9445 }
   9446 
   9447 template<typename Derived>
   9448 ExprResult
   9449 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
   9450   bool ArgChanged = false;
   9451   SmallVector<TypeSourceInfo *, 4> Args;
   9452   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
   9453     TypeSourceInfo *From = E->getArg(I);
   9454     TypeLoc FromTL = From->getTypeLoc();
   9455     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
   9456       TypeLocBuilder TLB;
   9457       TLB.reserve(FromTL.getFullDataSize());
   9458       QualType To = getDerived().TransformType(TLB, FromTL);
   9459       if (To.isNull())
   9460         return ExprError();
   9461 
   9462       if (To == From->getType())
   9463         Args.push_back(From);
   9464       else {
   9465         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
   9466         ArgChanged = true;
   9467       }
   9468       continue;
   9469     }
   9470 
   9471     ArgChanged = true;
   9472 
   9473     // We have a pack expansion. Instantiate it.
   9474     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
   9475     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
   9476     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   9477     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
   9478 
   9479     // Determine whether the set of unexpanded parameter packs can and should
   9480     // be expanded.
   9481     bool Expand = true;
   9482     bool RetainExpansion = false;
   9483     Optional<unsigned> OrigNumExpansions =
   9484         ExpansionTL.getTypePtr()->getNumExpansions();
   9485     Optional<unsigned> NumExpansions = OrigNumExpansions;
   9486     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
   9487                                              PatternTL.getSourceRange(),
   9488                                              Unexpanded,
   9489                                              Expand, RetainExpansion,
   9490                                              NumExpansions))
   9491       return ExprError();
   9492 
   9493     if (!Expand) {
   9494       // The transform has determined that we should perform a simple
   9495       // transformation on the pack expansion, producing another pack
   9496       // expansion.
   9497       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   9498 
   9499       TypeLocBuilder TLB;
   9500       TLB.reserve(From->getTypeLoc().getFullDataSize());
   9501 
   9502       QualType To = getDerived().TransformType(TLB, PatternTL);
   9503       if (To.isNull())
   9504         return ExprError();
   9505 
   9506       To = getDerived().RebuildPackExpansionType(To,
   9507                                                  PatternTL.getSourceRange(),
   9508                                                  ExpansionTL.getEllipsisLoc(),
   9509                                                  NumExpansions);
   9510       if (To.isNull())
   9511         return ExprError();
   9512 
   9513       PackExpansionTypeLoc ToExpansionTL
   9514         = TLB.push<PackExpansionTypeLoc>(To);
   9515       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
   9516       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
   9517       continue;
   9518     }
   9519 
   9520     // Expand the pack expansion by substituting for each argument in the
   9521     // pack(s).
   9522     for (unsigned I = 0; I != *NumExpansions; ++I) {
   9523       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
   9524       TypeLocBuilder TLB;
   9525       TLB.reserve(PatternTL.getFullDataSize());
   9526       QualType To = getDerived().TransformType(TLB, PatternTL);
   9527       if (To.isNull())
   9528         return ExprError();
   9529 
   9530       if (To->containsUnexpandedParameterPack()) {
   9531         To = getDerived().RebuildPackExpansionType(To,
   9532                                                    PatternTL.getSourceRange(),
   9533                                                    ExpansionTL.getEllipsisLoc(),
   9534                                                    NumExpansions);
   9535         if (To.isNull())
   9536           return ExprError();
   9537 
   9538         PackExpansionTypeLoc ToExpansionTL
   9539           = TLB.push<PackExpansionTypeLoc>(To);
   9540         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
   9541       }
   9542 
   9543       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
   9544     }
   9545 
   9546     if (!RetainExpansion)
   9547       continue;
   9548 
   9549     // If we're supposed to retain a pack expansion, do so by temporarily
   9550     // forgetting the partially-substituted parameter pack.
   9551     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   9552 
   9553     TypeLocBuilder TLB;
   9554     TLB.reserve(From->getTypeLoc().getFullDataSize());
   9555 
   9556     QualType To = getDerived().TransformType(TLB, PatternTL);
   9557     if (To.isNull())
   9558       return ExprError();
   9559 
   9560     To = getDerived().RebuildPackExpansionType(To,
   9561                                                PatternTL.getSourceRange(),
   9562                                                ExpansionTL.getEllipsisLoc(),
   9563                                                NumExpansions);
   9564     if (To.isNull())
   9565       return ExprError();
   9566 
   9567     PackExpansionTypeLoc ToExpansionTL
   9568       = TLB.push<PackExpansionTypeLoc>(To);
   9569     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
   9570     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
   9571   }
   9572 
   9573   if (!getDerived().AlwaysRebuild() && !ArgChanged)
   9574     return E;
   9575 
   9576   return getDerived().RebuildTypeTrait(E->getTrait(),
   9577                                        E->getLocStart(),
   9578                                        Args,
   9579                                        E->getLocEnd());
   9580 }
   9581 
   9582 template<typename Derived>
   9583 ExprResult
   9584 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
   9585   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
   9586   if (!T)
   9587     return ExprError();
   9588 
   9589   if (!getDerived().AlwaysRebuild() &&
   9590       T == E->getQueriedTypeSourceInfo())
   9591     return E;
   9592 
   9593   ExprResult SubExpr;
   9594   {
   9595     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   9596     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
   9597     if (SubExpr.isInvalid())
   9598       return ExprError();
   9599 
   9600     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
   9601       return E;
   9602   }
   9603 
   9604   return getDerived().RebuildArrayTypeTrait(E->getTrait(),
   9605                                             E->getLocStart(),
   9606                                             T,
   9607                                             SubExpr.get(),
   9608                                             E->getLocEnd());
   9609 }
   9610 
   9611 template<typename Derived>
   9612 ExprResult
   9613 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
   9614   ExprResult SubExpr;
   9615   {
   9616     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   9617     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
   9618     if (SubExpr.isInvalid())
   9619       return ExprError();
   9620 
   9621     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
   9622       return E;
   9623   }
   9624 
   9625   return getDerived().RebuildExpressionTrait(
   9626       E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
   9627 }
   9628 
   9629 template <typename Derived>
   9630 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
   9631     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
   9632     TypeSourceInfo **RecoveryTSI) {
   9633   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
   9634       DRE, AddrTaken, RecoveryTSI);
   9635 
   9636   // Propagate both errors and recovered types, which return ExprEmpty.
   9637   if (!NewDRE.isUsable())
   9638     return NewDRE;
   9639 
   9640   // We got an expr, wrap it up in parens.
   9641   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
   9642     return PE;
   9643   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
   9644                                        PE->getRParen());
   9645 }
   9646 
   9647 template <typename Derived>
   9648 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
   9649     DependentScopeDeclRefExpr *E) {
   9650   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
   9651                                             nullptr);
   9652 }
   9653 
   9654 template<typename Derived>
   9655 ExprResult
   9656 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
   9657                                                DependentScopeDeclRefExpr *E,
   9658                                                bool IsAddressOfOperand,
   9659                                                TypeSourceInfo **RecoveryTSI) {
   9660   assert(E->getQualifierLoc());
   9661   NestedNameSpecifierLoc QualifierLoc
   9662   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   9663   if (!QualifierLoc)
   9664     return ExprError();
   9665   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
   9666 
   9667   // TODO: If this is a conversion-function-id, verify that the
   9668   // destination type name (if present) resolves the same way after
   9669   // instantiation as it did in the local scope.
   9670 
   9671   DeclarationNameInfo NameInfo
   9672     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
   9673   if (!NameInfo.getName())
   9674     return ExprError();
   9675 
   9676   if (!E->hasExplicitTemplateArgs()) {
   9677     if (!getDerived().AlwaysRebuild() &&
   9678         QualifierLoc == E->getQualifierLoc() &&
   9679         // Note: it is sufficient to compare the Name component of NameInfo:
   9680         // if name has not changed, DNLoc has not changed either.
   9681         NameInfo.getName() == E->getDeclName())
   9682       return E;
   9683 
   9684     return getDerived().RebuildDependentScopeDeclRefExpr(
   9685         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
   9686         IsAddressOfOperand, RecoveryTSI);
   9687   }
   9688 
   9689   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
   9690   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   9691                                               E->getNumTemplateArgs(),
   9692                                               TransArgs))
   9693     return ExprError();
   9694 
   9695   return getDerived().RebuildDependentScopeDeclRefExpr(
   9696       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
   9697       RecoveryTSI);
   9698 }
   9699 
   9700 template<typename Derived>
   9701 ExprResult
   9702 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
   9703   // CXXConstructExprs other than for list-initialization and
   9704   // CXXTemporaryObjectExpr are always implicit, so when we have
   9705   // a 1-argument construction we just transform that argument.
   9706   if ((E->getNumArgs() == 1 ||
   9707        (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
   9708       (!getDerived().DropCallArgument(E->getArg(0))) &&
   9709       !E->isListInitialization())
   9710     return getDerived().TransformExpr(E->getArg(0));
   9711 
   9712   TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
   9713 
   9714   QualType T = getDerived().TransformType(E->getType());
   9715   if (T.isNull())
   9716     return ExprError();
   9717 
   9718   CXXConstructorDecl *Constructor
   9719     = cast_or_null<CXXConstructorDecl>(
   9720                                 getDerived().TransformDecl(E->getLocStart(),
   9721                                                          E->getConstructor()));
   9722   if (!Constructor)
   9723     return ExprError();
   9724 
   9725   bool ArgumentChanged = false;
   9726   SmallVector<Expr*, 8> Args;
   9727   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   9728                                   &ArgumentChanged))
   9729     return ExprError();
   9730 
   9731   if (!getDerived().AlwaysRebuild() &&
   9732       T == E->getType() &&
   9733       Constructor == E->getConstructor() &&
   9734       !ArgumentChanged) {
   9735     // Mark the constructor as referenced.
   9736     // FIXME: Instantiation-specific
   9737     SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
   9738     return E;
   9739   }
   9740 
   9741   return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
   9742                                               Constructor, E->isElidable(),
   9743                                               Args,
   9744                                               E->hadMultipleCandidates(),
   9745                                               E->isListInitialization(),
   9746                                               E->isStdInitListInitialization(),
   9747                                               E->requiresZeroInitialization(),
   9748                                               E->getConstructionKind(),
   9749                                               E->getParenOrBraceRange());
   9750 }
   9751 
   9752 /// \brief Transform a C++ temporary-binding expression.
   9753 ///
   9754 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
   9755 /// transform the subexpression and return that.
   9756 template<typename Derived>
   9757 ExprResult
   9758 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
   9759   return getDerived().TransformExpr(E->getSubExpr());
   9760 }
   9761 
   9762 /// \brief Transform a C++ expression that contains cleanups that should
   9763 /// be run after the expression is evaluated.
   9764 ///
   9765 /// Since ExprWithCleanups nodes are implicitly generated, we
   9766 /// just transform the subexpression and return that.
   9767 template<typename Derived>
   9768 ExprResult
   9769 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
   9770   return getDerived().TransformExpr(E->getSubExpr());
   9771 }
   9772 
   9773 template<typename Derived>
   9774 ExprResult
   9775 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
   9776                                                     CXXTemporaryObjectExpr *E) {
   9777   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
   9778   if (!T)
   9779     return ExprError();
   9780 
   9781   CXXConstructorDecl *Constructor
   9782     = cast_or_null<CXXConstructorDecl>(
   9783                                   getDerived().TransformDecl(E->getLocStart(),
   9784                                                          E->getConstructor()));
   9785   if (!Constructor)
   9786     return ExprError();
   9787 
   9788   bool ArgumentChanged = false;
   9789   SmallVector<Expr*, 8> Args;
   9790   Args.reserve(E->getNumArgs());
   9791   if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   9792                      &ArgumentChanged))
   9793     return ExprError();
   9794 
   9795   if (!getDerived().AlwaysRebuild() &&
   9796       T == E->getTypeSourceInfo() &&
   9797       Constructor == E->getConstructor() &&
   9798       !ArgumentChanged) {
   9799     // FIXME: Instantiation-specific
   9800     SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
   9801     return SemaRef.MaybeBindToTemporary(E);
   9802   }
   9803 
   9804   // FIXME: Pass in E->isListInitialization().
   9805   return getDerived().RebuildCXXTemporaryObjectExpr(T,
   9806                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
   9807                                                     Args,
   9808                                                     E->getLocEnd());
   9809 }
   9810 
   9811 template<typename Derived>
   9812 ExprResult
   9813 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
   9814   // Transform any init-capture expressions before entering the scope of the
   9815   // lambda body, because they are not semantically within that scope.
   9816   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
   9817   SmallVector<InitCaptureInfoTy, 8> InitCaptureExprsAndTypes;
   9818   InitCaptureExprsAndTypes.resize(E->explicit_capture_end() -
   9819                                   E->explicit_capture_begin());
   9820   for (LambdaExpr::capture_iterator C = E->capture_begin(),
   9821                                     CEnd = E->capture_end();
   9822        C != CEnd; ++C) {
   9823     if (!E->isInitCapture(C))
   9824       continue;
   9825     EnterExpressionEvaluationContext EEEC(getSema(),
   9826                                           Sema::PotentiallyEvaluated);
   9827     ExprResult NewExprInitResult = getDerived().TransformInitializer(
   9828         C->getCapturedVar()->getInit(),
   9829         C->getCapturedVar()->getInitStyle() == VarDecl::CallInit);
   9830 
   9831     if (NewExprInitResult.isInvalid())
   9832       return ExprError();
   9833     Expr *NewExprInit = NewExprInitResult.get();
   9834 
   9835     VarDecl *OldVD = C->getCapturedVar();
   9836     QualType NewInitCaptureType =
   9837         getSema().buildLambdaInitCaptureInitialization(
   9838             C->getLocation(), OldVD->getType()->isReferenceType(),
   9839             OldVD->getIdentifier(),
   9840             C->getCapturedVar()->getInitStyle() != VarDecl::CInit, NewExprInit);
   9841     NewExprInitResult = NewExprInit;
   9842     InitCaptureExprsAndTypes[C - E->capture_begin()] =
   9843         std::make_pair(NewExprInitResult, NewInitCaptureType);
   9844   }
   9845 
   9846   // Transform the template parameters, and add them to the current
   9847   // instantiation scope. The null case is handled correctly.
   9848   auto TPL = getDerived().TransformTemplateParameterList(
   9849       E->getTemplateParameterList());
   9850 
   9851   // Transform the type of the original lambda's call operator.
   9852   // The transformation MUST be done in the CurrentInstantiationScope since
   9853   // it introduces a mapping of the original to the newly created
   9854   // transformed parameters.
   9855   TypeSourceInfo *NewCallOpTSI = nullptr;
   9856   {
   9857     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
   9858     FunctionProtoTypeLoc OldCallOpFPTL =
   9859         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
   9860 
   9861     TypeLocBuilder NewCallOpTLBuilder;
   9862     SmallVector<QualType, 4> ExceptionStorage;
   9863     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
   9864     QualType NewCallOpType = TransformFunctionProtoType(
   9865         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, 0,
   9866         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
   9867           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
   9868                                               ExceptionStorage, Changed);
   9869         });
   9870     if (NewCallOpType.isNull())
   9871       return ExprError();
   9872     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
   9873                                                         NewCallOpType);
   9874   }
   9875 
   9876   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
   9877   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
   9878   LSI->GLTemplateParameterList = TPL;
   9879 
   9880   // Create the local class that will describe the lambda.
   9881   CXXRecordDecl *Class
   9882     = getSema().createLambdaClosureType(E->getIntroducerRange(),
   9883                                         NewCallOpTSI,
   9884                                         /*KnownDependent=*/false,
   9885                                         E->getCaptureDefault());
   9886   getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
   9887 
   9888   // Build the call operator.
   9889   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
   9890       Class, E->getIntroducerRange(), NewCallOpTSI,
   9891       E->getCallOperator()->getLocEnd(),
   9892       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams());
   9893   LSI->CallOperator = NewCallOperator;
   9894 
   9895   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
   9896   getDerived().transformedLocalDecl(E->getCallOperator(), NewCallOperator);
   9897 
   9898   // Introduce the context of the call operator.
   9899   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
   9900                                  /*NewThisContext*/false);
   9901 
   9902   // Enter the scope of the lambda.
   9903   getSema().buildLambdaScope(LSI, NewCallOperator,
   9904                              E->getIntroducerRange(),
   9905                              E->getCaptureDefault(),
   9906                              E->getCaptureDefaultLoc(),
   9907                              E->hasExplicitParameters(),
   9908                              E->hasExplicitResultType(),
   9909                              E->isMutable());
   9910 
   9911   bool Invalid = false;
   9912 
   9913   // Transform captures.
   9914   bool FinishedExplicitCaptures = false;
   9915   for (LambdaExpr::capture_iterator C = E->capture_begin(),
   9916                                  CEnd = E->capture_end();
   9917        C != CEnd; ++C) {
   9918     // When we hit the first implicit capture, tell Sema that we've finished
   9919     // the list of explicit captures.
   9920     if (!FinishedExplicitCaptures && C->isImplicit()) {
   9921       getSema().finishLambdaExplicitCaptures(LSI);
   9922       FinishedExplicitCaptures = true;
   9923     }
   9924 
   9925     // Capturing 'this' is trivial.
   9926     if (C->capturesThis()) {
   9927       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit());
   9928       continue;
   9929     }
   9930     // Captured expression will be recaptured during captured variables
   9931     // rebuilding.
   9932     if (C->capturesVLAType())
   9933       continue;
   9934 
   9935     // Rebuild init-captures, including the implied field declaration.
   9936     if (E->isInitCapture(C)) {
   9937       InitCaptureInfoTy InitExprTypePair =
   9938           InitCaptureExprsAndTypes[C - E->capture_begin()];
   9939       ExprResult Init = InitExprTypePair.first;
   9940       QualType InitQualType = InitExprTypePair.second;
   9941       if (Init.isInvalid() || InitQualType.isNull()) {
   9942         Invalid = true;
   9943         continue;
   9944       }
   9945       VarDecl *OldVD = C->getCapturedVar();
   9946       VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
   9947           OldVD->getLocation(), InitExprTypePair.second, OldVD->getIdentifier(),
   9948           OldVD->getInitStyle(), Init.get());
   9949       if (!NewVD)
   9950         Invalid = true;
   9951       else {
   9952         getDerived().transformedLocalDecl(OldVD, NewVD);
   9953       }
   9954       getSema().buildInitCaptureField(LSI, NewVD);
   9955       continue;
   9956     }
   9957 
   9958     assert(C->capturesVariable() && "unexpected kind of lambda capture");
   9959 
   9960     // Determine the capture kind for Sema.
   9961     Sema::TryCaptureKind Kind
   9962       = C->isImplicit()? Sema::TryCapture_Implicit
   9963                        : C->getCaptureKind() == LCK_ByCopy
   9964                            ? Sema::TryCapture_ExplicitByVal
   9965                            : Sema::TryCapture_ExplicitByRef;
   9966     SourceLocation EllipsisLoc;
   9967     if (C->isPackExpansion()) {
   9968       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
   9969       bool ShouldExpand = false;
   9970       bool RetainExpansion = false;
   9971       Optional<unsigned> NumExpansions;
   9972       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
   9973                                                C->getLocation(),
   9974                                                Unexpanded,
   9975                                                ShouldExpand, RetainExpansion,
   9976                                                NumExpansions)) {
   9977         Invalid = true;
   9978         continue;
   9979       }
   9980 
   9981       if (ShouldExpand) {
   9982         // The transform has determined that we should perform an expansion;
   9983         // transform and capture each of the arguments.
   9984         // expansion of the pattern. Do so.
   9985         VarDecl *Pack = C->getCapturedVar();
   9986         for (unsigned I = 0; I != *NumExpansions; ++I) {
   9987           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   9988           VarDecl *CapturedVar
   9989             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
   9990                                                                Pack));
   9991           if (!CapturedVar) {
   9992             Invalid = true;
   9993             continue;
   9994           }
   9995 
   9996           // Capture the transformed variable.
   9997           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
   9998         }
   9999 
   10000         // FIXME: Retain a pack expansion if RetainExpansion is true.
   10001 
   10002         continue;
   10003       }
   10004 
   10005       EllipsisLoc = C->getEllipsisLoc();
   10006     }
   10007 
   10008     // Transform the captured variable.
   10009     VarDecl *CapturedVar
   10010       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
   10011                                                          C->getCapturedVar()));
   10012     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
   10013       Invalid = true;
   10014       continue;
   10015     }
   10016 
   10017     // Capture the transformed variable.
   10018     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
   10019                                  EllipsisLoc);
   10020   }
   10021   if (!FinishedExplicitCaptures)
   10022     getSema().finishLambdaExplicitCaptures(LSI);
   10023 
   10024   // Enter a new evaluation context to insulate the lambda from any
   10025   // cleanups from the enclosing full-expression.
   10026   getSema().PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
   10027 
   10028   // Instantiate the body of the lambda expression.
   10029   StmtResult Body =
   10030       Invalid ? StmtError() : getDerived().TransformStmt(E->getBody());
   10031 
   10032   // ActOnLambda* will pop the function scope for us.
   10033   FuncScopeCleanup.disable();
   10034 
   10035   if (Body.isInvalid()) {
   10036     SavedContext.pop();
   10037     getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/nullptr,
   10038                                /*IsInstantiation=*/true);
   10039     return ExprError();
   10040   }
   10041 
   10042   // Copy the LSI before ActOnFinishFunctionBody removes it.
   10043   // FIXME: This is dumb. Store the lambda information somewhere that outlives
   10044   // the call operator.
   10045   auto LSICopy = *LSI;
   10046   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
   10047                                     /*IsInstantiation*/ true);
   10048   SavedContext.pop();
   10049 
   10050   return getSema().BuildLambdaExpr(E->getLocStart(), Body.get()->getLocEnd(),
   10051                                    &LSICopy);
   10052 }
   10053 
   10054 template<typename Derived>
   10055 ExprResult
   10056 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
   10057                                                   CXXUnresolvedConstructExpr *E) {
   10058   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
   10059   if (!T)
   10060     return ExprError();
   10061 
   10062   bool ArgumentChanged = false;
   10063   SmallVector<Expr*, 8> Args;
   10064   Args.reserve(E->arg_size());
   10065   if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
   10066                                   &ArgumentChanged))
   10067     return ExprError();
   10068 
   10069   if (!getDerived().AlwaysRebuild() &&
   10070       T == E->getTypeSourceInfo() &&
   10071       !ArgumentChanged)
   10072     return E;
   10073 
   10074   // FIXME: we're faking the locations of the commas
   10075   return getDerived().RebuildCXXUnresolvedConstructExpr(T,
   10076                                                         E->getLParenLoc(),
   10077                                                         Args,
   10078                                                         E->getRParenLoc());
   10079 }
   10080 
   10081 template<typename Derived>
   10082 ExprResult
   10083 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
   10084                                              CXXDependentScopeMemberExpr *E) {
   10085   // Transform the base of the expression.
   10086   ExprResult Base((Expr*) nullptr);
   10087   Expr *OldBase;
   10088   QualType BaseType;
   10089   QualType ObjectType;
   10090   if (!E->isImplicitAccess()) {
   10091     OldBase = E->getBase();
   10092     Base = getDerived().TransformExpr(OldBase);
   10093     if (Base.isInvalid())
   10094       return ExprError();
   10095 
   10096     // Start the member reference and compute the object's type.
   10097     ParsedType ObjectTy;
   10098     bool MayBePseudoDestructor = false;
   10099     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
   10100                                                 E->getOperatorLoc(),
   10101                                       E->isArrow()? tok::arrow : tok::period,
   10102                                                 ObjectTy,
   10103                                                 MayBePseudoDestructor);
   10104     if (Base.isInvalid())
   10105       return ExprError();
   10106 
   10107     ObjectType = ObjectTy.get();
   10108     BaseType = ((Expr*) Base.get())->getType();
   10109   } else {
   10110     OldBase = nullptr;
   10111     BaseType = getDerived().TransformType(E->getBaseType());
   10112     ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
   10113   }
   10114 
   10115   // Transform the first part of the nested-name-specifier that qualifies
   10116   // the member name.
   10117   NamedDecl *FirstQualifierInScope
   10118     = getDerived().TransformFirstQualifierInScope(
   10119                                             E->getFirstQualifierFoundInScope(),
   10120                                             E->getQualifierLoc().getBeginLoc());
   10121 
   10122   NestedNameSpecifierLoc QualifierLoc;
   10123   if (E->getQualifier()) {
   10124     QualifierLoc
   10125       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
   10126                                                      ObjectType,
   10127                                                      FirstQualifierInScope);
   10128     if (!QualifierLoc)
   10129       return ExprError();
   10130   }
   10131 
   10132   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
   10133 
   10134   // TODO: If this is a conversion-function-id, verify that the
   10135   // destination type name (if present) resolves the same way after
   10136   // instantiation as it did in the local scope.
   10137 
   10138   DeclarationNameInfo NameInfo
   10139     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
   10140   if (!NameInfo.getName())
   10141     return ExprError();
   10142 
   10143   if (!E->hasExplicitTemplateArgs()) {
   10144     // This is a reference to a member without an explicitly-specified
   10145     // template argument list. Optimize for this common case.
   10146     if (!getDerived().AlwaysRebuild() &&
   10147         Base.get() == OldBase &&
   10148         BaseType == E->getBaseType() &&
   10149         QualifierLoc == E->getQualifierLoc() &&
   10150         NameInfo.getName() == E->getMember() &&
   10151         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
   10152       return E;
   10153 
   10154     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
   10155                                                        BaseType,
   10156                                                        E->isArrow(),
   10157                                                        E->getOperatorLoc(),
   10158                                                        QualifierLoc,
   10159                                                        TemplateKWLoc,
   10160                                                        FirstQualifierInScope,
   10161                                                        NameInfo,
   10162                                                        /*TemplateArgs*/nullptr);
   10163   }
   10164 
   10165   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
   10166   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   10167                                               E->getNumTemplateArgs(),
   10168                                               TransArgs))
   10169     return ExprError();
   10170 
   10171   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
   10172                                                      BaseType,
   10173                                                      E->isArrow(),
   10174                                                      E->getOperatorLoc(),
   10175                                                      QualifierLoc,
   10176                                                      TemplateKWLoc,
   10177                                                      FirstQualifierInScope,
   10178                                                      NameInfo,
   10179                                                      &TransArgs);
   10180 }
   10181 
   10182 template<typename Derived>
   10183 ExprResult
   10184 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
   10185   // Transform the base of the expression.
   10186   ExprResult Base((Expr*) nullptr);
   10187   QualType BaseType;
   10188   if (!Old->isImplicitAccess()) {
   10189     Base = getDerived().TransformExpr(Old->getBase());
   10190     if (Base.isInvalid())
   10191       return ExprError();
   10192     Base = getSema().PerformMemberExprBaseConversion(Base.get(),
   10193                                                      Old->isArrow());
   10194     if (Base.isInvalid())
   10195       return ExprError();
   10196     BaseType = Base.get()->getType();
   10197   } else {
   10198     BaseType = getDerived().TransformType(Old->getBaseType());
   10199   }
   10200 
   10201   NestedNameSpecifierLoc QualifierLoc;
   10202   if (Old->getQualifierLoc()) {
   10203     QualifierLoc
   10204     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
   10205     if (!QualifierLoc)
   10206       return ExprError();
   10207   }
   10208 
   10209   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
   10210 
   10211   LookupResult R(SemaRef, Old->getMemberNameInfo(),
   10212                  Sema::LookupOrdinaryName);
   10213 
   10214   // Transform all the decls.
   10215   for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
   10216          E = Old->decls_end(); I != E; ++I) {
   10217     NamedDecl *InstD = static_cast<NamedDecl*>(
   10218                                 getDerived().TransformDecl(Old->getMemberLoc(),
   10219                                                            *I));
   10220     if (!InstD) {
   10221       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
   10222       // This can happen because of dependent hiding.
   10223       if (isa<UsingShadowDecl>(*I))
   10224         continue;
   10225       else {
   10226         R.clear();
   10227         return ExprError();
   10228       }
   10229     }
   10230 
   10231     // Expand using declarations.
   10232     if (isa<UsingDecl>(InstD)) {
   10233       UsingDecl *UD = cast<UsingDecl>(InstD);
   10234       for (auto *I : UD->shadows())
   10235         R.addDecl(I);
   10236       continue;
   10237     }
   10238 
   10239     R.addDecl(InstD);
   10240   }
   10241 
   10242   R.resolveKind();
   10243 
   10244   // Determine the naming class.
   10245   if (Old->getNamingClass()) {
   10246     CXXRecordDecl *NamingClass
   10247       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
   10248                                                           Old->getMemberLoc(),
   10249                                                         Old->getNamingClass()));
   10250     if (!NamingClass)
   10251       return ExprError();
   10252 
   10253     R.setNamingClass(NamingClass);
   10254   }
   10255 
   10256   TemplateArgumentListInfo TransArgs;
   10257   if (Old->hasExplicitTemplateArgs()) {
   10258     TransArgs.setLAngleLoc(Old->getLAngleLoc());
   10259     TransArgs.setRAngleLoc(Old->getRAngleLoc());
   10260     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
   10261                                                 Old->getNumTemplateArgs(),
   10262                                                 TransArgs))
   10263       return ExprError();
   10264   }
   10265 
   10266   // FIXME: to do this check properly, we will need to preserve the
   10267   // first-qualifier-in-scope here, just in case we had a dependent
   10268   // base (and therefore couldn't do the check) and a
   10269   // nested-name-qualifier (and therefore could do the lookup).
   10270   NamedDecl *FirstQualifierInScope = nullptr;
   10271 
   10272   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
   10273                                                   BaseType,
   10274                                                   Old->getOperatorLoc(),
   10275                                                   Old->isArrow(),
   10276                                                   QualifierLoc,
   10277                                                   TemplateKWLoc,
   10278                                                   FirstQualifierInScope,
   10279                                                   R,
   10280                                               (Old->hasExplicitTemplateArgs()
   10281                                                   ? &TransArgs : nullptr));
   10282 }
   10283 
   10284 template<typename Derived>
   10285 ExprResult
   10286 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
   10287   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   10288   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
   10289   if (SubExpr.isInvalid())
   10290     return ExprError();
   10291 
   10292   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
   10293     return E;
   10294 
   10295   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
   10296 }
   10297 
   10298 template<typename Derived>
   10299 ExprResult
   10300 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
   10301   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
   10302   if (Pattern.isInvalid())
   10303     return ExprError();
   10304 
   10305   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
   10306     return E;
   10307 
   10308   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
   10309                                            E->getNumExpansions());
   10310 }
   10311 
   10312 template<typename Derived>
   10313 ExprResult
   10314 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
   10315   // If E is not value-dependent, then nothing will change when we transform it.
   10316   // Note: This is an instantiation-centric view.
   10317   if (!E->isValueDependent())
   10318     return E;
   10319 
   10320   EnterExpressionEvaluationContext Unevaluated(getSema(), Sema::Unevaluated);
   10321 
   10322   ArrayRef<TemplateArgument> PackArgs;
   10323   TemplateArgument ArgStorage;
   10324 
   10325   // Find the argument list to transform.
   10326   if (E->isPartiallySubstituted()) {
   10327     PackArgs = E->getPartialArguments();
   10328   } else if (E->isValueDependent()) {
   10329     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
   10330     bool ShouldExpand = false;
   10331     bool RetainExpansion = false;
   10332     Optional<unsigned> NumExpansions;
   10333     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
   10334                                              Unexpanded,
   10335                                              ShouldExpand, RetainExpansion,
   10336                                              NumExpansions))
   10337       return ExprError();
   10338 
   10339     // If we need to expand the pack, build a template argument from it and
   10340     // expand that.
   10341     if (ShouldExpand) {
   10342       auto *Pack = E->getPack();
   10343       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
   10344         ArgStorage = getSema().Context.getPackExpansionType(
   10345             getSema().Context.getTypeDeclType(TTPD), None);
   10346       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
   10347         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
   10348       } else {
   10349         auto *VD = cast<ValueDecl>(Pack);
   10350         ExprResult DRE = getSema().BuildDeclRefExpr(VD, VD->getType(),
   10351                                                     VK_RValue, E->getPackLoc());
   10352         if (DRE.isInvalid())
   10353           return ExprError();
   10354         ArgStorage = new (getSema().Context) PackExpansionExpr(
   10355             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
   10356       }
   10357       PackArgs = ArgStorage;
   10358     }
   10359   }
   10360 
   10361   // If we're not expanding the pack, just transform the decl.
   10362   if (!PackArgs.size()) {
   10363     auto *Pack = cast_or_null<NamedDecl>(
   10364         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
   10365     if (!Pack)
   10366       return ExprError();
   10367     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
   10368                                               E->getPackLoc(),
   10369                                               E->getRParenLoc(), None, None);
   10370   }
   10371 
   10372   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
   10373                                                E->getPackLoc());
   10374   {
   10375     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
   10376     typedef TemplateArgumentLocInventIterator<
   10377         Derived, const TemplateArgument*> PackLocIterator;
   10378     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
   10379                                    PackLocIterator(*this, PackArgs.end()),
   10380                                    TransformedPackArgs, /*Uneval*/true))
   10381       return ExprError();
   10382   }
   10383 
   10384   SmallVector<TemplateArgument, 8> Args;
   10385   bool PartialSubstitution = false;
   10386   for (auto &Loc : TransformedPackArgs.arguments()) {
   10387     Args.push_back(Loc.getArgument());
   10388     if (Loc.getArgument().isPackExpansion())
   10389       PartialSubstitution = true;
   10390   }
   10391 
   10392   if (PartialSubstitution)
   10393     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
   10394                                               E->getPackLoc(),
   10395                                               E->getRParenLoc(), None, Args);
   10396 
   10397   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
   10398                                             E->getPackLoc(), E->getRParenLoc(),
   10399                                             Args.size(), None);
   10400 }
   10401 
   10402 template<typename Derived>
   10403 ExprResult
   10404 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
   10405                                           SubstNonTypeTemplateParmPackExpr *E) {
   10406   // Default behavior is to do nothing with this transformation.
   10407   return E;
   10408 }
   10409 
   10410 template<typename Derived>
   10411 ExprResult
   10412 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
   10413                                           SubstNonTypeTemplateParmExpr *E) {
   10414   // Default behavior is to do nothing with this transformation.
   10415   return E;
   10416 }
   10417 
   10418 template<typename Derived>
   10419 ExprResult
   10420 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
   10421   // Default behavior is to do nothing with this transformation.
   10422   return E;
   10423 }
   10424 
   10425 template<typename Derived>
   10426 ExprResult
   10427 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
   10428                                                   MaterializeTemporaryExpr *E) {
   10429   return getDerived().TransformExpr(E->GetTemporaryExpr());
   10430 }
   10431 
   10432 template<typename Derived>
   10433 ExprResult
   10434 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
   10435   Expr *Pattern = E->getPattern();
   10436 
   10437   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   10438   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   10439   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   10440 
   10441   // Determine whether the set of unexpanded parameter packs can and should
   10442   // be expanded.
   10443   bool Expand = true;
   10444   bool RetainExpansion = false;
   10445   Optional<unsigned> NumExpansions;
   10446   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
   10447                                            Pattern->getSourceRange(),
   10448                                            Unexpanded,
   10449                                            Expand, RetainExpansion,
   10450                                            NumExpansions))
   10451     return true;
   10452 
   10453   if (!Expand) {
   10454     // Do not expand any packs here, just transform and rebuild a fold
   10455     // expression.
   10456     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   10457 
   10458     ExprResult LHS =
   10459         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
   10460     if (LHS.isInvalid())
   10461       return true;
   10462 
   10463     ExprResult RHS =
   10464         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
   10465     if (RHS.isInvalid())
   10466       return true;
   10467 
   10468     if (!getDerived().AlwaysRebuild() &&
   10469         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
   10470       return E;
   10471 
   10472     return getDerived().RebuildCXXFoldExpr(
   10473         E->getLocStart(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
   10474         RHS.get(), E->getLocEnd());
   10475   }
   10476 
   10477   // The transform has determined that we should perform an elementwise
   10478   // expansion of the pattern. Do so.
   10479   ExprResult Result = getDerived().TransformExpr(E->getInit());
   10480   if (Result.isInvalid())
   10481     return true;
   10482   bool LeftFold = E->isLeftFold();
   10483 
   10484   // If we're retaining an expansion for a right fold, it is the innermost
   10485   // component and takes the init (if any).
   10486   if (!LeftFold && RetainExpansion) {
   10487     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   10488 
   10489     ExprResult Out = getDerived().TransformExpr(Pattern);
   10490     if (Out.isInvalid())
   10491       return true;
   10492 
   10493     Result = getDerived().RebuildCXXFoldExpr(
   10494         E->getLocStart(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
   10495         Result.get(), E->getLocEnd());
   10496     if (Result.isInvalid())
   10497       return true;
   10498   }
   10499 
   10500   for (unsigned I = 0; I != *NumExpansions; ++I) {
   10501     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
   10502         getSema(), LeftFold ? I : *NumExpansions - I - 1);
   10503     ExprResult Out = getDerived().TransformExpr(Pattern);
   10504     if (Out.isInvalid())
   10505       return true;
   10506 
   10507     if (Out.get()->containsUnexpandedParameterPack()) {
   10508       // We still have a pack; retain a pack expansion for this slice.
   10509       Result = getDerived().RebuildCXXFoldExpr(
   10510           E->getLocStart(),
   10511           LeftFold ? Result.get() : Out.get(),
   10512           E->getOperator(), E->getEllipsisLoc(),
   10513           LeftFold ? Out.get() : Result.get(),
   10514           E->getLocEnd());
   10515     } else if (Result.isUsable()) {
   10516       // We've got down to a single element; build a binary operator.
   10517       Result = getDerived().RebuildBinaryOperator(
   10518           E->getEllipsisLoc(), E->getOperator(),
   10519           LeftFold ? Result.get() : Out.get(),
   10520           LeftFold ? Out.get() : Result.get());
   10521     } else
   10522       Result = Out;
   10523 
   10524     if (Result.isInvalid())
   10525       return true;
   10526   }
   10527 
   10528   // If we're retaining an expansion for a left fold, it is the outermost
   10529   // component and takes the complete expansion so far as its init (if any).
   10530   if (LeftFold && RetainExpansion) {
   10531     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   10532 
   10533     ExprResult Out = getDerived().TransformExpr(Pattern);
   10534     if (Out.isInvalid())
   10535       return true;
   10536 
   10537     Result = getDerived().RebuildCXXFoldExpr(
   10538         E->getLocStart(), Result.get(),
   10539         E->getOperator(), E->getEllipsisLoc(),
   10540         Out.get(), E->getLocEnd());
   10541     if (Result.isInvalid())
   10542       return true;
   10543   }
   10544 
   10545   // If we had no init and an empty pack, and we're not retaining an expansion,
   10546   // then produce a fallback value or error.
   10547   if (Result.isUnset())
   10548     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
   10549                                                 E->getOperator());
   10550 
   10551   return Result;
   10552 }
   10553 
   10554 template<typename Derived>
   10555 ExprResult
   10556 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
   10557     CXXStdInitializerListExpr *E) {
   10558   return getDerived().TransformExpr(E->getSubExpr());
   10559 }
   10560 
   10561 template<typename Derived>
   10562 ExprResult
   10563 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
   10564   return SemaRef.MaybeBindToTemporary(E);
   10565 }
   10566 
   10567 template<typename Derived>
   10568 ExprResult
   10569 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
   10570   return E;
   10571 }
   10572 
   10573 template<typename Derived>
   10574 ExprResult
   10575 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
   10576   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   10577   if (SubExpr.isInvalid())
   10578     return ExprError();
   10579 
   10580   if (!getDerived().AlwaysRebuild() &&
   10581       SubExpr.get() == E->getSubExpr())
   10582     return E;
   10583 
   10584   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
   10585 }
   10586 
   10587 template<typename Derived>
   10588 ExprResult
   10589 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
   10590   // Transform each of the elements.
   10591   SmallVector<Expr *, 8> Elements;
   10592   bool ArgChanged = false;
   10593   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
   10594                                   /*IsCall=*/false, Elements, &ArgChanged))
   10595     return ExprError();
   10596 
   10597   if (!getDerived().AlwaysRebuild() && !ArgChanged)
   10598     return SemaRef.MaybeBindToTemporary(E);
   10599 
   10600   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
   10601                                               Elements.data(),
   10602                                               Elements.size());
   10603 }
   10604 
   10605 template<typename Derived>
   10606 ExprResult
   10607 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
   10608                                                     ObjCDictionaryLiteral *E) {
   10609   // Transform each of the elements.
   10610   SmallVector<ObjCDictionaryElement, 8> Elements;
   10611   bool ArgChanged = false;
   10612   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
   10613     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
   10614 
   10615     if (OrigElement.isPackExpansion()) {
   10616       // This key/value element is a pack expansion.
   10617       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   10618       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
   10619       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
   10620       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   10621 
   10622       // Determine whether the set of unexpanded parameter packs can
   10623       // and should be expanded.
   10624       bool Expand = true;
   10625       bool RetainExpansion = false;
   10626       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
   10627       Optional<unsigned> NumExpansions = OrigNumExpansions;
   10628       SourceRange PatternRange(OrigElement.Key->getLocStart(),
   10629                                OrigElement.Value->getLocEnd());
   10630      if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
   10631                                                PatternRange,
   10632                                                Unexpanded,
   10633                                                Expand, RetainExpansion,
   10634                                                NumExpansions))
   10635         return ExprError();
   10636 
   10637       if (!Expand) {
   10638         // The transform has determined that we should perform a simple
   10639         // transformation on the pack expansion, producing another pack
   10640         // expansion.
   10641         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   10642         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
   10643         if (Key.isInvalid())
   10644           return ExprError();
   10645 
   10646         if (Key.get() != OrigElement.Key)
   10647           ArgChanged = true;
   10648 
   10649         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
   10650         if (Value.isInvalid())
   10651           return ExprError();
   10652 
   10653         if (Value.get() != OrigElement.Value)
   10654           ArgChanged = true;
   10655 
   10656         ObjCDictionaryElement Expansion = {
   10657           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
   10658         };
   10659         Elements.push_back(Expansion);
   10660         continue;
   10661       }
   10662 
   10663       // Record right away that the argument was changed.  This needs
   10664       // to happen even if the array expands to nothing.
   10665       ArgChanged = true;
   10666 
   10667       // The transform has determined that we should perform an elementwise
   10668       // expansion of the pattern. Do so.
   10669       for (unsigned I = 0; I != *NumExpansions; ++I) {
   10670         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   10671         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
   10672         if (Key.isInvalid())
   10673           return ExprError();
   10674 
   10675         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
   10676         if (Value.isInvalid())
   10677           return ExprError();
   10678 
   10679         ObjCDictionaryElement Element = {
   10680           Key.get(), Value.get(), SourceLocation(), NumExpansions
   10681         };
   10682 
   10683         // If any unexpanded parameter packs remain, we still have a
   10684         // pack expansion.
   10685         // FIXME: Can this really happen?
   10686         if (Key.get()->containsUnexpandedParameterPack() ||
   10687             Value.get()->containsUnexpandedParameterPack())
   10688           Element.EllipsisLoc = OrigElement.EllipsisLoc;
   10689 
   10690         Elements.push_back(Element);
   10691       }
   10692 
   10693       // FIXME: Retain a pack expansion if RetainExpansion is true.
   10694 
   10695       // We've finished with this pack expansion.
   10696       continue;
   10697     }
   10698 
   10699     // Transform and check key.
   10700     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
   10701     if (Key.isInvalid())
   10702       return ExprError();
   10703 
   10704     if (Key.get() != OrigElement.Key)
   10705       ArgChanged = true;
   10706 
   10707     // Transform and check value.
   10708     ExprResult Value
   10709       = getDerived().TransformExpr(OrigElement.Value);
   10710     if (Value.isInvalid())
   10711       return ExprError();
   10712 
   10713     if (Value.get() != OrigElement.Value)
   10714       ArgChanged = true;
   10715 
   10716     ObjCDictionaryElement Element = {
   10717       Key.get(), Value.get(), SourceLocation(), None
   10718     };
   10719     Elements.push_back(Element);
   10720   }
   10721 
   10722   if (!getDerived().AlwaysRebuild() && !ArgChanged)
   10723     return SemaRef.MaybeBindToTemporary(E);
   10724 
   10725   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
   10726                                                    Elements.data(),
   10727                                                    Elements.size());
   10728 }
   10729 
   10730 template<typename Derived>
   10731 ExprResult
   10732 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
   10733   TypeSourceInfo *EncodedTypeInfo
   10734     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
   10735   if (!EncodedTypeInfo)
   10736     return ExprError();
   10737 
   10738   if (!getDerived().AlwaysRebuild() &&
   10739       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
   10740     return E;
   10741 
   10742   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
   10743                                             EncodedTypeInfo,
   10744                                             E->getRParenLoc());
   10745 }
   10746 
   10747 template<typename Derived>
   10748 ExprResult TreeTransform<Derived>::
   10749 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
   10750   // This is a kind of implicit conversion, and it needs to get dropped
   10751   // and recomputed for the same general reasons that ImplicitCastExprs
   10752   // do, as well a more specific one: this expression is only valid when
   10753   // it appears *immediately* as an argument expression.
   10754   return getDerived().TransformExpr(E->getSubExpr());
   10755 }
   10756 
   10757 template<typename Derived>
   10758 ExprResult TreeTransform<Derived>::
   10759 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
   10760   TypeSourceInfo *TSInfo
   10761     = getDerived().TransformType(E->getTypeInfoAsWritten());
   10762   if (!TSInfo)
   10763     return ExprError();
   10764 
   10765   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
   10766   if (Result.isInvalid())
   10767     return ExprError();
   10768 
   10769   if (!getDerived().AlwaysRebuild() &&
   10770       TSInfo == E->getTypeInfoAsWritten() &&
   10771       Result.get() == E->getSubExpr())
   10772     return E;
   10773 
   10774   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
   10775                                       E->getBridgeKeywordLoc(), TSInfo,
   10776                                       Result.get());
   10777 }
   10778 
   10779 template<typename Derived>
   10780 ExprResult
   10781 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
   10782   // Transform arguments.
   10783   bool ArgChanged = false;
   10784   SmallVector<Expr*, 8> Args;
   10785   Args.reserve(E->getNumArgs());
   10786   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
   10787                                   &ArgChanged))
   10788     return ExprError();
   10789 
   10790   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
   10791     // Class message: transform the receiver type.
   10792     TypeSourceInfo *ReceiverTypeInfo
   10793       = getDerived().TransformType(E->getClassReceiverTypeInfo());
   10794     if (!ReceiverTypeInfo)
   10795       return ExprError();
   10796 
   10797     // If nothing changed, just retain the existing message send.
   10798     if (!getDerived().AlwaysRebuild() &&
   10799         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
   10800       return SemaRef.MaybeBindToTemporary(E);
   10801 
   10802     // Build a new class message send.
   10803     SmallVector<SourceLocation, 16> SelLocs;
   10804     E->getSelectorLocs(SelLocs);
   10805     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
   10806                                                E->getSelector(),
   10807                                                SelLocs,
   10808                                                E->getMethodDecl(),
   10809                                                E->getLeftLoc(),
   10810                                                Args,
   10811                                                E->getRightLoc());
   10812   }
   10813   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
   10814            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
   10815     // Build a new class message send to 'super'.
   10816     SmallVector<SourceLocation, 16> SelLocs;
   10817     E->getSelectorLocs(SelLocs);
   10818     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
   10819                                                E->getSelector(),
   10820                                                SelLocs,
   10821                                                E->getReceiverType(),
   10822                                                E->getMethodDecl(),
   10823                                                E->getLeftLoc(),
   10824                                                Args,
   10825                                                E->getRightLoc());
   10826   }
   10827 
   10828   // Instance message: transform the receiver
   10829   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
   10830          "Only class and instance messages may be instantiated");
   10831   ExprResult Receiver
   10832     = getDerived().TransformExpr(E->getInstanceReceiver());
   10833   if (Receiver.isInvalid())
   10834     return ExprError();
   10835 
   10836   // If nothing changed, just retain the existing message send.
   10837   if (!getDerived().AlwaysRebuild() &&
   10838       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
   10839     return SemaRef.MaybeBindToTemporary(E);
   10840 
   10841   // Build a new instance message send.
   10842   SmallVector<SourceLocation, 16> SelLocs;
   10843   E->getSelectorLocs(SelLocs);
   10844   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
   10845                                              E->getSelector(),
   10846                                              SelLocs,
   10847                                              E->getMethodDecl(),
   10848                                              E->getLeftLoc(),
   10849                                              Args,
   10850                                              E->getRightLoc());
   10851 }
   10852 
   10853 template<typename Derived>
   10854 ExprResult
   10855 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
   10856   return E;
   10857 }
   10858 
   10859 template<typename Derived>
   10860 ExprResult
   10861 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
   10862   return E;
   10863 }
   10864 
   10865 template<typename Derived>
   10866 ExprResult
   10867 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
   10868   // Transform the base expression.
   10869   ExprResult Base = getDerived().TransformExpr(E->getBase());
   10870   if (Base.isInvalid())
   10871     return ExprError();
   10872 
   10873   // We don't need to transform the ivar; it will never change.
   10874 
   10875   // If nothing changed, just retain the existing expression.
   10876   if (!getDerived().AlwaysRebuild() &&
   10877       Base.get() == E->getBase())
   10878     return E;
   10879 
   10880   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
   10881                                              E->getLocation(),
   10882                                              E->isArrow(), E->isFreeIvar());
   10883 }
   10884 
   10885 template<typename Derived>
   10886 ExprResult
   10887 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
   10888   // 'super' and types never change. Property never changes. Just
   10889   // retain the existing expression.
   10890   if (!E->isObjectReceiver())
   10891     return E;
   10892 
   10893   // Transform the base expression.
   10894   ExprResult Base = getDerived().TransformExpr(E->getBase());
   10895   if (Base.isInvalid())
   10896     return ExprError();
   10897 
   10898   // We don't need to transform the property; it will never change.
   10899 
   10900   // If nothing changed, just retain the existing expression.
   10901   if (!getDerived().AlwaysRebuild() &&
   10902       Base.get() == E->getBase())
   10903     return E;
   10904 
   10905   if (E->isExplicitProperty())
   10906     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
   10907                                                    E->getExplicitProperty(),
   10908                                                    E->getLocation());
   10909 
   10910   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
   10911                                                  SemaRef.Context.PseudoObjectTy,
   10912                                                  E->getImplicitPropertyGetter(),
   10913                                                  E->getImplicitPropertySetter(),
   10914                                                  E->getLocation());
   10915 }
   10916 
   10917 template<typename Derived>
   10918 ExprResult
   10919 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
   10920   // Transform the base expression.
   10921   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
   10922   if (Base.isInvalid())
   10923     return ExprError();
   10924 
   10925   // Transform the key expression.
   10926   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
   10927   if (Key.isInvalid())
   10928     return ExprError();
   10929 
   10930   // If nothing changed, just retain the existing expression.
   10931   if (!getDerived().AlwaysRebuild() &&
   10932       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
   10933     return E;
   10934 
   10935   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
   10936                                                   Base.get(), Key.get(),
   10937                                                   E->getAtIndexMethodDecl(),
   10938                                                   E->setAtIndexMethodDecl());
   10939 }
   10940 
   10941 template<typename Derived>
   10942 ExprResult
   10943 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
   10944   // Transform the base expression.
   10945   ExprResult Base = getDerived().TransformExpr(E->getBase());
   10946   if (Base.isInvalid())
   10947     return ExprError();
   10948 
   10949   // If nothing changed, just retain the existing expression.
   10950   if (!getDerived().AlwaysRebuild() &&
   10951       Base.get() == E->getBase())
   10952     return E;
   10953 
   10954   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
   10955                                          E->getOpLoc(),
   10956                                          E->isArrow());
   10957 }
   10958 
   10959 template<typename Derived>
   10960 ExprResult
   10961 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
   10962   bool ArgumentChanged = false;
   10963   SmallVector<Expr*, 8> SubExprs;
   10964   SubExprs.reserve(E->getNumSubExprs());
   10965   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
   10966                                   SubExprs, &ArgumentChanged))
   10967     return ExprError();
   10968 
   10969   if (!getDerived().AlwaysRebuild() &&
   10970       !ArgumentChanged)
   10971     return E;
   10972 
   10973   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
   10974                                                SubExprs,
   10975                                                E->getRParenLoc());
   10976 }
   10977 
   10978 template<typename Derived>
   10979 ExprResult
   10980 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
   10981   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
   10982   if (SrcExpr.isInvalid())
   10983     return ExprError();
   10984 
   10985   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
   10986   if (!Type)
   10987     return ExprError();
   10988 
   10989   if (!getDerived().AlwaysRebuild() &&
   10990       Type == E->getTypeSourceInfo() &&
   10991       SrcExpr.get() == E->getSrcExpr())
   10992     return E;
   10993 
   10994   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
   10995                                                SrcExpr.get(), Type,
   10996                                                E->getRParenLoc());
   10997 }
   10998 
   10999 template<typename Derived>
   11000 ExprResult
   11001 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
   11002   BlockDecl *oldBlock = E->getBlockDecl();
   11003 
   11004   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
   11005   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
   11006 
   11007   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
   11008   blockScope->TheDecl->setBlockMissingReturnType(
   11009                          oldBlock->blockMissingReturnType());
   11010 
   11011   SmallVector<ParmVarDecl*, 4> params;
   11012   SmallVector<QualType, 4> paramTypes;
   11013 
   11014   // Parameter substitution.
   11015   if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
   11016                                                oldBlock->param_begin(),
   11017                                                oldBlock->param_size(),
   11018                                                nullptr, paramTypes, &params)) {
   11019     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
   11020     return ExprError();
   11021   }
   11022 
   11023   const FunctionProtoType *exprFunctionType = E->getFunctionType();
   11024   QualType exprResultType =
   11025       getDerived().TransformType(exprFunctionType->getReturnType());
   11026 
   11027   QualType functionType =
   11028     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes,
   11029                                           exprFunctionType->getExtProtoInfo());
   11030   blockScope->FunctionType = functionType;
   11031 
   11032   // Set the parameters on the block decl.
   11033   if (!params.empty())
   11034     blockScope->TheDecl->setParams(params);
   11035 
   11036   if (!oldBlock->blockMissingReturnType()) {
   11037     blockScope->HasImplicitReturnType = false;
   11038     blockScope->ReturnType = exprResultType;
   11039   }
   11040 
   11041   // Transform the body
   11042   StmtResult body = getDerived().TransformStmt(E->getBody());
   11043   if (body.isInvalid()) {
   11044     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
   11045     return ExprError();
   11046   }
   11047 
   11048 #ifndef NDEBUG
   11049   // In builds with assertions, make sure that we captured everything we
   11050   // captured before.
   11051   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
   11052     for (const auto &I : oldBlock->captures()) {
   11053       VarDecl *oldCapture = I.getVariable();
   11054 
   11055       // Ignore parameter packs.
   11056       if (isa<ParmVarDecl>(oldCapture) &&
   11057           cast<ParmVarDecl>(oldCapture)->isParameterPack())
   11058         continue;
   11059 
   11060       VarDecl *newCapture =
   11061         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
   11062                                                  oldCapture));
   11063       assert(blockScope->CaptureMap.count(newCapture));
   11064     }
   11065     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
   11066   }
   11067 #endif
   11068 
   11069   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
   11070                                     /*Scope=*/nullptr);
   11071 }
   11072 
   11073 template<typename Derived>
   11074 ExprResult
   11075 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
   11076   llvm_unreachable("Cannot transform asType expressions yet");
   11077 }
   11078 
   11079 template<typename Derived>
   11080 ExprResult
   11081 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
   11082   QualType RetTy = getDerived().TransformType(E->getType());
   11083   bool ArgumentChanged = false;
   11084   SmallVector<Expr*, 8> SubExprs;
   11085   SubExprs.reserve(E->getNumSubExprs());
   11086   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
   11087                                   SubExprs, &ArgumentChanged))
   11088     return ExprError();
   11089 
   11090   if (!getDerived().AlwaysRebuild() &&
   11091       !ArgumentChanged)
   11092     return E;
   11093 
   11094   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
   11095                                         RetTy, E->getOp(), E->getRParenLoc());
   11096 }
   11097 
   11098 //===----------------------------------------------------------------------===//
   11099 // Type reconstruction
   11100 //===----------------------------------------------------------------------===//
   11101 
   11102 template<typename Derived>
   11103 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
   11104                                                     SourceLocation Star) {
   11105   return SemaRef.BuildPointerType(PointeeType, Star,
   11106                                   getDerived().getBaseEntity());
   11107 }
   11108 
   11109 template<typename Derived>
   11110 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
   11111                                                          SourceLocation Star) {
   11112   return SemaRef.BuildBlockPointerType(PointeeType, Star,
   11113                                        getDerived().getBaseEntity());
   11114 }
   11115 
   11116 template<typename Derived>
   11117 QualType
   11118 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
   11119                                              bool WrittenAsLValue,
   11120                                              SourceLocation Sigil) {
   11121   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
   11122                                     Sigil, getDerived().getBaseEntity());
   11123 }
   11124 
   11125 template<typename Derived>
   11126 QualType
   11127 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
   11128                                                  QualType ClassType,
   11129                                                  SourceLocation Sigil) {
   11130   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
   11131                                         getDerived().getBaseEntity());
   11132 }
   11133 
   11134 template<typename Derived>
   11135 QualType TreeTransform<Derived>::RebuildObjCObjectType(
   11136            QualType BaseType,
   11137            SourceLocation Loc,
   11138            SourceLocation TypeArgsLAngleLoc,
   11139            ArrayRef<TypeSourceInfo *> TypeArgs,
   11140            SourceLocation TypeArgsRAngleLoc,
   11141            SourceLocation ProtocolLAngleLoc,
   11142            ArrayRef<ObjCProtocolDecl *> Protocols,
   11143            ArrayRef<SourceLocation> ProtocolLocs,
   11144            SourceLocation ProtocolRAngleLoc) {
   11145   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
   11146                                      TypeArgs, TypeArgsRAngleLoc,
   11147                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
   11148                                      ProtocolRAngleLoc,
   11149                                      /*FailOnError=*/true);
   11150 }
   11151 
   11152 template<typename Derived>
   11153 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
   11154            QualType PointeeType,
   11155            SourceLocation Star) {
   11156   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
   11157 }
   11158 
   11159 template<typename Derived>
   11160 QualType
   11161 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
   11162                                          ArrayType::ArraySizeModifier SizeMod,
   11163                                          const llvm::APInt *Size,
   11164                                          Expr *SizeExpr,
   11165                                          unsigned IndexTypeQuals,
   11166                                          SourceRange BracketsRange) {
   11167   if (SizeExpr || !Size)
   11168     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
   11169                                   IndexTypeQuals, BracketsRange,
   11170                                   getDerived().getBaseEntity());
   11171 
   11172   QualType Types[] = {
   11173     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
   11174     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
   11175     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
   11176   };
   11177   const unsigned NumTypes = llvm::array_lengthof(Types);
   11178   QualType SizeType;
   11179   for (unsigned I = 0; I != NumTypes; ++I)
   11180     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
   11181       SizeType = Types[I];
   11182       break;
   11183     }
   11184 
   11185   // Note that we can return a VariableArrayType here in the case where
   11186   // the element type was a dependent VariableArrayType.
   11187   IntegerLiteral *ArraySize
   11188       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
   11189                                /*FIXME*/BracketsRange.getBegin());
   11190   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
   11191                                 IndexTypeQuals, BracketsRange,
   11192                                 getDerived().getBaseEntity());
   11193 }
   11194 
   11195 template<typename Derived>
   11196 QualType
   11197 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
   11198                                                  ArrayType::ArraySizeModifier SizeMod,
   11199                                                  const llvm::APInt &Size,
   11200                                                  unsigned IndexTypeQuals,
   11201                                                  SourceRange BracketsRange) {
   11202   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
   11203                                         IndexTypeQuals, BracketsRange);
   11204 }
   11205 
   11206 template<typename Derived>
   11207 QualType
   11208 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
   11209                                           ArrayType::ArraySizeModifier SizeMod,
   11210                                                  unsigned IndexTypeQuals,
   11211                                                    SourceRange BracketsRange) {
   11212   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
   11213                                        IndexTypeQuals, BracketsRange);
   11214 }
   11215 
   11216 template<typename Derived>
   11217 QualType
   11218 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
   11219                                           ArrayType::ArraySizeModifier SizeMod,
   11220                                                  Expr *SizeExpr,
   11221                                                  unsigned IndexTypeQuals,
   11222                                                  SourceRange BracketsRange) {
   11223   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
   11224                                        SizeExpr,
   11225                                        IndexTypeQuals, BracketsRange);
   11226 }
   11227 
   11228 template<typename Derived>
   11229 QualType
   11230 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
   11231                                           ArrayType::ArraySizeModifier SizeMod,
   11232                                                        Expr *SizeExpr,
   11233                                                        unsigned IndexTypeQuals,
   11234                                                    SourceRange BracketsRange) {
   11235   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
   11236                                        SizeExpr,
   11237                                        IndexTypeQuals, BracketsRange);
   11238 }
   11239 
   11240 template<typename Derived>
   11241 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
   11242                                                unsigned NumElements,
   11243                                                VectorType::VectorKind VecKind) {
   11244   // FIXME: semantic checking!
   11245   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
   11246 }
   11247 
   11248 template<typename Derived>
   11249 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
   11250                                                       unsigned NumElements,
   11251                                                  SourceLocation AttributeLoc) {
   11252   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
   11253                           NumElements, true);
   11254   IntegerLiteral *VectorSize
   11255     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
   11256                              AttributeLoc);
   11257   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
   11258 }
   11259 
   11260 template<typename Derived>
   11261 QualType
   11262 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
   11263                                                            Expr *SizeExpr,
   11264                                                   SourceLocation AttributeLoc) {
   11265   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
   11266 }
   11267 
   11268 template<typename Derived>
   11269 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
   11270     QualType T,
   11271     MutableArrayRef<QualType> ParamTypes,
   11272     const FunctionProtoType::ExtProtoInfo &EPI) {
   11273   return SemaRef.BuildFunctionType(T, ParamTypes,
   11274                                    getDerived().getBaseLocation(),
   11275                                    getDerived().getBaseEntity(),
   11276                                    EPI);
   11277 }
   11278 
   11279 template<typename Derived>
   11280 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
   11281   return SemaRef.Context.getFunctionNoProtoType(T);
   11282 }
   11283 
   11284 template<typename Derived>
   11285 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
   11286   assert(D && "no decl found");
   11287   if (D->isInvalidDecl()) return QualType();
   11288 
   11289   // FIXME: Doesn't account for ObjCInterfaceDecl!
   11290   TypeDecl *Ty;
   11291   if (isa<UsingDecl>(D)) {
   11292     UsingDecl *Using = cast<UsingDecl>(D);
   11293     assert(Using->hasTypename() &&
   11294            "UnresolvedUsingTypenameDecl transformed to non-typename using");
   11295 
   11296     // A valid resolved using typename decl points to exactly one type decl.
   11297     assert(++Using->shadow_begin() == Using->shadow_end());
   11298     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
   11299 
   11300   } else {
   11301     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
   11302            "UnresolvedUsingTypenameDecl transformed to non-using decl");
   11303     Ty = cast<UnresolvedUsingTypenameDecl>(D);
   11304   }
   11305 
   11306   return SemaRef.Context.getTypeDeclType(Ty);
   11307 }
   11308 
   11309 template<typename Derived>
   11310 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
   11311                                                        SourceLocation Loc) {
   11312   return SemaRef.BuildTypeofExprType(E, Loc);
   11313 }
   11314 
   11315 template<typename Derived>
   11316 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
   11317   return SemaRef.Context.getTypeOfType(Underlying);
   11318 }
   11319 
   11320 template<typename Derived>
   11321 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
   11322                                                      SourceLocation Loc) {
   11323   return SemaRef.BuildDecltypeType(E, Loc);
   11324 }
   11325 
   11326 template<typename Derived>
   11327 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
   11328                                             UnaryTransformType::UTTKind UKind,
   11329                                             SourceLocation Loc) {
   11330   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
   11331 }
   11332 
   11333 template<typename Derived>
   11334 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
   11335                                                       TemplateName Template,
   11336                                              SourceLocation TemplateNameLoc,
   11337                                      TemplateArgumentListInfo &TemplateArgs) {
   11338   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
   11339 }
   11340 
   11341 template<typename Derived>
   11342 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
   11343                                                    SourceLocation KWLoc) {
   11344   return SemaRef.BuildAtomicType(ValueType, KWLoc);
   11345 }
   11346 
   11347 template<typename Derived>
   11348 TemplateName
   11349 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
   11350                                             bool TemplateKW,
   11351                                             TemplateDecl *Template) {
   11352   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
   11353                                                   Template);
   11354 }
   11355 
   11356 template<typename Derived>
   11357 TemplateName
   11358 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
   11359                                             const IdentifierInfo &Name,
   11360                                             SourceLocation NameLoc,
   11361                                             QualType ObjectType,
   11362                                             NamedDecl *FirstQualifierInScope) {
   11363   UnqualifiedId TemplateName;
   11364   TemplateName.setIdentifier(&Name, NameLoc);
   11365   Sema::TemplateTy Template;
   11366   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
   11367   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
   11368                                        SS, TemplateKWLoc, TemplateName,
   11369                                        ParsedType::make(ObjectType),
   11370                                        /*EnteringContext=*/false,
   11371                                        Template);
   11372   return Template.get();
   11373 }
   11374 
   11375 template<typename Derived>
   11376 TemplateName
   11377 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
   11378                                             OverloadedOperatorKind Operator,
   11379                                             SourceLocation NameLoc,
   11380                                             QualType ObjectType) {
   11381   UnqualifiedId Name;
   11382   // FIXME: Bogus location information.
   11383   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
   11384   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
   11385   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
   11386   Sema::TemplateTy Template;
   11387   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
   11388                                        SS, TemplateKWLoc, Name,
   11389                                        ParsedType::make(ObjectType),
   11390                                        /*EnteringContext=*/false,
   11391                                        Template);
   11392   return Template.get();
   11393 }
   11394 
   11395 template<typename Derived>
   11396 ExprResult
   11397 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
   11398                                                    SourceLocation OpLoc,
   11399                                                    Expr *OrigCallee,
   11400                                                    Expr *First,
   11401                                                    Expr *Second) {
   11402   Expr *Callee = OrigCallee->IgnoreParenCasts();
   11403   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
   11404 
   11405   if (First->getObjectKind() == OK_ObjCProperty) {
   11406     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
   11407     if (BinaryOperator::isAssignmentOp(Opc))
   11408       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
   11409                                                  First, Second);
   11410     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
   11411     if (Result.isInvalid())
   11412       return ExprError();
   11413     First = Result.get();
   11414   }
   11415 
   11416   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
   11417     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
   11418     if (Result.isInvalid())
   11419       return ExprError();
   11420     Second = Result.get();
   11421   }
   11422 
   11423   // Determine whether this should be a builtin operation.
   11424   if (Op == OO_Subscript) {
   11425     if (!First->getType()->isOverloadableType() &&
   11426         !Second->getType()->isOverloadableType())
   11427       return getSema().CreateBuiltinArraySubscriptExpr(First,
   11428                                                        Callee->getLocStart(),
   11429                                                        Second, OpLoc);
   11430   } else if (Op == OO_Arrow) {
   11431     // -> is never a builtin operation.
   11432     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
   11433   } else if (Second == nullptr || isPostIncDec) {
   11434     if (!First->getType()->isOverloadableType()) {
   11435       // The argument is not of overloadable type, so try to create a
   11436       // built-in unary operation.
   11437       UnaryOperatorKind Opc
   11438         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
   11439 
   11440       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
   11441     }
   11442   } else {
   11443     if (!First->getType()->isOverloadableType() &&
   11444         !Second->getType()->isOverloadableType()) {
   11445       // Neither of the arguments is an overloadable type, so try to
   11446       // create a built-in binary operation.
   11447       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
   11448       ExprResult Result
   11449         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
   11450       if (Result.isInvalid())
   11451         return ExprError();
   11452 
   11453       return Result;
   11454     }
   11455   }
   11456 
   11457   // Compute the transformed set of functions (and function templates) to be
   11458   // used during overload resolution.
   11459   UnresolvedSet<16> Functions;
   11460 
   11461   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
   11462     assert(ULE->requiresADL());
   11463     Functions.append(ULE->decls_begin(), ULE->decls_end());
   11464   } else {
   11465     // If we've resolved this to a particular non-member function, just call
   11466     // that function. If we resolved it to a member function,
   11467     // CreateOverloaded* will find that function for us.
   11468     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
   11469     if (!isa<CXXMethodDecl>(ND))
   11470       Functions.addDecl(ND);
   11471   }
   11472 
   11473   // Add any functions found via argument-dependent lookup.
   11474   Expr *Args[2] = { First, Second };
   11475   unsigned NumArgs = 1 + (Second != nullptr);
   11476 
   11477   // Create the overloaded operator invocation for unary operators.
   11478   if (NumArgs == 1 || isPostIncDec) {
   11479     UnaryOperatorKind Opc
   11480       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
   11481     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
   11482   }
   11483 
   11484   if (Op == OO_Subscript) {
   11485     SourceLocation LBrace;
   11486     SourceLocation RBrace;
   11487 
   11488     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
   11489         DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
   11490         LBrace = SourceLocation::getFromRawEncoding(
   11491                     NameLoc.CXXOperatorName.BeginOpNameLoc);
   11492         RBrace = SourceLocation::getFromRawEncoding(
   11493                     NameLoc.CXXOperatorName.EndOpNameLoc);
   11494     } else {
   11495         LBrace = Callee->getLocStart();
   11496         RBrace = OpLoc;
   11497     }
   11498 
   11499     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
   11500                                                       First, Second);
   11501   }
   11502 
   11503   // Create the overloaded operator invocation for binary operators.
   11504   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
   11505   ExprResult Result
   11506     = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
   11507   if (Result.isInvalid())
   11508     return ExprError();
   11509 
   11510   return Result;
   11511 }
   11512 
   11513 template<typename Derived>
   11514 ExprResult
   11515 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
   11516                                                      SourceLocation OperatorLoc,
   11517                                                        bool isArrow,
   11518                                                        CXXScopeSpec &SS,
   11519                                                      TypeSourceInfo *ScopeType,
   11520                                                        SourceLocation CCLoc,
   11521                                                        SourceLocation TildeLoc,
   11522                                         PseudoDestructorTypeStorage Destroyed) {
   11523   QualType BaseType = Base->getType();
   11524   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
   11525       (!isArrow && !BaseType->getAs<RecordType>()) ||
   11526       (isArrow && BaseType->getAs<PointerType>() &&
   11527        !BaseType->getAs<PointerType>()->getPointeeType()
   11528                                               ->template getAs<RecordType>())){
   11529     // This pseudo-destructor expression is still a pseudo-destructor.
   11530     return SemaRef.BuildPseudoDestructorExpr(
   11531         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
   11532         CCLoc, TildeLoc, Destroyed);
   11533   }
   11534 
   11535   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
   11536   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
   11537                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
   11538   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
   11539   NameInfo.setNamedTypeInfo(DestroyedType);
   11540 
   11541   // The scope type is now known to be a valid nested name specifier
   11542   // component. Tack it on to the end of the nested name specifier.
   11543   if (ScopeType) {
   11544     if (!ScopeType->getType()->getAs<TagType>()) {
   11545       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
   11546                      diag::err_expected_class_or_namespace)
   11547           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
   11548       return ExprError();
   11549     }
   11550     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
   11551               CCLoc);
   11552   }
   11553 
   11554   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
   11555   return getSema().BuildMemberReferenceExpr(Base, BaseType,
   11556                                             OperatorLoc, isArrow,
   11557                                             SS, TemplateKWLoc,
   11558                                             /*FIXME: FirstQualifier*/ nullptr,
   11559                                             NameInfo,
   11560                                             /*TemplateArgs*/ nullptr,
   11561                                             /*S*/nullptr);
   11562 }
   11563 
   11564 template<typename Derived>
   11565 StmtResult
   11566 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
   11567   SourceLocation Loc = S->getLocStart();
   11568   CapturedDecl *CD = S->getCapturedDecl();
   11569   unsigned NumParams = CD->getNumParams();
   11570   unsigned ContextParamPos = CD->getContextParamPosition();
   11571   SmallVector<Sema::CapturedParamNameType, 4> Params;
   11572   for (unsigned I = 0; I < NumParams; ++I) {
   11573     if (I != ContextParamPos) {
   11574       Params.push_back(
   11575              std::make_pair(
   11576                   CD->getParam(I)->getName(),
   11577                   getDerived().TransformType(CD->getParam(I)->getType())));
   11578     } else {
   11579       Params.push_back(std::make_pair(StringRef(), QualType()));
   11580     }
   11581   }
   11582   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
   11583                                      S->getCapturedRegionKind(), Params);
   11584   StmtResult Body;
   11585   {
   11586     Sema::CompoundScopeRAII CompoundScope(getSema());
   11587     Body = getDerived().TransformStmt(S->getCapturedStmt());
   11588   }
   11589 
   11590   if (Body.isInvalid()) {
   11591     getSema().ActOnCapturedRegionError();
   11592     return StmtError();
   11593   }
   11594 
   11595   return getSema().ActOnCapturedRegionEnd(Body.get());
   11596 }
   11597 
   11598 } // end namespace clang
   11599 
   11600 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
   11601