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_SEMA_TREETRANSFORM_H
     15 #define LLVM_CLANG_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/Stmt.h"
     25 #include "clang/AST/StmtCXX.h"
     26 #include "clang/AST/StmtObjC.h"
     27 #include "clang/AST/StmtOpenMP.h"
     28 #include "clang/Lex/Preprocessor.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   bool AlwaysRebuild() { return false; }
    146 
    147   /// \brief Returns the location of the entity being transformed, if that
    148   /// information was not available elsewhere in the AST.
    149   ///
    150   /// By default, returns no source-location information. Subclasses can
    151   /// provide an alternative implementation that provides better location
    152   /// information.
    153   SourceLocation getBaseLocation() { return SourceLocation(); }
    154 
    155   /// \brief Returns the name of the entity being transformed, if that
    156   /// information was not available elsewhere in the AST.
    157   ///
    158   /// By default, returns an empty name. Subclasses can provide an alternative
    159   /// implementation with a more precise name.
    160   DeclarationName getBaseEntity() { return DeclarationName(); }
    161 
    162   /// \brief Sets the "base" location and entity when that
    163   /// information is known based on another transformation.
    164   ///
    165   /// By default, the source location and entity are ignored. Subclasses can
    166   /// override this function to provide a customized implementation.
    167   void setBase(SourceLocation Loc, DeclarationName Entity) { }
    168 
    169   /// \brief RAII object that temporarily sets the base location and entity
    170   /// used for reporting diagnostics in types.
    171   class TemporaryBase {
    172     TreeTransform &Self;
    173     SourceLocation OldLocation;
    174     DeclarationName OldEntity;
    175 
    176   public:
    177     TemporaryBase(TreeTransform &Self, SourceLocation Location,
    178                   DeclarationName Entity) : Self(Self) {
    179       OldLocation = Self.getDerived().getBaseLocation();
    180       OldEntity = Self.getDerived().getBaseEntity();
    181 
    182       if (Location.isValid())
    183         Self.getDerived().setBase(Location, Entity);
    184     }
    185 
    186     ~TemporaryBase() {
    187       Self.getDerived().setBase(OldLocation, OldEntity);
    188     }
    189   };
    190 
    191   /// \brief Determine whether the given type \p T has already been
    192   /// transformed.
    193   ///
    194   /// Subclasses can provide an alternative implementation of this routine
    195   /// to short-circuit evaluation when it is known that a given type will
    196   /// not change. For example, template instantiation need not traverse
    197   /// non-dependent types.
    198   bool AlreadyTransformed(QualType T) {
    199     return T.isNull();
    200   }
    201 
    202   /// \brief Determine whether the given call argument should be dropped, e.g.,
    203   /// because it is a default argument.
    204   ///
    205   /// Subclasses can provide an alternative implementation of this routine to
    206   /// determine which kinds of call arguments get dropped. By default,
    207   /// CXXDefaultArgument nodes are dropped (prior to transformation).
    208   bool DropCallArgument(Expr *E) {
    209     return E->isDefaultArgument();
    210   }
    211 
    212   /// \brief Determine whether we should expand a pack expansion with the
    213   /// given set of parameter packs into separate arguments by repeatedly
    214   /// transforming the pattern.
    215   ///
    216   /// By default, the transformer never tries to expand pack expansions.
    217   /// Subclasses can override this routine to provide different behavior.
    218   ///
    219   /// \param EllipsisLoc The location of the ellipsis that identifies the
    220   /// pack expansion.
    221   ///
    222   /// \param PatternRange The source range that covers the entire pattern of
    223   /// the pack expansion.
    224   ///
    225   /// \param Unexpanded The set of unexpanded parameter packs within the
    226   /// pattern.
    227   ///
    228   /// \param ShouldExpand Will be set to \c true if the transformer should
    229   /// expand the corresponding pack expansions into separate arguments. When
    230   /// set, \c NumExpansions must also be set.
    231   ///
    232   /// \param RetainExpansion Whether the caller should add an unexpanded
    233   /// pack expansion after all of the expanded arguments. This is used
    234   /// when extending explicitly-specified template argument packs per
    235   /// C++0x [temp.arg.explicit]p9.
    236   ///
    237   /// \param NumExpansions The number of separate arguments that will be in
    238   /// the expanded form of the corresponding pack expansion. This is both an
    239   /// input and an output parameter, which can be set by the caller if the
    240   /// number of expansions is known a priori (e.g., due to a prior substitution)
    241   /// and will be set by the callee when the number of expansions is known.
    242   /// The callee must set this value when \c ShouldExpand is \c true; it may
    243   /// set this value in other cases.
    244   ///
    245   /// \returns true if an error occurred (e.g., because the parameter packs
    246   /// are to be instantiated with arguments of different lengths), false
    247   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
    248   /// must be set.
    249   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
    250                                SourceRange PatternRange,
    251                                ArrayRef<UnexpandedParameterPack> Unexpanded,
    252                                bool &ShouldExpand,
    253                                bool &RetainExpansion,
    254                                Optional<unsigned> &NumExpansions) {
    255     ShouldExpand = false;
    256     return false;
    257   }
    258 
    259   /// \brief "Forget" about the partially-substituted pack template argument,
    260   /// when performing an instantiation that must preserve the parameter pack
    261   /// use.
    262   ///
    263   /// This routine is meant to be overridden by the template instantiator.
    264   TemplateArgument ForgetPartiallySubstitutedPack() {
    265     return TemplateArgument();
    266   }
    267 
    268   /// \brief "Remember" the partially-substituted pack template argument
    269   /// after performing an instantiation that must preserve the parameter pack
    270   /// use.
    271   ///
    272   /// This routine is meant to be overridden by the template instantiator.
    273   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
    274 
    275   /// \brief Note to the derived class when a function parameter pack is
    276   /// being expanded.
    277   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
    278 
    279   /// \brief Transforms the given type into another type.
    280   ///
    281   /// By default, this routine transforms a type by creating a
    282   /// TypeSourceInfo for it and delegating to the appropriate
    283   /// function.  This is expensive, but we don't mind, because
    284   /// this method is deprecated anyway;  all users should be
    285   /// switched to storing TypeSourceInfos.
    286   ///
    287   /// \returns the transformed type.
    288   QualType TransformType(QualType T);
    289 
    290   /// \brief Transforms the given type-with-location into a new
    291   /// type-with-location.
    292   ///
    293   /// By default, this routine transforms a type by delegating to the
    294   /// appropriate TransformXXXType to build a new type.  Subclasses
    295   /// may override this function (to take over all type
    296   /// transformations) or some set of the TransformXXXType functions
    297   /// to alter the transformation.
    298   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
    299 
    300   /// \brief Transform the given type-with-location into a new
    301   /// type, collecting location information in the given builder
    302   /// as necessary.
    303   ///
    304   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
    305 
    306   /// \brief Transform the given statement.
    307   ///
    308   /// By default, this routine transforms a statement by delegating to the
    309   /// appropriate TransformXXXStmt function to transform a specific kind of
    310   /// statement or the TransformExpr() function to transform an expression.
    311   /// Subclasses may override this function to transform statements using some
    312   /// other mechanism.
    313   ///
    314   /// \returns the transformed statement.
    315   StmtResult TransformStmt(Stmt *S);
    316 
    317   /// \brief Transform the given statement.
    318   ///
    319   /// By default, this routine transforms a statement by delegating to the
    320   /// appropriate TransformOMPXXXClause function to transform a specific kind
    321   /// of clause. Subclasses may override this function to transform statements
    322   /// using some other mechanism.
    323   ///
    324   /// \returns the transformed OpenMP clause.
    325   OMPClause *TransformOMPClause(OMPClause *S);
    326 
    327   /// \brief Transform the given expression.
    328   ///
    329   /// By default, this routine transforms an expression by delegating to the
    330   /// appropriate TransformXXXExpr function to build a new expression.
    331   /// Subclasses may override this function to transform expressions using some
    332   /// other mechanism.
    333   ///
    334   /// \returns the transformed expression.
    335   ExprResult TransformExpr(Expr *E);
    336 
    337   /// \brief Transform the given initializer.
    338   ///
    339   /// By default, this routine transforms an initializer by stripping off the
    340   /// semantic nodes added by initialization, then passing the result to
    341   /// TransformExpr or TransformExprs.
    342   ///
    343   /// \returns the transformed initializer.
    344   ExprResult TransformInitializer(Expr *Init, bool CXXDirectInit);
    345 
    346   /// \brief Transform the given list of expressions.
    347   ///
    348   /// This routine transforms a list of expressions by invoking
    349   /// \c TransformExpr() for each subexpression. However, it also provides
    350   /// support for variadic templates by expanding any pack expansions (if the
    351   /// derived class permits such expansion) along the way. When pack expansions
    352   /// are present, the number of outputs may not equal the number of inputs.
    353   ///
    354   /// \param Inputs The set of expressions to be transformed.
    355   ///
    356   /// \param NumInputs The number of expressions in \c Inputs.
    357   ///
    358   /// \param IsCall If \c true, then this transform is being performed on
    359   /// function-call arguments, and any arguments that should be dropped, will
    360   /// be.
    361   ///
    362   /// \param Outputs The transformed input expressions will be added to this
    363   /// vector.
    364   ///
    365   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
    366   /// due to transformation.
    367   ///
    368   /// \returns true if an error occurred, false otherwise.
    369   bool TransformExprs(Expr **Inputs, unsigned NumInputs, bool IsCall,
    370                       SmallVectorImpl<Expr *> &Outputs,
    371                       bool *ArgChanged = 0);
    372 
    373   /// \brief Transform the given declaration, which is referenced from a type
    374   /// or expression.
    375   ///
    376   /// By default, acts as the identity function on declarations, unless the
    377   /// transformer has had to transform the declaration itself. Subclasses
    378   /// may override this function to provide alternate behavior.
    379   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
    380     llvm::DenseMap<Decl *, Decl *>::iterator Known
    381       = TransformedLocalDecls.find(D);
    382     if (Known != TransformedLocalDecls.end())
    383       return Known->second;
    384 
    385     return D;
    386   }
    387 
    388   /// \brief Transform the attributes associated with the given declaration and
    389   /// place them on the new declaration.
    390   ///
    391   /// By default, this operation does nothing. Subclasses may override this
    392   /// behavior to transform attributes.
    393   void transformAttrs(Decl *Old, Decl *New) { }
    394 
    395   /// \brief Note that a local declaration has been transformed by this
    396   /// transformer.
    397   ///
    398   /// Local declarations are typically transformed via a call to
    399   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
    400   /// the transformer itself has to transform the declarations. This routine
    401   /// can be overridden by a subclass that keeps track of such mappings.
    402   void transformedLocalDecl(Decl *Old, Decl *New) {
    403     TransformedLocalDecls[Old] = New;
    404   }
    405 
    406   /// \brief Transform the definition of the given declaration.
    407   ///
    408   /// By default, invokes TransformDecl() to transform the declaration.
    409   /// Subclasses may override this function to provide alternate behavior.
    410   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
    411     return getDerived().TransformDecl(Loc, D);
    412   }
    413 
    414   /// \brief Transform the given declaration, which was the first part of a
    415   /// nested-name-specifier in a member access expression.
    416   ///
    417   /// This specific declaration transformation only applies to the first
    418   /// identifier in a nested-name-specifier of a member access expression, e.g.,
    419   /// the \c T in \c x->T::member
    420   ///
    421   /// By default, invokes TransformDecl() to transform the declaration.
    422   /// Subclasses may override this function to provide alternate behavior.
    423   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
    424     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
    425   }
    426 
    427   /// \brief Transform the given nested-name-specifier with source-location
    428   /// information.
    429   ///
    430   /// By default, transforms all of the types and declarations within the
    431   /// nested-name-specifier. Subclasses may override this function to provide
    432   /// alternate behavior.
    433   NestedNameSpecifierLoc TransformNestedNameSpecifierLoc(
    434                                                     NestedNameSpecifierLoc NNS,
    435                                           QualType ObjectType = QualType(),
    436                                           NamedDecl *FirstQualifierInScope = 0);
    437 
    438   /// \brief Transform the given declaration name.
    439   ///
    440   /// By default, transforms the types of conversion function, constructor,
    441   /// and destructor names and then (if needed) rebuilds the declaration name.
    442   /// Identifiers and selectors are returned unmodified. Sublcasses may
    443   /// override this function to provide alternate behavior.
    444   DeclarationNameInfo
    445   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
    446 
    447   /// \brief Transform the given template name.
    448   ///
    449   /// \param SS The nested-name-specifier that qualifies the template
    450   /// name. This nested-name-specifier must already have been transformed.
    451   ///
    452   /// \param Name The template name to transform.
    453   ///
    454   /// \param NameLoc The source location of the template name.
    455   ///
    456   /// \param ObjectType If we're translating a template name within a member
    457   /// access expression, this is the type of the object whose member template
    458   /// is being referenced.
    459   ///
    460   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
    461   /// also refers to a name within the current (lexical) scope, this is the
    462   /// declaration it refers to.
    463   ///
    464   /// By default, transforms the template name by transforming the declarations
    465   /// and nested-name-specifiers that occur within the template name.
    466   /// Subclasses may override this function to provide alternate behavior.
    467   TemplateName TransformTemplateName(CXXScopeSpec &SS,
    468                                      TemplateName Name,
    469                                      SourceLocation NameLoc,
    470                                      QualType ObjectType = QualType(),
    471                                      NamedDecl *FirstQualifierInScope = 0);
    472 
    473   /// \brief Transform the given template argument.
    474   ///
    475   /// By default, this operation transforms the type, expression, or
    476   /// declaration stored within the template argument and constructs a
    477   /// new template argument from the transformed result. Subclasses may
    478   /// override this function to provide alternate behavior.
    479   ///
    480   /// Returns true if there was an error.
    481   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
    482                                  TemplateArgumentLoc &Output);
    483 
    484   /// \brief Transform the given set of template arguments.
    485   ///
    486   /// By default, this operation transforms all of the template arguments
    487   /// in the input set using \c TransformTemplateArgument(), and appends
    488   /// the transformed arguments to the output list.
    489   ///
    490   /// Note that this overload of \c TransformTemplateArguments() is merely
    491   /// a convenience function. Subclasses that wish to override this behavior
    492   /// should override the iterator-based member template version.
    493   ///
    494   /// \param Inputs The set of template arguments to be transformed.
    495   ///
    496   /// \param NumInputs The number of template arguments in \p Inputs.
    497   ///
    498   /// \param Outputs The set of transformed template arguments output by this
    499   /// routine.
    500   ///
    501   /// Returns true if an error occurred.
    502   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
    503                                   unsigned NumInputs,
    504                                   TemplateArgumentListInfo &Outputs) {
    505     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs);
    506   }
    507 
    508   /// \brief Transform the given set of template arguments.
    509   ///
    510   /// By default, this operation transforms all of the template arguments
    511   /// in the input set using \c TransformTemplateArgument(), and appends
    512   /// the transformed arguments to the output list.
    513   ///
    514   /// \param First An iterator to the first template argument.
    515   ///
    516   /// \param Last An iterator one step past the last template argument.
    517   ///
    518   /// \param Outputs The set of transformed template arguments output by this
    519   /// routine.
    520   ///
    521   /// Returns true if an error occurred.
    522   template<typename InputIterator>
    523   bool TransformTemplateArguments(InputIterator First,
    524                                   InputIterator Last,
    525                                   TemplateArgumentListInfo &Outputs);
    526 
    527   /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
    528   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
    529                                  TemplateArgumentLoc &ArgLoc);
    530 
    531   /// \brief Fakes up a TypeSourceInfo for a type.
    532   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
    533     return SemaRef.Context.getTrivialTypeSourceInfo(T,
    534                        getDerived().getBaseLocation());
    535   }
    536 
    537 #define ABSTRACT_TYPELOC(CLASS, PARENT)
    538 #define TYPELOC(CLASS, PARENT)                                   \
    539   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
    540 #include "clang/AST/TypeLocNodes.def"
    541 
    542   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
    543                                       FunctionProtoTypeLoc TL,
    544                                       CXXRecordDecl *ThisContext,
    545                                       unsigned ThisTypeQuals);
    546 
    547   StmtResult
    548   TransformSEHHandler(Stmt *Handler);
    549 
    550   QualType
    551   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
    552                                       TemplateSpecializationTypeLoc TL,
    553                                       TemplateName Template);
    554 
    555   QualType
    556   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
    557                                       DependentTemplateSpecializationTypeLoc TL,
    558                                                TemplateName Template,
    559                                                CXXScopeSpec &SS);
    560 
    561   QualType
    562   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
    563                                                DependentTemplateSpecializationTypeLoc TL,
    564                                          NestedNameSpecifierLoc QualifierLoc);
    565 
    566   /// \brief Transforms the parameters of a function type into the
    567   /// given vectors.
    568   ///
    569   /// The result vectors should be kept in sync; null entries in the
    570   /// variables vector are acceptable.
    571   ///
    572   /// Return true on error.
    573   bool TransformFunctionTypeParams(SourceLocation Loc,
    574                                    ParmVarDecl **Params, unsigned NumParams,
    575                                    const QualType *ParamTypes,
    576                                    SmallVectorImpl<QualType> &PTypes,
    577                                    SmallVectorImpl<ParmVarDecl*> *PVars);
    578 
    579   /// \brief Transforms a single function-type parameter.  Return null
    580   /// on error.
    581   ///
    582   /// \param indexAdjustment - A number to add to the parameter's
    583   ///   scope index;  can be negative
    584   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
    585                                           int indexAdjustment,
    586                                           Optional<unsigned> NumExpansions,
    587                                           bool ExpectParameterPack);
    588 
    589   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
    590 
    591   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
    592   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
    593 
    594   /// \brief Transform the captures and body of a lambda expression.
    595   ExprResult TransformLambdaScope(LambdaExpr *E, CXXMethodDecl *CallOperator);
    596 
    597   ExprResult TransformAddressOfOperand(Expr *E);
    598   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
    599                                                 bool IsAddressOfOperand);
    600 
    601 #define STMT(Node, Parent)                        \
    602   StmtResult Transform##Node(Node *S);
    603 #define EXPR(Node, Parent)                        \
    604   ExprResult Transform##Node(Node *E);
    605 #define ABSTRACT_STMT(Stmt)
    606 #include "clang/AST/StmtNodes.inc"
    607 
    608 #define OPENMP_CLAUSE(Name, Class)                        \
    609   OMPClause *Transform ## Class(Class *S);
    610 #include "clang/Basic/OpenMPKinds.def"
    611 
    612   /// \brief Build a new pointer type given its pointee type.
    613   ///
    614   /// By default, performs semantic analysis when building the pointer type.
    615   /// Subclasses may override this routine to provide different behavior.
    616   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
    617 
    618   /// \brief Build a new block pointer type given its pointee type.
    619   ///
    620   /// By default, performs semantic analysis when building the block pointer
    621   /// type. Subclasses may override this routine to provide different behavior.
    622   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
    623 
    624   /// \brief Build a new reference type given the type it references.
    625   ///
    626   /// By default, performs semantic analysis when building the
    627   /// reference type. Subclasses may override this routine to provide
    628   /// different behavior.
    629   ///
    630   /// \param LValue whether the type was written with an lvalue sigil
    631   /// or an rvalue sigil.
    632   QualType RebuildReferenceType(QualType ReferentType,
    633                                 bool LValue,
    634                                 SourceLocation Sigil);
    635 
    636   /// \brief Build a new member pointer type given the pointee type and the
    637   /// class type it refers into.
    638   ///
    639   /// By default, performs semantic analysis when building the member pointer
    640   /// type. Subclasses may override this routine to provide different behavior.
    641   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
    642                                     SourceLocation Sigil);
    643 
    644   /// \brief Build a new array type given the element type, size
    645   /// modifier, size of the array (if known), size expression, and index type
    646   /// qualifiers.
    647   ///
    648   /// By default, performs semantic analysis when building the array type.
    649   /// Subclasses may override this routine to provide different behavior.
    650   /// Also by default, all of the other Rebuild*Array
    651   QualType RebuildArrayType(QualType ElementType,
    652                             ArrayType::ArraySizeModifier SizeMod,
    653                             const llvm::APInt *Size,
    654                             Expr *SizeExpr,
    655                             unsigned IndexTypeQuals,
    656                             SourceRange BracketsRange);
    657 
    658   /// \brief Build a new constant array type given the element type, size
    659   /// modifier, (known) size of the array, and index type qualifiers.
    660   ///
    661   /// By default, performs semantic analysis when building the array type.
    662   /// Subclasses may override this routine to provide different behavior.
    663   QualType RebuildConstantArrayType(QualType ElementType,
    664                                     ArrayType::ArraySizeModifier SizeMod,
    665                                     const llvm::APInt &Size,
    666                                     unsigned IndexTypeQuals,
    667                                     SourceRange BracketsRange);
    668 
    669   /// \brief Build a new incomplete array type given the element type, size
    670   /// modifier, and index type qualifiers.
    671   ///
    672   /// By default, performs semantic analysis when building the array type.
    673   /// Subclasses may override this routine to provide different behavior.
    674   QualType RebuildIncompleteArrayType(QualType ElementType,
    675                                       ArrayType::ArraySizeModifier SizeMod,
    676                                       unsigned IndexTypeQuals,
    677                                       SourceRange BracketsRange);
    678 
    679   /// \brief Build a new variable-length array type given the element type,
    680   /// size modifier, size expression, and index type qualifiers.
    681   ///
    682   /// By default, performs semantic analysis when building the array type.
    683   /// Subclasses may override this routine to provide different behavior.
    684   QualType RebuildVariableArrayType(QualType ElementType,
    685                                     ArrayType::ArraySizeModifier SizeMod,
    686                                     Expr *SizeExpr,
    687                                     unsigned IndexTypeQuals,
    688                                     SourceRange BracketsRange);
    689 
    690   /// \brief Build a new dependent-sized array type given the element type,
    691   /// size modifier, size expression, and index type qualifiers.
    692   ///
    693   /// By default, performs semantic analysis when building the array type.
    694   /// Subclasses may override this routine to provide different behavior.
    695   QualType RebuildDependentSizedArrayType(QualType ElementType,
    696                                           ArrayType::ArraySizeModifier SizeMod,
    697                                           Expr *SizeExpr,
    698                                           unsigned IndexTypeQuals,
    699                                           SourceRange BracketsRange);
    700 
    701   /// \brief Build a new vector type given the element type and
    702   /// number of elements.
    703   ///
    704   /// By default, performs semantic analysis when building the vector type.
    705   /// Subclasses may override this routine to provide different behavior.
    706   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
    707                              VectorType::VectorKind VecKind);
    708 
    709   /// \brief Build a new extended vector type given the element type and
    710   /// number of elements.
    711   ///
    712   /// By default, performs semantic analysis when building the vector type.
    713   /// Subclasses may override this routine to provide different behavior.
    714   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
    715                                 SourceLocation AttributeLoc);
    716 
    717   /// \brief Build a new potentially dependently-sized extended vector type
    718   /// given the element type and number of elements.
    719   ///
    720   /// By default, performs semantic analysis when building the vector type.
    721   /// Subclasses may override this routine to provide different behavior.
    722   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
    723                                               Expr *SizeExpr,
    724                                               SourceLocation AttributeLoc);
    725 
    726   /// \brief Build a new function type.
    727   ///
    728   /// By default, performs semantic analysis when building the function type.
    729   /// Subclasses may override this routine to provide different behavior.
    730   QualType RebuildFunctionProtoType(QualType T,
    731                                     llvm::MutableArrayRef<QualType> ParamTypes,
    732                                     const FunctionProtoType::ExtProtoInfo &EPI);
    733 
    734   /// \brief Build a new unprototyped function type.
    735   QualType RebuildFunctionNoProtoType(QualType ResultType);
    736 
    737   /// \brief Rebuild an unresolved typename type, given the decl that
    738   /// the UnresolvedUsingTypenameDecl was transformed to.
    739   QualType RebuildUnresolvedUsingType(Decl *D);
    740 
    741   /// \brief Build a new typedef type.
    742   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
    743     return SemaRef.Context.getTypeDeclType(Typedef);
    744   }
    745 
    746   /// \brief Build a new class/struct/union type.
    747   QualType RebuildRecordType(RecordDecl *Record) {
    748     return SemaRef.Context.getTypeDeclType(Record);
    749   }
    750 
    751   /// \brief Build a new Enum type.
    752   QualType RebuildEnumType(EnumDecl *Enum) {
    753     return SemaRef.Context.getTypeDeclType(Enum);
    754   }
    755 
    756   /// \brief Build a new typeof(expr) type.
    757   ///
    758   /// By default, performs semantic analysis when building the typeof type.
    759   /// Subclasses may override this routine to provide different behavior.
    760   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
    761 
    762   /// \brief Build a new typeof(type) type.
    763   ///
    764   /// By default, builds a new TypeOfType with the given underlying type.
    765   QualType RebuildTypeOfType(QualType Underlying);
    766 
    767   /// \brief Build a new unary transform type.
    768   QualType RebuildUnaryTransformType(QualType BaseType,
    769                                      UnaryTransformType::UTTKind UKind,
    770                                      SourceLocation Loc);
    771 
    772   /// \brief Build a new C++11 decltype type.
    773   ///
    774   /// By default, performs semantic analysis when building the decltype type.
    775   /// Subclasses may override this routine to provide different behavior.
    776   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
    777 
    778   /// \brief Build a new C++11 auto type.
    779   ///
    780   /// By default, builds a new AutoType with the given deduced type.
    781   QualType RebuildAutoType(QualType Deduced, bool IsDecltypeAuto) {
    782     // Note, IsDependent is always false here: we implicitly convert an 'auto'
    783     // which has been deduced to a dependent type into an undeduced 'auto', so
    784     // that we'll retry deduction after the transformation.
    785     return SemaRef.Context.getAutoType(Deduced, IsDecltypeAuto);
    786   }
    787 
    788   /// \brief Build a new template specialization type.
    789   ///
    790   /// By default, performs semantic analysis when building the template
    791   /// specialization type. Subclasses may override this routine to provide
    792   /// different behavior.
    793   QualType RebuildTemplateSpecializationType(TemplateName Template,
    794                                              SourceLocation TemplateLoc,
    795                                              TemplateArgumentListInfo &Args);
    796 
    797   /// \brief Build a new parenthesized type.
    798   ///
    799   /// By default, builds a new ParenType type from the inner type.
    800   /// Subclasses may override this routine to provide different behavior.
    801   QualType RebuildParenType(QualType InnerType) {
    802     return SemaRef.Context.getParenType(InnerType);
    803   }
    804 
    805   /// \brief Build a new qualified name type.
    806   ///
    807   /// By default, builds a new ElaboratedType type from the keyword,
    808   /// the nested-name-specifier and the named type.
    809   /// Subclasses may override this routine to provide different behavior.
    810   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
    811                                  ElaboratedTypeKeyword Keyword,
    812                                  NestedNameSpecifierLoc QualifierLoc,
    813                                  QualType Named) {
    814     return SemaRef.Context.getElaboratedType(Keyword,
    815                                          QualifierLoc.getNestedNameSpecifier(),
    816                                              Named);
    817   }
    818 
    819   /// \brief Build a new typename type that refers to a template-id.
    820   ///
    821   /// By default, builds a new DependentNameType type from the
    822   /// nested-name-specifier and the given type. Subclasses may override
    823   /// this routine to provide different behavior.
    824   QualType RebuildDependentTemplateSpecializationType(
    825                                           ElaboratedTypeKeyword Keyword,
    826                                           NestedNameSpecifierLoc QualifierLoc,
    827                                           const IdentifierInfo *Name,
    828                                           SourceLocation NameLoc,
    829                                           TemplateArgumentListInfo &Args) {
    830     // Rebuild the template name.
    831     // TODO: avoid TemplateName abstraction
    832     CXXScopeSpec SS;
    833     SS.Adopt(QualifierLoc);
    834     TemplateName InstName
    835       = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(), 0);
    836 
    837     if (InstName.isNull())
    838       return QualType();
    839 
    840     // If it's still dependent, make a dependent specialization.
    841     if (InstName.getAsDependentTemplateName())
    842       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
    843                                           QualifierLoc.getNestedNameSpecifier(),
    844                                                                     Name,
    845                                                                     Args);
    846 
    847     // Otherwise, make an elaborated type wrapping a non-dependent
    848     // specialization.
    849     QualType T =
    850     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
    851     if (T.isNull()) return QualType();
    852 
    853     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == 0)
    854       return T;
    855 
    856     return SemaRef.Context.getElaboratedType(Keyword,
    857                                        QualifierLoc.getNestedNameSpecifier(),
    858                                              T);
    859   }
    860 
    861   /// \brief Build a new typename type that refers to an identifier.
    862   ///
    863   /// By default, performs semantic analysis when building the typename type
    864   /// (or elaborated type). Subclasses may override this routine to provide
    865   /// different behavior.
    866   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
    867                                     SourceLocation KeywordLoc,
    868                                     NestedNameSpecifierLoc QualifierLoc,
    869                                     const IdentifierInfo *Id,
    870                                     SourceLocation IdLoc) {
    871     CXXScopeSpec SS;
    872     SS.Adopt(QualifierLoc);
    873 
    874     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
    875       // If the name is still dependent, just build a new dependent name type.
    876       if (!SemaRef.computeDeclContext(SS))
    877         return SemaRef.Context.getDependentNameType(Keyword,
    878                                           QualifierLoc.getNestedNameSpecifier(),
    879                                                     Id);
    880     }
    881 
    882     if (Keyword == ETK_None || Keyword == ETK_Typename)
    883       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
    884                                        *Id, IdLoc);
    885 
    886     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
    887 
    888     // We had a dependent elaborated-type-specifier that has been transformed
    889     // into a non-dependent elaborated-type-specifier. Find the tag we're
    890     // referring to.
    891     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
    892     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
    893     if (!DC)
    894       return QualType();
    895 
    896     if (SemaRef.RequireCompleteDeclContext(SS, DC))
    897       return QualType();
    898 
    899     TagDecl *Tag = 0;
    900     SemaRef.LookupQualifiedName(Result, DC);
    901     switch (Result.getResultKind()) {
    902       case LookupResult::NotFound:
    903       case LookupResult::NotFoundInCurrentInstantiation:
    904         break;
    905 
    906       case LookupResult::Found:
    907         Tag = Result.getAsSingle<TagDecl>();
    908         break;
    909 
    910       case LookupResult::FoundOverloaded:
    911       case LookupResult::FoundUnresolvedValue:
    912         llvm_unreachable("Tag lookup cannot find non-tags");
    913 
    914       case LookupResult::Ambiguous:
    915         // Let the LookupResult structure handle ambiguities.
    916         return QualType();
    917     }
    918 
    919     if (!Tag) {
    920       // Check where the name exists but isn't a tag type and use that to emit
    921       // better diagnostics.
    922       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
    923       SemaRef.LookupQualifiedName(Result, DC);
    924       switch (Result.getResultKind()) {
    925         case LookupResult::Found:
    926         case LookupResult::FoundOverloaded:
    927         case LookupResult::FoundUnresolvedValue: {
    928           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
    929           unsigned Kind = 0;
    930           if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
    931           else if (isa<TypeAliasDecl>(SomeDecl)) Kind = 2;
    932           else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 3;
    933           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
    934           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
    935           break;
    936         }
    937         default:
    938           // FIXME: Would be nice to highlight just the source range.
    939           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
    940             << Kind << Id << DC;
    941           break;
    942       }
    943       return QualType();
    944     }
    945 
    946     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
    947                                               IdLoc, *Id)) {
    948       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
    949       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
    950       return QualType();
    951     }
    952 
    953     // Build the elaborated-type-specifier type.
    954     QualType T = SemaRef.Context.getTypeDeclType(Tag);
    955     return SemaRef.Context.getElaboratedType(Keyword,
    956                                          QualifierLoc.getNestedNameSpecifier(),
    957                                              T);
    958   }
    959 
    960   /// \brief Build a new pack expansion type.
    961   ///
    962   /// By default, builds a new PackExpansionType type from the given pattern.
    963   /// Subclasses may override this routine to provide different behavior.
    964   QualType RebuildPackExpansionType(QualType Pattern,
    965                                     SourceRange PatternRange,
    966                                     SourceLocation EllipsisLoc,
    967                                     Optional<unsigned> NumExpansions) {
    968     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
    969                                         NumExpansions);
    970   }
    971 
    972   /// \brief Build a new atomic type given its value type.
    973   ///
    974   /// By default, performs semantic analysis when building the atomic type.
    975   /// Subclasses may override this routine to provide different behavior.
    976   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
    977 
    978   /// \brief Build a new template name given a nested name specifier, a flag
    979   /// indicating whether the "template" keyword was provided, and the template
    980   /// that the template name refers to.
    981   ///
    982   /// By default, builds the new template name directly. Subclasses may override
    983   /// this routine to provide different behavior.
    984   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
    985                                    bool TemplateKW,
    986                                    TemplateDecl *Template);
    987 
    988   /// \brief Build a new template name given a nested name specifier and the
    989   /// name that is referred to as a template.
    990   ///
    991   /// By default, performs semantic analysis to determine whether the name can
    992   /// be resolved to a specific template, then builds the appropriate kind of
    993   /// template name. Subclasses may override this routine to provide different
    994   /// behavior.
    995   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
    996                                    const IdentifierInfo &Name,
    997                                    SourceLocation NameLoc,
    998                                    QualType ObjectType,
    999                                    NamedDecl *FirstQualifierInScope);
   1000 
   1001   /// \brief Build a new template name given a nested name specifier and the
   1002   /// overloaded operator name that is referred to as a template.
   1003   ///
   1004   /// By default, performs semantic analysis to determine whether the name can
   1005   /// be resolved to a specific template, then builds the appropriate kind of
   1006   /// template name. Subclasses may override this routine to provide different
   1007   /// behavior.
   1008   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
   1009                                    OverloadedOperatorKind Operator,
   1010                                    SourceLocation NameLoc,
   1011                                    QualType ObjectType);
   1012 
   1013   /// \brief Build a new template name given a template template parameter pack
   1014   /// and the
   1015   ///
   1016   /// By default, performs semantic analysis to determine whether the name can
   1017   /// be resolved to a specific template, then builds the appropriate kind of
   1018   /// template name. Subclasses may override this routine to provide different
   1019   /// behavior.
   1020   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
   1021                                    const TemplateArgument &ArgPack) {
   1022     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
   1023   }
   1024 
   1025   /// \brief Build a new compound statement.
   1026   ///
   1027   /// By default, performs semantic analysis to build the new statement.
   1028   /// Subclasses may override this routine to provide different behavior.
   1029   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
   1030                                        MultiStmtArg Statements,
   1031                                        SourceLocation RBraceLoc,
   1032                                        bool IsStmtExpr) {
   1033     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
   1034                                        IsStmtExpr);
   1035   }
   1036 
   1037   /// \brief Build a new case statement.
   1038   ///
   1039   /// By default, performs semantic analysis to build the new statement.
   1040   /// Subclasses may override this routine to provide different behavior.
   1041   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
   1042                                    Expr *LHS,
   1043                                    SourceLocation EllipsisLoc,
   1044                                    Expr *RHS,
   1045                                    SourceLocation ColonLoc) {
   1046     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
   1047                                    ColonLoc);
   1048   }
   1049 
   1050   /// \brief Attach the body to a new case statement.
   1051   ///
   1052   /// By default, performs semantic analysis to build the new statement.
   1053   /// Subclasses may override this routine to provide different behavior.
   1054   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
   1055     getSema().ActOnCaseStmtBody(S, Body);
   1056     return S;
   1057   }
   1058 
   1059   /// \brief Build a new default statement.
   1060   ///
   1061   /// By default, performs semantic analysis to build the new statement.
   1062   /// Subclasses may override this routine to provide different behavior.
   1063   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
   1064                                       SourceLocation ColonLoc,
   1065                                       Stmt *SubStmt) {
   1066     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
   1067                                       /*CurScope=*/0);
   1068   }
   1069 
   1070   /// \brief Build a new label statement.
   1071   ///
   1072   /// By default, performs semantic analysis to build the new statement.
   1073   /// Subclasses may override this routine to provide different behavior.
   1074   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
   1075                               SourceLocation ColonLoc, Stmt *SubStmt) {
   1076     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
   1077   }
   1078 
   1079   /// \brief Build a new label statement.
   1080   ///
   1081   /// By default, performs semantic analysis to build the new statement.
   1082   /// Subclasses may override this routine to provide different behavior.
   1083   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
   1084                                    ArrayRef<const Attr*> Attrs,
   1085                                    Stmt *SubStmt) {
   1086     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
   1087   }
   1088 
   1089   /// \brief Build a new "if" statement.
   1090   ///
   1091   /// By default, performs semantic analysis to build the new statement.
   1092   /// Subclasses may override this routine to provide different behavior.
   1093   StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
   1094                            VarDecl *CondVar, Stmt *Then,
   1095                            SourceLocation ElseLoc, Stmt *Else) {
   1096     return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
   1097   }
   1098 
   1099   /// \brief Start building a new switch statement.
   1100   ///
   1101   /// By default, performs semantic analysis to build the new statement.
   1102   /// Subclasses may override this routine to provide different behavior.
   1103   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
   1104                                     Expr *Cond, VarDecl *CondVar) {
   1105     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
   1106                                             CondVar);
   1107   }
   1108 
   1109   /// \brief Attach the body to the switch statement.
   1110   ///
   1111   /// By default, performs semantic analysis to build the new statement.
   1112   /// Subclasses may override this routine to provide different behavior.
   1113   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
   1114                                    Stmt *Switch, Stmt *Body) {
   1115     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
   1116   }
   1117 
   1118   /// \brief Build a new while statement.
   1119   ///
   1120   /// By default, performs semantic analysis to build the new statement.
   1121   /// Subclasses may override this routine to provide different behavior.
   1122   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, Sema::FullExprArg Cond,
   1123                               VarDecl *CondVar, Stmt *Body) {
   1124     return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
   1125   }
   1126 
   1127   /// \brief Build a new do-while statement.
   1128   ///
   1129   /// By default, performs semantic analysis to build the new statement.
   1130   /// Subclasses may override this routine to provide different behavior.
   1131   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
   1132                            SourceLocation WhileLoc, SourceLocation LParenLoc,
   1133                            Expr *Cond, SourceLocation RParenLoc) {
   1134     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
   1135                                  Cond, RParenLoc);
   1136   }
   1137 
   1138   /// \brief Build a new for statement.
   1139   ///
   1140   /// By default, performs semantic analysis to build the new statement.
   1141   /// Subclasses may override this routine to provide different behavior.
   1142   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
   1143                             Stmt *Init, Sema::FullExprArg Cond,
   1144                             VarDecl *CondVar, Sema::FullExprArg Inc,
   1145                             SourceLocation RParenLoc, Stmt *Body) {
   1146     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
   1147                                   CondVar, Inc, RParenLoc, Body);
   1148   }
   1149 
   1150   /// \brief Build a new goto 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 RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
   1155                              LabelDecl *Label) {
   1156     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
   1157   }
   1158 
   1159   /// \brief Build a new indirect goto statement.
   1160   ///
   1161   /// By default, performs semantic analysis to build the new statement.
   1162   /// Subclasses may override this routine to provide different behavior.
   1163   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
   1164                                      SourceLocation StarLoc,
   1165                                      Expr *Target) {
   1166     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
   1167   }
   1168 
   1169   /// \brief Build a new return statement.
   1170   ///
   1171   /// By default, performs semantic analysis to build the new statement.
   1172   /// Subclasses may override this routine to provide different behavior.
   1173   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
   1174     return getSema().ActOnReturnStmt(ReturnLoc, Result);
   1175   }
   1176 
   1177   /// \brief Build a new declaration statement.
   1178   ///
   1179   /// By default, performs semantic analysis to build the new statement.
   1180   /// Subclasses may override this routine to provide different behavior.
   1181   StmtResult RebuildDeclStmt(llvm::MutableArrayRef<Decl *> Decls,
   1182                              SourceLocation StartLoc, SourceLocation EndLoc) {
   1183     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
   1184     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
   1185   }
   1186 
   1187   /// \brief Build a new inline asm statement.
   1188   ///
   1189   /// By default, performs semantic analysis to build the new statement.
   1190   /// Subclasses may override this routine to provide different behavior.
   1191   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
   1192                                bool IsVolatile, unsigned NumOutputs,
   1193                                unsigned NumInputs, IdentifierInfo **Names,
   1194                                MultiExprArg Constraints, MultiExprArg Exprs,
   1195                                Expr *AsmString, MultiExprArg Clobbers,
   1196                                SourceLocation RParenLoc) {
   1197     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
   1198                                      NumInputs, Names, Constraints, Exprs,
   1199                                      AsmString, Clobbers, RParenLoc);
   1200   }
   1201 
   1202   /// \brief Build a new MS style inline asm statement.
   1203   ///
   1204   /// By default, performs semantic analysis to build the new statement.
   1205   /// Subclasses may override this routine to provide different behavior.
   1206   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
   1207                               ArrayRef<Token> AsmToks,
   1208                               StringRef AsmString,
   1209                               unsigned NumOutputs, unsigned NumInputs,
   1210                               ArrayRef<StringRef> Constraints,
   1211                               ArrayRef<StringRef> Clobbers,
   1212                               ArrayRef<Expr*> Exprs,
   1213                               SourceLocation EndLoc) {
   1214     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
   1215                                     NumOutputs, NumInputs,
   1216                                     Constraints, Clobbers, Exprs, EndLoc);
   1217   }
   1218 
   1219   /// \brief Build a new Objective-C \@try statement.
   1220   ///
   1221   /// By default, performs semantic analysis to build the new statement.
   1222   /// Subclasses may override this routine to provide different behavior.
   1223   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
   1224                                         Stmt *TryBody,
   1225                                         MultiStmtArg CatchStmts,
   1226                                         Stmt *Finally) {
   1227     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
   1228                                         Finally);
   1229   }
   1230 
   1231   /// \brief Rebuild an Objective-C exception declaration.
   1232   ///
   1233   /// By default, performs semantic analysis to build the new declaration.
   1234   /// Subclasses may override this routine to provide different behavior.
   1235   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
   1236                                     TypeSourceInfo *TInfo, QualType T) {
   1237     return getSema().BuildObjCExceptionDecl(TInfo, T,
   1238                                             ExceptionDecl->getInnerLocStart(),
   1239                                             ExceptionDecl->getLocation(),
   1240                                             ExceptionDecl->getIdentifier());
   1241   }
   1242 
   1243   /// \brief Build a new Objective-C \@catch statement.
   1244   ///
   1245   /// By default, performs semantic analysis to build the new statement.
   1246   /// Subclasses may override this routine to provide different behavior.
   1247   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
   1248                                           SourceLocation RParenLoc,
   1249                                           VarDecl *Var,
   1250                                           Stmt *Body) {
   1251     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
   1252                                           Var, Body);
   1253   }
   1254 
   1255   /// \brief Build a new Objective-C \@finally statement.
   1256   ///
   1257   /// By default, performs semantic analysis to build the new statement.
   1258   /// Subclasses may override this routine to provide different behavior.
   1259   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
   1260                                             Stmt *Body) {
   1261     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
   1262   }
   1263 
   1264   /// \brief Build a new Objective-C \@throw statement.
   1265   ///
   1266   /// By default, performs semantic analysis to build the new statement.
   1267   /// Subclasses may override this routine to provide different behavior.
   1268   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
   1269                                           Expr *Operand) {
   1270     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
   1271   }
   1272 
   1273   /// \brief Build a new OpenMP parallel directive.
   1274   ///
   1275   /// By default, performs semantic analysis to build the new statement.
   1276   /// Subclasses may override this routine to provide different behavior.
   1277   StmtResult RebuildOMPParallelDirective(ArrayRef<OMPClause *> Clauses,
   1278                                          Stmt *AStmt,
   1279                                          SourceLocation StartLoc,
   1280                                          SourceLocation EndLoc) {
   1281     return getSema().ActOnOpenMPParallelDirective(Clauses, AStmt,
   1282                                                   StartLoc, EndLoc);
   1283   }
   1284 
   1285   /// \brief Build a new OpenMP 'default' clause.
   1286   ///
   1287   /// By default, performs semantic analysis to build the new statement.
   1288   /// Subclasses may override this routine to provide different behavior.
   1289   OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
   1290                                      SourceLocation KindKwLoc,
   1291                                      SourceLocation StartLoc,
   1292                                      SourceLocation LParenLoc,
   1293                                      SourceLocation EndLoc) {
   1294     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
   1295                                               StartLoc, LParenLoc, EndLoc);
   1296   }
   1297 
   1298   /// \brief Build a new OpenMP 'private' clause.
   1299   ///
   1300   /// By default, performs semantic analysis to build the new statement.
   1301   /// Subclasses may override this routine to provide different behavior.
   1302   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
   1303                                      SourceLocation StartLoc,
   1304                                      SourceLocation LParenLoc,
   1305                                      SourceLocation EndLoc) {
   1306     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
   1307                                               EndLoc);
   1308   }
   1309 
   1310   /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
   1311   ///
   1312   /// By default, performs semantic analysis to build the new statement.
   1313   /// Subclasses may override this routine to provide different behavior.
   1314   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
   1315                                               Expr *object) {
   1316     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
   1317   }
   1318 
   1319   /// \brief Build a new Objective-C \@synchronized statement.
   1320   ///
   1321   /// By default, performs semantic analysis to build the new statement.
   1322   /// Subclasses may override this routine to provide different behavior.
   1323   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
   1324                                            Expr *Object, Stmt *Body) {
   1325     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
   1326   }
   1327 
   1328   /// \brief Build a new Objective-C \@autoreleasepool statement.
   1329   ///
   1330   /// By default, performs semantic analysis to build the new statement.
   1331   /// Subclasses may override this routine to provide different behavior.
   1332   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
   1333                                             Stmt *Body) {
   1334     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
   1335   }
   1336 
   1337   /// \brief Build a new Objective-C fast enumeration statement.
   1338   ///
   1339   /// By default, performs semantic analysis to build the new statement.
   1340   /// Subclasses may override this routine to provide different behavior.
   1341   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
   1342                                           Stmt *Element,
   1343                                           Expr *Collection,
   1344                                           SourceLocation RParenLoc,
   1345                                           Stmt *Body) {
   1346     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
   1347                                                 Element,
   1348                                                 Collection,
   1349                                                 RParenLoc);
   1350     if (ForEachStmt.isInvalid())
   1351       return StmtError();
   1352 
   1353     return getSema().FinishObjCForCollectionStmt(ForEachStmt.take(), Body);
   1354   }
   1355 
   1356   /// \brief Build a new C++ exception declaration.
   1357   ///
   1358   /// By default, performs semantic analysis to build the new decaration.
   1359   /// Subclasses may override this routine to provide different behavior.
   1360   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
   1361                                 TypeSourceInfo *Declarator,
   1362                                 SourceLocation StartLoc,
   1363                                 SourceLocation IdLoc,
   1364                                 IdentifierInfo *Id) {
   1365     VarDecl *Var = getSema().BuildExceptionDeclaration(0, Declarator,
   1366                                                        StartLoc, IdLoc, Id);
   1367     if (Var)
   1368       getSema().CurContext->addDecl(Var);
   1369     return Var;
   1370   }
   1371 
   1372   /// \brief Build a new C++ catch statement.
   1373   ///
   1374   /// By default, performs semantic analysis to build the new statement.
   1375   /// Subclasses may override this routine to provide different behavior.
   1376   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
   1377                                  VarDecl *ExceptionDecl,
   1378                                  Stmt *Handler) {
   1379     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
   1380                                                       Handler));
   1381   }
   1382 
   1383   /// \brief Build a new C++ try statement.
   1384   ///
   1385   /// By default, performs semantic analysis to build the new statement.
   1386   /// Subclasses may override this routine to provide different behavior.
   1387   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc,
   1388                                Stmt *TryBlock,
   1389                                MultiStmtArg Handlers) {
   1390     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
   1391   }
   1392 
   1393   /// \brief Build a new C++0x range-based for statement.
   1394   ///
   1395   /// By default, performs semantic analysis to build the new statement.
   1396   /// Subclasses may override this routine to provide different behavior.
   1397   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
   1398                                     SourceLocation ColonLoc,
   1399                                     Stmt *Range, Stmt *BeginEnd,
   1400                                     Expr *Cond, Expr *Inc,
   1401                                     Stmt *LoopVar,
   1402                                     SourceLocation RParenLoc) {
   1403     // If we've just learned that the range is actually an Objective-C
   1404     // collection, treat this as an Objective-C fast enumeration loop.
   1405     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
   1406       if (RangeStmt->isSingleDecl()) {
   1407         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
   1408           if (RangeVar->isInvalidDecl())
   1409             return StmtError();
   1410 
   1411           Expr *RangeExpr = RangeVar->getInit();
   1412           if (!RangeExpr->isTypeDependent() &&
   1413               RangeExpr->getType()->isObjCObjectPointerType())
   1414             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
   1415                                                         RParenLoc);
   1416         }
   1417       }
   1418     }
   1419 
   1420     return getSema().BuildCXXForRangeStmt(ForLoc, ColonLoc, Range, BeginEnd,
   1421                                           Cond, Inc, LoopVar, RParenLoc,
   1422                                           Sema::BFRK_Rebuild);
   1423   }
   1424 
   1425   /// \brief Build a new C++0x range-based for statement.
   1426   ///
   1427   /// By default, performs semantic analysis to build the new statement.
   1428   /// Subclasses may override this routine to provide different behavior.
   1429   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
   1430                                           bool IsIfExists,
   1431                                           NestedNameSpecifierLoc QualifierLoc,
   1432                                           DeclarationNameInfo NameInfo,
   1433                                           Stmt *Nested) {
   1434     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
   1435                                                 QualifierLoc, NameInfo, Nested);
   1436   }
   1437 
   1438   /// \brief Attach body to a C++0x range-based for statement.
   1439   ///
   1440   /// By default, performs semantic analysis to finish the new statement.
   1441   /// Subclasses may override this routine to provide different behavior.
   1442   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
   1443     return getSema().FinishCXXForRangeStmt(ForRange, Body);
   1444   }
   1445 
   1446   StmtResult RebuildSEHTryStmt(bool IsCXXTry,
   1447                                SourceLocation TryLoc,
   1448                                Stmt *TryBlock,
   1449                                Stmt *Handler) {
   1450     return getSema().ActOnSEHTryBlock(IsCXXTry,TryLoc,TryBlock,Handler);
   1451   }
   1452 
   1453   StmtResult RebuildSEHExceptStmt(SourceLocation Loc,
   1454                                   Expr *FilterExpr,
   1455                                   Stmt *Block) {
   1456     return getSema().ActOnSEHExceptBlock(Loc,FilterExpr,Block);
   1457   }
   1458 
   1459   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc,
   1460                                    Stmt *Block) {
   1461     return getSema().ActOnSEHFinallyBlock(Loc,Block);
   1462   }
   1463 
   1464   /// \brief Build a new expression that references a declaration.
   1465   ///
   1466   /// By default, performs semantic analysis to build the new expression.
   1467   /// Subclasses may override this routine to provide different behavior.
   1468   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
   1469                                         LookupResult &R,
   1470                                         bool RequiresADL) {
   1471     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
   1472   }
   1473 
   1474 
   1475   /// \brief Build a new expression that references a declaration.
   1476   ///
   1477   /// By default, performs semantic analysis to build the new expression.
   1478   /// Subclasses may override this routine to provide different behavior.
   1479   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
   1480                                 ValueDecl *VD,
   1481                                 const DeclarationNameInfo &NameInfo,
   1482                                 TemplateArgumentListInfo *TemplateArgs) {
   1483     CXXScopeSpec SS;
   1484     SS.Adopt(QualifierLoc);
   1485 
   1486     // FIXME: loses template args.
   1487 
   1488     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
   1489   }
   1490 
   1491   /// \brief Build a new expression in parentheses.
   1492   ///
   1493   /// By default, performs semantic analysis to build the new expression.
   1494   /// Subclasses may override this routine to provide different behavior.
   1495   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
   1496                                     SourceLocation RParen) {
   1497     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
   1498   }
   1499 
   1500   /// \brief Build a new pseudo-destructor expression.
   1501   ///
   1502   /// By default, performs semantic analysis to build the new expression.
   1503   /// Subclasses may override this routine to provide different behavior.
   1504   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
   1505                                             SourceLocation OperatorLoc,
   1506                                             bool isArrow,
   1507                                             CXXScopeSpec &SS,
   1508                                             TypeSourceInfo *ScopeType,
   1509                                             SourceLocation CCLoc,
   1510                                             SourceLocation TildeLoc,
   1511                                         PseudoDestructorTypeStorage Destroyed);
   1512 
   1513   /// \brief Build a new unary operator expression.
   1514   ///
   1515   /// By default, performs semantic analysis to build the new expression.
   1516   /// Subclasses may override this routine to provide different behavior.
   1517   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
   1518                                         UnaryOperatorKind Opc,
   1519                                         Expr *SubExpr) {
   1520     return getSema().BuildUnaryOp(/*Scope=*/0, OpLoc, Opc, SubExpr);
   1521   }
   1522 
   1523   /// \brief Build a new builtin offsetof expression.
   1524   ///
   1525   /// By default, performs semantic analysis to build the new expression.
   1526   /// Subclasses may override this routine to provide different behavior.
   1527   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
   1528                                        TypeSourceInfo *Type,
   1529                                        Sema::OffsetOfComponent *Components,
   1530                                        unsigned NumComponents,
   1531                                        SourceLocation RParenLoc) {
   1532     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
   1533                                           NumComponents, RParenLoc);
   1534   }
   1535 
   1536   /// \brief Build a new sizeof, alignof or vec_step expression with a
   1537   /// type argument.
   1538   ///
   1539   /// By default, performs semantic analysis to build the new expression.
   1540   /// Subclasses may override this routine to provide different behavior.
   1541   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
   1542                                          SourceLocation OpLoc,
   1543                                          UnaryExprOrTypeTrait ExprKind,
   1544                                          SourceRange R) {
   1545     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
   1546   }
   1547 
   1548   /// \brief Build a new sizeof, alignof or vec step expression with an
   1549   /// expression argument.
   1550   ///
   1551   /// By default, performs semantic analysis to build the new expression.
   1552   /// Subclasses may override this routine to provide different behavior.
   1553   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
   1554                                          UnaryExprOrTypeTrait ExprKind,
   1555                                          SourceRange R) {
   1556     ExprResult Result
   1557       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
   1558     if (Result.isInvalid())
   1559       return ExprError();
   1560 
   1561     return Result;
   1562   }
   1563 
   1564   /// \brief Build a new array subscript expression.
   1565   ///
   1566   /// By default, performs semantic analysis to build the new expression.
   1567   /// Subclasses may override this routine to provide different behavior.
   1568   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
   1569                                              SourceLocation LBracketLoc,
   1570                                              Expr *RHS,
   1571                                              SourceLocation RBracketLoc) {
   1572     return getSema().ActOnArraySubscriptExpr(/*Scope=*/0, LHS,
   1573                                              LBracketLoc, RHS,
   1574                                              RBracketLoc);
   1575   }
   1576 
   1577   /// \brief Build a new call expression.
   1578   ///
   1579   /// By default, performs semantic analysis to build the new expression.
   1580   /// Subclasses may override this routine to provide different behavior.
   1581   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
   1582                                    MultiExprArg Args,
   1583                                    SourceLocation RParenLoc,
   1584                                    Expr *ExecConfig = 0) {
   1585     return getSema().ActOnCallExpr(/*Scope=*/0, Callee, LParenLoc,
   1586                                    Args, RParenLoc, ExecConfig);
   1587   }
   1588 
   1589   /// \brief Build a new member access expression.
   1590   ///
   1591   /// By default, performs semantic analysis to build the new expression.
   1592   /// Subclasses may override this routine to provide different behavior.
   1593   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
   1594                                bool isArrow,
   1595                                NestedNameSpecifierLoc QualifierLoc,
   1596                                SourceLocation TemplateKWLoc,
   1597                                const DeclarationNameInfo &MemberNameInfo,
   1598                                ValueDecl *Member,
   1599                                NamedDecl *FoundDecl,
   1600                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
   1601                                NamedDecl *FirstQualifierInScope) {
   1602     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
   1603                                                                       isArrow);
   1604     if (!Member->getDeclName()) {
   1605       // We have a reference to an unnamed field.  This is always the
   1606       // base of an anonymous struct/union member access, i.e. the
   1607       // field is always of record type.
   1608       assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
   1609       assert(Member->getType()->isRecordType() &&
   1610              "unnamed member not of record type?");
   1611 
   1612       BaseResult =
   1613         getSema().PerformObjectMemberConversion(BaseResult.take(),
   1614                                                 QualifierLoc.getNestedNameSpecifier(),
   1615                                                 FoundDecl, Member);
   1616       if (BaseResult.isInvalid())
   1617         return ExprError();
   1618       Base = BaseResult.take();
   1619       ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
   1620       MemberExpr *ME =
   1621         new (getSema().Context) MemberExpr(Base, isArrow,
   1622                                            Member, MemberNameInfo,
   1623                                            cast<FieldDecl>(Member)->getType(),
   1624                                            VK, OK_Ordinary);
   1625       return getSema().Owned(ME);
   1626     }
   1627 
   1628     CXXScopeSpec SS;
   1629     SS.Adopt(QualifierLoc);
   1630 
   1631     Base = BaseResult.take();
   1632     QualType BaseType = Base->getType();
   1633 
   1634     // FIXME: this involves duplicating earlier analysis in a lot of
   1635     // cases; we should avoid this when possible.
   1636     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
   1637     R.addDecl(FoundDecl);
   1638     R.resolveKind();
   1639 
   1640     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
   1641                                               SS, TemplateKWLoc,
   1642                                               FirstQualifierInScope,
   1643                                               R, ExplicitTemplateArgs);
   1644   }
   1645 
   1646   /// \brief Build a new binary operator expression.
   1647   ///
   1648   /// By default, performs semantic analysis to build the new expression.
   1649   /// Subclasses may override this routine to provide different behavior.
   1650   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
   1651                                          BinaryOperatorKind Opc,
   1652                                          Expr *LHS, Expr *RHS) {
   1653     return getSema().BuildBinOp(/*Scope=*/0, OpLoc, Opc, LHS, RHS);
   1654   }
   1655 
   1656   /// \brief Build a new conditional operator expression.
   1657   ///
   1658   /// By default, performs semantic analysis to build the new expression.
   1659   /// Subclasses may override this routine to provide different behavior.
   1660   ExprResult RebuildConditionalOperator(Expr *Cond,
   1661                                         SourceLocation QuestionLoc,
   1662                                         Expr *LHS,
   1663                                         SourceLocation ColonLoc,
   1664                                         Expr *RHS) {
   1665     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
   1666                                         LHS, RHS);
   1667   }
   1668 
   1669   /// \brief Build a new C-style cast expression.
   1670   ///
   1671   /// By default, performs semantic analysis to build the new expression.
   1672   /// Subclasses may override this routine to provide different behavior.
   1673   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
   1674                                          TypeSourceInfo *TInfo,
   1675                                          SourceLocation RParenLoc,
   1676                                          Expr *SubExpr) {
   1677     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
   1678                                          SubExpr);
   1679   }
   1680 
   1681   /// \brief Build a new compound literal expression.
   1682   ///
   1683   /// By default, performs semantic analysis to build the new expression.
   1684   /// Subclasses may override this routine to provide different behavior.
   1685   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
   1686                                               TypeSourceInfo *TInfo,
   1687                                               SourceLocation RParenLoc,
   1688                                               Expr *Init) {
   1689     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
   1690                                               Init);
   1691   }
   1692 
   1693   /// \brief Build a new extended vector element access expression.
   1694   ///
   1695   /// By default, performs semantic analysis to build the new expression.
   1696   /// Subclasses may override this routine to provide different behavior.
   1697   ExprResult RebuildExtVectorElementExpr(Expr *Base,
   1698                                                SourceLocation OpLoc,
   1699                                                SourceLocation AccessorLoc,
   1700                                                IdentifierInfo &Accessor) {
   1701 
   1702     CXXScopeSpec SS;
   1703     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
   1704     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
   1705                                               OpLoc, /*IsArrow*/ false,
   1706                                               SS, SourceLocation(),
   1707                                               /*FirstQualifierInScope*/ 0,
   1708                                               NameInfo,
   1709                                               /* TemplateArgs */ 0);
   1710   }
   1711 
   1712   /// \brief Build a new initializer list expression.
   1713   ///
   1714   /// By default, performs semantic analysis to build the new expression.
   1715   /// Subclasses may override this routine to provide different behavior.
   1716   ExprResult RebuildInitList(SourceLocation LBraceLoc,
   1717                              MultiExprArg Inits,
   1718                              SourceLocation RBraceLoc,
   1719                              QualType ResultTy) {
   1720     ExprResult Result
   1721       = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
   1722     if (Result.isInvalid() || ResultTy->isDependentType())
   1723       return Result;
   1724 
   1725     // Patch in the result type we were given, which may have been computed
   1726     // when the initial InitListExpr was built.
   1727     InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
   1728     ILE->setType(ResultTy);
   1729     return Result;
   1730   }
   1731 
   1732   /// \brief Build a new designated initializer expression.
   1733   ///
   1734   /// By default, performs semantic analysis to build the new expression.
   1735   /// Subclasses may override this routine to provide different behavior.
   1736   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
   1737                                              MultiExprArg ArrayExprs,
   1738                                              SourceLocation EqualOrColonLoc,
   1739                                              bool GNUSyntax,
   1740                                              Expr *Init) {
   1741     ExprResult Result
   1742       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
   1743                                            Init);
   1744     if (Result.isInvalid())
   1745       return ExprError();
   1746 
   1747     return Result;
   1748   }
   1749 
   1750   /// \brief Build a new value-initialized expression.
   1751   ///
   1752   /// By default, builds the implicit value initialization without performing
   1753   /// any semantic analysis. Subclasses may override this routine to provide
   1754   /// different behavior.
   1755   ExprResult RebuildImplicitValueInitExpr(QualType T) {
   1756     return SemaRef.Owned(new (SemaRef.Context) ImplicitValueInitExpr(T));
   1757   }
   1758 
   1759   /// \brief Build a new \c va_arg expression.
   1760   ///
   1761   /// By default, performs semantic analysis to build the new expression.
   1762   /// Subclasses may override this routine to provide different behavior.
   1763   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
   1764                                     Expr *SubExpr, TypeSourceInfo *TInfo,
   1765                                     SourceLocation RParenLoc) {
   1766     return getSema().BuildVAArgExpr(BuiltinLoc,
   1767                                     SubExpr, TInfo,
   1768                                     RParenLoc);
   1769   }
   1770 
   1771   /// \brief Build a new expression list in parentheses.
   1772   ///
   1773   /// By default, performs semantic analysis to build the new expression.
   1774   /// Subclasses may override this routine to provide different behavior.
   1775   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
   1776                                   MultiExprArg SubExprs,
   1777                                   SourceLocation RParenLoc) {
   1778     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
   1779   }
   1780 
   1781   /// \brief Build a new address-of-label expression.
   1782   ///
   1783   /// By default, performs semantic analysis, using the name of the label
   1784   /// rather than attempting to map the label statement itself.
   1785   /// Subclasses may override this routine to provide different behavior.
   1786   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
   1787                                   SourceLocation LabelLoc, LabelDecl *Label) {
   1788     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
   1789   }
   1790 
   1791   /// \brief Build a new GNU statement expression.
   1792   ///
   1793   /// By default, performs semantic analysis to build the new expression.
   1794   /// Subclasses may override this routine to provide different behavior.
   1795   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
   1796                                    Stmt *SubStmt,
   1797                                    SourceLocation RParenLoc) {
   1798     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
   1799   }
   1800 
   1801   /// \brief Build a new __builtin_choose_expr expression.
   1802   ///
   1803   /// By default, performs semantic analysis to build the new expression.
   1804   /// Subclasses may override this routine to provide different behavior.
   1805   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
   1806                                      Expr *Cond, Expr *LHS, Expr *RHS,
   1807                                      SourceLocation RParenLoc) {
   1808     return SemaRef.ActOnChooseExpr(BuiltinLoc,
   1809                                    Cond, LHS, RHS,
   1810                                    RParenLoc);
   1811   }
   1812 
   1813   /// \brief Build a new generic selection expression.
   1814   ///
   1815   /// By default, performs semantic analysis to build the new expression.
   1816   /// Subclasses may override this routine to provide different behavior.
   1817   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
   1818                                          SourceLocation DefaultLoc,
   1819                                          SourceLocation RParenLoc,
   1820                                          Expr *ControllingExpr,
   1821                                          ArrayRef<TypeSourceInfo *> Types,
   1822                                          ArrayRef<Expr *> Exprs) {
   1823     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
   1824                                                 ControllingExpr, Types, Exprs);
   1825   }
   1826 
   1827   /// \brief Build a new overloaded operator call expression.
   1828   ///
   1829   /// By default, performs semantic analysis to build the new expression.
   1830   /// The semantic analysis provides the behavior of template instantiation,
   1831   /// copying with transformations that turn what looks like an overloaded
   1832   /// operator call into a use of a builtin operator, performing
   1833   /// argument-dependent lookup, etc. Subclasses may override this routine to
   1834   /// provide different behavior.
   1835   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
   1836                                               SourceLocation OpLoc,
   1837                                               Expr *Callee,
   1838                                               Expr *First,
   1839                                               Expr *Second);
   1840 
   1841   /// \brief Build a new C++ "named" cast expression, such as static_cast or
   1842   /// reinterpret_cast.
   1843   ///
   1844   /// By default, this routine dispatches to one of the more-specific routines
   1845   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
   1846   /// Subclasses may override this routine to provide different behavior.
   1847   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
   1848                                            Stmt::StmtClass Class,
   1849                                            SourceLocation LAngleLoc,
   1850                                            TypeSourceInfo *TInfo,
   1851                                            SourceLocation RAngleLoc,
   1852                                            SourceLocation LParenLoc,
   1853                                            Expr *SubExpr,
   1854                                            SourceLocation RParenLoc) {
   1855     switch (Class) {
   1856     case Stmt::CXXStaticCastExprClass:
   1857       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
   1858                                                    RAngleLoc, LParenLoc,
   1859                                                    SubExpr, RParenLoc);
   1860 
   1861     case Stmt::CXXDynamicCastExprClass:
   1862       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
   1863                                                     RAngleLoc, LParenLoc,
   1864                                                     SubExpr, RParenLoc);
   1865 
   1866     case Stmt::CXXReinterpretCastExprClass:
   1867       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
   1868                                                         RAngleLoc, LParenLoc,
   1869                                                         SubExpr,
   1870                                                         RParenLoc);
   1871 
   1872     case Stmt::CXXConstCastExprClass:
   1873       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
   1874                                                    RAngleLoc, LParenLoc,
   1875                                                    SubExpr, RParenLoc);
   1876 
   1877     default:
   1878       llvm_unreachable("Invalid C++ named cast");
   1879     }
   1880   }
   1881 
   1882   /// \brief Build a new C++ static_cast expression.
   1883   ///
   1884   /// By default, performs semantic analysis to build the new expression.
   1885   /// Subclasses may override this routine to provide different behavior.
   1886   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
   1887                                             SourceLocation LAngleLoc,
   1888                                             TypeSourceInfo *TInfo,
   1889                                             SourceLocation RAngleLoc,
   1890                                             SourceLocation LParenLoc,
   1891                                             Expr *SubExpr,
   1892                                             SourceLocation RParenLoc) {
   1893     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
   1894                                        TInfo, SubExpr,
   1895                                        SourceRange(LAngleLoc, RAngleLoc),
   1896                                        SourceRange(LParenLoc, RParenLoc));
   1897   }
   1898 
   1899   /// \brief Build a new C++ dynamic_cast expression.
   1900   ///
   1901   /// By default, performs semantic analysis to build the new expression.
   1902   /// Subclasses may override this routine to provide different behavior.
   1903   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
   1904                                              SourceLocation LAngleLoc,
   1905                                              TypeSourceInfo *TInfo,
   1906                                              SourceLocation RAngleLoc,
   1907                                              SourceLocation LParenLoc,
   1908                                              Expr *SubExpr,
   1909                                              SourceLocation RParenLoc) {
   1910     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
   1911                                        TInfo, SubExpr,
   1912                                        SourceRange(LAngleLoc, RAngleLoc),
   1913                                        SourceRange(LParenLoc, RParenLoc));
   1914   }
   1915 
   1916   /// \brief Build a new C++ reinterpret_cast expression.
   1917   ///
   1918   /// By default, performs semantic analysis to build the new expression.
   1919   /// Subclasses may override this routine to provide different behavior.
   1920   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
   1921                                                  SourceLocation LAngleLoc,
   1922                                                  TypeSourceInfo *TInfo,
   1923                                                  SourceLocation RAngleLoc,
   1924                                                  SourceLocation LParenLoc,
   1925                                                  Expr *SubExpr,
   1926                                                  SourceLocation RParenLoc) {
   1927     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
   1928                                        TInfo, SubExpr,
   1929                                        SourceRange(LAngleLoc, RAngleLoc),
   1930                                        SourceRange(LParenLoc, RParenLoc));
   1931   }
   1932 
   1933   /// \brief Build a new C++ const_cast expression.
   1934   ///
   1935   /// By default, performs semantic analysis to build the new expression.
   1936   /// Subclasses may override this routine to provide different behavior.
   1937   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
   1938                                            SourceLocation LAngleLoc,
   1939                                            TypeSourceInfo *TInfo,
   1940                                            SourceLocation RAngleLoc,
   1941                                            SourceLocation LParenLoc,
   1942                                            Expr *SubExpr,
   1943                                            SourceLocation RParenLoc) {
   1944     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
   1945                                        TInfo, SubExpr,
   1946                                        SourceRange(LAngleLoc, RAngleLoc),
   1947                                        SourceRange(LParenLoc, RParenLoc));
   1948   }
   1949 
   1950   /// \brief Build a new C++ functional-style cast expression.
   1951   ///
   1952   /// By default, performs semantic analysis to build the new expression.
   1953   /// Subclasses may override this routine to provide different behavior.
   1954   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
   1955                                           SourceLocation LParenLoc,
   1956                                           Expr *Sub,
   1957                                           SourceLocation RParenLoc) {
   1958     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
   1959                                                MultiExprArg(&Sub, 1),
   1960                                                RParenLoc);
   1961   }
   1962 
   1963   /// \brief Build a new C++ typeid(type) expression.
   1964   ///
   1965   /// By default, performs semantic analysis to build the new expression.
   1966   /// Subclasses may override this routine to provide different behavior.
   1967   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
   1968                                         SourceLocation TypeidLoc,
   1969                                         TypeSourceInfo *Operand,
   1970                                         SourceLocation RParenLoc) {
   1971     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
   1972                                     RParenLoc);
   1973   }
   1974 
   1975 
   1976   /// \brief Build a new C++ typeid(expr) expression.
   1977   ///
   1978   /// By default, performs semantic analysis to build the new expression.
   1979   /// Subclasses may override this routine to provide different behavior.
   1980   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
   1981                                         SourceLocation TypeidLoc,
   1982                                         Expr *Operand,
   1983                                         SourceLocation RParenLoc) {
   1984     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
   1985                                     RParenLoc);
   1986   }
   1987 
   1988   /// \brief Build a new C++ __uuidof(type) expression.
   1989   ///
   1990   /// By default, performs semantic analysis to build the new expression.
   1991   /// Subclasses may override this routine to provide different behavior.
   1992   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
   1993                                         SourceLocation TypeidLoc,
   1994                                         TypeSourceInfo *Operand,
   1995                                         SourceLocation RParenLoc) {
   1996     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
   1997                                     RParenLoc);
   1998   }
   1999 
   2000   /// \brief Build a new C++ __uuidof(expr) expression.
   2001   ///
   2002   /// By default, performs semantic analysis to build the new expression.
   2003   /// Subclasses may override this routine to provide different behavior.
   2004   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
   2005                                         SourceLocation TypeidLoc,
   2006                                         Expr *Operand,
   2007                                         SourceLocation RParenLoc) {
   2008     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
   2009                                     RParenLoc);
   2010   }
   2011 
   2012   /// \brief Build a new C++ "this" expression.
   2013   ///
   2014   /// By default, builds a new "this" expression without performing any
   2015   /// semantic analysis. Subclasses may override this routine to provide
   2016   /// different behavior.
   2017   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
   2018                                 QualType ThisType,
   2019                                 bool isImplicit) {
   2020     getSema().CheckCXXThisCapture(ThisLoc);
   2021     return getSema().Owned(
   2022                       new (getSema().Context) CXXThisExpr(ThisLoc, ThisType,
   2023                                                           isImplicit));
   2024   }
   2025 
   2026   /// \brief Build a new C++ throw expression.
   2027   ///
   2028   /// By default, performs semantic analysis to build the new expression.
   2029   /// Subclasses may override this routine to provide different behavior.
   2030   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
   2031                                  bool IsThrownVariableInScope) {
   2032     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
   2033   }
   2034 
   2035   /// \brief Build a new C++ default-argument expression.
   2036   ///
   2037   /// By default, builds a new default-argument expression, which does not
   2038   /// require any semantic analysis. Subclasses may override this routine to
   2039   /// provide different behavior.
   2040   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
   2041                                             ParmVarDecl *Param) {
   2042     return getSema().Owned(CXXDefaultArgExpr::Create(getSema().Context, Loc,
   2043                                                      Param));
   2044   }
   2045 
   2046   /// \brief Build a new C++11 default-initialization expression.
   2047   ///
   2048   /// By default, builds a new default field initialization expression, which
   2049   /// does not require any semantic analysis. Subclasses may override this
   2050   /// routine to provide different behavior.
   2051   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
   2052                                        FieldDecl *Field) {
   2053     return getSema().Owned(CXXDefaultInitExpr::Create(getSema().Context, Loc,
   2054                                                       Field));
   2055   }
   2056 
   2057   /// \brief Build a new C++ zero-initialization expression.
   2058   ///
   2059   /// By default, performs semantic analysis to build the new expression.
   2060   /// Subclasses may override this routine to provide different behavior.
   2061   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
   2062                                            SourceLocation LParenLoc,
   2063                                            SourceLocation RParenLoc) {
   2064     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
   2065                                                None, RParenLoc);
   2066   }
   2067 
   2068   /// \brief Build a new C++ "new" expression.
   2069   ///
   2070   /// By default, performs semantic analysis to build the new expression.
   2071   /// Subclasses may override this routine to provide different behavior.
   2072   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
   2073                                bool UseGlobal,
   2074                                SourceLocation PlacementLParen,
   2075                                MultiExprArg PlacementArgs,
   2076                                SourceLocation PlacementRParen,
   2077                                SourceRange TypeIdParens,
   2078                                QualType AllocatedType,
   2079                                TypeSourceInfo *AllocatedTypeInfo,
   2080                                Expr *ArraySize,
   2081                                SourceRange DirectInitRange,
   2082                                Expr *Initializer) {
   2083     return getSema().BuildCXXNew(StartLoc, UseGlobal,
   2084                                  PlacementLParen,
   2085                                  PlacementArgs,
   2086                                  PlacementRParen,
   2087                                  TypeIdParens,
   2088                                  AllocatedType,
   2089                                  AllocatedTypeInfo,
   2090                                  ArraySize,
   2091                                  DirectInitRange,
   2092                                  Initializer);
   2093   }
   2094 
   2095   /// \brief Build a new C++ "delete" expression.
   2096   ///
   2097   /// By default, performs semantic analysis to build the new expression.
   2098   /// Subclasses may override this routine to provide different behavior.
   2099   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
   2100                                         bool IsGlobalDelete,
   2101                                         bool IsArrayForm,
   2102                                         Expr *Operand) {
   2103     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
   2104                                     Operand);
   2105   }
   2106 
   2107   /// \brief Build a new unary type trait expression.
   2108   ///
   2109   /// By default, performs semantic analysis to build the new expression.
   2110   /// Subclasses may override this routine to provide different behavior.
   2111   ExprResult RebuildUnaryTypeTrait(UnaryTypeTrait Trait,
   2112                                    SourceLocation StartLoc,
   2113                                    TypeSourceInfo *T,
   2114                                    SourceLocation RParenLoc) {
   2115     return getSema().BuildUnaryTypeTrait(Trait, StartLoc, T, RParenLoc);
   2116   }
   2117 
   2118   /// \brief Build a new binary type trait expression.
   2119   ///
   2120   /// By default, performs semantic analysis to build the new expression.
   2121   /// Subclasses may override this routine to provide different behavior.
   2122   ExprResult RebuildBinaryTypeTrait(BinaryTypeTrait Trait,
   2123                                     SourceLocation StartLoc,
   2124                                     TypeSourceInfo *LhsT,
   2125                                     TypeSourceInfo *RhsT,
   2126                                     SourceLocation RParenLoc) {
   2127     return getSema().BuildBinaryTypeTrait(Trait, StartLoc, LhsT, RhsT, RParenLoc);
   2128   }
   2129 
   2130   /// \brief Build a new type trait expression.
   2131   ///
   2132   /// By default, performs semantic analysis to build the new expression.
   2133   /// Subclasses may override this routine to provide different behavior.
   2134   ExprResult RebuildTypeTrait(TypeTrait Trait,
   2135                               SourceLocation StartLoc,
   2136                               ArrayRef<TypeSourceInfo *> Args,
   2137                               SourceLocation RParenLoc) {
   2138     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
   2139   }
   2140 
   2141   /// \brief Build a new array type trait expression.
   2142   ///
   2143   /// By default, performs semantic analysis to build the new expression.
   2144   /// Subclasses may override this routine to provide different behavior.
   2145   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
   2146                                    SourceLocation StartLoc,
   2147                                    TypeSourceInfo *TSInfo,
   2148                                    Expr *DimExpr,
   2149                                    SourceLocation RParenLoc) {
   2150     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
   2151   }
   2152 
   2153   /// \brief Build a new expression trait expression.
   2154   ///
   2155   /// By default, performs semantic analysis to build the new expression.
   2156   /// Subclasses may override this routine to provide different behavior.
   2157   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
   2158                                    SourceLocation StartLoc,
   2159                                    Expr *Queried,
   2160                                    SourceLocation RParenLoc) {
   2161     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
   2162   }
   2163 
   2164   /// \brief Build a new (previously unresolved) declaration reference
   2165   /// expression.
   2166   ///
   2167   /// By default, performs semantic analysis to build the new expression.
   2168   /// Subclasses may override this routine to provide different behavior.
   2169   ExprResult RebuildDependentScopeDeclRefExpr(
   2170                                           NestedNameSpecifierLoc QualifierLoc,
   2171                                           SourceLocation TemplateKWLoc,
   2172                                        const DeclarationNameInfo &NameInfo,
   2173                               const TemplateArgumentListInfo *TemplateArgs,
   2174                                           bool IsAddressOfOperand) {
   2175     CXXScopeSpec SS;
   2176     SS.Adopt(QualifierLoc);
   2177 
   2178     if (TemplateArgs || TemplateKWLoc.isValid())
   2179       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc,
   2180                                                     NameInfo, TemplateArgs);
   2181 
   2182     return getSema().BuildQualifiedDeclarationNameExpr(SS, NameInfo,
   2183                                                        IsAddressOfOperand);
   2184   }
   2185 
   2186   /// \brief Build a new template-id expression.
   2187   ///
   2188   /// By default, performs semantic analysis to build the new expression.
   2189   /// Subclasses may override this routine to provide different behavior.
   2190   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
   2191                                    SourceLocation TemplateKWLoc,
   2192                                    LookupResult &R,
   2193                                    bool RequiresADL,
   2194                               const TemplateArgumentListInfo *TemplateArgs) {
   2195     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
   2196                                          TemplateArgs);
   2197   }
   2198 
   2199   /// \brief Build a new object-construction expression.
   2200   ///
   2201   /// By default, performs semantic analysis to build the new expression.
   2202   /// Subclasses may override this routine to provide different behavior.
   2203   ExprResult RebuildCXXConstructExpr(QualType T,
   2204                                      SourceLocation Loc,
   2205                                      CXXConstructorDecl *Constructor,
   2206                                      bool IsElidable,
   2207                                      MultiExprArg Args,
   2208                                      bool HadMultipleCandidates,
   2209                                      bool ListInitialization,
   2210                                      bool RequiresZeroInit,
   2211                              CXXConstructExpr::ConstructionKind ConstructKind,
   2212                                      SourceRange ParenRange) {
   2213     SmallVector<Expr*, 8> ConvertedArgs;
   2214     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
   2215                                           ConvertedArgs))
   2216       return ExprError();
   2217 
   2218     return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
   2219                                            ConvertedArgs,
   2220                                            HadMultipleCandidates,
   2221                                            ListInitialization,
   2222                                            RequiresZeroInit, ConstructKind,
   2223                                            ParenRange);
   2224   }
   2225 
   2226   /// \brief Build a new object-construction expression.
   2227   ///
   2228   /// By default, performs semantic analysis to build the new expression.
   2229   /// Subclasses may override this routine to provide different behavior.
   2230   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
   2231                                            SourceLocation LParenLoc,
   2232                                            MultiExprArg Args,
   2233                                            SourceLocation RParenLoc) {
   2234     return getSema().BuildCXXTypeConstructExpr(TSInfo,
   2235                                                LParenLoc,
   2236                                                Args,
   2237                                                RParenLoc);
   2238   }
   2239 
   2240   /// \brief Build a new object-construction expression.
   2241   ///
   2242   /// By default, performs semantic analysis to build the new expression.
   2243   /// Subclasses may override this routine to provide different behavior.
   2244   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
   2245                                                SourceLocation LParenLoc,
   2246                                                MultiExprArg Args,
   2247                                                SourceLocation RParenLoc) {
   2248     return getSema().BuildCXXTypeConstructExpr(TSInfo,
   2249                                                LParenLoc,
   2250                                                Args,
   2251                                                RParenLoc);
   2252   }
   2253 
   2254   /// \brief Build a new member reference expression.
   2255   ///
   2256   /// By default, performs semantic analysis to build the new expression.
   2257   /// Subclasses may override this routine to provide different behavior.
   2258   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
   2259                                                 QualType BaseType,
   2260                                                 bool IsArrow,
   2261                                                 SourceLocation OperatorLoc,
   2262                                           NestedNameSpecifierLoc QualifierLoc,
   2263                                                 SourceLocation TemplateKWLoc,
   2264                                             NamedDecl *FirstQualifierInScope,
   2265                                    const DeclarationNameInfo &MemberNameInfo,
   2266                               const TemplateArgumentListInfo *TemplateArgs) {
   2267     CXXScopeSpec SS;
   2268     SS.Adopt(QualifierLoc);
   2269 
   2270     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
   2271                                             OperatorLoc, IsArrow,
   2272                                             SS, TemplateKWLoc,
   2273                                             FirstQualifierInScope,
   2274                                             MemberNameInfo,
   2275                                             TemplateArgs);
   2276   }
   2277 
   2278   /// \brief Build a new member reference expression.
   2279   ///
   2280   /// By default, performs semantic analysis to build the new expression.
   2281   /// Subclasses may override this routine to provide different behavior.
   2282   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
   2283                                          SourceLocation OperatorLoc,
   2284                                          bool IsArrow,
   2285                                          NestedNameSpecifierLoc QualifierLoc,
   2286                                          SourceLocation TemplateKWLoc,
   2287                                          NamedDecl *FirstQualifierInScope,
   2288                                          LookupResult &R,
   2289                                 const TemplateArgumentListInfo *TemplateArgs) {
   2290     CXXScopeSpec SS;
   2291     SS.Adopt(QualifierLoc);
   2292 
   2293     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
   2294                                             OperatorLoc, IsArrow,
   2295                                             SS, TemplateKWLoc,
   2296                                             FirstQualifierInScope,
   2297                                             R, TemplateArgs);
   2298   }
   2299 
   2300   /// \brief Build a new noexcept expression.
   2301   ///
   2302   /// By default, performs semantic analysis to build the new expression.
   2303   /// Subclasses may override this routine to provide different behavior.
   2304   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
   2305     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
   2306   }
   2307 
   2308   /// \brief Build a new expression to compute the length of a parameter pack.
   2309   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
   2310                                    SourceLocation PackLoc,
   2311                                    SourceLocation RParenLoc,
   2312                                    Optional<unsigned> Length) {
   2313     if (Length)
   2314       return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
   2315                                                   OperatorLoc, Pack, PackLoc,
   2316                                                   RParenLoc, *Length);
   2317 
   2318     return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
   2319                                                 OperatorLoc, Pack, PackLoc,
   2320                                                 RParenLoc);
   2321   }
   2322 
   2323   /// \brief Build a new Objective-C boxed expression.
   2324   ///
   2325   /// By default, performs semantic analysis to build the new expression.
   2326   /// Subclasses may override this routine to provide different behavior.
   2327   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
   2328     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
   2329   }
   2330 
   2331   /// \brief Build a new Objective-C array literal.
   2332   ///
   2333   /// By default, performs semantic analysis to build the new expression.
   2334   /// Subclasses may override this routine to provide different behavior.
   2335   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
   2336                                      Expr **Elements, unsigned NumElements) {
   2337     return getSema().BuildObjCArrayLiteral(Range,
   2338                                            MultiExprArg(Elements, NumElements));
   2339   }
   2340 
   2341   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
   2342                                          Expr *Base, Expr *Key,
   2343                                          ObjCMethodDecl *getterMethod,
   2344                                          ObjCMethodDecl *setterMethod) {
   2345     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
   2346                                                    getterMethod, setterMethod);
   2347   }
   2348 
   2349   /// \brief Build a new Objective-C dictionary literal.
   2350   ///
   2351   /// By default, performs semantic analysis to build the new expression.
   2352   /// Subclasses may override this routine to provide different behavior.
   2353   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
   2354                                           ObjCDictionaryElement *Elements,
   2355                                           unsigned NumElements) {
   2356     return getSema().BuildObjCDictionaryLiteral(Range, Elements, NumElements);
   2357   }
   2358 
   2359   /// \brief Build a new Objective-C \@encode expression.
   2360   ///
   2361   /// By default, performs semantic analysis to build the new expression.
   2362   /// Subclasses may override this routine to provide different behavior.
   2363   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
   2364                                          TypeSourceInfo *EncodeTypeInfo,
   2365                                          SourceLocation RParenLoc) {
   2366     return SemaRef.Owned(SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo,
   2367                                                            RParenLoc));
   2368   }
   2369 
   2370   /// \brief Build a new Objective-C class message.
   2371   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
   2372                                           Selector Sel,
   2373                                           ArrayRef<SourceLocation> SelectorLocs,
   2374                                           ObjCMethodDecl *Method,
   2375                                           SourceLocation LBracLoc,
   2376                                           MultiExprArg Args,
   2377                                           SourceLocation RBracLoc) {
   2378     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
   2379                                      ReceiverTypeInfo->getType(),
   2380                                      /*SuperLoc=*/SourceLocation(),
   2381                                      Sel, Method, LBracLoc, SelectorLocs,
   2382                                      RBracLoc, Args);
   2383   }
   2384 
   2385   /// \brief Build a new Objective-C instance message.
   2386   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
   2387                                           Selector Sel,
   2388                                           ArrayRef<SourceLocation> SelectorLocs,
   2389                                           ObjCMethodDecl *Method,
   2390                                           SourceLocation LBracLoc,
   2391                                           MultiExprArg Args,
   2392                                           SourceLocation RBracLoc) {
   2393     return SemaRef.BuildInstanceMessage(Receiver,
   2394                                         Receiver->getType(),
   2395                                         /*SuperLoc=*/SourceLocation(),
   2396                                         Sel, Method, LBracLoc, SelectorLocs,
   2397                                         RBracLoc, Args);
   2398   }
   2399 
   2400   /// \brief Build a new Objective-C ivar reference expression.
   2401   ///
   2402   /// By default, performs semantic analysis to build the new expression.
   2403   /// Subclasses may override this routine to provide different behavior.
   2404   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
   2405                                           SourceLocation IvarLoc,
   2406                                           bool IsArrow, bool IsFreeIvar) {
   2407     // FIXME: We lose track of the IsFreeIvar bit.
   2408     CXXScopeSpec SS;
   2409     ExprResult Base = getSema().Owned(BaseArg);
   2410     LookupResult R(getSema(), Ivar->getDeclName(), IvarLoc,
   2411                    Sema::LookupMemberName);
   2412     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
   2413                                                          /*FIME:*/IvarLoc,
   2414                                                          SS, 0,
   2415                                                          false);
   2416     if (Result.isInvalid() || Base.isInvalid())
   2417       return ExprError();
   2418 
   2419     if (Result.get())
   2420       return Result;
   2421 
   2422     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
   2423                                               /*FIXME:*/IvarLoc, IsArrow,
   2424                                               SS, SourceLocation(),
   2425                                               /*FirstQualifierInScope=*/0,
   2426                                               R,
   2427                                               /*TemplateArgs=*/0);
   2428   }
   2429 
   2430   /// \brief Build a new Objective-C property reference 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 RebuildObjCPropertyRefExpr(Expr *BaseArg,
   2435                                         ObjCPropertyDecl *Property,
   2436                                         SourceLocation PropertyLoc) {
   2437     CXXScopeSpec SS;
   2438     ExprResult Base = getSema().Owned(BaseArg);
   2439     LookupResult R(getSema(), Property->getDeclName(), PropertyLoc,
   2440                    Sema::LookupMemberName);
   2441     bool IsArrow = false;
   2442     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
   2443                                                          /*FIME:*/PropertyLoc,
   2444                                                          SS, 0, false);
   2445     if (Result.isInvalid() || Base.isInvalid())
   2446       return ExprError();
   2447 
   2448     if (Result.get())
   2449       return Result;
   2450 
   2451     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
   2452                                               /*FIXME:*/PropertyLoc, IsArrow,
   2453                                               SS, SourceLocation(),
   2454                                               /*FirstQualifierInScope=*/0,
   2455                                               R,
   2456                                               /*TemplateArgs=*/0);
   2457   }
   2458 
   2459   /// \brief Build a new Objective-C property reference expression.
   2460   ///
   2461   /// By default, performs semantic analysis to build the new expression.
   2462   /// Subclasses may override this routine to provide different behavior.
   2463   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
   2464                                         ObjCMethodDecl *Getter,
   2465                                         ObjCMethodDecl *Setter,
   2466                                         SourceLocation PropertyLoc) {
   2467     // Since these expressions can only be value-dependent, we do not
   2468     // need to perform semantic analysis again.
   2469     return Owned(
   2470       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
   2471                                                   VK_LValue, OK_ObjCProperty,
   2472                                                   PropertyLoc, Base));
   2473   }
   2474 
   2475   /// \brief Build a new Objective-C "isa" expression.
   2476   ///
   2477   /// By default, performs semantic analysis to build the new expression.
   2478   /// Subclasses may override this routine to provide different behavior.
   2479   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
   2480                                 SourceLocation OpLoc,
   2481                                       bool IsArrow) {
   2482     CXXScopeSpec SS;
   2483     ExprResult Base = getSema().Owned(BaseArg);
   2484     LookupResult R(getSema(), &getSema().Context.Idents.get("isa"), IsaLoc,
   2485                    Sema::LookupMemberName);
   2486     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
   2487                                                          OpLoc,
   2488                                                          SS, 0, false);
   2489     if (Result.isInvalid() || Base.isInvalid())
   2490       return ExprError();
   2491 
   2492     if (Result.get())
   2493       return Result;
   2494 
   2495     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
   2496                                               OpLoc, IsArrow,
   2497                                               SS, SourceLocation(),
   2498                                               /*FirstQualifierInScope=*/0,
   2499                                               R,
   2500                                               /*TemplateArgs=*/0);
   2501   }
   2502 
   2503   /// \brief Build a new shuffle vector expression.
   2504   ///
   2505   /// By default, performs semantic analysis to build the new expression.
   2506   /// Subclasses may override this routine to provide different behavior.
   2507   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
   2508                                       MultiExprArg SubExprs,
   2509                                       SourceLocation RParenLoc) {
   2510     // Find the declaration for __builtin_shufflevector
   2511     const IdentifierInfo &Name
   2512       = SemaRef.Context.Idents.get("__builtin_shufflevector");
   2513     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
   2514     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
   2515     assert(!Lookup.empty() && "No __builtin_shufflevector?");
   2516 
   2517     // Build a reference to the __builtin_shufflevector builtin
   2518     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
   2519     Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
   2520                                                   SemaRef.Context.BuiltinFnTy,
   2521                                                   VK_RValue, BuiltinLoc);
   2522     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
   2523     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
   2524                                        CK_BuiltinFnToFnPtr).take();
   2525 
   2526     // Build the CallExpr
   2527     ExprResult TheCall = SemaRef.Owned(
   2528       new (SemaRef.Context) CallExpr(SemaRef.Context, Callee, SubExprs,
   2529                                      Builtin->getCallResultType(),
   2530                             Expr::getValueKindForType(Builtin->getResultType()),
   2531                                      RParenLoc));
   2532 
   2533     // Type-check the __builtin_shufflevector expression.
   2534     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.take()));
   2535   }
   2536 
   2537   /// \brief Build a new template argument pack expansion.
   2538   ///
   2539   /// By default, performs semantic analysis to build a new pack expansion
   2540   /// for a template argument. Subclasses may override this routine to provide
   2541   /// different behavior.
   2542   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
   2543                                            SourceLocation EllipsisLoc,
   2544                                            Optional<unsigned> NumExpansions) {
   2545     switch (Pattern.getArgument().getKind()) {
   2546     case TemplateArgument::Expression: {
   2547       ExprResult Result
   2548         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
   2549                                        EllipsisLoc, NumExpansions);
   2550       if (Result.isInvalid())
   2551         return TemplateArgumentLoc();
   2552 
   2553       return TemplateArgumentLoc(Result.get(), Result.get());
   2554     }
   2555 
   2556     case TemplateArgument::Template:
   2557       return TemplateArgumentLoc(TemplateArgument(
   2558                                           Pattern.getArgument().getAsTemplate(),
   2559                                                   NumExpansions),
   2560                                  Pattern.getTemplateQualifierLoc(),
   2561                                  Pattern.getTemplateNameLoc(),
   2562                                  EllipsisLoc);
   2563 
   2564     case TemplateArgument::Null:
   2565     case TemplateArgument::Integral:
   2566     case TemplateArgument::Declaration:
   2567     case TemplateArgument::Pack:
   2568     case TemplateArgument::TemplateExpansion:
   2569     case TemplateArgument::NullPtr:
   2570       llvm_unreachable("Pack expansion pattern has no parameter packs");
   2571 
   2572     case TemplateArgument::Type:
   2573       if (TypeSourceInfo *Expansion
   2574             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
   2575                                            EllipsisLoc,
   2576                                            NumExpansions))
   2577         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
   2578                                    Expansion);
   2579       break;
   2580     }
   2581 
   2582     return TemplateArgumentLoc();
   2583   }
   2584 
   2585   /// \brief Build a new expression pack expansion.
   2586   ///
   2587   /// By default, performs semantic analysis to build a new pack expansion
   2588   /// for an expression. Subclasses may override this routine to provide
   2589   /// different behavior.
   2590   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
   2591                                   Optional<unsigned> NumExpansions) {
   2592     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
   2593   }
   2594 
   2595   /// \brief Build a new atomic operation expression.
   2596   ///
   2597   /// By default, performs semantic analysis to build the new expression.
   2598   /// Subclasses may override this routine to provide different behavior.
   2599   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
   2600                                MultiExprArg SubExprs,
   2601                                QualType RetTy,
   2602                                AtomicExpr::AtomicOp Op,
   2603                                SourceLocation RParenLoc) {
   2604     // Just create the expression; there is not any interesting semantic
   2605     // analysis here because we can't actually build an AtomicExpr until
   2606     // we are sure it is semantically sound.
   2607     return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
   2608                                             RParenLoc);
   2609   }
   2610 
   2611 private:
   2612   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
   2613                                      QualType ObjectType,
   2614                                      NamedDecl *FirstQualifierInScope,
   2615                                      CXXScopeSpec &SS);
   2616 
   2617   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
   2618                                              QualType ObjectType,
   2619                                              NamedDecl *FirstQualifierInScope,
   2620                                              CXXScopeSpec &SS);
   2621 };
   2622 
   2623 template<typename Derived>
   2624 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
   2625   if (!S)
   2626     return SemaRef.Owned(S);
   2627 
   2628   switch (S->getStmtClass()) {
   2629   case Stmt::NoStmtClass: break;
   2630 
   2631   // Transform individual statement nodes
   2632 #define STMT(Node, Parent)                                              \
   2633   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
   2634 #define ABSTRACT_STMT(Node)
   2635 #define EXPR(Node, Parent)
   2636 #include "clang/AST/StmtNodes.inc"
   2637 
   2638   // Transform expressions by calling TransformExpr.
   2639 #define STMT(Node, Parent)
   2640 #define ABSTRACT_STMT(Stmt)
   2641 #define EXPR(Node, Parent) case Stmt::Node##Class:
   2642 #include "clang/AST/StmtNodes.inc"
   2643     {
   2644       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
   2645       if (E.isInvalid())
   2646         return StmtError();
   2647 
   2648       return getSema().ActOnExprStmt(E);
   2649     }
   2650   }
   2651 
   2652   return SemaRef.Owned(S);
   2653 }
   2654 
   2655 template<typename Derived>
   2656 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
   2657   if (!S)
   2658     return S;
   2659 
   2660   switch (S->getClauseKind()) {
   2661   default: break;
   2662   // Transform individual clause nodes
   2663 #define OPENMP_CLAUSE(Name, Class)                                             \
   2664   case OMPC_ ## Name :                                                         \
   2665     return getDerived().Transform ## Class(cast<Class>(S));
   2666 #include "clang/Basic/OpenMPKinds.def"
   2667   }
   2668 
   2669   return S;
   2670 }
   2671 
   2672 
   2673 template<typename Derived>
   2674 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
   2675   if (!E)
   2676     return SemaRef.Owned(E);
   2677 
   2678   switch (E->getStmtClass()) {
   2679     case Stmt::NoStmtClass: break;
   2680 #define STMT(Node, Parent) case Stmt::Node##Class: break;
   2681 #define ABSTRACT_STMT(Stmt)
   2682 #define EXPR(Node, Parent)                                              \
   2683     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
   2684 #include "clang/AST/StmtNodes.inc"
   2685   }
   2686 
   2687   return SemaRef.Owned(E);
   2688 }
   2689 
   2690 template<typename Derived>
   2691 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
   2692                                                         bool CXXDirectInit) {
   2693   // Initializers are instantiated like expressions, except that various outer
   2694   // layers are stripped.
   2695   if (!Init)
   2696     return SemaRef.Owned(Init);
   2697 
   2698   if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
   2699     Init = ExprTemp->getSubExpr();
   2700 
   2701   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
   2702     Init = MTE->GetTemporaryExpr();
   2703 
   2704   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
   2705     Init = Binder->getSubExpr();
   2706 
   2707   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
   2708     Init = ICE->getSubExprAsWritten();
   2709 
   2710   if (CXXStdInitializerListExpr *ILE =
   2711           dyn_cast<CXXStdInitializerListExpr>(Init))
   2712     return TransformInitializer(ILE->getSubExpr(), CXXDirectInit);
   2713 
   2714   // If this is not a direct-initializer, we only need to reconstruct
   2715   // InitListExprs. Other forms of copy-initialization will be a no-op if
   2716   // the initializer is already the right type.
   2717   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
   2718   if (!CXXDirectInit && !(Construct && Construct->isListInitialization()))
   2719     return getDerived().TransformExpr(Init);
   2720 
   2721   // Revert value-initialization back to empty parens.
   2722   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
   2723     SourceRange Parens = VIE->getSourceRange();
   2724     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
   2725                                              Parens.getEnd());
   2726   }
   2727 
   2728   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
   2729   if (isa<ImplicitValueInitExpr>(Init))
   2730     return getDerived().RebuildParenListExpr(SourceLocation(), None,
   2731                                              SourceLocation());
   2732 
   2733   // Revert initialization by constructor back to a parenthesized or braced list
   2734   // of expressions. Any other form of initializer can just be reused directly.
   2735   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
   2736     return getDerived().TransformExpr(Init);
   2737 
   2738   SmallVector<Expr*, 8> NewArgs;
   2739   bool ArgChanged = false;
   2740   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
   2741                      /*IsCall*/true, NewArgs, &ArgChanged))
   2742     return ExprError();
   2743 
   2744   // If this was list initialization, revert to list form.
   2745   if (Construct->isListInitialization())
   2746     return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
   2747                                         Construct->getLocEnd(),
   2748                                         Construct->getType());
   2749 
   2750   // Build a ParenListExpr to represent anything else.
   2751   SourceRange Parens = Construct->getParenRange();
   2752   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
   2753                                            Parens.getEnd());
   2754 }
   2755 
   2756 template<typename Derived>
   2757 bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
   2758                                             unsigned NumInputs,
   2759                                             bool IsCall,
   2760                                       SmallVectorImpl<Expr *> &Outputs,
   2761                                             bool *ArgChanged) {
   2762   for (unsigned I = 0; I != NumInputs; ++I) {
   2763     // If requested, drop call arguments that need to be dropped.
   2764     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
   2765       if (ArgChanged)
   2766         *ArgChanged = true;
   2767 
   2768       break;
   2769     }
   2770 
   2771     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
   2772       Expr *Pattern = Expansion->getPattern();
   2773 
   2774       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   2775       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   2776       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   2777 
   2778       // Determine whether the set of unexpanded parameter packs can and should
   2779       // be expanded.
   2780       bool Expand = true;
   2781       bool RetainExpansion = false;
   2782       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
   2783       Optional<unsigned> NumExpansions = OrigNumExpansions;
   2784       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
   2785                                                Pattern->getSourceRange(),
   2786                                                Unexpanded,
   2787                                                Expand, RetainExpansion,
   2788                                                NumExpansions))
   2789         return true;
   2790 
   2791       if (!Expand) {
   2792         // The transform has determined that we should perform a simple
   2793         // transformation on the pack expansion, producing another pack
   2794         // expansion.
   2795         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   2796         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
   2797         if (OutPattern.isInvalid())
   2798           return true;
   2799 
   2800         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
   2801                                                 Expansion->getEllipsisLoc(),
   2802                                                            NumExpansions);
   2803         if (Out.isInvalid())
   2804           return true;
   2805 
   2806         if (ArgChanged)
   2807           *ArgChanged = true;
   2808         Outputs.push_back(Out.get());
   2809         continue;
   2810       }
   2811 
   2812       // Record right away that the argument was changed.  This needs
   2813       // to happen even if the array expands to nothing.
   2814       if (ArgChanged) *ArgChanged = true;
   2815 
   2816       // The transform has determined that we should perform an elementwise
   2817       // expansion of the pattern. Do so.
   2818       for (unsigned I = 0; I != *NumExpansions; ++I) {
   2819         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   2820         ExprResult Out = getDerived().TransformExpr(Pattern);
   2821         if (Out.isInvalid())
   2822           return true;
   2823 
   2824         if (Out.get()->containsUnexpandedParameterPack()) {
   2825           Out = RebuildPackExpansion(Out.get(), Expansion->getEllipsisLoc(),
   2826                                      OrigNumExpansions);
   2827           if (Out.isInvalid())
   2828             return true;
   2829         }
   2830 
   2831         Outputs.push_back(Out.get());
   2832       }
   2833 
   2834       continue;
   2835     }
   2836 
   2837     ExprResult Result =
   2838       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
   2839              : getDerived().TransformExpr(Inputs[I]);
   2840     if (Result.isInvalid())
   2841       return true;
   2842 
   2843     if (Result.get() != Inputs[I] && ArgChanged)
   2844       *ArgChanged = true;
   2845 
   2846     Outputs.push_back(Result.get());
   2847   }
   2848 
   2849   return false;
   2850 }
   2851 
   2852 template<typename Derived>
   2853 NestedNameSpecifierLoc
   2854 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
   2855                                                     NestedNameSpecifierLoc NNS,
   2856                                                      QualType ObjectType,
   2857                                              NamedDecl *FirstQualifierInScope) {
   2858   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
   2859   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
   2860        Qualifier = Qualifier.getPrefix())
   2861     Qualifiers.push_back(Qualifier);
   2862 
   2863   CXXScopeSpec SS;
   2864   while (!Qualifiers.empty()) {
   2865     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
   2866     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
   2867 
   2868     switch (QNNS->getKind()) {
   2869     case NestedNameSpecifier::Identifier:
   2870       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/0,
   2871                                               *QNNS->getAsIdentifier(),
   2872                                               Q.getLocalBeginLoc(),
   2873                                               Q.getLocalEndLoc(),
   2874                                               ObjectType, false, SS,
   2875                                               FirstQualifierInScope, false))
   2876         return NestedNameSpecifierLoc();
   2877 
   2878       break;
   2879 
   2880     case NestedNameSpecifier::Namespace: {
   2881       NamespaceDecl *NS
   2882         = cast_or_null<NamespaceDecl>(
   2883                                     getDerived().TransformDecl(
   2884                                                           Q.getLocalBeginLoc(),
   2885                                                        QNNS->getAsNamespace()));
   2886       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
   2887       break;
   2888     }
   2889 
   2890     case NestedNameSpecifier::NamespaceAlias: {
   2891       NamespaceAliasDecl *Alias
   2892         = cast_or_null<NamespaceAliasDecl>(
   2893                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
   2894                                                  QNNS->getAsNamespaceAlias()));
   2895       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
   2896                 Q.getLocalEndLoc());
   2897       break;
   2898     }
   2899 
   2900     case NestedNameSpecifier::Global:
   2901       // There is no meaningful transformation that one could perform on the
   2902       // global scope.
   2903       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
   2904       break;
   2905 
   2906     case NestedNameSpecifier::TypeSpecWithTemplate:
   2907     case NestedNameSpecifier::TypeSpec: {
   2908       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
   2909                                               FirstQualifierInScope, SS);
   2910 
   2911       if (!TL)
   2912         return NestedNameSpecifierLoc();
   2913 
   2914       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
   2915           (SemaRef.getLangOpts().CPlusPlus11 &&
   2916            TL.getType()->isEnumeralType())) {
   2917         assert(!TL.getType().hasLocalQualifiers() &&
   2918                "Can't get cv-qualifiers here");
   2919         if (TL.getType()->isEnumeralType())
   2920           SemaRef.Diag(TL.getBeginLoc(),
   2921                        diag::warn_cxx98_compat_enum_nested_name_spec);
   2922         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
   2923                   Q.getLocalEndLoc());
   2924         break;
   2925       }
   2926       // If the nested-name-specifier is an invalid type def, don't emit an
   2927       // error because a previous error should have already been emitted.
   2928       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
   2929       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
   2930         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
   2931           << TL.getType() << SS.getRange();
   2932       }
   2933       return NestedNameSpecifierLoc();
   2934     }
   2935     }
   2936 
   2937     // The qualifier-in-scope and object type only apply to the leftmost entity.
   2938     FirstQualifierInScope = 0;
   2939     ObjectType = QualType();
   2940   }
   2941 
   2942   // Don't rebuild the nested-name-specifier if we don't have to.
   2943   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
   2944       !getDerived().AlwaysRebuild())
   2945     return NNS;
   2946 
   2947   // If we can re-use the source-location data from the original
   2948   // nested-name-specifier, do so.
   2949   if (SS.location_size() == NNS.getDataLength() &&
   2950       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
   2951     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
   2952 
   2953   // Allocate new nested-name-specifier location information.
   2954   return SS.getWithLocInContext(SemaRef.Context);
   2955 }
   2956 
   2957 template<typename Derived>
   2958 DeclarationNameInfo
   2959 TreeTransform<Derived>
   2960 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
   2961   DeclarationName Name = NameInfo.getName();
   2962   if (!Name)
   2963     return DeclarationNameInfo();
   2964 
   2965   switch (Name.getNameKind()) {
   2966   case DeclarationName::Identifier:
   2967   case DeclarationName::ObjCZeroArgSelector:
   2968   case DeclarationName::ObjCOneArgSelector:
   2969   case DeclarationName::ObjCMultiArgSelector:
   2970   case DeclarationName::CXXOperatorName:
   2971   case DeclarationName::CXXLiteralOperatorName:
   2972   case DeclarationName::CXXUsingDirective:
   2973     return NameInfo;
   2974 
   2975   case DeclarationName::CXXConstructorName:
   2976   case DeclarationName::CXXDestructorName:
   2977   case DeclarationName::CXXConversionFunctionName: {
   2978     TypeSourceInfo *NewTInfo;
   2979     CanQualType NewCanTy;
   2980     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
   2981       NewTInfo = getDerived().TransformType(OldTInfo);
   2982       if (!NewTInfo)
   2983         return DeclarationNameInfo();
   2984       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
   2985     }
   2986     else {
   2987       NewTInfo = 0;
   2988       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
   2989       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
   2990       if (NewT.isNull())
   2991         return DeclarationNameInfo();
   2992       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
   2993     }
   2994 
   2995     DeclarationName NewName
   2996       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
   2997                                                            NewCanTy);
   2998     DeclarationNameInfo NewNameInfo(NameInfo);
   2999     NewNameInfo.setName(NewName);
   3000     NewNameInfo.setNamedTypeInfo(NewTInfo);
   3001     return NewNameInfo;
   3002   }
   3003   }
   3004 
   3005   llvm_unreachable("Unknown name kind.");
   3006 }
   3007 
   3008 template<typename Derived>
   3009 TemplateName
   3010 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
   3011                                               TemplateName Name,
   3012                                               SourceLocation NameLoc,
   3013                                               QualType ObjectType,
   3014                                               NamedDecl *FirstQualifierInScope) {
   3015   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
   3016     TemplateDecl *Template = QTN->getTemplateDecl();
   3017     assert(Template && "qualified template name must refer to a template");
   3018 
   3019     TemplateDecl *TransTemplate
   3020       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
   3021                                                               Template));
   3022     if (!TransTemplate)
   3023       return TemplateName();
   3024 
   3025     if (!getDerived().AlwaysRebuild() &&
   3026         SS.getScopeRep() == QTN->getQualifier() &&
   3027         TransTemplate == Template)
   3028       return Name;
   3029 
   3030     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
   3031                                             TransTemplate);
   3032   }
   3033 
   3034   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
   3035     if (SS.getScopeRep()) {
   3036       // These apply to the scope specifier, not the template.
   3037       ObjectType = QualType();
   3038       FirstQualifierInScope = 0;
   3039     }
   3040 
   3041     if (!getDerived().AlwaysRebuild() &&
   3042         SS.getScopeRep() == DTN->getQualifier() &&
   3043         ObjectType.isNull())
   3044       return Name;
   3045 
   3046     if (DTN->isIdentifier()) {
   3047       return getDerived().RebuildTemplateName(SS,
   3048                                               *DTN->getIdentifier(),
   3049                                               NameLoc,
   3050                                               ObjectType,
   3051                                               FirstQualifierInScope);
   3052     }
   3053 
   3054     return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
   3055                                             ObjectType);
   3056   }
   3057 
   3058   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
   3059     TemplateDecl *TransTemplate
   3060       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
   3061                                                               Template));
   3062     if (!TransTemplate)
   3063       return TemplateName();
   3064 
   3065     if (!getDerived().AlwaysRebuild() &&
   3066         TransTemplate == Template)
   3067       return Name;
   3068 
   3069     return TemplateName(TransTemplate);
   3070   }
   3071 
   3072   if (SubstTemplateTemplateParmPackStorage *SubstPack
   3073       = Name.getAsSubstTemplateTemplateParmPack()) {
   3074     TemplateTemplateParmDecl *TransParam
   3075     = cast_or_null<TemplateTemplateParmDecl>(
   3076             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
   3077     if (!TransParam)
   3078       return TemplateName();
   3079 
   3080     if (!getDerived().AlwaysRebuild() &&
   3081         TransParam == SubstPack->getParameterPack())
   3082       return Name;
   3083 
   3084     return getDerived().RebuildTemplateName(TransParam,
   3085                                             SubstPack->getArgumentPack());
   3086   }
   3087 
   3088   // These should be getting filtered out before they reach the AST.
   3089   llvm_unreachable("overloaded function decl survived to here");
   3090 }
   3091 
   3092 template<typename Derived>
   3093 void TreeTransform<Derived>::InventTemplateArgumentLoc(
   3094                                          const TemplateArgument &Arg,
   3095                                          TemplateArgumentLoc &Output) {
   3096   SourceLocation Loc = getDerived().getBaseLocation();
   3097   switch (Arg.getKind()) {
   3098   case TemplateArgument::Null:
   3099     llvm_unreachable("null template argument in TreeTransform");
   3100     break;
   3101 
   3102   case TemplateArgument::Type:
   3103     Output = TemplateArgumentLoc(Arg,
   3104                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
   3105 
   3106     break;
   3107 
   3108   case TemplateArgument::Template:
   3109   case TemplateArgument::TemplateExpansion: {
   3110     NestedNameSpecifierLocBuilder Builder;
   3111     TemplateName Template = Arg.getAsTemplate();
   3112     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
   3113       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
   3114     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
   3115       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
   3116 
   3117     if (Arg.getKind() == TemplateArgument::Template)
   3118       Output = TemplateArgumentLoc(Arg,
   3119                                    Builder.getWithLocInContext(SemaRef.Context),
   3120                                    Loc);
   3121     else
   3122       Output = TemplateArgumentLoc(Arg,
   3123                                    Builder.getWithLocInContext(SemaRef.Context),
   3124                                    Loc, Loc);
   3125 
   3126     break;
   3127   }
   3128 
   3129   case TemplateArgument::Expression:
   3130     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
   3131     break;
   3132 
   3133   case TemplateArgument::Declaration:
   3134   case TemplateArgument::Integral:
   3135   case TemplateArgument::Pack:
   3136   case TemplateArgument::NullPtr:
   3137     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
   3138     break;
   3139   }
   3140 }
   3141 
   3142 template<typename Derived>
   3143 bool TreeTransform<Derived>::TransformTemplateArgument(
   3144                                          const TemplateArgumentLoc &Input,
   3145                                          TemplateArgumentLoc &Output) {
   3146   const TemplateArgument &Arg = Input.getArgument();
   3147   switch (Arg.getKind()) {
   3148   case TemplateArgument::Null:
   3149   case TemplateArgument::Integral:
   3150   case TemplateArgument::Pack:
   3151   case TemplateArgument::Declaration:
   3152   case TemplateArgument::NullPtr:
   3153     llvm_unreachable("Unexpected TemplateArgument");
   3154 
   3155   case TemplateArgument::Type: {
   3156     TypeSourceInfo *DI = Input.getTypeSourceInfo();
   3157     if (DI == NULL)
   3158       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
   3159 
   3160     DI = getDerived().TransformType(DI);
   3161     if (!DI) return true;
   3162 
   3163     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
   3164     return false;
   3165   }
   3166 
   3167   case TemplateArgument::Template: {
   3168     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
   3169     if (QualifierLoc) {
   3170       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
   3171       if (!QualifierLoc)
   3172         return true;
   3173     }
   3174 
   3175     CXXScopeSpec SS;
   3176     SS.Adopt(QualifierLoc);
   3177     TemplateName Template
   3178       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
   3179                                            Input.getTemplateNameLoc());
   3180     if (Template.isNull())
   3181       return true;
   3182 
   3183     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
   3184                                  Input.getTemplateNameLoc());
   3185     return false;
   3186   }
   3187 
   3188   case TemplateArgument::TemplateExpansion:
   3189     llvm_unreachable("Caller should expand pack expansions");
   3190 
   3191   case TemplateArgument::Expression: {
   3192     // Template argument expressions are constant expressions.
   3193     EnterExpressionEvaluationContext Unevaluated(getSema(),
   3194                                                  Sema::ConstantEvaluated);
   3195 
   3196     Expr *InputExpr = Input.getSourceExpression();
   3197     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
   3198 
   3199     ExprResult E = getDerived().TransformExpr(InputExpr);
   3200     E = SemaRef.ActOnConstantExpression(E);
   3201     if (E.isInvalid()) return true;
   3202     Output = TemplateArgumentLoc(TemplateArgument(E.take()), E.take());
   3203     return false;
   3204   }
   3205   }
   3206 
   3207   // Work around bogus GCC warning
   3208   return true;
   3209 }
   3210 
   3211 /// \brief Iterator adaptor that invents template argument location information
   3212 /// for each of the template arguments in its underlying iterator.
   3213 template<typename Derived, typename InputIterator>
   3214 class TemplateArgumentLocInventIterator {
   3215   TreeTransform<Derived> &Self;
   3216   InputIterator Iter;
   3217 
   3218 public:
   3219   typedef TemplateArgumentLoc value_type;
   3220   typedef TemplateArgumentLoc reference;
   3221   typedef typename std::iterator_traits<InputIterator>::difference_type
   3222     difference_type;
   3223   typedef std::input_iterator_tag iterator_category;
   3224 
   3225   class pointer {
   3226     TemplateArgumentLoc Arg;
   3227 
   3228   public:
   3229     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
   3230 
   3231     const TemplateArgumentLoc *operator->() const { return &Arg; }
   3232   };
   3233 
   3234   TemplateArgumentLocInventIterator() { }
   3235 
   3236   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
   3237                                              InputIterator Iter)
   3238     : Self(Self), Iter(Iter) { }
   3239 
   3240   TemplateArgumentLocInventIterator &operator++() {
   3241     ++Iter;
   3242     return *this;
   3243   }
   3244 
   3245   TemplateArgumentLocInventIterator operator++(int) {
   3246     TemplateArgumentLocInventIterator Old(*this);
   3247     ++(*this);
   3248     return Old;
   3249   }
   3250 
   3251   reference operator*() const {
   3252     TemplateArgumentLoc Result;
   3253     Self.InventTemplateArgumentLoc(*Iter, Result);
   3254     return Result;
   3255   }
   3256 
   3257   pointer operator->() const { return pointer(**this); }
   3258 
   3259   friend bool operator==(const TemplateArgumentLocInventIterator &X,
   3260                          const TemplateArgumentLocInventIterator &Y) {
   3261     return X.Iter == Y.Iter;
   3262   }
   3263 
   3264   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
   3265                          const TemplateArgumentLocInventIterator &Y) {
   3266     return X.Iter != Y.Iter;
   3267   }
   3268 };
   3269 
   3270 template<typename Derived>
   3271 template<typename InputIterator>
   3272 bool TreeTransform<Derived>::TransformTemplateArguments(InputIterator First,
   3273                                                         InputIterator Last,
   3274                                             TemplateArgumentListInfo &Outputs) {
   3275   for (; First != Last; ++First) {
   3276     TemplateArgumentLoc Out;
   3277     TemplateArgumentLoc In = *First;
   3278 
   3279     if (In.getArgument().getKind() == TemplateArgument::Pack) {
   3280       // Unpack argument packs, which we translate them into separate
   3281       // arguments.
   3282       // FIXME: We could do much better if we could guarantee that the
   3283       // TemplateArgumentLocInfo for the pack expansion would be usable for
   3284       // all of the template arguments in the argument pack.
   3285       typedef TemplateArgumentLocInventIterator<Derived,
   3286                                                 TemplateArgument::pack_iterator>
   3287         PackLocIterator;
   3288       if (TransformTemplateArguments(PackLocIterator(*this,
   3289                                                  In.getArgument().pack_begin()),
   3290                                      PackLocIterator(*this,
   3291                                                    In.getArgument().pack_end()),
   3292                                      Outputs))
   3293         return true;
   3294 
   3295       continue;
   3296     }
   3297 
   3298     if (In.getArgument().isPackExpansion()) {
   3299       // We have a pack expansion, for which we will be substituting into
   3300       // the pattern.
   3301       SourceLocation Ellipsis;
   3302       Optional<unsigned> OrigNumExpansions;
   3303       TemplateArgumentLoc Pattern
   3304         = getSema().getTemplateArgumentPackExpansionPattern(
   3305               In, Ellipsis, OrigNumExpansions);
   3306 
   3307       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   3308       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   3309       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   3310 
   3311       // Determine whether the set of unexpanded parameter packs can and should
   3312       // be expanded.
   3313       bool Expand = true;
   3314       bool RetainExpansion = false;
   3315       Optional<unsigned> NumExpansions = OrigNumExpansions;
   3316       if (getDerived().TryExpandParameterPacks(Ellipsis,
   3317                                                Pattern.getSourceRange(),
   3318                                                Unexpanded,
   3319                                                Expand,
   3320                                                RetainExpansion,
   3321                                                NumExpansions))
   3322         return true;
   3323 
   3324       if (!Expand) {
   3325         // The transform has determined that we should perform a simple
   3326         // transformation on the pack expansion, producing another pack
   3327         // expansion.
   3328         TemplateArgumentLoc OutPattern;
   3329         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   3330         if (getDerived().TransformTemplateArgument(Pattern, OutPattern))
   3331           return true;
   3332 
   3333         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
   3334                                                 NumExpansions);
   3335         if (Out.getArgument().isNull())
   3336           return true;
   3337 
   3338         Outputs.addArgument(Out);
   3339         continue;
   3340       }
   3341 
   3342       // The transform has determined that we should perform an elementwise
   3343       // expansion of the pattern. Do so.
   3344       for (unsigned I = 0; I != *NumExpansions; ++I) {
   3345         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   3346 
   3347         if (getDerived().TransformTemplateArgument(Pattern, Out))
   3348           return true;
   3349 
   3350         if (Out.getArgument().containsUnexpandedParameterPack()) {
   3351           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
   3352                                                   OrigNumExpansions);
   3353           if (Out.getArgument().isNull())
   3354             return true;
   3355         }
   3356 
   3357         Outputs.addArgument(Out);
   3358       }
   3359 
   3360       // If we're supposed to retain a pack expansion, do so by temporarily
   3361       // forgetting the partially-substituted parameter pack.
   3362       if (RetainExpansion) {
   3363         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   3364 
   3365         if (getDerived().TransformTemplateArgument(Pattern, Out))
   3366           return true;
   3367 
   3368         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
   3369                                                 OrigNumExpansions);
   3370         if (Out.getArgument().isNull())
   3371           return true;
   3372 
   3373         Outputs.addArgument(Out);
   3374       }
   3375 
   3376       continue;
   3377     }
   3378 
   3379     // The simple case:
   3380     if (getDerived().TransformTemplateArgument(In, Out))
   3381       return true;
   3382 
   3383     Outputs.addArgument(Out);
   3384   }
   3385 
   3386   return false;
   3387 
   3388 }
   3389 
   3390 //===----------------------------------------------------------------------===//
   3391 // Type transformation
   3392 //===----------------------------------------------------------------------===//
   3393 
   3394 template<typename Derived>
   3395 QualType TreeTransform<Derived>::TransformType(QualType T) {
   3396   if (getDerived().AlreadyTransformed(T))
   3397     return T;
   3398 
   3399   // Temporary workaround.  All of these transformations should
   3400   // eventually turn into transformations on TypeLocs.
   3401   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
   3402                                                 getDerived().getBaseLocation());
   3403 
   3404   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
   3405 
   3406   if (!NewDI)
   3407     return QualType();
   3408 
   3409   return NewDI->getType();
   3410 }
   3411 
   3412 template<typename Derived>
   3413 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
   3414   // Refine the base location to the type's location.
   3415   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
   3416                        getDerived().getBaseEntity());
   3417   if (getDerived().AlreadyTransformed(DI->getType()))
   3418     return DI;
   3419 
   3420   TypeLocBuilder TLB;
   3421 
   3422   TypeLoc TL = DI->getTypeLoc();
   3423   TLB.reserve(TL.getFullDataSize());
   3424 
   3425   QualType Result = getDerived().TransformType(TLB, TL);
   3426   if (Result.isNull())
   3427     return 0;
   3428 
   3429   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
   3430 }
   3431 
   3432 template<typename Derived>
   3433 QualType
   3434 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
   3435   switch (T.getTypeLocClass()) {
   3436 #define ABSTRACT_TYPELOC(CLASS, PARENT)
   3437 #define TYPELOC(CLASS, PARENT)                                                 \
   3438   case TypeLoc::CLASS:                                                         \
   3439     return getDerived().Transform##CLASS##Type(TLB,                            \
   3440                                                T.castAs<CLASS##TypeLoc>());
   3441 #include "clang/AST/TypeLocNodes.def"
   3442   }
   3443 
   3444   llvm_unreachable("unhandled type loc!");
   3445 }
   3446 
   3447 /// FIXME: By default, this routine adds type qualifiers only to types
   3448 /// that can have qualifiers, and silently suppresses those qualifiers
   3449 /// that are not permitted (e.g., qualifiers on reference or function
   3450 /// types). This is the right thing for template instantiation, but
   3451 /// probably not for other clients.
   3452 template<typename Derived>
   3453 QualType
   3454 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
   3455                                                QualifiedTypeLoc T) {
   3456   Qualifiers Quals = T.getType().getLocalQualifiers();
   3457 
   3458   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
   3459   if (Result.isNull())
   3460     return QualType();
   3461 
   3462   // Silently suppress qualifiers if the result type can't be qualified.
   3463   // FIXME: this is the right thing for template instantiation, but
   3464   // probably not for other clients.
   3465   if (Result->isFunctionType() || Result->isReferenceType())
   3466     return Result;
   3467 
   3468   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
   3469   // resulting type.
   3470   if (Quals.hasObjCLifetime()) {
   3471     if (!Result->isObjCLifetimeType() && !Result->isDependentType())
   3472       Quals.removeObjCLifetime();
   3473     else if (Result.getObjCLifetime()) {
   3474       // Objective-C ARC:
   3475       //   A lifetime qualifier applied to a substituted template parameter
   3476       //   overrides the lifetime qualifier from the template argument.
   3477       const AutoType *AutoTy;
   3478       if (const SubstTemplateTypeParmType *SubstTypeParam
   3479                                 = dyn_cast<SubstTemplateTypeParmType>(Result)) {
   3480         QualType Replacement = SubstTypeParam->getReplacementType();
   3481         Qualifiers Qs = Replacement.getQualifiers();
   3482         Qs.removeObjCLifetime();
   3483         Replacement
   3484           = SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(),
   3485                                              Qs);
   3486         Result = SemaRef.Context.getSubstTemplateTypeParmType(
   3487                                         SubstTypeParam->getReplacedParameter(),
   3488                                                               Replacement);
   3489         TLB.TypeWasModifiedSafely(Result);
   3490       } else if ((AutoTy = dyn_cast<AutoType>(Result)) && AutoTy->isDeduced()) {
   3491         // 'auto' types behave the same way as template parameters.
   3492         QualType Deduced = AutoTy->getDeducedType();
   3493         Qualifiers Qs = Deduced.getQualifiers();
   3494         Qs.removeObjCLifetime();
   3495         Deduced = SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(),
   3496                                                    Qs);
   3497         Result = SemaRef.Context.getAutoType(Deduced, AutoTy->isDecltypeAuto());
   3498         TLB.TypeWasModifiedSafely(Result);
   3499       } else {
   3500         // Otherwise, complain about the addition of a qualifier to an
   3501         // already-qualified type.
   3502         SourceRange R = T.getUnqualifiedLoc().getSourceRange();
   3503         SemaRef.Diag(R.getBegin(), diag::err_attr_objc_ownership_redundant)
   3504           << Result << R;
   3505 
   3506         Quals.removeObjCLifetime();
   3507       }
   3508     }
   3509   }
   3510   if (!Quals.empty()) {
   3511     Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
   3512     // BuildQualifiedType might not add qualifiers if they are invalid.
   3513     if (Result.hasLocalQualifiers())
   3514       TLB.push<QualifiedTypeLoc>(Result);
   3515     // No location information to preserve.
   3516   }
   3517 
   3518   return Result;
   3519 }
   3520 
   3521 template<typename Derived>
   3522 TypeLoc
   3523 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
   3524                                                    QualType ObjectType,
   3525                                                    NamedDecl *UnqualLookup,
   3526                                                    CXXScopeSpec &SS) {
   3527   QualType T = TL.getType();
   3528   if (getDerived().AlreadyTransformed(T))
   3529     return TL;
   3530 
   3531   TypeLocBuilder TLB;
   3532   QualType Result;
   3533 
   3534   if (isa<TemplateSpecializationType>(T)) {
   3535     TemplateSpecializationTypeLoc SpecTL =
   3536         TL.castAs<TemplateSpecializationTypeLoc>();
   3537 
   3538     TemplateName Template =
   3539       getDerived().TransformTemplateName(SS,
   3540                                          SpecTL.getTypePtr()->getTemplateName(),
   3541                                          SpecTL.getTemplateNameLoc(),
   3542                                          ObjectType, UnqualLookup);
   3543     if (Template.isNull())
   3544       return TypeLoc();
   3545 
   3546     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
   3547                                                               Template);
   3548   } else if (isa<DependentTemplateSpecializationType>(T)) {
   3549     DependentTemplateSpecializationTypeLoc SpecTL =
   3550         TL.castAs<DependentTemplateSpecializationTypeLoc>();
   3551 
   3552     TemplateName Template
   3553       = getDerived().RebuildTemplateName(SS,
   3554                                          *SpecTL.getTypePtr()->getIdentifier(),
   3555                                          SpecTL.getTemplateNameLoc(),
   3556                                          ObjectType, UnqualLookup);
   3557     if (Template.isNull())
   3558       return TypeLoc();
   3559 
   3560     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
   3561                                                                        SpecTL,
   3562                                                                      Template,
   3563                                                                        SS);
   3564   } else {
   3565     // Nothing special needs to be done for these.
   3566     Result = getDerived().TransformType(TLB, TL);
   3567   }
   3568 
   3569   if (Result.isNull())
   3570     return TypeLoc();
   3571 
   3572   return TLB.getTypeSourceInfo(SemaRef.Context, Result)->getTypeLoc();
   3573 }
   3574 
   3575 template<typename Derived>
   3576 TypeSourceInfo *
   3577 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
   3578                                                    QualType ObjectType,
   3579                                                    NamedDecl *UnqualLookup,
   3580                                                    CXXScopeSpec &SS) {
   3581   // FIXME: Painfully copy-paste from the above!
   3582 
   3583   QualType T = TSInfo->getType();
   3584   if (getDerived().AlreadyTransformed(T))
   3585     return TSInfo;
   3586 
   3587   TypeLocBuilder TLB;
   3588   QualType Result;
   3589 
   3590   TypeLoc TL = TSInfo->getTypeLoc();
   3591   if (isa<TemplateSpecializationType>(T)) {
   3592     TemplateSpecializationTypeLoc SpecTL =
   3593         TL.castAs<TemplateSpecializationTypeLoc>();
   3594 
   3595     TemplateName Template
   3596     = getDerived().TransformTemplateName(SS,
   3597                                          SpecTL.getTypePtr()->getTemplateName(),
   3598                                          SpecTL.getTemplateNameLoc(),
   3599                                          ObjectType, UnqualLookup);
   3600     if (Template.isNull())
   3601       return 0;
   3602 
   3603     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
   3604                                                               Template);
   3605   } else if (isa<DependentTemplateSpecializationType>(T)) {
   3606     DependentTemplateSpecializationTypeLoc SpecTL =
   3607         TL.castAs<DependentTemplateSpecializationTypeLoc>();
   3608 
   3609     TemplateName Template
   3610       = getDerived().RebuildTemplateName(SS,
   3611                                          *SpecTL.getTypePtr()->getIdentifier(),
   3612                                          SpecTL.getTemplateNameLoc(),
   3613                                          ObjectType, UnqualLookup);
   3614     if (Template.isNull())
   3615       return 0;
   3616 
   3617     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
   3618                                                                        SpecTL,
   3619                                                                        Template,
   3620                                                                        SS);
   3621   } else {
   3622     // Nothing special needs to be done for these.
   3623     Result = getDerived().TransformType(TLB, TL);
   3624   }
   3625 
   3626   if (Result.isNull())
   3627     return 0;
   3628 
   3629   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
   3630 }
   3631 
   3632 template <class TyLoc> static inline
   3633 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
   3634   TyLoc NewT = TLB.push<TyLoc>(T.getType());
   3635   NewT.setNameLoc(T.getNameLoc());
   3636   return T.getType();
   3637 }
   3638 
   3639 template<typename Derived>
   3640 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
   3641                                                       BuiltinTypeLoc T) {
   3642   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
   3643   NewT.setBuiltinLoc(T.getBuiltinLoc());
   3644   if (T.needsExtraLocalData())
   3645     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
   3646   return T.getType();
   3647 }
   3648 
   3649 template<typename Derived>
   3650 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
   3651                                                       ComplexTypeLoc T) {
   3652   // FIXME: recurse?
   3653   return TransformTypeSpecType(TLB, T);
   3654 }
   3655 
   3656 template<typename Derived>
   3657 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
   3658                                                       DecayedTypeLoc TL) {
   3659   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
   3660   if (OriginalType.isNull())
   3661     return QualType();
   3662 
   3663   QualType Result = TL.getType();
   3664   if (getDerived().AlwaysRebuild() ||
   3665       OriginalType != TL.getOriginalLoc().getType())
   3666     Result = SemaRef.Context.getDecayedType(OriginalType);
   3667   TLB.push<DecayedTypeLoc>(Result);
   3668   // Nothing to set for DecayedTypeLoc.
   3669   return Result;
   3670 }
   3671 
   3672 template<typename Derived>
   3673 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
   3674                                                       PointerTypeLoc TL) {
   3675   QualType PointeeType
   3676     = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3677   if (PointeeType.isNull())
   3678     return QualType();
   3679 
   3680   QualType Result = TL.getType();
   3681   if (PointeeType->getAs<ObjCObjectType>()) {
   3682     // A dependent pointer type 'T *' has is being transformed such
   3683     // that an Objective-C class type is being replaced for 'T'. The
   3684     // resulting pointer type is an ObjCObjectPointerType, not a
   3685     // PointerType.
   3686     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
   3687 
   3688     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
   3689     NewT.setStarLoc(TL.getStarLoc());
   3690     return Result;
   3691   }
   3692 
   3693   if (getDerived().AlwaysRebuild() ||
   3694       PointeeType != TL.getPointeeLoc().getType()) {
   3695     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
   3696     if (Result.isNull())
   3697       return QualType();
   3698   }
   3699 
   3700   // Objective-C ARC can add lifetime qualifiers to the type that we're
   3701   // pointing to.
   3702   TLB.TypeWasModifiedSafely(Result->getPointeeType());
   3703 
   3704   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
   3705   NewT.setSigilLoc(TL.getSigilLoc());
   3706   return Result;
   3707 }
   3708 
   3709 template<typename Derived>
   3710 QualType
   3711 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
   3712                                                   BlockPointerTypeLoc TL) {
   3713   QualType PointeeType
   3714     = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3715   if (PointeeType.isNull())
   3716     return QualType();
   3717 
   3718   QualType Result = TL.getType();
   3719   if (getDerived().AlwaysRebuild() ||
   3720       PointeeType != TL.getPointeeLoc().getType()) {
   3721     Result = getDerived().RebuildBlockPointerType(PointeeType,
   3722                                                   TL.getSigilLoc());
   3723     if (Result.isNull())
   3724       return QualType();
   3725   }
   3726 
   3727   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
   3728   NewT.setSigilLoc(TL.getSigilLoc());
   3729   return Result;
   3730 }
   3731 
   3732 /// Transforms a reference type.  Note that somewhat paradoxically we
   3733 /// don't care whether the type itself is an l-value type or an r-value
   3734 /// type;  we only care if the type was *written* as an l-value type
   3735 /// or an r-value type.
   3736 template<typename Derived>
   3737 QualType
   3738 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
   3739                                                ReferenceTypeLoc TL) {
   3740   const ReferenceType *T = TL.getTypePtr();
   3741 
   3742   // Note that this works with the pointee-as-written.
   3743   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3744   if (PointeeType.isNull())
   3745     return QualType();
   3746 
   3747   QualType Result = TL.getType();
   3748   if (getDerived().AlwaysRebuild() ||
   3749       PointeeType != T->getPointeeTypeAsWritten()) {
   3750     Result = getDerived().RebuildReferenceType(PointeeType,
   3751                                                T->isSpelledAsLValue(),
   3752                                                TL.getSigilLoc());
   3753     if (Result.isNull())
   3754       return QualType();
   3755   }
   3756 
   3757   // Objective-C ARC can add lifetime qualifiers to the type that we're
   3758   // referring to.
   3759   TLB.TypeWasModifiedSafely(
   3760                      Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
   3761 
   3762   // r-value references can be rebuilt as l-value references.
   3763   ReferenceTypeLoc NewTL;
   3764   if (isa<LValueReferenceType>(Result))
   3765     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
   3766   else
   3767     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
   3768   NewTL.setSigilLoc(TL.getSigilLoc());
   3769 
   3770   return Result;
   3771 }
   3772 
   3773 template<typename Derived>
   3774 QualType
   3775 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
   3776                                                  LValueReferenceTypeLoc TL) {
   3777   return TransformReferenceType(TLB, TL);
   3778 }
   3779 
   3780 template<typename Derived>
   3781 QualType
   3782 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
   3783                                                  RValueReferenceTypeLoc TL) {
   3784   return TransformReferenceType(TLB, TL);
   3785 }
   3786 
   3787 template<typename Derived>
   3788 QualType
   3789 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
   3790                                                    MemberPointerTypeLoc TL) {
   3791   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3792   if (PointeeType.isNull())
   3793     return QualType();
   3794 
   3795   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
   3796   TypeSourceInfo* NewClsTInfo = 0;
   3797   if (OldClsTInfo) {
   3798     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
   3799     if (!NewClsTInfo)
   3800       return QualType();
   3801   }
   3802 
   3803   const MemberPointerType *T = TL.getTypePtr();
   3804   QualType OldClsType = QualType(T->getClass(), 0);
   3805   QualType NewClsType;
   3806   if (NewClsTInfo)
   3807     NewClsType = NewClsTInfo->getType();
   3808   else {
   3809     NewClsType = getDerived().TransformType(OldClsType);
   3810     if (NewClsType.isNull())
   3811       return QualType();
   3812   }
   3813 
   3814   QualType Result = TL.getType();
   3815   if (getDerived().AlwaysRebuild() ||
   3816       PointeeType != T->getPointeeType() ||
   3817       NewClsType != OldClsType) {
   3818     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
   3819                                                    TL.getStarLoc());
   3820     if (Result.isNull())
   3821       return QualType();
   3822   }
   3823 
   3824   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
   3825   NewTL.setSigilLoc(TL.getSigilLoc());
   3826   NewTL.setClassTInfo(NewClsTInfo);
   3827 
   3828   return Result;
   3829 }
   3830 
   3831 template<typename Derived>
   3832 QualType
   3833 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
   3834                                                    ConstantArrayTypeLoc TL) {
   3835   const ConstantArrayType *T = TL.getTypePtr();
   3836   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3837   if (ElementType.isNull())
   3838     return QualType();
   3839 
   3840   QualType Result = TL.getType();
   3841   if (getDerived().AlwaysRebuild() ||
   3842       ElementType != T->getElementType()) {
   3843     Result = getDerived().RebuildConstantArrayType(ElementType,
   3844                                                    T->getSizeModifier(),
   3845                                                    T->getSize(),
   3846                                              T->getIndexTypeCVRQualifiers(),
   3847                                                    TL.getBracketsRange());
   3848     if (Result.isNull())
   3849       return QualType();
   3850   }
   3851 
   3852   // We might have either a ConstantArrayType or a VariableArrayType now:
   3853   // a ConstantArrayType is allowed to have an element type which is a
   3854   // VariableArrayType if the type is dependent.  Fortunately, all array
   3855   // types have the same location layout.
   3856   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
   3857   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3858   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3859 
   3860   Expr *Size = TL.getSizeExpr();
   3861   if (Size) {
   3862     EnterExpressionEvaluationContext Unevaluated(SemaRef,
   3863                                                  Sema::ConstantEvaluated);
   3864     Size = getDerived().TransformExpr(Size).template takeAs<Expr>();
   3865     Size = SemaRef.ActOnConstantExpression(Size).take();
   3866   }
   3867   NewTL.setSizeExpr(Size);
   3868 
   3869   return Result;
   3870 }
   3871 
   3872 template<typename Derived>
   3873 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
   3874                                               TypeLocBuilder &TLB,
   3875                                               IncompleteArrayTypeLoc TL) {
   3876   const IncompleteArrayType *T = TL.getTypePtr();
   3877   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3878   if (ElementType.isNull())
   3879     return QualType();
   3880 
   3881   QualType Result = TL.getType();
   3882   if (getDerived().AlwaysRebuild() ||
   3883       ElementType != T->getElementType()) {
   3884     Result = getDerived().RebuildIncompleteArrayType(ElementType,
   3885                                                      T->getSizeModifier(),
   3886                                            T->getIndexTypeCVRQualifiers(),
   3887                                                      TL.getBracketsRange());
   3888     if (Result.isNull())
   3889       return QualType();
   3890   }
   3891 
   3892   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
   3893   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3894   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3895   NewTL.setSizeExpr(0);
   3896 
   3897   return Result;
   3898 }
   3899 
   3900 template<typename Derived>
   3901 QualType
   3902 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
   3903                                                    VariableArrayTypeLoc TL) {
   3904   const VariableArrayType *T = TL.getTypePtr();
   3905   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3906   if (ElementType.isNull())
   3907     return QualType();
   3908 
   3909   ExprResult SizeResult
   3910     = getDerived().TransformExpr(T->getSizeExpr());
   3911   if (SizeResult.isInvalid())
   3912     return QualType();
   3913 
   3914   Expr *Size = SizeResult.take();
   3915 
   3916   QualType Result = TL.getType();
   3917   if (getDerived().AlwaysRebuild() ||
   3918       ElementType != T->getElementType() ||
   3919       Size != T->getSizeExpr()) {
   3920     Result = getDerived().RebuildVariableArrayType(ElementType,
   3921                                                    T->getSizeModifier(),
   3922                                                    Size,
   3923                                              T->getIndexTypeCVRQualifiers(),
   3924                                                    TL.getBracketsRange());
   3925     if (Result.isNull())
   3926       return QualType();
   3927   }
   3928 
   3929   VariableArrayTypeLoc NewTL = TLB.push<VariableArrayTypeLoc>(Result);
   3930   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3931   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3932   NewTL.setSizeExpr(Size);
   3933 
   3934   return Result;
   3935 }
   3936 
   3937 template<typename Derived>
   3938 QualType
   3939 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
   3940                                              DependentSizedArrayTypeLoc TL) {
   3941   const DependentSizedArrayType *T = TL.getTypePtr();
   3942   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3943   if (ElementType.isNull())
   3944     return QualType();
   3945 
   3946   // Array bounds are constant expressions.
   3947   EnterExpressionEvaluationContext Unevaluated(SemaRef,
   3948                                                Sema::ConstantEvaluated);
   3949 
   3950   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
   3951   Expr *origSize = TL.getSizeExpr();
   3952   if (!origSize) origSize = T->getSizeExpr();
   3953 
   3954   ExprResult sizeResult
   3955     = getDerived().TransformExpr(origSize);
   3956   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
   3957   if (sizeResult.isInvalid())
   3958     return QualType();
   3959 
   3960   Expr *size = sizeResult.get();
   3961 
   3962   QualType Result = TL.getType();
   3963   if (getDerived().AlwaysRebuild() ||
   3964       ElementType != T->getElementType() ||
   3965       size != origSize) {
   3966     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
   3967                                                          T->getSizeModifier(),
   3968                                                          size,
   3969                                                 T->getIndexTypeCVRQualifiers(),
   3970                                                         TL.getBracketsRange());
   3971     if (Result.isNull())
   3972       return QualType();
   3973   }
   3974 
   3975   // We might have any sort of array type now, but fortunately they
   3976   // all have the same location layout.
   3977   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
   3978   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3979   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3980   NewTL.setSizeExpr(size);
   3981 
   3982   return Result;
   3983 }
   3984 
   3985 template<typename Derived>
   3986 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
   3987                                       TypeLocBuilder &TLB,
   3988                                       DependentSizedExtVectorTypeLoc TL) {
   3989   const DependentSizedExtVectorType *T = TL.getTypePtr();
   3990 
   3991   // FIXME: ext vector locs should be nested
   3992   QualType ElementType = getDerived().TransformType(T->getElementType());
   3993   if (ElementType.isNull())
   3994     return QualType();
   3995 
   3996   // Vector sizes are constant expressions.
   3997   EnterExpressionEvaluationContext Unevaluated(SemaRef,
   3998                                                Sema::ConstantEvaluated);
   3999 
   4000   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
   4001   Size = SemaRef.ActOnConstantExpression(Size);
   4002   if (Size.isInvalid())
   4003     return QualType();
   4004 
   4005   QualType Result = TL.getType();
   4006   if (getDerived().AlwaysRebuild() ||
   4007       ElementType != T->getElementType() ||
   4008       Size.get() != T->getSizeExpr()) {
   4009     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
   4010                                                              Size.take(),
   4011                                                          T->getAttributeLoc());
   4012     if (Result.isNull())
   4013       return QualType();
   4014   }
   4015 
   4016   // Result might be dependent or not.
   4017   if (isa<DependentSizedExtVectorType>(Result)) {
   4018     DependentSizedExtVectorTypeLoc NewTL
   4019       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
   4020     NewTL.setNameLoc(TL.getNameLoc());
   4021   } else {
   4022     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
   4023     NewTL.setNameLoc(TL.getNameLoc());
   4024   }
   4025 
   4026   return Result;
   4027 }
   4028 
   4029 template<typename Derived>
   4030 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
   4031                                                      VectorTypeLoc TL) {
   4032   const VectorType *T = TL.getTypePtr();
   4033   QualType ElementType = getDerived().TransformType(T->getElementType());
   4034   if (ElementType.isNull())
   4035     return QualType();
   4036 
   4037   QualType Result = TL.getType();
   4038   if (getDerived().AlwaysRebuild() ||
   4039       ElementType != T->getElementType()) {
   4040     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
   4041                                             T->getVectorKind());
   4042     if (Result.isNull())
   4043       return QualType();
   4044   }
   4045 
   4046   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
   4047   NewTL.setNameLoc(TL.getNameLoc());
   4048 
   4049   return Result;
   4050 }
   4051 
   4052 template<typename Derived>
   4053 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
   4054                                                         ExtVectorTypeLoc TL) {
   4055   const VectorType *T = TL.getTypePtr();
   4056   QualType ElementType = getDerived().TransformType(T->getElementType());
   4057   if (ElementType.isNull())
   4058     return QualType();
   4059 
   4060   QualType Result = TL.getType();
   4061   if (getDerived().AlwaysRebuild() ||
   4062       ElementType != T->getElementType()) {
   4063     Result = getDerived().RebuildExtVectorType(ElementType,
   4064                                                T->getNumElements(),
   4065                                                /*FIXME*/ SourceLocation());
   4066     if (Result.isNull())
   4067       return QualType();
   4068   }
   4069 
   4070   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
   4071   NewTL.setNameLoc(TL.getNameLoc());
   4072 
   4073   return Result;
   4074 }
   4075 
   4076 template <typename Derived>
   4077 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
   4078     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
   4079     bool ExpectParameterPack) {
   4080   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
   4081   TypeSourceInfo *NewDI = 0;
   4082 
   4083   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
   4084     // If we're substituting into a pack expansion type and we know the
   4085     // length we want to expand to, just substitute for the pattern.
   4086     TypeLoc OldTL = OldDI->getTypeLoc();
   4087     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
   4088 
   4089     TypeLocBuilder TLB;
   4090     TypeLoc NewTL = OldDI->getTypeLoc();
   4091     TLB.reserve(NewTL.getFullDataSize());
   4092 
   4093     QualType Result = getDerived().TransformType(TLB,
   4094                                                OldExpansionTL.getPatternLoc());
   4095     if (Result.isNull())
   4096       return 0;
   4097 
   4098     Result = RebuildPackExpansionType(Result,
   4099                                 OldExpansionTL.getPatternLoc().getSourceRange(),
   4100                                       OldExpansionTL.getEllipsisLoc(),
   4101                                       NumExpansions);
   4102     if (Result.isNull())
   4103       return 0;
   4104 
   4105     PackExpansionTypeLoc NewExpansionTL
   4106       = TLB.push<PackExpansionTypeLoc>(Result);
   4107     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
   4108     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
   4109   } else
   4110     NewDI = getDerived().TransformType(OldDI);
   4111   if (!NewDI)
   4112     return 0;
   4113 
   4114   if (NewDI == OldDI && indexAdjustment == 0)
   4115     return OldParm;
   4116 
   4117   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
   4118                                              OldParm->getDeclContext(),
   4119                                              OldParm->getInnerLocStart(),
   4120                                              OldParm->getLocation(),
   4121                                              OldParm->getIdentifier(),
   4122                                              NewDI->getType(),
   4123                                              NewDI,
   4124                                              OldParm->getStorageClass(),
   4125                                              /* DefArg */ NULL);
   4126   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
   4127                         OldParm->getFunctionScopeIndex() + indexAdjustment);
   4128   return newParm;
   4129 }
   4130 
   4131 template<typename Derived>
   4132 bool TreeTransform<Derived>::
   4133   TransformFunctionTypeParams(SourceLocation Loc,
   4134                               ParmVarDecl **Params, unsigned NumParams,
   4135                               const QualType *ParamTypes,
   4136                               SmallVectorImpl<QualType> &OutParamTypes,
   4137                               SmallVectorImpl<ParmVarDecl*> *PVars) {
   4138   int indexAdjustment = 0;
   4139 
   4140   for (unsigned i = 0; i != NumParams; ++i) {
   4141     if (ParmVarDecl *OldParm = Params[i]) {
   4142       assert(OldParm->getFunctionScopeIndex() == i);
   4143 
   4144       Optional<unsigned> NumExpansions;
   4145       ParmVarDecl *NewParm = 0;
   4146       if (OldParm->isParameterPack()) {
   4147         // We have a function parameter pack that may need to be expanded.
   4148         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   4149 
   4150         // Find the parameter packs that could be expanded.
   4151         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
   4152         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
   4153         TypeLoc Pattern = ExpansionTL.getPatternLoc();
   4154         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
   4155         assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
   4156 
   4157         // Determine whether we should expand the parameter packs.
   4158         bool ShouldExpand = false;
   4159         bool RetainExpansion = false;
   4160         Optional<unsigned> OrigNumExpansions =
   4161             ExpansionTL.getTypePtr()->getNumExpansions();
   4162         NumExpansions = OrigNumExpansions;
   4163         if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
   4164                                                  Pattern.getSourceRange(),
   4165                                                  Unexpanded,
   4166                                                  ShouldExpand,
   4167                                                  RetainExpansion,
   4168                                                  NumExpansions)) {
   4169           return true;
   4170         }
   4171 
   4172         if (ShouldExpand) {
   4173           // Expand the function parameter pack into multiple, separate
   4174           // parameters.
   4175           getDerived().ExpandingFunctionParameterPack(OldParm);
   4176           for (unsigned I = 0; I != *NumExpansions; ++I) {
   4177             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   4178             ParmVarDecl *NewParm
   4179               = getDerived().TransformFunctionTypeParam(OldParm,
   4180                                                         indexAdjustment++,
   4181                                                         OrigNumExpansions,
   4182                                                 /*ExpectParameterPack=*/false);
   4183             if (!NewParm)
   4184               return true;
   4185 
   4186             OutParamTypes.push_back(NewParm->getType());
   4187             if (PVars)
   4188               PVars->push_back(NewParm);
   4189           }
   4190 
   4191           // If we're supposed to retain a pack expansion, do so by temporarily
   4192           // forgetting the partially-substituted parameter pack.
   4193           if (RetainExpansion) {
   4194             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   4195             ParmVarDecl *NewParm
   4196               = getDerived().TransformFunctionTypeParam(OldParm,
   4197                                                         indexAdjustment++,
   4198                                                         OrigNumExpansions,
   4199                                                 /*ExpectParameterPack=*/false);
   4200             if (!NewParm)
   4201               return true;
   4202 
   4203             OutParamTypes.push_back(NewParm->getType());
   4204             if (PVars)
   4205               PVars->push_back(NewParm);
   4206           }
   4207 
   4208           // The next parameter should have the same adjustment as the
   4209           // last thing we pushed, but we post-incremented indexAdjustment
   4210           // on every push.  Also, if we push nothing, the adjustment should
   4211           // go down by one.
   4212           indexAdjustment--;
   4213 
   4214           // We're done with the pack expansion.
   4215           continue;
   4216         }
   4217 
   4218         // We'll substitute the parameter now without expanding the pack
   4219         // expansion.
   4220         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   4221         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
   4222                                                           indexAdjustment,
   4223                                                           NumExpansions,
   4224                                                   /*ExpectParameterPack=*/true);
   4225       } else {
   4226         NewParm = getDerived().TransformFunctionTypeParam(
   4227             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
   4228       }
   4229 
   4230       if (!NewParm)
   4231         return true;
   4232 
   4233       OutParamTypes.push_back(NewParm->getType());
   4234       if (PVars)
   4235         PVars->push_back(NewParm);
   4236       continue;
   4237     }
   4238 
   4239     // Deal with the possibility that we don't have a parameter
   4240     // declaration for this parameter.
   4241     QualType OldType = ParamTypes[i];
   4242     bool IsPackExpansion = false;
   4243     Optional<unsigned> NumExpansions;
   4244     QualType NewType;
   4245     if (const PackExpansionType *Expansion
   4246                                        = dyn_cast<PackExpansionType>(OldType)) {
   4247       // We have a function parameter pack that may need to be expanded.
   4248       QualType Pattern = Expansion->getPattern();
   4249       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   4250       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   4251 
   4252       // Determine whether we should expand the parameter packs.
   4253       bool ShouldExpand = false;
   4254       bool RetainExpansion = false;
   4255       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
   4256                                                Unexpanded,
   4257                                                ShouldExpand,
   4258                                                RetainExpansion,
   4259                                                NumExpansions)) {
   4260         return true;
   4261       }
   4262 
   4263       if (ShouldExpand) {
   4264         // Expand the function parameter pack into multiple, separate
   4265         // parameters.
   4266         for (unsigned I = 0; I != *NumExpansions; ++I) {
   4267           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   4268           QualType NewType = getDerived().TransformType(Pattern);
   4269           if (NewType.isNull())
   4270             return true;
   4271 
   4272           OutParamTypes.push_back(NewType);
   4273           if (PVars)
   4274             PVars->push_back(0);
   4275         }
   4276 
   4277         // We're done with the pack expansion.
   4278         continue;
   4279       }
   4280 
   4281       // If we're supposed to retain a pack expansion, do so by temporarily
   4282       // forgetting the partially-substituted parameter pack.
   4283       if (RetainExpansion) {
   4284         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   4285         QualType NewType = getDerived().TransformType(Pattern);
   4286         if (NewType.isNull())
   4287           return true;
   4288 
   4289         OutParamTypes.push_back(NewType);
   4290         if (PVars)
   4291           PVars->push_back(0);
   4292       }
   4293 
   4294       // We'll substitute the parameter now without expanding the pack
   4295       // expansion.
   4296       OldType = Expansion->getPattern();
   4297       IsPackExpansion = true;
   4298       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   4299       NewType = getDerived().TransformType(OldType);
   4300     } else {
   4301       NewType = getDerived().TransformType(OldType);
   4302     }
   4303 
   4304     if (NewType.isNull())
   4305       return true;
   4306 
   4307     if (IsPackExpansion)
   4308       NewType = getSema().Context.getPackExpansionType(NewType,
   4309                                                        NumExpansions);
   4310 
   4311     OutParamTypes.push_back(NewType);
   4312     if (PVars)
   4313       PVars->push_back(0);
   4314   }
   4315 
   4316 #ifndef NDEBUG
   4317   if (PVars) {
   4318     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
   4319       if (ParmVarDecl *parm = (*PVars)[i])
   4320         assert(parm->getFunctionScopeIndex() == i);
   4321   }
   4322 #endif
   4323 
   4324   return false;
   4325 }
   4326 
   4327 template<typename Derived>
   4328 QualType
   4329 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
   4330                                                    FunctionProtoTypeLoc TL) {
   4331   return getDerived().TransformFunctionProtoType(TLB, TL, 0, 0);
   4332 }
   4333 
   4334 template<typename Derived>
   4335 QualType
   4336 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
   4337                                                    FunctionProtoTypeLoc TL,
   4338                                                    CXXRecordDecl *ThisContext,
   4339                                                    unsigned ThisTypeQuals) {
   4340   // Transform the parameters and return type.
   4341   //
   4342   // We are required to instantiate the params and return type in source order.
   4343   // When the function has a trailing return type, we instantiate the
   4344   // parameters before the return type,  since the return type can then refer
   4345   // to the parameters themselves (via decltype, sizeof, etc.).
   4346   //
   4347   SmallVector<QualType, 4> ParamTypes;
   4348   SmallVector<ParmVarDecl*, 4> ParamDecls;
   4349   const FunctionProtoType *T = TL.getTypePtr();
   4350 
   4351   QualType ResultType;
   4352 
   4353   if (T->hasTrailingReturn()) {
   4354     if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
   4355                                                  TL.getParmArray(),
   4356                                                  TL.getNumArgs(),
   4357                                              TL.getTypePtr()->arg_type_begin(),
   4358                                                  ParamTypes, &ParamDecls))
   4359       return QualType();
   4360 
   4361     {
   4362       // C++11 [expr.prim.general]p3:
   4363       //   If a declaration declares a member function or member function
   4364       //   template of a class X, the expression this is a prvalue of type
   4365       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
   4366       //   and the end of the function-definition, member-declarator, or
   4367       //   declarator.
   4368       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
   4369 
   4370       ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
   4371       if (ResultType.isNull())
   4372         return QualType();
   4373     }
   4374   }
   4375   else {
   4376     ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
   4377     if (ResultType.isNull())
   4378       return QualType();
   4379 
   4380     if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
   4381                                                  TL.getParmArray(),
   4382                                                  TL.getNumArgs(),
   4383                                              TL.getTypePtr()->arg_type_begin(),
   4384                                                  ParamTypes, &ParamDecls))
   4385       return QualType();
   4386   }
   4387 
   4388   // FIXME: Need to transform the exception-specification too.
   4389 
   4390   QualType Result = TL.getType();
   4391   if (getDerived().AlwaysRebuild() ||
   4392       ResultType != T->getResultType() ||
   4393       T->getNumArgs() != ParamTypes.size() ||
   4394       !std::equal(T->arg_type_begin(), T->arg_type_end(), ParamTypes.begin())) {
   4395     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes,
   4396                                                    T->getExtProtoInfo());
   4397     if (Result.isNull())
   4398       return QualType();
   4399   }
   4400 
   4401   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
   4402   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
   4403   NewTL.setLParenLoc(TL.getLParenLoc());
   4404   NewTL.setRParenLoc(TL.getRParenLoc());
   4405   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
   4406   for (unsigned i = 0, e = NewTL.getNumArgs(); i != e; ++i)
   4407     NewTL.setArg(i, ParamDecls[i]);
   4408 
   4409   return Result;
   4410 }
   4411 
   4412 template<typename Derived>
   4413 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
   4414                                                  TypeLocBuilder &TLB,
   4415                                                  FunctionNoProtoTypeLoc TL) {
   4416   const FunctionNoProtoType *T = TL.getTypePtr();
   4417   QualType ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
   4418   if (ResultType.isNull())
   4419     return QualType();
   4420 
   4421   QualType Result = TL.getType();
   4422   if (getDerived().AlwaysRebuild() ||
   4423       ResultType != T->getResultType())
   4424     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
   4425 
   4426   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
   4427   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
   4428   NewTL.setLParenLoc(TL.getLParenLoc());
   4429   NewTL.setRParenLoc(TL.getRParenLoc());
   4430   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
   4431 
   4432   return Result;
   4433 }
   4434 
   4435 template<typename Derived> QualType
   4436 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
   4437                                                  UnresolvedUsingTypeLoc TL) {
   4438   const UnresolvedUsingType *T = TL.getTypePtr();
   4439   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
   4440   if (!D)
   4441     return QualType();
   4442 
   4443   QualType Result = TL.getType();
   4444   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
   4445     Result = getDerived().RebuildUnresolvedUsingType(D);
   4446     if (Result.isNull())
   4447       return QualType();
   4448   }
   4449 
   4450   // We might get an arbitrary type spec type back.  We should at
   4451   // least always get a type spec type, though.
   4452   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
   4453   NewTL.setNameLoc(TL.getNameLoc());
   4454 
   4455   return Result;
   4456 }
   4457 
   4458 template<typename Derived>
   4459 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
   4460                                                       TypedefTypeLoc TL) {
   4461   const TypedefType *T = TL.getTypePtr();
   4462   TypedefNameDecl *Typedef
   4463     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   4464                                                                T->getDecl()));
   4465   if (!Typedef)
   4466     return QualType();
   4467 
   4468   QualType Result = TL.getType();
   4469   if (getDerived().AlwaysRebuild() ||
   4470       Typedef != T->getDecl()) {
   4471     Result = getDerived().RebuildTypedefType(Typedef);
   4472     if (Result.isNull())
   4473       return QualType();
   4474   }
   4475 
   4476   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
   4477   NewTL.setNameLoc(TL.getNameLoc());
   4478 
   4479   return Result;
   4480 }
   4481 
   4482 template<typename Derived>
   4483 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
   4484                                                       TypeOfExprTypeLoc TL) {
   4485   // typeof expressions are not potentially evaluated contexts
   4486   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
   4487                                                Sema::ReuseLambdaContextDecl);
   4488 
   4489   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
   4490   if (E.isInvalid())
   4491     return QualType();
   4492 
   4493   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
   4494   if (E.isInvalid())
   4495     return QualType();
   4496 
   4497   QualType Result = TL.getType();
   4498   if (getDerived().AlwaysRebuild() ||
   4499       E.get() != TL.getUnderlyingExpr()) {
   4500     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
   4501     if (Result.isNull())
   4502       return QualType();
   4503   }
   4504   else E.take();
   4505 
   4506   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
   4507   NewTL.setTypeofLoc(TL.getTypeofLoc());
   4508   NewTL.setLParenLoc(TL.getLParenLoc());
   4509   NewTL.setRParenLoc(TL.getRParenLoc());
   4510 
   4511   return Result;
   4512 }
   4513 
   4514 template<typename Derived>
   4515 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
   4516                                                      TypeOfTypeLoc TL) {
   4517   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
   4518   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
   4519   if (!New_Under_TI)
   4520     return QualType();
   4521 
   4522   QualType Result = TL.getType();
   4523   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
   4524     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
   4525     if (Result.isNull())
   4526       return QualType();
   4527   }
   4528 
   4529   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
   4530   NewTL.setTypeofLoc(TL.getTypeofLoc());
   4531   NewTL.setLParenLoc(TL.getLParenLoc());
   4532   NewTL.setRParenLoc(TL.getRParenLoc());
   4533   NewTL.setUnderlyingTInfo(New_Under_TI);
   4534 
   4535   return Result;
   4536 }
   4537 
   4538 template<typename Derived>
   4539 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
   4540                                                        DecltypeTypeLoc TL) {
   4541   const DecltypeType *T = TL.getTypePtr();
   4542 
   4543   // decltype expressions are not potentially evaluated contexts
   4544   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated, 0,
   4545                                                /*IsDecltype=*/ true);
   4546 
   4547   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
   4548   if (E.isInvalid())
   4549     return QualType();
   4550 
   4551   E = getSema().ActOnDecltypeExpression(E.take());
   4552   if (E.isInvalid())
   4553     return QualType();
   4554 
   4555   QualType Result = TL.getType();
   4556   if (getDerived().AlwaysRebuild() ||
   4557       E.get() != T->getUnderlyingExpr()) {
   4558     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
   4559     if (Result.isNull())
   4560       return QualType();
   4561   }
   4562   else E.take();
   4563 
   4564   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
   4565   NewTL.setNameLoc(TL.getNameLoc());
   4566 
   4567   return Result;
   4568 }
   4569 
   4570 template<typename Derived>
   4571 QualType TreeTransform<Derived>::TransformUnaryTransformType(
   4572                                                             TypeLocBuilder &TLB,
   4573                                                      UnaryTransformTypeLoc TL) {
   4574   QualType Result = TL.getType();
   4575   if (Result->isDependentType()) {
   4576     const UnaryTransformType *T = TL.getTypePtr();
   4577     QualType NewBase =
   4578       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
   4579     Result = getDerived().RebuildUnaryTransformType(NewBase,
   4580                                                     T->getUTTKind(),
   4581                                                     TL.getKWLoc());
   4582     if (Result.isNull())
   4583       return QualType();
   4584   }
   4585 
   4586   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
   4587   NewTL.setKWLoc(TL.getKWLoc());
   4588   NewTL.setParensRange(TL.getParensRange());
   4589   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
   4590   return Result;
   4591 }
   4592 
   4593 template<typename Derived>
   4594 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
   4595                                                    AutoTypeLoc TL) {
   4596   const AutoType *T = TL.getTypePtr();
   4597   QualType OldDeduced = T->getDeducedType();
   4598   QualType NewDeduced;
   4599   if (!OldDeduced.isNull()) {
   4600     NewDeduced = getDerived().TransformType(OldDeduced);
   4601     if (NewDeduced.isNull())
   4602       return QualType();
   4603   }
   4604 
   4605   QualType Result = TL.getType();
   4606   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
   4607       T->isDependentType()) {
   4608     Result = getDerived().RebuildAutoType(NewDeduced, T->isDecltypeAuto());
   4609     if (Result.isNull())
   4610       return QualType();
   4611   }
   4612 
   4613   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
   4614   NewTL.setNameLoc(TL.getNameLoc());
   4615 
   4616   return Result;
   4617 }
   4618 
   4619 template<typename Derived>
   4620 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
   4621                                                      RecordTypeLoc TL) {
   4622   const RecordType *T = TL.getTypePtr();
   4623   RecordDecl *Record
   4624     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   4625                                                           T->getDecl()));
   4626   if (!Record)
   4627     return QualType();
   4628 
   4629   QualType Result = TL.getType();
   4630   if (getDerived().AlwaysRebuild() ||
   4631       Record != T->getDecl()) {
   4632     Result = getDerived().RebuildRecordType(Record);
   4633     if (Result.isNull())
   4634       return QualType();
   4635   }
   4636 
   4637   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
   4638   NewTL.setNameLoc(TL.getNameLoc());
   4639 
   4640   return Result;
   4641 }
   4642 
   4643 template<typename Derived>
   4644 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
   4645                                                    EnumTypeLoc TL) {
   4646   const EnumType *T = TL.getTypePtr();
   4647   EnumDecl *Enum
   4648     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   4649                                                         T->getDecl()));
   4650   if (!Enum)
   4651     return QualType();
   4652 
   4653   QualType Result = TL.getType();
   4654   if (getDerived().AlwaysRebuild() ||
   4655       Enum != T->getDecl()) {
   4656     Result = getDerived().RebuildEnumType(Enum);
   4657     if (Result.isNull())
   4658       return QualType();
   4659   }
   4660 
   4661   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
   4662   NewTL.setNameLoc(TL.getNameLoc());
   4663 
   4664   return Result;
   4665 }
   4666 
   4667 template<typename Derived>
   4668 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
   4669                                          TypeLocBuilder &TLB,
   4670                                          InjectedClassNameTypeLoc TL) {
   4671   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
   4672                                        TL.getTypePtr()->getDecl());
   4673   if (!D) return QualType();
   4674 
   4675   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
   4676   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
   4677   return T;
   4678 }
   4679 
   4680 template<typename Derived>
   4681 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
   4682                                                 TypeLocBuilder &TLB,
   4683                                                 TemplateTypeParmTypeLoc TL) {
   4684   return TransformTypeSpecType(TLB, TL);
   4685 }
   4686 
   4687 template<typename Derived>
   4688 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
   4689                                          TypeLocBuilder &TLB,
   4690                                          SubstTemplateTypeParmTypeLoc TL) {
   4691   const SubstTemplateTypeParmType *T = TL.getTypePtr();
   4692 
   4693   // Substitute into the replacement type, which itself might involve something
   4694   // that needs to be transformed. This only tends to occur with default
   4695   // template arguments of template template parameters.
   4696   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
   4697   QualType Replacement = getDerived().TransformType(T->getReplacementType());
   4698   if (Replacement.isNull())
   4699     return QualType();
   4700 
   4701   // Always canonicalize the replacement type.
   4702   Replacement = SemaRef.Context.getCanonicalType(Replacement);
   4703   QualType Result
   4704     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
   4705                                                    Replacement);
   4706 
   4707   // Propagate type-source information.
   4708   SubstTemplateTypeParmTypeLoc NewTL
   4709     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
   4710   NewTL.setNameLoc(TL.getNameLoc());
   4711   return Result;
   4712 
   4713 }
   4714 
   4715 template<typename Derived>
   4716 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
   4717                                           TypeLocBuilder &TLB,
   4718                                           SubstTemplateTypeParmPackTypeLoc TL) {
   4719   return TransformTypeSpecType(TLB, TL);
   4720 }
   4721 
   4722 template<typename Derived>
   4723 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
   4724                                                         TypeLocBuilder &TLB,
   4725                                            TemplateSpecializationTypeLoc TL) {
   4726   const TemplateSpecializationType *T = TL.getTypePtr();
   4727 
   4728   // The nested-name-specifier never matters in a TemplateSpecializationType,
   4729   // because we can't have a dependent nested-name-specifier anyway.
   4730   CXXScopeSpec SS;
   4731   TemplateName Template
   4732     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
   4733                                          TL.getTemplateNameLoc());
   4734   if (Template.isNull())
   4735     return QualType();
   4736 
   4737   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
   4738 }
   4739 
   4740 template<typename Derived>
   4741 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
   4742                                                      AtomicTypeLoc TL) {
   4743   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
   4744   if (ValueType.isNull())
   4745     return QualType();
   4746 
   4747   QualType Result = TL.getType();
   4748   if (getDerived().AlwaysRebuild() ||
   4749       ValueType != TL.getValueLoc().getType()) {
   4750     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
   4751     if (Result.isNull())
   4752       return QualType();
   4753   }
   4754 
   4755   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
   4756   NewTL.setKWLoc(TL.getKWLoc());
   4757   NewTL.setLParenLoc(TL.getLParenLoc());
   4758   NewTL.setRParenLoc(TL.getRParenLoc());
   4759 
   4760   return Result;
   4761 }
   4762 
   4763   /// \brief Simple iterator that traverses the template arguments in a
   4764   /// container that provides a \c getArgLoc() member function.
   4765   ///
   4766   /// This iterator is intended to be used with the iterator form of
   4767   /// \c TreeTransform<Derived>::TransformTemplateArguments().
   4768   template<typename ArgLocContainer>
   4769   class TemplateArgumentLocContainerIterator {
   4770     ArgLocContainer *Container;
   4771     unsigned Index;
   4772 
   4773   public:
   4774     typedef TemplateArgumentLoc value_type;
   4775     typedef TemplateArgumentLoc reference;
   4776     typedef int difference_type;
   4777     typedef std::input_iterator_tag iterator_category;
   4778 
   4779     class pointer {
   4780       TemplateArgumentLoc Arg;
   4781 
   4782     public:
   4783       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
   4784 
   4785       const TemplateArgumentLoc *operator->() const {
   4786         return &Arg;
   4787       }
   4788     };
   4789 
   4790 
   4791     TemplateArgumentLocContainerIterator() {}
   4792 
   4793     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
   4794                                  unsigned Index)
   4795       : Container(&Container), Index(Index) { }
   4796 
   4797     TemplateArgumentLocContainerIterator &operator++() {
   4798       ++Index;
   4799       return *this;
   4800     }
   4801 
   4802     TemplateArgumentLocContainerIterator operator++(int) {
   4803       TemplateArgumentLocContainerIterator Old(*this);
   4804       ++(*this);
   4805       return Old;
   4806     }
   4807 
   4808     TemplateArgumentLoc operator*() const {
   4809       return Container->getArgLoc(Index);
   4810     }
   4811 
   4812     pointer operator->() const {
   4813       return pointer(Container->getArgLoc(Index));
   4814     }
   4815 
   4816     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
   4817                            const TemplateArgumentLocContainerIterator &Y) {
   4818       return X.Container == Y.Container && X.Index == Y.Index;
   4819     }
   4820 
   4821     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
   4822                            const TemplateArgumentLocContainerIterator &Y) {
   4823       return !(X == Y);
   4824     }
   4825   };
   4826 
   4827 
   4828 template <typename Derived>
   4829 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
   4830                                                         TypeLocBuilder &TLB,
   4831                                            TemplateSpecializationTypeLoc TL,
   4832                                                       TemplateName Template) {
   4833   TemplateArgumentListInfo NewTemplateArgs;
   4834   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   4835   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   4836   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
   4837     ArgIterator;
   4838   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   4839                                               ArgIterator(TL, TL.getNumArgs()),
   4840                                               NewTemplateArgs))
   4841     return QualType();
   4842 
   4843   // FIXME: maybe don't rebuild if all the template arguments are the same.
   4844 
   4845   QualType Result =
   4846     getDerived().RebuildTemplateSpecializationType(Template,
   4847                                                    TL.getTemplateNameLoc(),
   4848                                                    NewTemplateArgs);
   4849 
   4850   if (!Result.isNull()) {
   4851     // Specializations of template template parameters are represented as
   4852     // TemplateSpecializationTypes, and substitution of type alias templates
   4853     // within a dependent context can transform them into
   4854     // DependentTemplateSpecializationTypes.
   4855     if (isa<DependentTemplateSpecializationType>(Result)) {
   4856       DependentTemplateSpecializationTypeLoc NewTL
   4857         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   4858       NewTL.setElaboratedKeywordLoc(SourceLocation());
   4859       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
   4860       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   4861       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   4862       NewTL.setLAngleLoc(TL.getLAngleLoc());
   4863       NewTL.setRAngleLoc(TL.getRAngleLoc());
   4864       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4865         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4866       return Result;
   4867     }
   4868 
   4869     TemplateSpecializationTypeLoc NewTL
   4870       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   4871     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   4872     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   4873     NewTL.setLAngleLoc(TL.getLAngleLoc());
   4874     NewTL.setRAngleLoc(TL.getRAngleLoc());
   4875     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4876       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4877   }
   4878 
   4879   return Result;
   4880 }
   4881 
   4882 template <typename Derived>
   4883 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
   4884                                      TypeLocBuilder &TLB,
   4885                                      DependentTemplateSpecializationTypeLoc TL,
   4886                                      TemplateName Template,
   4887                                      CXXScopeSpec &SS) {
   4888   TemplateArgumentListInfo NewTemplateArgs;
   4889   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   4890   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   4891   typedef TemplateArgumentLocContainerIterator<
   4892             DependentTemplateSpecializationTypeLoc> ArgIterator;
   4893   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   4894                                               ArgIterator(TL, TL.getNumArgs()),
   4895                                               NewTemplateArgs))
   4896     return QualType();
   4897 
   4898   // FIXME: maybe don't rebuild if all the template arguments are the same.
   4899 
   4900   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
   4901     QualType Result
   4902       = getSema().Context.getDependentTemplateSpecializationType(
   4903                                                 TL.getTypePtr()->getKeyword(),
   4904                                                          DTN->getQualifier(),
   4905                                                          DTN->getIdentifier(),
   4906                                                                NewTemplateArgs);
   4907 
   4908     DependentTemplateSpecializationTypeLoc NewTL
   4909       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   4910     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   4911     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
   4912     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   4913     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   4914     NewTL.setLAngleLoc(TL.getLAngleLoc());
   4915     NewTL.setRAngleLoc(TL.getRAngleLoc());
   4916     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4917       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4918     return Result;
   4919   }
   4920 
   4921   QualType Result
   4922     = getDerived().RebuildTemplateSpecializationType(Template,
   4923                                                      TL.getTemplateNameLoc(),
   4924                                                      NewTemplateArgs);
   4925 
   4926   if (!Result.isNull()) {
   4927     /// FIXME: Wrap this in an elaborated-type-specifier?
   4928     TemplateSpecializationTypeLoc NewTL
   4929       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   4930     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   4931     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   4932     NewTL.setLAngleLoc(TL.getLAngleLoc());
   4933     NewTL.setRAngleLoc(TL.getRAngleLoc());
   4934     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4935       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4936   }
   4937 
   4938   return Result;
   4939 }
   4940 
   4941 template<typename Derived>
   4942 QualType
   4943 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
   4944                                                 ElaboratedTypeLoc TL) {
   4945   const ElaboratedType *T = TL.getTypePtr();
   4946 
   4947   NestedNameSpecifierLoc QualifierLoc;
   4948   // NOTE: the qualifier in an ElaboratedType is optional.
   4949   if (TL.getQualifierLoc()) {
   4950     QualifierLoc
   4951       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   4952     if (!QualifierLoc)
   4953       return QualType();
   4954   }
   4955 
   4956   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
   4957   if (NamedT.isNull())
   4958     return QualType();
   4959 
   4960   // C++0x [dcl.type.elab]p2:
   4961   //   If the identifier resolves to a typedef-name or the simple-template-id
   4962   //   resolves to an alias template specialization, the
   4963   //   elaborated-type-specifier is ill-formed.
   4964   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
   4965     if (const TemplateSpecializationType *TST =
   4966           NamedT->getAs<TemplateSpecializationType>()) {
   4967       TemplateName Template = TST->getTemplateName();
   4968       if (TypeAliasTemplateDecl *TAT =
   4969           dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
   4970         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
   4971                      diag::err_tag_reference_non_tag) << 4;
   4972         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
   4973       }
   4974     }
   4975   }
   4976 
   4977   QualType Result = TL.getType();
   4978   if (getDerived().AlwaysRebuild() ||
   4979       QualifierLoc != TL.getQualifierLoc() ||
   4980       NamedT != T->getNamedType()) {
   4981     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
   4982                                                 T->getKeyword(),
   4983                                                 QualifierLoc, NamedT);
   4984     if (Result.isNull())
   4985       return QualType();
   4986   }
   4987 
   4988   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   4989   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   4990   NewTL.setQualifierLoc(QualifierLoc);
   4991   return Result;
   4992 }
   4993 
   4994 template<typename Derived>
   4995 QualType TreeTransform<Derived>::TransformAttributedType(
   4996                                                 TypeLocBuilder &TLB,
   4997                                                 AttributedTypeLoc TL) {
   4998   const AttributedType *oldType = TL.getTypePtr();
   4999   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
   5000   if (modifiedType.isNull())
   5001     return QualType();
   5002 
   5003   QualType result = TL.getType();
   5004 
   5005   // FIXME: dependent operand expressions?
   5006   if (getDerived().AlwaysRebuild() ||
   5007       modifiedType != oldType->getModifiedType()) {
   5008     // TODO: this is really lame; we should really be rebuilding the
   5009     // equivalent type from first principles.
   5010     QualType equivalentType
   5011       = getDerived().TransformType(oldType->getEquivalentType());
   5012     if (equivalentType.isNull())
   5013       return QualType();
   5014     result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
   5015                                                modifiedType,
   5016                                                equivalentType);
   5017   }
   5018 
   5019   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
   5020   newTL.setAttrNameLoc(TL.getAttrNameLoc());
   5021   if (TL.hasAttrOperand())
   5022     newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
   5023   if (TL.hasAttrExprOperand())
   5024     newTL.setAttrExprOperand(TL.getAttrExprOperand());
   5025   else if (TL.hasAttrEnumOperand())
   5026     newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
   5027 
   5028   return result;
   5029 }
   5030 
   5031 template<typename Derived>
   5032 QualType
   5033 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
   5034                                            ParenTypeLoc TL) {
   5035   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
   5036   if (Inner.isNull())
   5037     return QualType();
   5038 
   5039   QualType Result = TL.getType();
   5040   if (getDerived().AlwaysRebuild() ||
   5041       Inner != TL.getInnerLoc().getType()) {
   5042     Result = getDerived().RebuildParenType(Inner);
   5043     if (Result.isNull())
   5044       return QualType();
   5045   }
   5046 
   5047   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
   5048   NewTL.setLParenLoc(TL.getLParenLoc());
   5049   NewTL.setRParenLoc(TL.getRParenLoc());
   5050   return Result;
   5051 }
   5052 
   5053 template<typename Derived>
   5054 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
   5055                                                       DependentNameTypeLoc TL) {
   5056   const DependentNameType *T = TL.getTypePtr();
   5057 
   5058   NestedNameSpecifierLoc QualifierLoc
   5059     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   5060   if (!QualifierLoc)
   5061     return QualType();
   5062 
   5063   QualType Result
   5064     = getDerived().RebuildDependentNameType(T->getKeyword(),
   5065                                             TL.getElaboratedKeywordLoc(),
   5066                                             QualifierLoc,
   5067                                             T->getIdentifier(),
   5068                                             TL.getNameLoc());
   5069   if (Result.isNull())
   5070     return QualType();
   5071 
   5072   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
   5073     QualType NamedT = ElabT->getNamedType();
   5074     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
   5075 
   5076     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   5077     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5078     NewTL.setQualifierLoc(QualifierLoc);
   5079   } else {
   5080     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
   5081     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5082     NewTL.setQualifierLoc(QualifierLoc);
   5083     NewTL.setNameLoc(TL.getNameLoc());
   5084   }
   5085   return Result;
   5086 }
   5087 
   5088 template<typename Derived>
   5089 QualType TreeTransform<Derived>::
   5090           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
   5091                                  DependentTemplateSpecializationTypeLoc TL) {
   5092   NestedNameSpecifierLoc QualifierLoc;
   5093   if (TL.getQualifierLoc()) {
   5094     QualifierLoc
   5095       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   5096     if (!QualifierLoc)
   5097       return QualType();
   5098   }
   5099 
   5100   return getDerived()
   5101            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
   5102 }
   5103 
   5104 template<typename Derived>
   5105 QualType TreeTransform<Derived>::
   5106 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
   5107                                    DependentTemplateSpecializationTypeLoc TL,
   5108                                        NestedNameSpecifierLoc QualifierLoc) {
   5109   const DependentTemplateSpecializationType *T = TL.getTypePtr();
   5110 
   5111   TemplateArgumentListInfo NewTemplateArgs;
   5112   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   5113   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   5114 
   5115   typedef TemplateArgumentLocContainerIterator<
   5116   DependentTemplateSpecializationTypeLoc> ArgIterator;
   5117   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   5118                                               ArgIterator(TL, TL.getNumArgs()),
   5119                                               NewTemplateArgs))
   5120     return QualType();
   5121 
   5122   QualType Result
   5123     = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
   5124                                                               QualifierLoc,
   5125                                                             T->getIdentifier(),
   5126                                                        TL.getTemplateNameLoc(),
   5127                                                             NewTemplateArgs);
   5128   if (Result.isNull())
   5129     return QualType();
   5130 
   5131   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
   5132     QualType NamedT = ElabT->getNamedType();
   5133 
   5134     // Copy information relevant to the template specialization.
   5135     TemplateSpecializationTypeLoc NamedTL
   5136       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
   5137     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5138     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5139     NamedTL.setLAngleLoc(TL.getLAngleLoc());
   5140     NamedTL.setRAngleLoc(TL.getRAngleLoc());
   5141     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   5142       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   5143 
   5144     // Copy information relevant to the elaborated type.
   5145     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   5146     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5147     NewTL.setQualifierLoc(QualifierLoc);
   5148   } else if (isa<DependentTemplateSpecializationType>(Result)) {
   5149     DependentTemplateSpecializationTypeLoc SpecTL
   5150       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   5151     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5152     SpecTL.setQualifierLoc(QualifierLoc);
   5153     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5154     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5155     SpecTL.setLAngleLoc(TL.getLAngleLoc());
   5156     SpecTL.setRAngleLoc(TL.getRAngleLoc());
   5157     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   5158       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   5159   } else {
   5160     TemplateSpecializationTypeLoc SpecTL
   5161       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   5162     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5163     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5164     SpecTL.setLAngleLoc(TL.getLAngleLoc());
   5165     SpecTL.setRAngleLoc(TL.getRAngleLoc());
   5166     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   5167       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   5168   }
   5169   return Result;
   5170 }
   5171 
   5172 template<typename Derived>
   5173 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
   5174                                                       PackExpansionTypeLoc TL) {
   5175   QualType Pattern
   5176     = getDerived().TransformType(TLB, TL.getPatternLoc());
   5177   if (Pattern.isNull())
   5178     return QualType();
   5179 
   5180   QualType Result = TL.getType();
   5181   if (getDerived().AlwaysRebuild() ||
   5182       Pattern != TL.getPatternLoc().getType()) {
   5183     Result = getDerived().RebuildPackExpansionType(Pattern,
   5184                                            TL.getPatternLoc().getSourceRange(),
   5185                                                    TL.getEllipsisLoc(),
   5186                                            TL.getTypePtr()->getNumExpansions());
   5187     if (Result.isNull())
   5188       return QualType();
   5189   }
   5190 
   5191   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
   5192   NewT.setEllipsisLoc(TL.getEllipsisLoc());
   5193   return Result;
   5194 }
   5195 
   5196 template<typename Derived>
   5197 QualType
   5198 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
   5199                                                    ObjCInterfaceTypeLoc TL) {
   5200   // ObjCInterfaceType is never dependent.
   5201   TLB.pushFullCopy(TL);
   5202   return TL.getType();
   5203 }
   5204 
   5205 template<typename Derived>
   5206 QualType
   5207 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
   5208                                                 ObjCObjectTypeLoc TL) {
   5209   // ObjCObjectType is never dependent.
   5210   TLB.pushFullCopy(TL);
   5211   return TL.getType();
   5212 }
   5213 
   5214 template<typename Derived>
   5215 QualType
   5216 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
   5217                                                ObjCObjectPointerTypeLoc TL) {
   5218   // ObjCObjectPointerType is never dependent.
   5219   TLB.pushFullCopy(TL);
   5220   return TL.getType();
   5221 }
   5222 
   5223 //===----------------------------------------------------------------------===//
   5224 // Statement transformation
   5225 //===----------------------------------------------------------------------===//
   5226 template<typename Derived>
   5227 StmtResult
   5228 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
   5229   return SemaRef.Owned(S);
   5230 }
   5231 
   5232 template<typename Derived>
   5233 StmtResult
   5234 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
   5235   return getDerived().TransformCompoundStmt(S, false);
   5236 }
   5237 
   5238 template<typename Derived>
   5239 StmtResult
   5240 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
   5241                                               bool IsStmtExpr) {
   5242   Sema::CompoundScopeRAII CompoundScope(getSema());
   5243 
   5244   bool SubStmtInvalid = false;
   5245   bool SubStmtChanged = false;
   5246   SmallVector<Stmt*, 8> Statements;
   5247   for (CompoundStmt::body_iterator B = S->body_begin(), BEnd = S->body_end();
   5248        B != BEnd; ++B) {
   5249     StmtResult Result = getDerived().TransformStmt(*B);
   5250     if (Result.isInvalid()) {
   5251       // Immediately fail if this was a DeclStmt, since it's very
   5252       // likely that this will cause problems for future statements.
   5253       if (isa<DeclStmt>(*B))
   5254         return StmtError();
   5255 
   5256       // Otherwise, just keep processing substatements and fail later.
   5257       SubStmtInvalid = true;
   5258       continue;
   5259     }
   5260 
   5261     SubStmtChanged = SubStmtChanged || Result.get() != *B;
   5262     Statements.push_back(Result.takeAs<Stmt>());
   5263   }
   5264 
   5265   if (SubStmtInvalid)
   5266     return StmtError();
   5267 
   5268   if (!getDerived().AlwaysRebuild() &&
   5269       !SubStmtChanged)
   5270     return SemaRef.Owned(S);
   5271 
   5272   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
   5273                                           Statements,
   5274                                           S->getRBracLoc(),
   5275                                           IsStmtExpr);
   5276 }
   5277 
   5278 template<typename Derived>
   5279 StmtResult
   5280 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
   5281   ExprResult LHS, RHS;
   5282   {
   5283     EnterExpressionEvaluationContext Unevaluated(SemaRef,
   5284                                                  Sema::ConstantEvaluated);
   5285 
   5286     // Transform the left-hand case value.
   5287     LHS = getDerived().TransformExpr(S->getLHS());
   5288     LHS = SemaRef.ActOnConstantExpression(LHS);
   5289     if (LHS.isInvalid())
   5290       return StmtError();
   5291 
   5292     // Transform the right-hand case value (for the GNU case-range extension).
   5293     RHS = getDerived().TransformExpr(S->getRHS());
   5294     RHS = SemaRef.ActOnConstantExpression(RHS);
   5295     if (RHS.isInvalid())
   5296       return StmtError();
   5297   }
   5298 
   5299   // Build the case statement.
   5300   // Case statements are always rebuilt so that they will attached to their
   5301   // transformed switch statement.
   5302   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
   5303                                                        LHS.get(),
   5304                                                        S->getEllipsisLoc(),
   5305                                                        RHS.get(),
   5306                                                        S->getColonLoc());
   5307   if (Case.isInvalid())
   5308     return StmtError();
   5309 
   5310   // Transform the statement following the case
   5311   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   5312   if (SubStmt.isInvalid())
   5313     return StmtError();
   5314 
   5315   // Attach the body to the case statement
   5316   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
   5317 }
   5318 
   5319 template<typename Derived>
   5320 StmtResult
   5321 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
   5322   // Transform the statement following the default case
   5323   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   5324   if (SubStmt.isInvalid())
   5325     return StmtError();
   5326 
   5327   // Default statements are always rebuilt
   5328   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
   5329                                          SubStmt.get());
   5330 }
   5331 
   5332 template<typename Derived>
   5333 StmtResult
   5334 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
   5335   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   5336   if (SubStmt.isInvalid())
   5337     return StmtError();
   5338 
   5339   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
   5340                                         S->getDecl());
   5341   if (!LD)
   5342     return StmtError();
   5343 
   5344 
   5345   // FIXME: Pass the real colon location in.
   5346   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
   5347                                        cast<LabelDecl>(LD), SourceLocation(),
   5348                                        SubStmt.get());
   5349 }
   5350 
   5351 template<typename Derived>
   5352 StmtResult
   5353 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
   5354   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   5355   if (SubStmt.isInvalid())
   5356     return StmtError();
   5357 
   5358   // TODO: transform attributes
   5359   if (SubStmt.get() == S->getSubStmt() /* && attrs are the same */)
   5360     return S;
   5361 
   5362   return getDerived().RebuildAttributedStmt(S->getAttrLoc(),
   5363                                             S->getAttrs(),
   5364                                             SubStmt.get());
   5365 }
   5366 
   5367 template<typename Derived>
   5368 StmtResult
   5369 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
   5370   // Transform the condition
   5371   ExprResult Cond;
   5372   VarDecl *ConditionVar = 0;
   5373   if (S->getConditionVariable()) {
   5374     ConditionVar
   5375       = cast_or_null<VarDecl>(
   5376                    getDerived().TransformDefinition(
   5377                                       S->getConditionVariable()->getLocation(),
   5378                                                     S->getConditionVariable()));
   5379     if (!ConditionVar)
   5380       return StmtError();
   5381   } else {
   5382     Cond = getDerived().TransformExpr(S->getCond());
   5383 
   5384     if (Cond.isInvalid())
   5385       return StmtError();
   5386 
   5387     // Convert the condition to a boolean value.
   5388     if (S->getCond()) {
   5389       ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getIfLoc(),
   5390                                                          Cond.get());
   5391       if (CondE.isInvalid())
   5392         return StmtError();
   5393 
   5394       Cond = CondE.get();
   5395     }
   5396   }
   5397 
   5398   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
   5399   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   5400     return StmtError();
   5401 
   5402   // Transform the "then" branch.
   5403   StmtResult Then = getDerived().TransformStmt(S->getThen());
   5404   if (Then.isInvalid())
   5405     return StmtError();
   5406 
   5407   // Transform the "else" branch.
   5408   StmtResult Else = getDerived().TransformStmt(S->getElse());
   5409   if (Else.isInvalid())
   5410     return StmtError();
   5411 
   5412   if (!getDerived().AlwaysRebuild() &&
   5413       FullCond.get() == S->getCond() &&
   5414       ConditionVar == S->getConditionVariable() &&
   5415       Then.get() == S->getThen() &&
   5416       Else.get() == S->getElse())
   5417     return SemaRef.Owned(S);
   5418 
   5419   return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
   5420                                     Then.get(),
   5421                                     S->getElseLoc(), Else.get());
   5422 }
   5423 
   5424 template<typename Derived>
   5425 StmtResult
   5426 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
   5427   // Transform the condition.
   5428   ExprResult Cond;
   5429   VarDecl *ConditionVar = 0;
   5430   if (S->getConditionVariable()) {
   5431     ConditionVar
   5432       = cast_or_null<VarDecl>(
   5433                    getDerived().TransformDefinition(
   5434                                       S->getConditionVariable()->getLocation(),
   5435                                                     S->getConditionVariable()));
   5436     if (!ConditionVar)
   5437       return StmtError();
   5438   } else {
   5439     Cond = getDerived().TransformExpr(S->getCond());
   5440 
   5441     if (Cond.isInvalid())
   5442       return StmtError();
   5443   }
   5444 
   5445   // Rebuild the switch statement.
   5446   StmtResult Switch
   5447     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
   5448                                           ConditionVar);
   5449   if (Switch.isInvalid())
   5450     return StmtError();
   5451 
   5452   // Transform the body of the switch statement.
   5453   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5454   if (Body.isInvalid())
   5455     return StmtError();
   5456 
   5457   // Complete the switch statement.
   5458   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
   5459                                             Body.get());
   5460 }
   5461 
   5462 template<typename Derived>
   5463 StmtResult
   5464 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
   5465   // Transform the condition
   5466   ExprResult Cond;
   5467   VarDecl *ConditionVar = 0;
   5468   if (S->getConditionVariable()) {
   5469     ConditionVar
   5470       = cast_or_null<VarDecl>(
   5471                    getDerived().TransformDefinition(
   5472                                       S->getConditionVariable()->getLocation(),
   5473                                                     S->getConditionVariable()));
   5474     if (!ConditionVar)
   5475       return StmtError();
   5476   } else {
   5477     Cond = getDerived().TransformExpr(S->getCond());
   5478 
   5479     if (Cond.isInvalid())
   5480       return StmtError();
   5481 
   5482     if (S->getCond()) {
   5483       // Convert the condition to a boolean value.
   5484       ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getWhileLoc(),
   5485                                                          Cond.get());
   5486       if (CondE.isInvalid())
   5487         return StmtError();
   5488       Cond = CondE;
   5489     }
   5490   }
   5491 
   5492   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
   5493   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   5494     return StmtError();
   5495 
   5496   // Transform the body
   5497   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5498   if (Body.isInvalid())
   5499     return StmtError();
   5500 
   5501   if (!getDerived().AlwaysRebuild() &&
   5502       FullCond.get() == S->getCond() &&
   5503       ConditionVar == S->getConditionVariable() &&
   5504       Body.get() == S->getBody())
   5505     return Owned(S);
   5506 
   5507   return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
   5508                                        ConditionVar, Body.get());
   5509 }
   5510 
   5511 template<typename Derived>
   5512 StmtResult
   5513 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
   5514   // Transform the body
   5515   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5516   if (Body.isInvalid())
   5517     return StmtError();
   5518 
   5519   // Transform the condition
   5520   ExprResult Cond = getDerived().TransformExpr(S->getCond());
   5521   if (Cond.isInvalid())
   5522     return StmtError();
   5523 
   5524   if (!getDerived().AlwaysRebuild() &&
   5525       Cond.get() == S->getCond() &&
   5526       Body.get() == S->getBody())
   5527     return SemaRef.Owned(S);
   5528 
   5529   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
   5530                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
   5531                                     S->getRParenLoc());
   5532 }
   5533 
   5534 template<typename Derived>
   5535 StmtResult
   5536 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
   5537   // Transform the initialization statement
   5538   StmtResult Init = getDerived().TransformStmt(S->getInit());
   5539   if (Init.isInvalid())
   5540     return StmtError();
   5541 
   5542   // Transform the condition
   5543   ExprResult Cond;
   5544   VarDecl *ConditionVar = 0;
   5545   if (S->getConditionVariable()) {
   5546     ConditionVar
   5547       = cast_or_null<VarDecl>(
   5548                    getDerived().TransformDefinition(
   5549                                       S->getConditionVariable()->getLocation(),
   5550                                                     S->getConditionVariable()));
   5551     if (!ConditionVar)
   5552       return StmtError();
   5553   } else {
   5554     Cond = getDerived().TransformExpr(S->getCond());
   5555 
   5556     if (Cond.isInvalid())
   5557       return StmtError();
   5558 
   5559     if (S->getCond()) {
   5560       // Convert the condition to a boolean value.
   5561       ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getForLoc(),
   5562                                                          Cond.get());
   5563       if (CondE.isInvalid())
   5564         return StmtError();
   5565 
   5566       Cond = CondE.get();
   5567     }
   5568   }
   5569 
   5570   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
   5571   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   5572     return StmtError();
   5573 
   5574   // Transform the increment
   5575   ExprResult Inc = getDerived().TransformExpr(S->getInc());
   5576   if (Inc.isInvalid())
   5577     return StmtError();
   5578 
   5579   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
   5580   if (S->getInc() && !FullInc.get())
   5581     return StmtError();
   5582 
   5583   // Transform the body
   5584   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5585   if (Body.isInvalid())
   5586     return StmtError();
   5587 
   5588   if (!getDerived().AlwaysRebuild() &&
   5589       Init.get() == S->getInit() &&
   5590       FullCond.get() == S->getCond() &&
   5591       Inc.get() == S->getInc() &&
   5592       Body.get() == S->getBody())
   5593     return SemaRef.Owned(S);
   5594 
   5595   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
   5596                                      Init.get(), FullCond, ConditionVar,
   5597                                      FullInc, S->getRParenLoc(), Body.get());
   5598 }
   5599 
   5600 template<typename Derived>
   5601 StmtResult
   5602 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
   5603   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
   5604                                         S->getLabel());
   5605   if (!LD)
   5606     return StmtError();
   5607 
   5608   // Goto statements must always be rebuilt, to resolve the label.
   5609   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
   5610                                       cast<LabelDecl>(LD));
   5611 }
   5612 
   5613 template<typename Derived>
   5614 StmtResult
   5615 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
   5616   ExprResult Target = getDerived().TransformExpr(S->getTarget());
   5617   if (Target.isInvalid())
   5618     return StmtError();
   5619   Target = SemaRef.MaybeCreateExprWithCleanups(Target.take());
   5620 
   5621   if (!getDerived().AlwaysRebuild() &&
   5622       Target.get() == S->getTarget())
   5623     return SemaRef.Owned(S);
   5624 
   5625   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
   5626                                               Target.get());
   5627 }
   5628 
   5629 template<typename Derived>
   5630 StmtResult
   5631 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
   5632   return SemaRef.Owned(S);
   5633 }
   5634 
   5635 template<typename Derived>
   5636 StmtResult
   5637 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
   5638   return SemaRef.Owned(S);
   5639 }
   5640 
   5641 template<typename Derived>
   5642 StmtResult
   5643 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
   5644   ExprResult Result = getDerived().TransformExpr(S->getRetValue());
   5645   if (Result.isInvalid())
   5646     return StmtError();
   5647 
   5648   // FIXME: We always rebuild the return statement because there is no way
   5649   // to tell whether the return type of the function has changed.
   5650   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
   5651 }
   5652 
   5653 template<typename Derived>
   5654 StmtResult
   5655 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
   5656   bool DeclChanged = false;
   5657   SmallVector<Decl *, 4> Decls;
   5658   for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
   5659        D != DEnd; ++D) {
   5660     Decl *Transformed = getDerived().TransformDefinition((*D)->getLocation(),
   5661                                                          *D);
   5662     if (!Transformed)
   5663       return StmtError();
   5664 
   5665     if (Transformed != *D)
   5666       DeclChanged = true;
   5667 
   5668     Decls.push_back(Transformed);
   5669   }
   5670 
   5671   if (!getDerived().AlwaysRebuild() && !DeclChanged)
   5672     return SemaRef.Owned(S);
   5673 
   5674   return getDerived().RebuildDeclStmt(Decls, S->getStartLoc(), S->getEndLoc());
   5675 }
   5676 
   5677 template<typename Derived>
   5678 StmtResult
   5679 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
   5680 
   5681   SmallVector<Expr*, 8> Constraints;
   5682   SmallVector<Expr*, 8> Exprs;
   5683   SmallVector<IdentifierInfo *, 4> Names;
   5684 
   5685   ExprResult AsmString;
   5686   SmallVector<Expr*, 8> Clobbers;
   5687 
   5688   bool ExprsChanged = false;
   5689 
   5690   // Go through the outputs.
   5691   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
   5692     Names.push_back(S->getOutputIdentifier(I));
   5693 
   5694     // No need to transform the constraint literal.
   5695     Constraints.push_back(S->getOutputConstraintLiteral(I));
   5696 
   5697     // Transform the output expr.
   5698     Expr *OutputExpr = S->getOutputExpr(I);
   5699     ExprResult Result = getDerived().TransformExpr(OutputExpr);
   5700     if (Result.isInvalid())
   5701       return StmtError();
   5702 
   5703     ExprsChanged |= Result.get() != OutputExpr;
   5704 
   5705     Exprs.push_back(Result.get());
   5706   }
   5707 
   5708   // Go through the inputs.
   5709   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
   5710     Names.push_back(S->getInputIdentifier(I));
   5711 
   5712     // No need to transform the constraint literal.
   5713     Constraints.push_back(S->getInputConstraintLiteral(I));
   5714 
   5715     // Transform the input expr.
   5716     Expr *InputExpr = S->getInputExpr(I);
   5717     ExprResult Result = getDerived().TransformExpr(InputExpr);
   5718     if (Result.isInvalid())
   5719       return StmtError();
   5720 
   5721     ExprsChanged |= Result.get() != InputExpr;
   5722 
   5723     Exprs.push_back(Result.get());
   5724   }
   5725 
   5726   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
   5727     return SemaRef.Owned(S);
   5728 
   5729   // Go through the clobbers.
   5730   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
   5731     Clobbers.push_back(S->getClobberStringLiteral(I));
   5732 
   5733   // No need to transform the asm string literal.
   5734   AsmString = SemaRef.Owned(S->getAsmString());
   5735   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
   5736                                         S->isVolatile(), S->getNumOutputs(),
   5737                                         S->getNumInputs(), Names.data(),
   5738                                         Constraints, Exprs, AsmString.get(),
   5739                                         Clobbers, S->getRParenLoc());
   5740 }
   5741 
   5742 template<typename Derived>
   5743 StmtResult
   5744 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
   5745   ArrayRef<Token> AsmToks =
   5746     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
   5747 
   5748   bool HadError = false, HadChange = false;
   5749 
   5750   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
   5751   SmallVector<Expr*, 8> TransformedExprs;
   5752   TransformedExprs.reserve(SrcExprs.size());
   5753   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
   5754     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
   5755     if (!Result.isUsable()) {
   5756       HadError = true;
   5757     } else {
   5758       HadChange |= (Result.get() != SrcExprs[i]);
   5759       TransformedExprs.push_back(Result.take());
   5760     }
   5761   }
   5762 
   5763   if (HadError) return StmtError();
   5764   if (!HadChange && !getDerived().AlwaysRebuild())
   5765     return Owned(S);
   5766 
   5767   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
   5768                                        AsmToks, S->getAsmString(),
   5769                                        S->getNumOutputs(), S->getNumInputs(),
   5770                                        S->getAllConstraints(), S->getClobbers(),
   5771                                        TransformedExprs, S->getEndLoc());
   5772 }
   5773 
   5774 template<typename Derived>
   5775 StmtResult
   5776 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
   5777   // Transform the body of the @try.
   5778   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
   5779   if (TryBody.isInvalid())
   5780     return StmtError();
   5781 
   5782   // Transform the @catch statements (if present).
   5783   bool AnyCatchChanged = false;
   5784   SmallVector<Stmt*, 8> CatchStmts;
   5785   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
   5786     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
   5787     if (Catch.isInvalid())
   5788       return StmtError();
   5789     if (Catch.get() != S->getCatchStmt(I))
   5790       AnyCatchChanged = true;
   5791     CatchStmts.push_back(Catch.release());
   5792   }
   5793 
   5794   // Transform the @finally statement (if present).
   5795   StmtResult Finally;
   5796   if (S->getFinallyStmt()) {
   5797     Finally = getDerived().TransformStmt(S->getFinallyStmt());
   5798     if (Finally.isInvalid())
   5799       return StmtError();
   5800   }
   5801 
   5802   // If nothing changed, just retain this statement.
   5803   if (!getDerived().AlwaysRebuild() &&
   5804       TryBody.get() == S->getTryBody() &&
   5805       !AnyCatchChanged &&
   5806       Finally.get() == S->getFinallyStmt())
   5807     return SemaRef.Owned(S);
   5808 
   5809   // Build a new statement.
   5810   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
   5811                                            CatchStmts, Finally.get());
   5812 }
   5813 
   5814 template<typename Derived>
   5815 StmtResult
   5816 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
   5817   // Transform the @catch parameter, if there is one.
   5818   VarDecl *Var = 0;
   5819   if (VarDecl *FromVar = S->getCatchParamDecl()) {
   5820     TypeSourceInfo *TSInfo = 0;
   5821     if (FromVar->getTypeSourceInfo()) {
   5822       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
   5823       if (!TSInfo)
   5824         return StmtError();
   5825     }
   5826 
   5827     QualType T;
   5828     if (TSInfo)
   5829       T = TSInfo->getType();
   5830     else {
   5831       T = getDerived().TransformType(FromVar->getType());
   5832       if (T.isNull())
   5833         return StmtError();
   5834     }
   5835 
   5836     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
   5837     if (!Var)
   5838       return StmtError();
   5839   }
   5840 
   5841   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
   5842   if (Body.isInvalid())
   5843     return StmtError();
   5844 
   5845   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
   5846                                              S->getRParenLoc(),
   5847                                              Var, Body.get());
   5848 }
   5849 
   5850 template<typename Derived>
   5851 StmtResult
   5852 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
   5853   // Transform the body.
   5854   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
   5855   if (Body.isInvalid())
   5856     return StmtError();
   5857 
   5858   // If nothing changed, just retain this statement.
   5859   if (!getDerived().AlwaysRebuild() &&
   5860       Body.get() == S->getFinallyBody())
   5861     return SemaRef.Owned(S);
   5862 
   5863   // Build a new statement.
   5864   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
   5865                                                Body.get());
   5866 }
   5867 
   5868 template<typename Derived>
   5869 StmtResult
   5870 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
   5871   ExprResult Operand;
   5872   if (S->getThrowExpr()) {
   5873     Operand = getDerived().TransformExpr(S->getThrowExpr());
   5874     if (Operand.isInvalid())
   5875       return StmtError();
   5876   }
   5877 
   5878   if (!getDerived().AlwaysRebuild() &&
   5879       Operand.get() == S->getThrowExpr())
   5880     return getSema().Owned(S);
   5881 
   5882   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
   5883 }
   5884 
   5885 template<typename Derived>
   5886 StmtResult
   5887 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
   5888                                                   ObjCAtSynchronizedStmt *S) {
   5889   // Transform the object we are locking.
   5890   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
   5891   if (Object.isInvalid())
   5892     return StmtError();
   5893   Object =
   5894     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
   5895                                                   Object.get());
   5896   if (Object.isInvalid())
   5897     return StmtError();
   5898 
   5899   // Transform the body.
   5900   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
   5901   if (Body.isInvalid())
   5902     return StmtError();
   5903 
   5904   // If nothing change, just retain the current statement.
   5905   if (!getDerived().AlwaysRebuild() &&
   5906       Object.get() == S->getSynchExpr() &&
   5907       Body.get() == S->getSynchBody())
   5908     return SemaRef.Owned(S);
   5909 
   5910   // Build a new statement.
   5911   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
   5912                                                     Object.get(), Body.get());
   5913 }
   5914 
   5915 template<typename Derived>
   5916 StmtResult
   5917 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
   5918                                               ObjCAutoreleasePoolStmt *S) {
   5919   // Transform the body.
   5920   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
   5921   if (Body.isInvalid())
   5922     return StmtError();
   5923 
   5924   // If nothing changed, just retain this statement.
   5925   if (!getDerived().AlwaysRebuild() &&
   5926       Body.get() == S->getSubStmt())
   5927     return SemaRef.Owned(S);
   5928 
   5929   // Build a new statement.
   5930   return getDerived().RebuildObjCAutoreleasePoolStmt(
   5931                         S->getAtLoc(), Body.get());
   5932 }
   5933 
   5934 template<typename Derived>
   5935 StmtResult
   5936 TreeTransform<Derived>::TransformObjCForCollectionStmt(
   5937                                                   ObjCForCollectionStmt *S) {
   5938   // Transform the element statement.
   5939   StmtResult Element = getDerived().TransformStmt(S->getElement());
   5940   if (Element.isInvalid())
   5941     return StmtError();
   5942 
   5943   // Transform the collection expression.
   5944   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
   5945   if (Collection.isInvalid())
   5946     return StmtError();
   5947 
   5948   // Transform the body.
   5949   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5950   if (Body.isInvalid())
   5951     return StmtError();
   5952 
   5953   // If nothing changed, just retain this statement.
   5954   if (!getDerived().AlwaysRebuild() &&
   5955       Element.get() == S->getElement() &&
   5956       Collection.get() == S->getCollection() &&
   5957       Body.get() == S->getBody())
   5958     return SemaRef.Owned(S);
   5959 
   5960   // Build a new statement.
   5961   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
   5962                                                    Element.get(),
   5963                                                    Collection.get(),
   5964                                                    S->getRParenLoc(),
   5965                                                    Body.get());
   5966 }
   5967 
   5968 
   5969 template<typename Derived>
   5970 StmtResult
   5971 TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
   5972   // Transform the exception declaration, if any.
   5973   VarDecl *Var = 0;
   5974   if (S->getExceptionDecl()) {
   5975     VarDecl *ExceptionDecl = S->getExceptionDecl();
   5976     TypeSourceInfo *T = getDerived().TransformType(
   5977                                             ExceptionDecl->getTypeSourceInfo());
   5978     if (!T)
   5979       return StmtError();
   5980 
   5981     Var = getDerived().RebuildExceptionDecl(ExceptionDecl, T,
   5982                                             ExceptionDecl->getInnerLocStart(),
   5983                                             ExceptionDecl->getLocation(),
   5984                                             ExceptionDecl->getIdentifier());
   5985     if (!Var || Var->isInvalidDecl())
   5986       return StmtError();
   5987   }
   5988 
   5989   // Transform the actual exception handler.
   5990   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
   5991   if (Handler.isInvalid())
   5992     return StmtError();
   5993 
   5994   if (!getDerived().AlwaysRebuild() &&
   5995       !Var &&
   5996       Handler.get() == S->getHandlerBlock())
   5997     return SemaRef.Owned(S);
   5998 
   5999   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(),
   6000                                           Var,
   6001                                           Handler.get());
   6002 }
   6003 
   6004 template<typename Derived>
   6005 StmtResult
   6006 TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
   6007   // Transform the try block itself.
   6008   StmtResult TryBlock
   6009     = getDerived().TransformCompoundStmt(S->getTryBlock());
   6010   if (TryBlock.isInvalid())
   6011     return StmtError();
   6012 
   6013   // Transform the handlers.
   6014   bool HandlerChanged = false;
   6015   SmallVector<Stmt*, 8> Handlers;
   6016   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
   6017     StmtResult Handler
   6018       = getDerived().TransformCXXCatchStmt(S->getHandler(I));
   6019     if (Handler.isInvalid())
   6020       return StmtError();
   6021 
   6022     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
   6023     Handlers.push_back(Handler.takeAs<Stmt>());
   6024   }
   6025 
   6026   if (!getDerived().AlwaysRebuild() &&
   6027       TryBlock.get() == S->getTryBlock() &&
   6028       !HandlerChanged)
   6029     return SemaRef.Owned(S);
   6030 
   6031   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
   6032                                         Handlers);
   6033 }
   6034 
   6035 template<typename Derived>
   6036 StmtResult
   6037 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
   6038   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
   6039   if (Range.isInvalid())
   6040     return StmtError();
   6041 
   6042   StmtResult BeginEnd = getDerived().TransformStmt(S->getBeginEndStmt());
   6043   if (BeginEnd.isInvalid())
   6044     return StmtError();
   6045 
   6046   ExprResult Cond = getDerived().TransformExpr(S->getCond());
   6047   if (Cond.isInvalid())
   6048     return StmtError();
   6049   if (Cond.get())
   6050     Cond = SemaRef.CheckBooleanCondition(Cond.take(), S->getColonLoc());
   6051   if (Cond.isInvalid())
   6052     return StmtError();
   6053   if (Cond.get())
   6054     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.take());
   6055 
   6056   ExprResult Inc = getDerived().TransformExpr(S->getInc());
   6057   if (Inc.isInvalid())
   6058     return StmtError();
   6059   if (Inc.get())
   6060     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.take());
   6061 
   6062   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
   6063   if (LoopVar.isInvalid())
   6064     return StmtError();
   6065 
   6066   StmtResult NewStmt = S;
   6067   if (getDerived().AlwaysRebuild() ||
   6068       Range.get() != S->getRangeStmt() ||
   6069       BeginEnd.get() != S->getBeginEndStmt() ||
   6070       Cond.get() != S->getCond() ||
   6071       Inc.get() != S->getInc() ||
   6072       LoopVar.get() != S->getLoopVarStmt()) {
   6073     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
   6074                                                   S->getColonLoc(), Range.get(),
   6075                                                   BeginEnd.get(), Cond.get(),
   6076                                                   Inc.get(), LoopVar.get(),
   6077                                                   S->getRParenLoc());
   6078     if (NewStmt.isInvalid())
   6079       return StmtError();
   6080   }
   6081 
   6082   StmtResult Body = getDerived().TransformStmt(S->getBody());
   6083   if (Body.isInvalid())
   6084     return StmtError();
   6085 
   6086   // Body has changed but we didn't rebuild the for-range statement. Rebuild
   6087   // it now so we have a new statement to attach the body to.
   6088   if (Body.get() != S->getBody() && NewStmt.get() == S) {
   6089     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
   6090                                                   S->getColonLoc(), Range.get(),
   6091                                                   BeginEnd.get(), Cond.get(),
   6092                                                   Inc.get(), LoopVar.get(),
   6093                                                   S->getRParenLoc());
   6094     if (NewStmt.isInvalid())
   6095       return StmtError();
   6096   }
   6097 
   6098   if (NewStmt.get() == S)
   6099     return SemaRef.Owned(S);
   6100 
   6101   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
   6102 }
   6103 
   6104 template<typename Derived>
   6105 StmtResult
   6106 TreeTransform<Derived>::TransformMSDependentExistsStmt(
   6107                                                     MSDependentExistsStmt *S) {
   6108   // Transform the nested-name-specifier, if any.
   6109   NestedNameSpecifierLoc QualifierLoc;
   6110   if (S->getQualifierLoc()) {
   6111     QualifierLoc
   6112       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
   6113     if (!QualifierLoc)
   6114       return StmtError();
   6115   }
   6116 
   6117   // Transform the declaration name.
   6118   DeclarationNameInfo NameInfo = S->getNameInfo();
   6119   if (NameInfo.getName()) {
   6120     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
   6121     if (!NameInfo.getName())
   6122       return StmtError();
   6123   }
   6124 
   6125   // Check whether anything changed.
   6126   if (!getDerived().AlwaysRebuild() &&
   6127       QualifierLoc == S->getQualifierLoc() &&
   6128       NameInfo.getName() == S->getNameInfo().getName())
   6129     return S;
   6130 
   6131   // Determine whether this name exists, if we can.
   6132   CXXScopeSpec SS;
   6133   SS.Adopt(QualifierLoc);
   6134   bool Dependent = false;
   6135   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/0, SS, NameInfo)) {
   6136   case Sema::IER_Exists:
   6137     if (S->isIfExists())
   6138       break;
   6139 
   6140     return new (getSema().Context) NullStmt(S->getKeywordLoc());
   6141 
   6142   case Sema::IER_DoesNotExist:
   6143     if (S->isIfNotExists())
   6144       break;
   6145 
   6146     return new (getSema().Context) NullStmt(S->getKeywordLoc());
   6147 
   6148   case Sema::IER_Dependent:
   6149     Dependent = true;
   6150     break;
   6151 
   6152   case Sema::IER_Error:
   6153     return StmtError();
   6154   }
   6155 
   6156   // We need to continue with the instantiation, so do so now.
   6157   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
   6158   if (SubStmt.isInvalid())
   6159     return StmtError();
   6160 
   6161   // If we have resolved the name, just transform to the substatement.
   6162   if (!Dependent)
   6163     return SubStmt;
   6164 
   6165   // The name is still dependent, so build a dependent expression again.
   6166   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
   6167                                                    S->isIfExists(),
   6168                                                    QualifierLoc,
   6169                                                    NameInfo,
   6170                                                    SubStmt.get());
   6171 }
   6172 
   6173 template<typename Derived>
   6174 ExprResult
   6175 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
   6176   NestedNameSpecifierLoc QualifierLoc;
   6177   if (E->getQualifierLoc()) {
   6178     QualifierLoc
   6179     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   6180     if (!QualifierLoc)
   6181       return ExprError();
   6182   }
   6183 
   6184   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
   6185     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
   6186   if (!PD)
   6187     return ExprError();
   6188 
   6189   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
   6190   if (Base.isInvalid())
   6191     return ExprError();
   6192 
   6193   return new (SemaRef.getASTContext())
   6194       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
   6195                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
   6196                         QualifierLoc, E->getMemberLoc());
   6197 }
   6198 
   6199 template<typename Derived>
   6200 StmtResult
   6201 TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
   6202   StmtResult TryBlock; //  = getDerived().TransformCompoundStmt(S->getTryBlock());
   6203   if(TryBlock.isInvalid()) return StmtError();
   6204 
   6205   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
   6206   if(!getDerived().AlwaysRebuild() &&
   6207      TryBlock.get() == S->getTryBlock() &&
   6208      Handler.get() == S->getHandler())
   6209     return SemaRef.Owned(S);
   6210 
   6211   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(),
   6212                                         S->getTryLoc(),
   6213                                         TryBlock.take(),
   6214                                         Handler.take());
   6215 }
   6216 
   6217 template<typename Derived>
   6218 StmtResult
   6219 TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
   6220   StmtResult Block; //  = getDerived().TransformCompoundStatement(S->getBlock());
   6221   if(Block.isInvalid()) return StmtError();
   6222 
   6223   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(),
   6224                                             Block.take());
   6225 }
   6226 
   6227 template<typename Derived>
   6228 StmtResult
   6229 TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
   6230   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
   6231   if(FilterExpr.isInvalid()) return StmtError();
   6232 
   6233   StmtResult Block; //  = getDerived().TransformCompoundStatement(S->getBlock());
   6234   if(Block.isInvalid()) return StmtError();
   6235 
   6236   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(),
   6237                                            FilterExpr.take(),
   6238                                            Block.take());
   6239 }
   6240 
   6241 template<typename Derived>
   6242 StmtResult
   6243 TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
   6244   if(isa<SEHFinallyStmt>(Handler))
   6245     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
   6246   else
   6247     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
   6248 }
   6249 
   6250 template<typename Derived>
   6251 StmtResult
   6252 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
   6253   // Transform the clauses
   6254   llvm::SmallVector<OMPClause *, 5> TClauses;
   6255   ArrayRef<OMPClause *> Clauses = D->clauses();
   6256   TClauses.reserve(Clauses.size());
   6257   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
   6258        I != E; ++I) {
   6259     if (*I) {
   6260       OMPClause *Clause = getDerived().TransformOMPClause(*I);
   6261       if (!Clause)
   6262         return StmtError();
   6263       TClauses.push_back(Clause);
   6264     }
   6265     else {
   6266       TClauses.push_back(0);
   6267     }
   6268   }
   6269   if (!D->getAssociatedStmt())
   6270     return StmtError();
   6271   StmtResult AssociatedStmt =
   6272     getDerived().TransformStmt(D->getAssociatedStmt());
   6273   if (AssociatedStmt.isInvalid())
   6274     return StmtError();
   6275 
   6276   return getDerived().RebuildOMPParallelDirective(TClauses,
   6277                                                   AssociatedStmt.take(),
   6278                                                   D->getLocStart(),
   6279                                                   D->getLocEnd());
   6280 }
   6281 
   6282 template<typename Derived>
   6283 OMPClause *
   6284 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
   6285   return getDerived().RebuildOMPDefaultClause(C->getDefaultKind(),
   6286                                               C->getDefaultKindKwLoc(),
   6287                                               C->getLocStart(),
   6288                                               C->getLParenLoc(),
   6289                                               C->getLocEnd());
   6290 }
   6291 
   6292 template<typename Derived>
   6293 OMPClause *
   6294 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
   6295   llvm::SmallVector<Expr *, 5> Vars;
   6296   Vars.reserve(C->varlist_size());
   6297   for (OMPVarList<OMPPrivateClause>::varlist_iterator I = C->varlist_begin(),
   6298                                                       E = C->varlist_end();
   6299        I != E; ++I) {
   6300     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(*I));
   6301     if (EVar.isInvalid())
   6302       return 0;
   6303     Vars.push_back(EVar.take());
   6304   }
   6305   return getDerived().RebuildOMPPrivateClause(Vars,
   6306                                               C->getLocStart(),
   6307                                               C->getLParenLoc(),
   6308                                               C->getLocEnd());
   6309 }
   6310 
   6311 //===----------------------------------------------------------------------===//
   6312 // Expression transformation
   6313 //===----------------------------------------------------------------------===//
   6314 template<typename Derived>
   6315 ExprResult
   6316 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
   6317   return SemaRef.Owned(E);
   6318 }
   6319 
   6320 template<typename Derived>
   6321 ExprResult
   6322 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
   6323   NestedNameSpecifierLoc QualifierLoc;
   6324   if (E->getQualifierLoc()) {
   6325     QualifierLoc
   6326       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   6327     if (!QualifierLoc)
   6328       return ExprError();
   6329   }
   6330 
   6331   ValueDecl *ND
   6332     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
   6333                                                          E->getDecl()));
   6334   if (!ND)
   6335     return ExprError();
   6336 
   6337   DeclarationNameInfo NameInfo = E->getNameInfo();
   6338   if (NameInfo.getName()) {
   6339     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
   6340     if (!NameInfo.getName())
   6341       return ExprError();
   6342   }
   6343 
   6344   if (!getDerived().AlwaysRebuild() &&
   6345       QualifierLoc == E->getQualifierLoc() &&
   6346       ND == E->getDecl() &&
   6347       NameInfo.getName() == E->getDecl()->getDeclName() &&
   6348       !E->hasExplicitTemplateArgs()) {
   6349 
   6350     // Mark it referenced in the new context regardless.
   6351     // FIXME: this is a bit instantiation-specific.
   6352     SemaRef.MarkDeclRefReferenced(E);
   6353 
   6354     return SemaRef.Owned(E);
   6355   }
   6356 
   6357   TemplateArgumentListInfo TransArgs, *TemplateArgs = 0;
   6358   if (E->hasExplicitTemplateArgs()) {
   6359     TemplateArgs = &TransArgs;
   6360     TransArgs.setLAngleLoc(E->getLAngleLoc());
   6361     TransArgs.setRAngleLoc(E->getRAngleLoc());
   6362     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   6363                                                 E->getNumTemplateArgs(),
   6364                                                 TransArgs))
   6365       return ExprError();
   6366   }
   6367 
   6368   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
   6369                                          TemplateArgs);
   6370 }
   6371 
   6372 template<typename Derived>
   6373 ExprResult
   6374 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
   6375   return SemaRef.Owned(E);
   6376 }
   6377 
   6378 template<typename Derived>
   6379 ExprResult
   6380 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
   6381   return SemaRef.Owned(E);
   6382 }
   6383 
   6384 template<typename Derived>
   6385 ExprResult
   6386 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
   6387   return SemaRef.Owned(E);
   6388 }
   6389 
   6390 template<typename Derived>
   6391 ExprResult
   6392 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
   6393   return SemaRef.Owned(E);
   6394 }
   6395 
   6396 template<typename Derived>
   6397 ExprResult
   6398 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
   6399   return SemaRef.Owned(E);
   6400 }
   6401 
   6402 template<typename Derived>
   6403 ExprResult
   6404 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
   6405   if (FunctionDecl *FD = E->getDirectCallee())
   6406     SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
   6407   return SemaRef.MaybeBindToTemporary(E);
   6408 }
   6409 
   6410 template<typename Derived>
   6411 ExprResult
   6412 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
   6413   ExprResult ControllingExpr =
   6414     getDerived().TransformExpr(E->getControllingExpr());
   6415   if (ControllingExpr.isInvalid())
   6416     return ExprError();
   6417 
   6418   SmallVector<Expr *, 4> AssocExprs;
   6419   SmallVector<TypeSourceInfo *, 4> AssocTypes;
   6420   for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
   6421     TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
   6422     if (TS) {
   6423       TypeSourceInfo *AssocType = getDerived().TransformType(TS);
   6424       if (!AssocType)
   6425         return ExprError();
   6426       AssocTypes.push_back(AssocType);
   6427     } else {
   6428       AssocTypes.push_back(0);
   6429     }
   6430 
   6431     ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
   6432     if (AssocExpr.isInvalid())
   6433       return ExprError();
   6434     AssocExprs.push_back(AssocExpr.release());
   6435   }
   6436 
   6437   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
   6438                                                   E->getDefaultLoc(),
   6439                                                   E->getRParenLoc(),
   6440                                                   ControllingExpr.release(),
   6441                                                   AssocTypes,
   6442                                                   AssocExprs);
   6443 }
   6444 
   6445 template<typename Derived>
   6446 ExprResult
   6447 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
   6448   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   6449   if (SubExpr.isInvalid())
   6450     return ExprError();
   6451 
   6452   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
   6453     return SemaRef.Owned(E);
   6454 
   6455   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
   6456                                        E->getRParen());
   6457 }
   6458 
   6459 /// \brief The operand of a unary address-of operator has special rules: it's
   6460 /// allowed to refer to a non-static member of a class even if there's no 'this'
   6461 /// object available.
   6462 template<typename Derived>
   6463 ExprResult
   6464 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
   6465   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
   6466     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true);
   6467   else
   6468     return getDerived().TransformExpr(E);
   6469 }
   6470 
   6471 template<typename Derived>
   6472 ExprResult
   6473 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
   6474   ExprResult SubExpr;
   6475   if (E->getOpcode() == UO_AddrOf)
   6476     SubExpr = TransformAddressOfOperand(E->getSubExpr());
   6477   else
   6478     SubExpr = TransformExpr(E->getSubExpr());
   6479   if (SubExpr.isInvalid())
   6480     return ExprError();
   6481 
   6482   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
   6483     return SemaRef.Owned(E);
   6484 
   6485   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
   6486                                            E->getOpcode(),
   6487                                            SubExpr.get());
   6488 }
   6489 
   6490 template<typename Derived>
   6491 ExprResult
   6492 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
   6493   // Transform the type.
   6494   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
   6495   if (!Type)
   6496     return ExprError();
   6497 
   6498   // Transform all of the components into components similar to what the
   6499   // parser uses.
   6500   // FIXME: It would be slightly more efficient in the non-dependent case to
   6501   // just map FieldDecls, rather than requiring the rebuilder to look for
   6502   // the fields again. However, __builtin_offsetof is rare enough in
   6503   // template code that we don't care.
   6504   bool ExprChanged = false;
   6505   typedef Sema::OffsetOfComponent Component;
   6506   typedef OffsetOfExpr::OffsetOfNode Node;
   6507   SmallVector<Component, 4> Components;
   6508   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
   6509     const Node &ON = E->getComponent(I);
   6510     Component Comp;
   6511     Comp.isBrackets = true;
   6512     Comp.LocStart = ON.getSourceRange().getBegin();
   6513     Comp.LocEnd = ON.getSourceRange().getEnd();
   6514     switch (ON.getKind()) {
   6515     case Node::Array: {
   6516       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
   6517       ExprResult Index = getDerived().TransformExpr(FromIndex);
   6518       if (Index.isInvalid())
   6519         return ExprError();
   6520 
   6521       ExprChanged = ExprChanged || Index.get() != FromIndex;
   6522       Comp.isBrackets = true;
   6523       Comp.U.E = Index.get();
   6524       break;
   6525     }
   6526 
   6527     case Node::Field:
   6528     case Node::Identifier:
   6529       Comp.isBrackets = false;
   6530       Comp.U.IdentInfo = ON.getFieldName();
   6531       if (!Comp.U.IdentInfo)
   6532         continue;
   6533 
   6534       break;
   6535 
   6536     case Node::Base:
   6537       // Will be recomputed during the rebuild.
   6538       continue;
   6539     }
   6540 
   6541     Components.push_back(Comp);
   6542   }
   6543 
   6544   // If nothing changed, retain the existing expression.
   6545   if (!getDerived().AlwaysRebuild() &&
   6546       Type == E->getTypeSourceInfo() &&
   6547       !ExprChanged)
   6548     return SemaRef.Owned(E);
   6549 
   6550   // Build a new offsetof expression.
   6551   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
   6552                                           Components.data(), Components.size(),
   6553                                           E->getRParenLoc());
   6554 }
   6555 
   6556 template<typename Derived>
   6557 ExprResult
   6558 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
   6559   assert(getDerived().AlreadyTransformed(E->getType()) &&
   6560          "opaque value expression requires transformation");
   6561   return SemaRef.Owned(E);
   6562 }
   6563 
   6564 template<typename Derived>
   6565 ExprResult
   6566 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
   6567   // Rebuild the syntactic form.  The original syntactic form has
   6568   // opaque-value expressions in it, so strip those away and rebuild
   6569   // the result.  This is a really awful way of doing this, but the
   6570   // better solution (rebuilding the semantic expressions and
   6571   // rebinding OVEs as necessary) doesn't work; we'd need
   6572   // TreeTransform to not strip away implicit conversions.
   6573   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
   6574   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
   6575   if (result.isInvalid()) return ExprError();
   6576 
   6577   // If that gives us a pseudo-object result back, the pseudo-object
   6578   // expression must have been an lvalue-to-rvalue conversion which we
   6579   // should reapply.
   6580   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
   6581     result = SemaRef.checkPseudoObjectRValue(result.take());
   6582 
   6583   return result;
   6584 }
   6585 
   6586 template<typename Derived>
   6587 ExprResult
   6588 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
   6589                                                 UnaryExprOrTypeTraitExpr *E) {
   6590   if (E->isArgumentType()) {
   6591     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
   6592 
   6593     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
   6594     if (!NewT)
   6595       return ExprError();
   6596 
   6597     if (!getDerived().AlwaysRebuild() && OldT == NewT)
   6598       return SemaRef.Owned(E);
   6599 
   6600     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
   6601                                                     E->getKind(),
   6602                                                     E->getSourceRange());
   6603   }
   6604 
   6605   // C++0x [expr.sizeof]p1:
   6606   //   The operand is either an expression, which is an unevaluated operand
   6607   //   [...]
   6608   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
   6609                                                Sema::ReuseLambdaContextDecl);
   6610 
   6611   ExprResult SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
   6612   if (SubExpr.isInvalid())
   6613     return ExprError();
   6614 
   6615   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
   6616     return SemaRef.Owned(E);
   6617 
   6618   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
   6619                                                   E->getOperatorLoc(),
   6620                                                   E->getKind(),
   6621                                                   E->getSourceRange());
   6622 }
   6623 
   6624 template<typename Derived>
   6625 ExprResult
   6626 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
   6627   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   6628   if (LHS.isInvalid())
   6629     return ExprError();
   6630 
   6631   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   6632   if (RHS.isInvalid())
   6633     return ExprError();
   6634 
   6635 
   6636   if (!getDerived().AlwaysRebuild() &&
   6637       LHS.get() == E->getLHS() &&
   6638       RHS.get() == E->getRHS())
   6639     return SemaRef.Owned(E);
   6640 
   6641   return getDerived().RebuildArraySubscriptExpr(LHS.get(),
   6642                                            /*FIXME:*/E->getLHS()->getLocStart(),
   6643                                                 RHS.get(),
   6644                                                 E->getRBracketLoc());
   6645 }
   6646 
   6647 template<typename Derived>
   6648 ExprResult
   6649 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
   6650   // Transform the callee.
   6651   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
   6652   if (Callee.isInvalid())
   6653     return ExprError();
   6654 
   6655   // Transform arguments.
   6656   bool ArgChanged = false;
   6657   SmallVector<Expr*, 8> Args;
   6658   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   6659                                   &ArgChanged))
   6660     return ExprError();
   6661 
   6662   if (!getDerived().AlwaysRebuild() &&
   6663       Callee.get() == E->getCallee() &&
   6664       !ArgChanged)
   6665     return SemaRef.MaybeBindToTemporary(E);
   6666 
   6667   // FIXME: Wrong source location information for the '('.
   6668   SourceLocation FakeLParenLoc
   6669     = ((Expr *)Callee.get())->getSourceRange().getBegin();
   6670   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
   6671                                       Args,
   6672                                       E->getRParenLoc());
   6673 }
   6674 
   6675 template<typename Derived>
   6676 ExprResult
   6677 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
   6678   ExprResult Base = getDerived().TransformExpr(E->getBase());
   6679   if (Base.isInvalid())
   6680     return ExprError();
   6681 
   6682   NestedNameSpecifierLoc QualifierLoc;
   6683   if (E->hasQualifier()) {
   6684     QualifierLoc
   6685       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   6686 
   6687     if (!QualifierLoc)
   6688       return ExprError();
   6689   }
   6690   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
   6691 
   6692   ValueDecl *Member
   6693     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
   6694                                                          E->getMemberDecl()));
   6695   if (!Member)
   6696     return ExprError();
   6697 
   6698   NamedDecl *FoundDecl = E->getFoundDecl();
   6699   if (FoundDecl == E->getMemberDecl()) {
   6700     FoundDecl = Member;
   6701   } else {
   6702     FoundDecl = cast_or_null<NamedDecl>(
   6703                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
   6704     if (!FoundDecl)
   6705       return ExprError();
   6706   }
   6707 
   6708   if (!getDerived().AlwaysRebuild() &&
   6709       Base.get() == E->getBase() &&
   6710       QualifierLoc == E->getQualifierLoc() &&
   6711       Member == E->getMemberDecl() &&
   6712       FoundDecl == E->getFoundDecl() &&
   6713       !E->hasExplicitTemplateArgs()) {
   6714 
   6715     // Mark it referenced in the new context regardless.
   6716     // FIXME: this is a bit instantiation-specific.
   6717     SemaRef.MarkMemberReferenced(E);
   6718 
   6719     return SemaRef.Owned(E);
   6720   }
   6721 
   6722   TemplateArgumentListInfo TransArgs;
   6723   if (E->hasExplicitTemplateArgs()) {
   6724     TransArgs.setLAngleLoc(E->getLAngleLoc());
   6725     TransArgs.setRAngleLoc(E->getRAngleLoc());
   6726     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   6727                                                 E->getNumTemplateArgs(),
   6728                                                 TransArgs))
   6729       return ExprError();
   6730   }
   6731 
   6732   // FIXME: Bogus source location for the operator
   6733   SourceLocation FakeOperatorLoc
   6734     = SemaRef.PP.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
   6735 
   6736   // FIXME: to do this check properly, we will need to preserve the
   6737   // first-qualifier-in-scope here, just in case we had a dependent
   6738   // base (and therefore couldn't do the check) and a
   6739   // nested-name-qualifier (and therefore could do the lookup).
   6740   NamedDecl *FirstQualifierInScope = 0;
   6741 
   6742   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
   6743                                         E->isArrow(),
   6744                                         QualifierLoc,
   6745                                         TemplateKWLoc,
   6746                                         E->getMemberNameInfo(),
   6747                                         Member,
   6748                                         FoundDecl,
   6749                                         (E->hasExplicitTemplateArgs()
   6750                                            ? &TransArgs : 0),
   6751                                         FirstQualifierInScope);
   6752 }
   6753 
   6754 template<typename Derived>
   6755 ExprResult
   6756 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
   6757   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   6758   if (LHS.isInvalid())
   6759     return ExprError();
   6760 
   6761   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   6762   if (RHS.isInvalid())
   6763     return ExprError();
   6764 
   6765   if (!getDerived().AlwaysRebuild() &&
   6766       LHS.get() == E->getLHS() &&
   6767       RHS.get() == E->getRHS())
   6768     return SemaRef.Owned(E);
   6769 
   6770   Sema::FPContractStateRAII FPContractState(getSema());
   6771   getSema().FPFeatures.fp_contract = E->isFPContractable();
   6772 
   6773   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
   6774                                             LHS.get(), RHS.get());
   6775 }
   6776 
   6777 template<typename Derived>
   6778 ExprResult
   6779 TreeTransform<Derived>::TransformCompoundAssignOperator(
   6780                                                       CompoundAssignOperator *E) {
   6781   return getDerived().TransformBinaryOperator(E);
   6782 }
   6783 
   6784 template<typename Derived>
   6785 ExprResult TreeTransform<Derived>::
   6786 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
   6787   // Just rebuild the common and RHS expressions and see whether we
   6788   // get any changes.
   6789 
   6790   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
   6791   if (commonExpr.isInvalid())
   6792     return ExprError();
   6793 
   6794   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
   6795   if (rhs.isInvalid())
   6796     return ExprError();
   6797 
   6798   if (!getDerived().AlwaysRebuild() &&
   6799       commonExpr.get() == e->getCommon() &&
   6800       rhs.get() == e->getFalseExpr())
   6801     return SemaRef.Owned(e);
   6802 
   6803   return getDerived().RebuildConditionalOperator(commonExpr.take(),
   6804                                                  e->getQuestionLoc(),
   6805                                                  0,
   6806                                                  e->getColonLoc(),
   6807                                                  rhs.get());
   6808 }
   6809 
   6810 template<typename Derived>
   6811 ExprResult
   6812 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
   6813   ExprResult Cond = getDerived().TransformExpr(E->getCond());
   6814   if (Cond.isInvalid())
   6815     return ExprError();
   6816 
   6817   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   6818   if (LHS.isInvalid())
   6819     return ExprError();
   6820 
   6821   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   6822   if (RHS.isInvalid())
   6823     return ExprError();
   6824 
   6825   if (!getDerived().AlwaysRebuild() &&
   6826       Cond.get() == E->getCond() &&
   6827       LHS.get() == E->getLHS() &&
   6828       RHS.get() == E->getRHS())
   6829     return SemaRef.Owned(E);
   6830 
   6831   return getDerived().RebuildConditionalOperator(Cond.get(),
   6832                                                  E->getQuestionLoc(),
   6833                                                  LHS.get(),
   6834                                                  E->getColonLoc(),
   6835                                                  RHS.get());
   6836 }
   6837 
   6838 template<typename Derived>
   6839 ExprResult
   6840 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
   6841   // Implicit casts are eliminated during transformation, since they
   6842   // will be recomputed by semantic analysis after transformation.
   6843   return getDerived().TransformExpr(E->getSubExprAsWritten());
   6844 }
   6845 
   6846 template<typename Derived>
   6847 ExprResult
   6848 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
   6849   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
   6850   if (!Type)
   6851     return ExprError();
   6852 
   6853   ExprResult SubExpr
   6854     = getDerived().TransformExpr(E->getSubExprAsWritten());
   6855   if (SubExpr.isInvalid())
   6856     return ExprError();
   6857 
   6858   if (!getDerived().AlwaysRebuild() &&
   6859       Type == E->getTypeInfoAsWritten() &&
   6860       SubExpr.get() == E->getSubExpr())
   6861     return SemaRef.Owned(E);
   6862 
   6863   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
   6864                                             Type,
   6865                                             E->getRParenLoc(),
   6866                                             SubExpr.get());
   6867 }
   6868 
   6869 template<typename Derived>
   6870 ExprResult
   6871 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
   6872   TypeSourceInfo *OldT = E->getTypeSourceInfo();
   6873   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
   6874   if (!NewT)
   6875     return ExprError();
   6876 
   6877   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
   6878   if (Init.isInvalid())
   6879     return ExprError();
   6880 
   6881   if (!getDerived().AlwaysRebuild() &&
   6882       OldT == NewT &&
   6883       Init.get() == E->getInitializer())
   6884     return SemaRef.MaybeBindToTemporary(E);
   6885 
   6886   // Note: the expression type doesn't necessarily match the
   6887   // type-as-written, but that's okay, because it should always be
   6888   // derivable from the initializer.
   6889 
   6890   return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
   6891                                    /*FIXME:*/E->getInitializer()->getLocEnd(),
   6892                                                  Init.get());
   6893 }
   6894 
   6895 template<typename Derived>
   6896 ExprResult
   6897 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
   6898   ExprResult Base = getDerived().TransformExpr(E->getBase());
   6899   if (Base.isInvalid())
   6900     return ExprError();
   6901 
   6902   if (!getDerived().AlwaysRebuild() &&
   6903       Base.get() == E->getBase())
   6904     return SemaRef.Owned(E);
   6905 
   6906   // FIXME: Bad source location
   6907   SourceLocation FakeOperatorLoc
   6908     = SemaRef.PP.getLocForEndOfToken(E->getBase()->getLocEnd());
   6909   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
   6910                                                   E->getAccessorLoc(),
   6911                                                   E->getAccessor());
   6912 }
   6913 
   6914 template<typename Derived>
   6915 ExprResult
   6916 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
   6917   bool InitChanged = false;
   6918 
   6919   SmallVector<Expr*, 4> Inits;
   6920   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
   6921                                   Inits, &InitChanged))
   6922     return ExprError();
   6923 
   6924   if (!getDerived().AlwaysRebuild() && !InitChanged)
   6925     return SemaRef.Owned(E);
   6926 
   6927   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
   6928                                       E->getRBraceLoc(), E->getType());
   6929 }
   6930 
   6931 template<typename Derived>
   6932 ExprResult
   6933 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
   6934   Designation Desig;
   6935 
   6936   // transform the initializer value
   6937   ExprResult Init = getDerived().TransformExpr(E->getInit());
   6938   if (Init.isInvalid())
   6939     return ExprError();
   6940 
   6941   // transform the designators.
   6942   SmallVector<Expr*, 4> ArrayExprs;
   6943   bool ExprChanged = false;
   6944   for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
   6945                                              DEnd = E->designators_end();
   6946        D != DEnd; ++D) {
   6947     if (D->isFieldDesignator()) {
   6948       Desig.AddDesignator(Designator::getField(D->getFieldName(),
   6949                                                D->getDotLoc(),
   6950                                                D->getFieldLoc()));
   6951       continue;
   6952     }
   6953 
   6954     if (D->isArrayDesignator()) {
   6955       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
   6956       if (Index.isInvalid())
   6957         return ExprError();
   6958 
   6959       Desig.AddDesignator(Designator::getArray(Index.get(),
   6960                                                D->getLBracketLoc()));
   6961 
   6962       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
   6963       ArrayExprs.push_back(Index.release());
   6964       continue;
   6965     }
   6966 
   6967     assert(D->isArrayRangeDesignator() && "New kind of designator?");
   6968     ExprResult Start
   6969       = getDerived().TransformExpr(E->getArrayRangeStart(*D));
   6970     if (Start.isInvalid())
   6971       return ExprError();
   6972 
   6973     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
   6974     if (End.isInvalid())
   6975       return ExprError();
   6976 
   6977     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
   6978                                                   End.get(),
   6979                                                   D->getLBracketLoc(),
   6980                                                   D->getEllipsisLoc()));
   6981 
   6982     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
   6983       End.get() != E->getArrayRangeEnd(*D);
   6984 
   6985     ArrayExprs.push_back(Start.release());
   6986     ArrayExprs.push_back(End.release());
   6987   }
   6988 
   6989   if (!getDerived().AlwaysRebuild() &&
   6990       Init.get() == E->getInit() &&
   6991       !ExprChanged)
   6992     return SemaRef.Owned(E);
   6993 
   6994   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
   6995                                                 E->getEqualOrColonLoc(),
   6996                                                 E->usesGNUSyntax(), Init.get());
   6997 }
   6998 
   6999 template<typename Derived>
   7000 ExprResult
   7001 TreeTransform<Derived>::TransformImplicitValueInitExpr(
   7002                                                      ImplicitValueInitExpr *E) {
   7003   TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
   7004 
   7005   // FIXME: Will we ever have proper type location here? Will we actually
   7006   // need to transform the type?
   7007   QualType T = getDerived().TransformType(E->getType());
   7008   if (T.isNull())
   7009     return ExprError();
   7010 
   7011   if (!getDerived().AlwaysRebuild() &&
   7012       T == E->getType())
   7013     return SemaRef.Owned(E);
   7014 
   7015   return getDerived().RebuildImplicitValueInitExpr(T);
   7016 }
   7017 
   7018 template<typename Derived>
   7019 ExprResult
   7020 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
   7021   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
   7022   if (!TInfo)
   7023     return ExprError();
   7024 
   7025   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   7026   if (SubExpr.isInvalid())
   7027     return ExprError();
   7028 
   7029   if (!getDerived().AlwaysRebuild() &&
   7030       TInfo == E->getWrittenTypeInfo() &&
   7031       SubExpr.get() == E->getSubExpr())
   7032     return SemaRef.Owned(E);
   7033 
   7034   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
   7035                                        TInfo, E->getRParenLoc());
   7036 }
   7037 
   7038 template<typename Derived>
   7039 ExprResult
   7040 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
   7041   bool ArgumentChanged = false;
   7042   SmallVector<Expr*, 4> Inits;
   7043   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
   7044                      &ArgumentChanged))
   7045     return ExprError();
   7046 
   7047   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
   7048                                            Inits,
   7049                                            E->getRParenLoc());
   7050 }
   7051 
   7052 /// \brief Transform an address-of-label expression.
   7053 ///
   7054 /// By default, the transformation of an address-of-label expression always
   7055 /// rebuilds the expression, so that the label identifier can be resolved to
   7056 /// the corresponding label statement by semantic analysis.
   7057 template<typename Derived>
   7058 ExprResult
   7059 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
   7060   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
   7061                                         E->getLabel());
   7062   if (!LD)
   7063     return ExprError();
   7064 
   7065   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
   7066                                            cast<LabelDecl>(LD));
   7067 }
   7068 
   7069 template<typename Derived>
   7070 ExprResult
   7071 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
   7072   SemaRef.ActOnStartStmtExpr();
   7073   StmtResult SubStmt
   7074     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
   7075   if (SubStmt.isInvalid()) {
   7076     SemaRef.ActOnStmtExprError();
   7077     return ExprError();
   7078   }
   7079 
   7080   if (!getDerived().AlwaysRebuild() &&
   7081       SubStmt.get() == E->getSubStmt()) {
   7082     // Calling this an 'error' is unintuitive, but it does the right thing.
   7083     SemaRef.ActOnStmtExprError();
   7084     return SemaRef.MaybeBindToTemporary(E);
   7085   }
   7086 
   7087   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
   7088                                       SubStmt.get(),
   7089                                       E->getRParenLoc());
   7090 }
   7091 
   7092 template<typename Derived>
   7093 ExprResult
   7094 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
   7095   ExprResult Cond = getDerived().TransformExpr(E->getCond());
   7096   if (Cond.isInvalid())
   7097     return ExprError();
   7098 
   7099   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   7100   if (LHS.isInvalid())
   7101     return ExprError();
   7102 
   7103   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   7104   if (RHS.isInvalid())
   7105     return ExprError();
   7106 
   7107   if (!getDerived().AlwaysRebuild() &&
   7108       Cond.get() == E->getCond() &&
   7109       LHS.get() == E->getLHS() &&
   7110       RHS.get() == E->getRHS())
   7111     return SemaRef.Owned(E);
   7112 
   7113   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
   7114                                         Cond.get(), LHS.get(), RHS.get(),
   7115                                         E->getRParenLoc());
   7116 }
   7117 
   7118 template<typename Derived>
   7119 ExprResult
   7120 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
   7121   return SemaRef.Owned(E);
   7122 }
   7123 
   7124 template<typename Derived>
   7125 ExprResult
   7126 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
   7127   switch (E->getOperator()) {
   7128   case OO_New:
   7129   case OO_Delete:
   7130   case OO_Array_New:
   7131   case OO_Array_Delete:
   7132     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
   7133 
   7134   case OO_Call: {
   7135     // This is a call to an object's operator().
   7136     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
   7137 
   7138     // Transform the object itself.
   7139     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
   7140     if (Object.isInvalid())
   7141       return ExprError();
   7142 
   7143     // FIXME: Poor location information
   7144     SourceLocation FakeLParenLoc
   7145       = SemaRef.PP.getLocForEndOfToken(
   7146                               static_cast<Expr *>(Object.get())->getLocEnd());
   7147 
   7148     // Transform the call arguments.
   7149     SmallVector<Expr*, 8> Args;
   7150     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
   7151                                     Args))
   7152       return ExprError();
   7153 
   7154     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
   7155                                         Args,
   7156                                         E->getLocEnd());
   7157   }
   7158 
   7159 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
   7160   case OO_##Name:
   7161 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
   7162 #include "clang/Basic/OperatorKinds.def"
   7163   case OO_Subscript:
   7164     // Handled below.
   7165     break;
   7166 
   7167   case OO_Conditional:
   7168     llvm_unreachable("conditional operator is not actually overloadable");
   7169 
   7170   case OO_None:
   7171   case NUM_OVERLOADED_OPERATORS:
   7172     llvm_unreachable("not an overloaded operator?");
   7173   }
   7174 
   7175   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
   7176   if (Callee.isInvalid())
   7177     return ExprError();
   7178 
   7179   ExprResult First;
   7180   if (E->getOperator() == OO_Amp)
   7181     First = getDerived().TransformAddressOfOperand(E->getArg(0));
   7182   else
   7183     First = getDerived().TransformExpr(E->getArg(0));
   7184   if (First.isInvalid())
   7185     return ExprError();
   7186 
   7187   ExprResult Second;
   7188   if (E->getNumArgs() == 2) {
   7189     Second = getDerived().TransformExpr(E->getArg(1));
   7190     if (Second.isInvalid())
   7191       return ExprError();
   7192   }
   7193 
   7194   if (!getDerived().AlwaysRebuild() &&
   7195       Callee.get() == E->getCallee() &&
   7196       First.get() == E->getArg(0) &&
   7197       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
   7198     return SemaRef.MaybeBindToTemporary(E);
   7199 
   7200   Sema::FPContractStateRAII FPContractState(getSema());
   7201   getSema().FPFeatures.fp_contract = E->isFPContractable();
   7202 
   7203   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
   7204                                                  E->getOperatorLoc(),
   7205                                                  Callee.get(),
   7206                                                  First.get(),
   7207                                                  Second.get());
   7208 }
   7209 
   7210 template<typename Derived>
   7211 ExprResult
   7212 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
   7213   return getDerived().TransformCallExpr(E);
   7214 }
   7215 
   7216 template<typename Derived>
   7217 ExprResult
   7218 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
   7219   // Transform the callee.
   7220   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
   7221   if (Callee.isInvalid())
   7222     return ExprError();
   7223 
   7224   // Transform exec config.
   7225   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
   7226   if (EC.isInvalid())
   7227     return ExprError();
   7228 
   7229   // Transform arguments.
   7230   bool ArgChanged = false;
   7231   SmallVector<Expr*, 8> Args;
   7232   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   7233                                   &ArgChanged))
   7234     return ExprError();
   7235 
   7236   if (!getDerived().AlwaysRebuild() &&
   7237       Callee.get() == E->getCallee() &&
   7238       !ArgChanged)
   7239     return SemaRef.MaybeBindToTemporary(E);
   7240 
   7241   // FIXME: Wrong source location information for the '('.
   7242   SourceLocation FakeLParenLoc
   7243     = ((Expr *)Callee.get())->getSourceRange().getBegin();
   7244   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
   7245                                       Args,
   7246                                       E->getRParenLoc(), EC.get());
   7247 }
   7248 
   7249 template<typename Derived>
   7250 ExprResult
   7251 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
   7252   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
   7253   if (!Type)
   7254     return ExprError();
   7255 
   7256   ExprResult SubExpr
   7257     = getDerived().TransformExpr(E->getSubExprAsWritten());
   7258   if (SubExpr.isInvalid())
   7259     return ExprError();
   7260 
   7261   if (!getDerived().AlwaysRebuild() &&
   7262       Type == E->getTypeInfoAsWritten() &&
   7263       SubExpr.get() == E->getSubExpr())
   7264     return SemaRef.Owned(E);
   7265   return getDerived().RebuildCXXNamedCastExpr(E->getOperatorLoc(),
   7266                                               E->getStmtClass(),
   7267                                               E->getAngleBrackets().getBegin(),
   7268                                               Type,
   7269                                               E->getAngleBrackets().getEnd(),
   7270                                               // FIXME. this should be '(' location
   7271                                               E->getAngleBrackets().getEnd(),
   7272                                               SubExpr.get(),
   7273                                               E->getRParenLoc());
   7274 }
   7275 
   7276 template<typename Derived>
   7277 ExprResult
   7278 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
   7279   return getDerived().TransformCXXNamedCastExpr(E);
   7280 }
   7281 
   7282 template<typename Derived>
   7283 ExprResult
   7284 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
   7285   return getDerived().TransformCXXNamedCastExpr(E);
   7286 }
   7287 
   7288 template<typename Derived>
   7289 ExprResult
   7290 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
   7291                                                       CXXReinterpretCastExpr *E) {
   7292   return getDerived().TransformCXXNamedCastExpr(E);
   7293 }
   7294 
   7295 template<typename Derived>
   7296 ExprResult
   7297 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
   7298   return getDerived().TransformCXXNamedCastExpr(E);
   7299 }
   7300 
   7301 template<typename Derived>
   7302 ExprResult
   7303 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
   7304                                                      CXXFunctionalCastExpr *E) {
   7305   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
   7306   if (!Type)
   7307     return ExprError();
   7308 
   7309   ExprResult SubExpr
   7310     = getDerived().TransformExpr(E->getSubExprAsWritten());
   7311   if (SubExpr.isInvalid())
   7312     return ExprError();
   7313 
   7314   if (!getDerived().AlwaysRebuild() &&
   7315       Type == E->getTypeInfoAsWritten() &&
   7316       SubExpr.get() == E->getSubExpr())
   7317     return SemaRef.Owned(E);
   7318 
   7319   return getDerived().RebuildCXXFunctionalCastExpr(Type,
   7320                                       /*FIXME:*/E->getSubExpr()->getLocStart(),
   7321                                                    SubExpr.get(),
   7322                                                    E->getRParenLoc());
   7323 }
   7324 
   7325 template<typename Derived>
   7326 ExprResult
   7327 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
   7328   if (E->isTypeOperand()) {
   7329     TypeSourceInfo *TInfo
   7330       = getDerived().TransformType(E->getTypeOperandSourceInfo());
   7331     if (!TInfo)
   7332       return ExprError();
   7333 
   7334     if (!getDerived().AlwaysRebuild() &&
   7335         TInfo == E->getTypeOperandSourceInfo())
   7336       return SemaRef.Owned(E);
   7337 
   7338     return getDerived().RebuildCXXTypeidExpr(E->getType(),
   7339                                              E->getLocStart(),
   7340                                              TInfo,
   7341                                              E->getLocEnd());
   7342   }
   7343 
   7344   // We don't know whether the subexpression is potentially evaluated until
   7345   // after we perform semantic analysis.  We speculatively assume it is
   7346   // unevaluated; it will get fixed later if the subexpression is in fact
   7347   // potentially evaluated.
   7348   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
   7349                                                Sema::ReuseLambdaContextDecl);
   7350 
   7351   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
   7352   if (SubExpr.isInvalid())
   7353     return ExprError();
   7354 
   7355   if (!getDerived().AlwaysRebuild() &&
   7356       SubExpr.get() == E->getExprOperand())
   7357     return SemaRef.Owned(E);
   7358 
   7359   return getDerived().RebuildCXXTypeidExpr(E->getType(),
   7360                                            E->getLocStart(),
   7361                                            SubExpr.get(),
   7362                                            E->getLocEnd());
   7363 }
   7364 
   7365 template<typename Derived>
   7366 ExprResult
   7367 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
   7368   if (E->isTypeOperand()) {
   7369     TypeSourceInfo *TInfo
   7370       = getDerived().TransformType(E->getTypeOperandSourceInfo());
   7371     if (!TInfo)
   7372       return ExprError();
   7373 
   7374     if (!getDerived().AlwaysRebuild() &&
   7375         TInfo == E->getTypeOperandSourceInfo())
   7376       return SemaRef.Owned(E);
   7377 
   7378     return getDerived().RebuildCXXUuidofExpr(E->getType(),
   7379                                              E->getLocStart(),
   7380                                              TInfo,
   7381                                              E->getLocEnd());
   7382   }
   7383 
   7384   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   7385 
   7386   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
   7387   if (SubExpr.isInvalid())
   7388     return ExprError();
   7389 
   7390   if (!getDerived().AlwaysRebuild() &&
   7391       SubExpr.get() == E->getExprOperand())
   7392     return SemaRef.Owned(E);
   7393 
   7394   return getDerived().RebuildCXXUuidofExpr(E->getType(),
   7395                                            E->getLocStart(),
   7396                                            SubExpr.get(),
   7397                                            E->getLocEnd());
   7398 }
   7399 
   7400 template<typename Derived>
   7401 ExprResult
   7402 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
   7403   return SemaRef.Owned(E);
   7404 }
   7405 
   7406 template<typename Derived>
   7407 ExprResult
   7408 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
   7409                                                      CXXNullPtrLiteralExpr *E) {
   7410   return SemaRef.Owned(E);
   7411 }
   7412 
   7413 template<typename Derived>
   7414 ExprResult
   7415 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
   7416   QualType T = getSema().getCurrentThisType();
   7417 
   7418   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
   7419     // Make sure that we capture 'this'.
   7420     getSema().CheckCXXThisCapture(E->getLocStart());
   7421     return SemaRef.Owned(E);
   7422   }
   7423 
   7424   return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
   7425 }
   7426 
   7427 template<typename Derived>
   7428 ExprResult
   7429 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
   7430   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   7431   if (SubExpr.isInvalid())
   7432     return ExprError();
   7433 
   7434   if (!getDerived().AlwaysRebuild() &&
   7435       SubExpr.get() == E->getSubExpr())
   7436     return SemaRef.Owned(E);
   7437 
   7438   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
   7439                                           E->isThrownVariableInScope());
   7440 }
   7441 
   7442 template<typename Derived>
   7443 ExprResult
   7444 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
   7445   ParmVarDecl *Param
   7446     = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
   7447                                                            E->getParam()));
   7448   if (!Param)
   7449     return ExprError();
   7450 
   7451   if (!getDerived().AlwaysRebuild() &&
   7452       Param == E->getParam())
   7453     return SemaRef.Owned(E);
   7454 
   7455   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
   7456 }
   7457 
   7458 template<typename Derived>
   7459 ExprResult
   7460 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
   7461   FieldDecl *Field
   7462     = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
   7463                                                          E->getField()));
   7464   if (!Field)
   7465     return ExprError();
   7466 
   7467   if (!getDerived().AlwaysRebuild() && Field == E->getField())
   7468     return SemaRef.Owned(E);
   7469 
   7470   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
   7471 }
   7472 
   7473 template<typename Derived>
   7474 ExprResult
   7475 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
   7476                                                     CXXScalarValueInitExpr *E) {
   7477   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
   7478   if (!T)
   7479     return ExprError();
   7480 
   7481   if (!getDerived().AlwaysRebuild() &&
   7482       T == E->getTypeSourceInfo())
   7483     return SemaRef.Owned(E);
   7484 
   7485   return getDerived().RebuildCXXScalarValueInitExpr(T,
   7486                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
   7487                                                     E->getRParenLoc());
   7488 }
   7489 
   7490 template<typename Derived>
   7491 ExprResult
   7492 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
   7493   // Transform the type that we're allocating
   7494   TypeSourceInfo *AllocTypeInfo
   7495     = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
   7496   if (!AllocTypeInfo)
   7497     return ExprError();
   7498 
   7499   // Transform the size of the array we're allocating (if any).
   7500   ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
   7501   if (ArraySize.isInvalid())
   7502     return ExprError();
   7503 
   7504   // Transform the placement arguments (if any).
   7505   bool ArgumentChanged = false;
   7506   SmallVector<Expr*, 8> PlacementArgs;
   7507   if (getDerived().TransformExprs(E->getPlacementArgs(),
   7508                                   E->getNumPlacementArgs(), true,
   7509                                   PlacementArgs, &ArgumentChanged))
   7510     return ExprError();
   7511 
   7512   // Transform the initializer (if any).
   7513   Expr *OldInit = E->getInitializer();
   7514   ExprResult NewInit;
   7515   if (OldInit)
   7516     NewInit = getDerived().TransformExpr(OldInit);
   7517   if (NewInit.isInvalid())
   7518     return ExprError();
   7519 
   7520   // Transform new operator and delete operator.
   7521   FunctionDecl *OperatorNew = 0;
   7522   if (E->getOperatorNew()) {
   7523     OperatorNew = cast_or_null<FunctionDecl>(
   7524                                  getDerived().TransformDecl(E->getLocStart(),
   7525                                                          E->getOperatorNew()));
   7526     if (!OperatorNew)
   7527       return ExprError();
   7528   }
   7529 
   7530   FunctionDecl *OperatorDelete = 0;
   7531   if (E->getOperatorDelete()) {
   7532     OperatorDelete = cast_or_null<FunctionDecl>(
   7533                                    getDerived().TransformDecl(E->getLocStart(),
   7534                                                        E->getOperatorDelete()));
   7535     if (!OperatorDelete)
   7536       return ExprError();
   7537   }
   7538 
   7539   if (!getDerived().AlwaysRebuild() &&
   7540       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
   7541       ArraySize.get() == E->getArraySize() &&
   7542       NewInit.get() == OldInit &&
   7543       OperatorNew == E->getOperatorNew() &&
   7544       OperatorDelete == E->getOperatorDelete() &&
   7545       !ArgumentChanged) {
   7546     // Mark any declarations we need as referenced.
   7547     // FIXME: instantiation-specific.
   7548     if (OperatorNew)
   7549       SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
   7550     if (OperatorDelete)
   7551       SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
   7552 
   7553     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
   7554       QualType ElementType
   7555         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
   7556       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
   7557         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
   7558         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
   7559           SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
   7560         }
   7561       }
   7562     }
   7563 
   7564     return SemaRef.Owned(E);
   7565   }
   7566 
   7567   QualType AllocType = AllocTypeInfo->getType();
   7568   if (!ArraySize.get()) {
   7569     // If no array size was specified, but the new expression was
   7570     // instantiated with an array type (e.g., "new T" where T is
   7571     // instantiated with "int[4]"), extract the outer bound from the
   7572     // array type as our array size. We do this with constant and
   7573     // dependently-sized array types.
   7574     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
   7575     if (!ArrayT) {
   7576       // Do nothing
   7577     } else if (const ConstantArrayType *ConsArrayT
   7578                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
   7579       ArraySize
   7580         = SemaRef.Owned(IntegerLiteral::Create(SemaRef.Context,
   7581                                                ConsArrayT->getSize(),
   7582                                                SemaRef.Context.getSizeType(),
   7583                                                /*FIXME:*/E->getLocStart()));
   7584       AllocType = ConsArrayT->getElementType();
   7585     } else if (const DependentSizedArrayType *DepArrayT
   7586                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
   7587       if (DepArrayT->getSizeExpr()) {
   7588         ArraySize = SemaRef.Owned(DepArrayT->getSizeExpr());
   7589         AllocType = DepArrayT->getElementType();
   7590       }
   7591     }
   7592   }
   7593 
   7594   return getDerived().RebuildCXXNewExpr(E->getLocStart(),
   7595                                         E->isGlobalNew(),
   7596                                         /*FIXME:*/E->getLocStart(),
   7597                                         PlacementArgs,
   7598                                         /*FIXME:*/E->getLocStart(),
   7599                                         E->getTypeIdParens(),
   7600                                         AllocType,
   7601                                         AllocTypeInfo,
   7602                                         ArraySize.get(),
   7603                                         E->getDirectInitRange(),
   7604                                         NewInit.take());
   7605 }
   7606 
   7607 template<typename Derived>
   7608 ExprResult
   7609 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
   7610   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
   7611   if (Operand.isInvalid())
   7612     return ExprError();
   7613 
   7614   // Transform the delete operator, if known.
   7615   FunctionDecl *OperatorDelete = 0;
   7616   if (E->getOperatorDelete()) {
   7617     OperatorDelete = cast_or_null<FunctionDecl>(
   7618                                    getDerived().TransformDecl(E->getLocStart(),
   7619                                                        E->getOperatorDelete()));
   7620     if (!OperatorDelete)
   7621       return ExprError();
   7622   }
   7623 
   7624   if (!getDerived().AlwaysRebuild() &&
   7625       Operand.get() == E->getArgument() &&
   7626       OperatorDelete == E->getOperatorDelete()) {
   7627     // Mark any declarations we need as referenced.
   7628     // FIXME: instantiation-specific.
   7629     if (OperatorDelete)
   7630       SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
   7631 
   7632     if (!E->getArgument()->isTypeDependent()) {
   7633       QualType Destroyed = SemaRef.Context.getBaseElementType(
   7634                                                          E->getDestroyedType());
   7635       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
   7636         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
   7637         SemaRef.MarkFunctionReferenced(E->getLocStart(),
   7638                                        SemaRef.LookupDestructor(Record));
   7639       }
   7640     }
   7641 
   7642     return SemaRef.Owned(E);
   7643   }
   7644 
   7645   return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
   7646                                            E->isGlobalDelete(),
   7647                                            E->isArrayForm(),
   7648                                            Operand.get());
   7649 }
   7650 
   7651 template<typename Derived>
   7652 ExprResult
   7653 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
   7654                                                      CXXPseudoDestructorExpr *E) {
   7655   ExprResult Base = getDerived().TransformExpr(E->getBase());
   7656   if (Base.isInvalid())
   7657     return ExprError();
   7658 
   7659   ParsedType ObjectTypePtr;
   7660   bool MayBePseudoDestructor = false;
   7661   Base = SemaRef.ActOnStartCXXMemberReference(0, Base.get(),
   7662                                               E->getOperatorLoc(),
   7663                                         E->isArrow()? tok::arrow : tok::period,
   7664                                               ObjectTypePtr,
   7665                                               MayBePseudoDestructor);
   7666   if (Base.isInvalid())
   7667     return ExprError();
   7668 
   7669   QualType ObjectType = ObjectTypePtr.get();
   7670   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
   7671   if (QualifierLoc) {
   7672     QualifierLoc
   7673       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
   7674     if (!QualifierLoc)
   7675       return ExprError();
   7676   }
   7677   CXXScopeSpec SS;
   7678   SS.Adopt(QualifierLoc);
   7679 
   7680   PseudoDestructorTypeStorage Destroyed;
   7681   if (E->getDestroyedTypeInfo()) {
   7682     TypeSourceInfo *DestroyedTypeInfo
   7683       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
   7684                                                 ObjectType, 0, SS);
   7685     if (!DestroyedTypeInfo)
   7686       return ExprError();
   7687     Destroyed = DestroyedTypeInfo;
   7688   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
   7689     // We aren't likely to be able to resolve the identifier down to a type
   7690     // now anyway, so just retain the identifier.
   7691     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
   7692                                             E->getDestroyedTypeLoc());
   7693   } else {
   7694     // Look for a destructor known with the given name.
   7695     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
   7696                                               *E->getDestroyedTypeIdentifier(),
   7697                                                 E->getDestroyedTypeLoc(),
   7698                                                 /*Scope=*/0,
   7699                                                 SS, ObjectTypePtr,
   7700                                                 false);
   7701     if (!T)
   7702       return ExprError();
   7703 
   7704     Destroyed
   7705       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
   7706                                                  E->getDestroyedTypeLoc());
   7707   }
   7708 
   7709   TypeSourceInfo *ScopeTypeInfo = 0;
   7710   if (E->getScopeTypeInfo()) {
   7711     CXXScopeSpec EmptySS;
   7712     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
   7713                       E->getScopeTypeInfo(), ObjectType, 0, EmptySS);
   7714     if (!ScopeTypeInfo)
   7715       return ExprError();
   7716   }
   7717 
   7718   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
   7719                                                      E->getOperatorLoc(),
   7720                                                      E->isArrow(),
   7721                                                      SS,
   7722                                                      ScopeTypeInfo,
   7723                                                      E->getColonColonLoc(),
   7724                                                      E->getTildeLoc(),
   7725                                                      Destroyed);
   7726 }
   7727 
   7728 template<typename Derived>
   7729 ExprResult
   7730 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
   7731                                                   UnresolvedLookupExpr *Old) {
   7732   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
   7733                  Sema::LookupOrdinaryName);
   7734 
   7735   // Transform all the decls.
   7736   for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
   7737          E = Old->decls_end(); I != E; ++I) {
   7738     NamedDecl *InstD = static_cast<NamedDecl*>(
   7739                                  getDerived().TransformDecl(Old->getNameLoc(),
   7740                                                             *I));
   7741     if (!InstD) {
   7742       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
   7743       // This can happen because of dependent hiding.
   7744       if (isa<UsingShadowDecl>(*I))
   7745         continue;
   7746       else
   7747         return ExprError();
   7748     }
   7749 
   7750     // Expand using declarations.
   7751     if (isa<UsingDecl>(InstD)) {
   7752       UsingDecl *UD = cast<UsingDecl>(InstD);
   7753       for (UsingDecl::shadow_iterator I = UD->shadow_begin(),
   7754              E = UD->shadow_end(); I != E; ++I)
   7755         R.addDecl(*I);
   7756       continue;
   7757     }
   7758 
   7759     R.addDecl(InstD);
   7760   }
   7761 
   7762   // Resolve a kind, but don't do any further analysis.  If it's
   7763   // ambiguous, the callee needs to deal with it.
   7764   R.resolveKind();
   7765 
   7766   // Rebuild the nested-name qualifier, if present.
   7767   CXXScopeSpec SS;
   7768   if (Old->getQualifierLoc()) {
   7769     NestedNameSpecifierLoc QualifierLoc
   7770       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
   7771     if (!QualifierLoc)
   7772       return ExprError();
   7773 
   7774     SS.Adopt(QualifierLoc);
   7775   }
   7776 
   7777   if (Old->getNamingClass()) {
   7778     CXXRecordDecl *NamingClass
   7779       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
   7780                                                             Old->getNameLoc(),
   7781                                                         Old->getNamingClass()));
   7782     if (!NamingClass)
   7783       return ExprError();
   7784 
   7785     R.setNamingClass(NamingClass);
   7786   }
   7787 
   7788   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
   7789 
   7790   // If we have neither explicit template arguments, nor the template keyword,
   7791   // it's a normal declaration name.
   7792   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid())
   7793     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
   7794 
   7795   // If we have template arguments, rebuild them, then rebuild the
   7796   // templateid expression.
   7797   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
   7798   if (Old->hasExplicitTemplateArgs() &&
   7799       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
   7800                                               Old->getNumTemplateArgs(),
   7801                                               TransArgs))
   7802     return ExprError();
   7803 
   7804   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
   7805                                             Old->requiresADL(), &TransArgs);
   7806 }
   7807 
   7808 template<typename Derived>
   7809 ExprResult
   7810 TreeTransform<Derived>::TransformUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
   7811   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
   7812   if (!T)
   7813     return ExprError();
   7814 
   7815   if (!getDerived().AlwaysRebuild() &&
   7816       T == E->getQueriedTypeSourceInfo())
   7817     return SemaRef.Owned(E);
   7818 
   7819   return getDerived().RebuildUnaryTypeTrait(E->getTrait(),
   7820                                             E->getLocStart(),
   7821                                             T,
   7822                                             E->getLocEnd());
   7823 }
   7824 
   7825 template<typename Derived>
   7826 ExprResult
   7827 TreeTransform<Derived>::TransformBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
   7828   TypeSourceInfo *LhsT = getDerived().TransformType(E->getLhsTypeSourceInfo());
   7829   if (!LhsT)
   7830     return ExprError();
   7831 
   7832   TypeSourceInfo *RhsT = getDerived().TransformType(E->getRhsTypeSourceInfo());
   7833   if (!RhsT)
   7834     return ExprError();
   7835 
   7836   if (!getDerived().AlwaysRebuild() &&
   7837       LhsT == E->getLhsTypeSourceInfo() && RhsT == E->getRhsTypeSourceInfo())
   7838     return SemaRef.Owned(E);
   7839 
   7840   return getDerived().RebuildBinaryTypeTrait(E->getTrait(),
   7841                                             E->getLocStart(),
   7842                                             LhsT, RhsT,
   7843                                             E->getLocEnd());
   7844 }
   7845 
   7846 template<typename Derived>
   7847 ExprResult
   7848 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
   7849   bool ArgChanged = false;
   7850   SmallVector<TypeSourceInfo *, 4> Args;
   7851   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
   7852     TypeSourceInfo *From = E->getArg(I);
   7853     TypeLoc FromTL = From->getTypeLoc();
   7854     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
   7855       TypeLocBuilder TLB;
   7856       TLB.reserve(FromTL.getFullDataSize());
   7857       QualType To = getDerived().TransformType(TLB, FromTL);
   7858       if (To.isNull())
   7859         return ExprError();
   7860 
   7861       if (To == From->getType())
   7862         Args.push_back(From);
   7863       else {
   7864         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
   7865         ArgChanged = true;
   7866       }
   7867       continue;
   7868     }
   7869 
   7870     ArgChanged = true;
   7871 
   7872     // We have a pack expansion. Instantiate it.
   7873     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
   7874     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
   7875     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   7876     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
   7877 
   7878     // Determine whether the set of unexpanded parameter packs can and should
   7879     // be expanded.
   7880     bool Expand = true;
   7881     bool RetainExpansion = false;
   7882     Optional<unsigned> OrigNumExpansions =
   7883         ExpansionTL.getTypePtr()->getNumExpansions();
   7884     Optional<unsigned> NumExpansions = OrigNumExpansions;
   7885     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
   7886                                              PatternTL.getSourceRange(),
   7887                                              Unexpanded,
   7888                                              Expand, RetainExpansion,
   7889                                              NumExpansions))
   7890       return ExprError();
   7891 
   7892     if (!Expand) {
   7893       // The transform has determined that we should perform a simple
   7894       // transformation on the pack expansion, producing another pack
   7895       // expansion.
   7896       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   7897 
   7898       TypeLocBuilder TLB;
   7899       TLB.reserve(From->getTypeLoc().getFullDataSize());
   7900 
   7901       QualType To = getDerived().TransformType(TLB, PatternTL);
   7902       if (To.isNull())
   7903         return ExprError();
   7904 
   7905       To = getDerived().RebuildPackExpansionType(To,
   7906                                                  PatternTL.getSourceRange(),
   7907                                                  ExpansionTL.getEllipsisLoc(),
   7908                                                  NumExpansions);
   7909       if (To.isNull())
   7910         return ExprError();
   7911 
   7912       PackExpansionTypeLoc ToExpansionTL
   7913         = TLB.push<PackExpansionTypeLoc>(To);
   7914       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
   7915       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
   7916       continue;
   7917     }
   7918 
   7919     // Expand the pack expansion by substituting for each argument in the
   7920     // pack(s).
   7921     for (unsigned I = 0; I != *NumExpansions; ++I) {
   7922       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
   7923       TypeLocBuilder TLB;
   7924       TLB.reserve(PatternTL.getFullDataSize());
   7925       QualType To = getDerived().TransformType(TLB, PatternTL);
   7926       if (To.isNull())
   7927         return ExprError();
   7928 
   7929       if (To->containsUnexpandedParameterPack()) {
   7930         To = getDerived().RebuildPackExpansionType(To,
   7931                                                    PatternTL.getSourceRange(),
   7932                                                    ExpansionTL.getEllipsisLoc(),
   7933                                                    NumExpansions);
   7934         if (To.isNull())
   7935           return ExprError();
   7936 
   7937         PackExpansionTypeLoc ToExpansionTL
   7938           = TLB.push<PackExpansionTypeLoc>(To);
   7939         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
   7940       }
   7941 
   7942       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
   7943     }
   7944 
   7945     if (!RetainExpansion)
   7946       continue;
   7947 
   7948     // If we're supposed to retain a pack expansion, do so by temporarily
   7949     // forgetting the partially-substituted parameter pack.
   7950     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   7951 
   7952     TypeLocBuilder TLB;
   7953     TLB.reserve(From->getTypeLoc().getFullDataSize());
   7954 
   7955     QualType To = getDerived().TransformType(TLB, PatternTL);
   7956     if (To.isNull())
   7957       return ExprError();
   7958 
   7959     To = getDerived().RebuildPackExpansionType(To,
   7960                                                PatternTL.getSourceRange(),
   7961                                                ExpansionTL.getEllipsisLoc(),
   7962                                                NumExpansions);
   7963     if (To.isNull())
   7964       return ExprError();
   7965 
   7966     PackExpansionTypeLoc ToExpansionTL
   7967       = TLB.push<PackExpansionTypeLoc>(To);
   7968     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
   7969     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
   7970   }
   7971 
   7972   if (!getDerived().AlwaysRebuild() && !ArgChanged)
   7973     return SemaRef.Owned(E);
   7974 
   7975   return getDerived().RebuildTypeTrait(E->getTrait(),
   7976                                        E->getLocStart(),
   7977                                        Args,
   7978                                        E->getLocEnd());
   7979 }
   7980 
   7981 template<typename Derived>
   7982 ExprResult
   7983 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
   7984   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
   7985   if (!T)
   7986     return ExprError();
   7987 
   7988   if (!getDerived().AlwaysRebuild() &&
   7989       T == E->getQueriedTypeSourceInfo())
   7990     return SemaRef.Owned(E);
   7991 
   7992   ExprResult SubExpr;
   7993   {
   7994     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   7995     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
   7996     if (SubExpr.isInvalid())
   7997       return ExprError();
   7998 
   7999     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
   8000       return SemaRef.Owned(E);
   8001   }
   8002 
   8003   return getDerived().RebuildArrayTypeTrait(E->getTrait(),
   8004                                             E->getLocStart(),
   8005                                             T,
   8006                                             SubExpr.get(),
   8007                                             E->getLocEnd());
   8008 }
   8009 
   8010 template<typename Derived>
   8011 ExprResult
   8012 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
   8013   ExprResult SubExpr;
   8014   {
   8015     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   8016     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
   8017     if (SubExpr.isInvalid())
   8018       return ExprError();
   8019 
   8020     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
   8021       return SemaRef.Owned(E);
   8022   }
   8023 
   8024   return getDerived().RebuildExpressionTrait(
   8025       E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
   8026 }
   8027 
   8028 template<typename Derived>
   8029 ExprResult
   8030 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
   8031                                                DependentScopeDeclRefExpr *E) {
   8032   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand*/false);
   8033 }
   8034 
   8035 template<typename Derived>
   8036 ExprResult
   8037 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
   8038                                                DependentScopeDeclRefExpr *E,
   8039                                                bool IsAddressOfOperand) {
   8040   NestedNameSpecifierLoc QualifierLoc
   8041   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   8042   if (!QualifierLoc)
   8043     return ExprError();
   8044   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
   8045 
   8046   // TODO: If this is a conversion-function-id, verify that the
   8047   // destination type name (if present) resolves the same way after
   8048   // instantiation as it did in the local scope.
   8049 
   8050   DeclarationNameInfo NameInfo
   8051     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
   8052   if (!NameInfo.getName())
   8053     return ExprError();
   8054 
   8055   if (!E->hasExplicitTemplateArgs()) {
   8056     if (!getDerived().AlwaysRebuild() &&
   8057         QualifierLoc == E->getQualifierLoc() &&
   8058         // Note: it is sufficient to compare the Name component of NameInfo:
   8059         // if name has not changed, DNLoc has not changed either.
   8060         NameInfo.getName() == E->getDeclName())
   8061       return SemaRef.Owned(E);
   8062 
   8063     return getDerived().RebuildDependentScopeDeclRefExpr(QualifierLoc,
   8064                                                          TemplateKWLoc,
   8065                                                          NameInfo,
   8066                                                          /*TemplateArgs*/ 0,
   8067                                                          IsAddressOfOperand);
   8068   }
   8069 
   8070   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
   8071   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   8072                                               E->getNumTemplateArgs(),
   8073                                               TransArgs))
   8074     return ExprError();
   8075 
   8076   return getDerived().RebuildDependentScopeDeclRefExpr(QualifierLoc,
   8077                                                        TemplateKWLoc,
   8078                                                        NameInfo,
   8079                                                        &TransArgs,
   8080                                                        IsAddressOfOperand);
   8081 }
   8082 
   8083 template<typename Derived>
   8084 ExprResult
   8085 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
   8086   // CXXConstructExprs other than for list-initialization and
   8087   // CXXTemporaryObjectExpr are always implicit, so when we have
   8088   // a 1-argument construction we just transform that argument.
   8089   if ((E->getNumArgs() == 1 ||
   8090        (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
   8091       (!getDerived().DropCallArgument(E->getArg(0))) &&
   8092       !E->isListInitialization())
   8093     return getDerived().TransformExpr(E->getArg(0));
   8094 
   8095   TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
   8096 
   8097   QualType T = getDerived().TransformType(E->getType());
   8098   if (T.isNull())
   8099     return ExprError();
   8100 
   8101   CXXConstructorDecl *Constructor
   8102     = cast_or_null<CXXConstructorDecl>(
   8103                                 getDerived().TransformDecl(E->getLocStart(),
   8104                                                          E->getConstructor()));
   8105   if (!Constructor)
   8106     return ExprError();
   8107 
   8108   bool ArgumentChanged = false;
   8109   SmallVector<Expr*, 8> Args;
   8110   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   8111                                   &ArgumentChanged))
   8112     return ExprError();
   8113 
   8114   if (!getDerived().AlwaysRebuild() &&
   8115       T == E->getType() &&
   8116       Constructor == E->getConstructor() &&
   8117       !ArgumentChanged) {
   8118     // Mark the constructor as referenced.
   8119     // FIXME: Instantiation-specific
   8120     SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
   8121     return SemaRef.Owned(E);
   8122   }
   8123 
   8124   return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
   8125                                               Constructor, E->isElidable(),
   8126                                               Args,
   8127                                               E->hadMultipleCandidates(),
   8128                                               E->isListInitialization(),
   8129                                               E->requiresZeroInitialization(),
   8130                                               E->getConstructionKind(),
   8131                                               E->getParenRange());
   8132 }
   8133 
   8134 /// \brief Transform a C++ temporary-binding expression.
   8135 ///
   8136 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
   8137 /// transform the subexpression and return that.
   8138 template<typename Derived>
   8139 ExprResult
   8140 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
   8141   return getDerived().TransformExpr(E->getSubExpr());
   8142 }
   8143 
   8144 /// \brief Transform a C++ expression that contains cleanups that should
   8145 /// be run after the expression is evaluated.
   8146 ///
   8147 /// Since ExprWithCleanups nodes are implicitly generated, we
   8148 /// just transform the subexpression and return that.
   8149 template<typename Derived>
   8150 ExprResult
   8151 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
   8152   return getDerived().TransformExpr(E->getSubExpr());
   8153 }
   8154 
   8155 template<typename Derived>
   8156 ExprResult
   8157 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
   8158                                                     CXXTemporaryObjectExpr *E) {
   8159   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
   8160   if (!T)
   8161     return ExprError();
   8162 
   8163   CXXConstructorDecl *Constructor
   8164     = cast_or_null<CXXConstructorDecl>(
   8165                                   getDerived().TransformDecl(E->getLocStart(),
   8166                                                          E->getConstructor()));
   8167   if (!Constructor)
   8168     return ExprError();
   8169 
   8170   bool ArgumentChanged = false;
   8171   SmallVector<Expr*, 8> Args;
   8172   Args.reserve(E->getNumArgs());
   8173   if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   8174                      &ArgumentChanged))
   8175     return ExprError();
   8176 
   8177   if (!getDerived().AlwaysRebuild() &&
   8178       T == E->getTypeSourceInfo() &&
   8179       Constructor == E->getConstructor() &&
   8180       !ArgumentChanged) {
   8181     // FIXME: Instantiation-specific
   8182     SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
   8183     return SemaRef.MaybeBindToTemporary(E);
   8184   }
   8185 
   8186   // FIXME: Pass in E->isListInitialization().
   8187   return getDerived().RebuildCXXTemporaryObjectExpr(T,
   8188                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
   8189                                                     Args,
   8190                                                     E->getLocEnd());
   8191 }
   8192 
   8193 template<typename Derived>
   8194 ExprResult
   8195 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
   8196   // Transform the type of the lambda parameters and start the definition of
   8197   // the lambda itself.
   8198   TypeSourceInfo *MethodTy
   8199     = TransformType(E->getCallOperator()->getTypeSourceInfo());
   8200   if (!MethodTy)
   8201     return ExprError();
   8202 
   8203   // Create the local class that will describe the lambda.
   8204   CXXRecordDecl *Class
   8205     = getSema().createLambdaClosureType(E->getIntroducerRange(),
   8206                                         MethodTy,
   8207                                         /*KnownDependent=*/false);
   8208   getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
   8209 
   8210   // Transform lambda parameters.
   8211   SmallVector<QualType, 4> ParamTypes;
   8212   SmallVector<ParmVarDecl *, 4> Params;
   8213   if (getDerived().TransformFunctionTypeParams(E->getLocStart(),
   8214         E->getCallOperator()->param_begin(),
   8215         E->getCallOperator()->param_size(),
   8216         0, ParamTypes, &Params))
   8217     return ExprError();
   8218 
   8219   // Build the call operator.
   8220   CXXMethodDecl *CallOperator
   8221     = getSema().startLambdaDefinition(Class, E->getIntroducerRange(),
   8222                                       MethodTy,
   8223                                       E->getCallOperator()->getLocEnd(),
   8224                                       Params);
   8225   getDerived().transformAttrs(E->getCallOperator(), CallOperator);
   8226 
   8227   return getDerived().TransformLambdaScope(E, CallOperator);
   8228 }
   8229 
   8230 template<typename Derived>
   8231 ExprResult
   8232 TreeTransform<Derived>::TransformLambdaScope(LambdaExpr *E,
   8233                                              CXXMethodDecl *CallOperator) {
   8234   bool Invalid = false;
   8235 
   8236   // Transform any init-capture expressions before entering the scope of the
   8237   // lambda.
   8238   llvm::SmallVector<ExprResult, 8> InitCaptureExprs;
   8239   InitCaptureExprs.resize(E->explicit_capture_end() -
   8240                           E->explicit_capture_begin());
   8241   for (LambdaExpr::capture_iterator C = E->capture_begin(),
   8242                                  CEnd = E->capture_end();
   8243        C != CEnd; ++C) {
   8244     if (!C->isInitCapture())
   8245       continue;
   8246     InitCaptureExprs[C - E->capture_begin()] =
   8247         getDerived().TransformExpr(E->getInitCaptureInit(C));
   8248   }
   8249 
   8250   // Introduce the context of the call operator.
   8251   Sema::ContextRAII SavedContext(getSema(), CallOperator);
   8252 
   8253   // Enter the scope of the lambda.
   8254   sema::LambdaScopeInfo *LSI
   8255     = getSema().enterLambdaScope(CallOperator, E->getIntroducerRange(),
   8256                                  E->getCaptureDefault(),
   8257                                  E->hasExplicitParameters(),
   8258                                  E->hasExplicitResultType(),
   8259                                  E->isMutable());
   8260 
   8261   // Transform captures.
   8262   bool FinishedExplicitCaptures = false;
   8263   for (LambdaExpr::capture_iterator C = E->capture_begin(),
   8264                                  CEnd = E->capture_end();
   8265        C != CEnd; ++C) {
   8266     // When we hit the first implicit capture, tell Sema that we've finished
   8267     // the list of explicit captures.
   8268     if (!FinishedExplicitCaptures && C->isImplicit()) {
   8269       getSema().finishLambdaExplicitCaptures(LSI);
   8270       FinishedExplicitCaptures = true;
   8271     }
   8272 
   8273     // Capturing 'this' is trivial.
   8274     if (C->capturesThis()) {
   8275       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit());
   8276       continue;
   8277     }
   8278 
   8279     // Rebuild init-captures, including the implied field declaration.
   8280     if (C->isInitCapture()) {
   8281       ExprResult Init = InitCaptureExprs[C - E->capture_begin()];
   8282       if (Init.isInvalid()) {
   8283         Invalid = true;
   8284         continue;
   8285       }
   8286       FieldDecl *OldFD = C->getInitCaptureField();
   8287       FieldDecl *NewFD = getSema().checkInitCapture(
   8288           C->getLocation(), OldFD->getType()->isReferenceType(),
   8289           OldFD->getIdentifier(), Init.take());
   8290       if (!NewFD)
   8291         Invalid = true;
   8292       else
   8293         getDerived().transformedLocalDecl(OldFD, NewFD);
   8294       continue;
   8295     }
   8296 
   8297     assert(C->capturesVariable() && "unexpected kind of lambda capture");
   8298 
   8299     // Determine the capture kind for Sema.
   8300     Sema::TryCaptureKind Kind
   8301       = C->isImplicit()? Sema::TryCapture_Implicit
   8302                        : C->getCaptureKind() == LCK_ByCopy
   8303                            ? Sema::TryCapture_ExplicitByVal
   8304                            : Sema::TryCapture_ExplicitByRef;
   8305     SourceLocation EllipsisLoc;
   8306     if (C->isPackExpansion()) {
   8307       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
   8308       bool ShouldExpand = false;
   8309       bool RetainExpansion = false;
   8310       Optional<unsigned> NumExpansions;
   8311       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
   8312                                                C->getLocation(),
   8313                                                Unexpanded,
   8314                                                ShouldExpand, RetainExpansion,
   8315                                                NumExpansions)) {
   8316         Invalid = true;
   8317         continue;
   8318       }
   8319 
   8320       if (ShouldExpand) {
   8321         // The transform has determined that we should perform an expansion;
   8322         // transform and capture each of the arguments.
   8323         // expansion of the pattern. Do so.
   8324         VarDecl *Pack = C->getCapturedVar();
   8325         for (unsigned I = 0; I != *NumExpansions; ++I) {
   8326           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   8327           VarDecl *CapturedVar
   8328             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
   8329                                                                Pack));
   8330           if (!CapturedVar) {
   8331             Invalid = true;
   8332             continue;
   8333           }
   8334 
   8335           // Capture the transformed variable.
   8336           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
   8337         }
   8338         continue;
   8339       }
   8340 
   8341       EllipsisLoc = C->getEllipsisLoc();
   8342     }
   8343 
   8344     // Transform the captured variable.
   8345     VarDecl *CapturedVar
   8346       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
   8347                                                          C->getCapturedVar()));
   8348     if (!CapturedVar) {
   8349       Invalid = true;
   8350       continue;
   8351     }
   8352 
   8353     // Capture the transformed variable.
   8354     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
   8355   }
   8356   if (!FinishedExplicitCaptures)
   8357     getSema().finishLambdaExplicitCaptures(LSI);
   8358 
   8359 
   8360   // Enter a new evaluation context to insulate the lambda from any
   8361   // cleanups from the enclosing full-expression.
   8362   getSema().PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
   8363 
   8364   if (Invalid) {
   8365     getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/0,
   8366                                /*IsInstantiation=*/true);
   8367     return ExprError();
   8368   }
   8369 
   8370   // Instantiate the body of the lambda expression.
   8371   StmtResult Body = getDerived().TransformStmt(E->getBody());
   8372   if (Body.isInvalid()) {
   8373     getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/0,
   8374                                /*IsInstantiation=*/true);
   8375     return ExprError();
   8376   }
   8377 
   8378   return getSema().ActOnLambdaExpr(E->getLocStart(), Body.take(),
   8379                                    /*CurScope=*/0, /*IsInstantiation=*/true);
   8380 }
   8381 
   8382 template<typename Derived>
   8383 ExprResult
   8384 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
   8385                                                   CXXUnresolvedConstructExpr *E) {
   8386   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
   8387   if (!T)
   8388     return ExprError();
   8389 
   8390   bool ArgumentChanged = false;
   8391   SmallVector<Expr*, 8> Args;
   8392   Args.reserve(E->arg_size());
   8393   if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
   8394                                   &ArgumentChanged))
   8395     return ExprError();
   8396 
   8397   if (!getDerived().AlwaysRebuild() &&
   8398       T == E->getTypeSourceInfo() &&
   8399       !ArgumentChanged)
   8400     return SemaRef.Owned(E);
   8401 
   8402   // FIXME: we're faking the locations of the commas
   8403   return getDerived().RebuildCXXUnresolvedConstructExpr(T,
   8404                                                         E->getLParenLoc(),
   8405                                                         Args,
   8406                                                         E->getRParenLoc());
   8407 }
   8408 
   8409 template<typename Derived>
   8410 ExprResult
   8411 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
   8412                                              CXXDependentScopeMemberExpr *E) {
   8413   // Transform the base of the expression.
   8414   ExprResult Base((Expr*) 0);
   8415   Expr *OldBase;
   8416   QualType BaseType;
   8417   QualType ObjectType;
   8418   if (!E->isImplicitAccess()) {
   8419     OldBase = E->getBase();
   8420     Base = getDerived().TransformExpr(OldBase);
   8421     if (Base.isInvalid())
   8422       return ExprError();
   8423 
   8424     // Start the member reference and compute the object's type.
   8425     ParsedType ObjectTy;
   8426     bool MayBePseudoDestructor = false;
   8427     Base = SemaRef.ActOnStartCXXMemberReference(0, Base.get(),
   8428                                                 E->getOperatorLoc(),
   8429                                       E->isArrow()? tok::arrow : tok::period,
   8430                                                 ObjectTy,
   8431                                                 MayBePseudoDestructor);
   8432     if (Base.isInvalid())
   8433       return ExprError();
   8434 
   8435     ObjectType = ObjectTy.get();
   8436     BaseType = ((Expr*) Base.get())->getType();
   8437   } else {
   8438     OldBase = 0;
   8439     BaseType = getDerived().TransformType(E->getBaseType());
   8440     ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
   8441   }
   8442 
   8443   // Transform the first part of the nested-name-specifier that qualifies
   8444   // the member name.
   8445   NamedDecl *FirstQualifierInScope
   8446     = getDerived().TransformFirstQualifierInScope(
   8447                                             E->getFirstQualifierFoundInScope(),
   8448                                             E->getQualifierLoc().getBeginLoc());
   8449 
   8450   NestedNameSpecifierLoc QualifierLoc;
   8451   if (E->getQualifier()) {
   8452     QualifierLoc
   8453       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
   8454                                                      ObjectType,
   8455                                                      FirstQualifierInScope);
   8456     if (!QualifierLoc)
   8457       return ExprError();
   8458   }
   8459 
   8460   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
   8461 
   8462   // TODO: If this is a conversion-function-id, verify that the
   8463   // destination type name (if present) resolves the same way after
   8464   // instantiation as it did in the local scope.
   8465 
   8466   DeclarationNameInfo NameInfo
   8467     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
   8468   if (!NameInfo.getName())
   8469     return ExprError();
   8470 
   8471   if (!E->hasExplicitTemplateArgs()) {
   8472     // This is a reference to a member without an explicitly-specified
   8473     // template argument list. Optimize for this common case.
   8474     if (!getDerived().AlwaysRebuild() &&
   8475         Base.get() == OldBase &&
   8476         BaseType == E->getBaseType() &&
   8477         QualifierLoc == E->getQualifierLoc() &&
   8478         NameInfo.getName() == E->getMember() &&
   8479         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
   8480       return SemaRef.Owned(E);
   8481 
   8482     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
   8483                                                        BaseType,
   8484                                                        E->isArrow(),
   8485                                                        E->getOperatorLoc(),
   8486                                                        QualifierLoc,
   8487                                                        TemplateKWLoc,
   8488                                                        FirstQualifierInScope,
   8489                                                        NameInfo,
   8490                                                        /*TemplateArgs*/ 0);
   8491   }
   8492 
   8493   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
   8494   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   8495                                               E->getNumTemplateArgs(),
   8496                                               TransArgs))
   8497     return ExprError();
   8498 
   8499   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
   8500                                                      BaseType,
   8501                                                      E->isArrow(),
   8502                                                      E->getOperatorLoc(),
   8503                                                      QualifierLoc,
   8504                                                      TemplateKWLoc,
   8505                                                      FirstQualifierInScope,
   8506                                                      NameInfo,
   8507                                                      &TransArgs);
   8508 }
   8509 
   8510 template<typename Derived>
   8511 ExprResult
   8512 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
   8513   // Transform the base of the expression.
   8514   ExprResult Base((Expr*) 0);
   8515   QualType BaseType;
   8516   if (!Old->isImplicitAccess()) {
   8517     Base = getDerived().TransformExpr(Old->getBase());
   8518     if (Base.isInvalid())
   8519       return ExprError();
   8520     Base = getSema().PerformMemberExprBaseConversion(Base.take(),
   8521                                                      Old->isArrow());
   8522     if (Base.isInvalid())
   8523       return ExprError();
   8524     BaseType = Base.get()->getType();
   8525   } else {
   8526     BaseType = getDerived().TransformType(Old->getBaseType());
   8527   }
   8528 
   8529   NestedNameSpecifierLoc QualifierLoc;
   8530   if (Old->getQualifierLoc()) {
   8531     QualifierLoc
   8532     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
   8533     if (!QualifierLoc)
   8534       return ExprError();
   8535   }
   8536 
   8537   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
   8538 
   8539   LookupResult R(SemaRef, Old->getMemberNameInfo(),
   8540                  Sema::LookupOrdinaryName);
   8541 
   8542   // Transform all the decls.
   8543   for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
   8544          E = Old->decls_end(); I != E; ++I) {
   8545     NamedDecl *InstD = static_cast<NamedDecl*>(
   8546                                 getDerived().TransformDecl(Old->getMemberLoc(),
   8547                                                            *I));
   8548     if (!InstD) {
   8549       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
   8550       // This can happen because of dependent hiding.
   8551       if (isa<UsingShadowDecl>(*I))
   8552         continue;
   8553       else {
   8554         R.clear();
   8555         return ExprError();
   8556       }
   8557     }
   8558 
   8559     // Expand using declarations.
   8560     if (isa<UsingDecl>(InstD)) {
   8561       UsingDecl *UD = cast<UsingDecl>(InstD);
   8562       for (UsingDecl::shadow_iterator I = UD->shadow_begin(),
   8563              E = UD->shadow_end(); I != E; ++I)
   8564         R.addDecl(*I);
   8565       continue;
   8566     }
   8567 
   8568     R.addDecl(InstD);
   8569   }
   8570 
   8571   R.resolveKind();
   8572 
   8573   // Determine the naming class.
   8574   if (Old->getNamingClass()) {
   8575     CXXRecordDecl *NamingClass
   8576       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
   8577                                                           Old->getMemberLoc(),
   8578                                                         Old->getNamingClass()));
   8579     if (!NamingClass)
   8580       return ExprError();
   8581 
   8582     R.setNamingClass(NamingClass);
   8583   }
   8584 
   8585   TemplateArgumentListInfo TransArgs;
   8586   if (Old->hasExplicitTemplateArgs()) {
   8587     TransArgs.setLAngleLoc(Old->getLAngleLoc());
   8588     TransArgs.setRAngleLoc(Old->getRAngleLoc());
   8589     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
   8590                                                 Old->getNumTemplateArgs(),
   8591                                                 TransArgs))
   8592       return ExprError();
   8593   }
   8594 
   8595   // FIXME: to do this check properly, we will need to preserve the
   8596   // first-qualifier-in-scope here, just in case we had a dependent
   8597   // base (and therefore couldn't do the check) and a
   8598   // nested-name-qualifier (and therefore could do the lookup).
   8599   NamedDecl *FirstQualifierInScope = 0;
   8600 
   8601   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
   8602                                                   BaseType,
   8603                                                   Old->getOperatorLoc(),
   8604                                                   Old->isArrow(),
   8605                                                   QualifierLoc,
   8606                                                   TemplateKWLoc,
   8607                                                   FirstQualifierInScope,
   8608                                                   R,
   8609                                               (Old->hasExplicitTemplateArgs()
   8610                                                   ? &TransArgs : 0));
   8611 }
   8612 
   8613 template<typename Derived>
   8614 ExprResult
   8615 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
   8616   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   8617   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
   8618   if (SubExpr.isInvalid())
   8619     return ExprError();
   8620 
   8621   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
   8622     return SemaRef.Owned(E);
   8623 
   8624   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
   8625 }
   8626 
   8627 template<typename Derived>
   8628 ExprResult
   8629 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
   8630   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
   8631   if (Pattern.isInvalid())
   8632     return ExprError();
   8633 
   8634   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
   8635     return SemaRef.Owned(E);
   8636 
   8637   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
   8638                                            E->getNumExpansions());
   8639 }
   8640 
   8641 template<typename Derived>
   8642 ExprResult
   8643 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
   8644   // If E is not value-dependent, then nothing will change when we transform it.
   8645   // Note: This is an instantiation-centric view.
   8646   if (!E->isValueDependent())
   8647     return SemaRef.Owned(E);
   8648 
   8649   // Note: None of the implementations of TryExpandParameterPacks can ever
   8650   // produce a diagnostic when given only a single unexpanded parameter pack,
   8651   // so
   8652   UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
   8653   bool ShouldExpand = false;
   8654   bool RetainExpansion = false;
   8655   Optional<unsigned> NumExpansions;
   8656   if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
   8657                                            Unexpanded,
   8658                                            ShouldExpand, RetainExpansion,
   8659                                            NumExpansions))
   8660     return ExprError();
   8661 
   8662   if (RetainExpansion)
   8663     return SemaRef.Owned(E);
   8664 
   8665   NamedDecl *Pack = E->getPack();
   8666   if (!ShouldExpand) {
   8667     Pack = cast_or_null<NamedDecl>(getDerived().TransformDecl(E->getPackLoc(),
   8668                                                               Pack));
   8669     if (!Pack)
   8670       return ExprError();
   8671   }
   8672 
   8673 
   8674   // We now know the length of the parameter pack, so build a new expression
   8675   // that stores that length.
   8676   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
   8677                                             E->getPackLoc(), E->getRParenLoc(),
   8678                                             NumExpansions);
   8679 }
   8680 
   8681 template<typename Derived>
   8682 ExprResult
   8683 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
   8684                                           SubstNonTypeTemplateParmPackExpr *E) {
   8685   // Default behavior is to do nothing with this transformation.
   8686   return SemaRef.Owned(E);
   8687 }
   8688 
   8689 template<typename Derived>
   8690 ExprResult
   8691 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
   8692                                           SubstNonTypeTemplateParmExpr *E) {
   8693   // Default behavior is to do nothing with this transformation.
   8694   return SemaRef.Owned(E);
   8695 }
   8696 
   8697 template<typename Derived>
   8698 ExprResult
   8699 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
   8700   // Default behavior is to do nothing with this transformation.
   8701   return SemaRef.Owned(E);
   8702 }
   8703 
   8704 template<typename Derived>
   8705 ExprResult
   8706 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
   8707                                                   MaterializeTemporaryExpr *E) {
   8708   return getDerived().TransformExpr(E->GetTemporaryExpr());
   8709 }
   8710 
   8711 template<typename Derived>
   8712 ExprResult
   8713 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
   8714     CXXStdInitializerListExpr *E) {
   8715   return getDerived().TransformExpr(E->getSubExpr());
   8716 }
   8717 
   8718 template<typename Derived>
   8719 ExprResult
   8720 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
   8721   return SemaRef.MaybeBindToTemporary(E);
   8722 }
   8723 
   8724 template<typename Derived>
   8725 ExprResult
   8726 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
   8727   return SemaRef.Owned(E);
   8728 }
   8729 
   8730 template<typename Derived>
   8731 ExprResult
   8732 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
   8733   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   8734   if (SubExpr.isInvalid())
   8735     return ExprError();
   8736 
   8737   if (!getDerived().AlwaysRebuild() &&
   8738       SubExpr.get() == E->getSubExpr())
   8739     return SemaRef.Owned(E);
   8740 
   8741   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
   8742 }
   8743 
   8744 template<typename Derived>
   8745 ExprResult
   8746 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
   8747   // Transform each of the elements.
   8748   SmallVector<Expr *, 8> Elements;
   8749   bool ArgChanged = false;
   8750   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
   8751                                   /*IsCall=*/false, Elements, &ArgChanged))
   8752     return ExprError();
   8753 
   8754   if (!getDerived().AlwaysRebuild() && !ArgChanged)
   8755     return SemaRef.MaybeBindToTemporary(E);
   8756 
   8757   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
   8758                                               Elements.data(),
   8759                                               Elements.size());
   8760 }
   8761 
   8762 template<typename Derived>
   8763 ExprResult
   8764 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
   8765                                                     ObjCDictionaryLiteral *E) {
   8766   // Transform each of the elements.
   8767   SmallVector<ObjCDictionaryElement, 8> Elements;
   8768   bool ArgChanged = false;
   8769   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
   8770     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
   8771 
   8772     if (OrigElement.isPackExpansion()) {
   8773       // This key/value element is a pack expansion.
   8774       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   8775       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
   8776       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
   8777       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   8778 
   8779       // Determine whether the set of unexpanded parameter packs can
   8780       // and should be expanded.
   8781       bool Expand = true;
   8782       bool RetainExpansion = false;
   8783       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
   8784       Optional<unsigned> NumExpansions = OrigNumExpansions;
   8785       SourceRange PatternRange(OrigElement.Key->getLocStart(),
   8786                                OrigElement.Value->getLocEnd());
   8787      if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
   8788                                                PatternRange,
   8789                                                Unexpanded,
   8790                                                Expand, RetainExpansion,
   8791                                                NumExpansions))
   8792         return ExprError();
   8793 
   8794       if (!Expand) {
   8795         // The transform has determined that we should perform a simple
   8796         // transformation on the pack expansion, producing another pack
   8797         // expansion.
   8798         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   8799         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
   8800         if (Key.isInvalid())
   8801           return ExprError();
   8802 
   8803         if (Key.get() != OrigElement.Key)
   8804           ArgChanged = true;
   8805 
   8806         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
   8807         if (Value.isInvalid())
   8808           return ExprError();
   8809 
   8810         if (Value.get() != OrigElement.Value)
   8811           ArgChanged = true;
   8812 
   8813         ObjCDictionaryElement Expansion = {
   8814           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
   8815         };
   8816         Elements.push_back(Expansion);
   8817         continue;
   8818       }
   8819 
   8820       // Record right away that the argument was changed.  This needs
   8821       // to happen even if the array expands to nothing.
   8822       ArgChanged = true;
   8823 
   8824       // The transform has determined that we should perform an elementwise
   8825       // expansion of the pattern. Do so.
   8826       for (unsigned I = 0; I != *NumExpansions; ++I) {
   8827         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   8828         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
   8829         if (Key.isInvalid())
   8830           return ExprError();
   8831 
   8832         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
   8833         if (Value.isInvalid())
   8834           return ExprError();
   8835 
   8836         ObjCDictionaryElement Element = {
   8837           Key.get(), Value.get(), SourceLocation(), NumExpansions
   8838         };
   8839 
   8840         // If any unexpanded parameter packs remain, we still have a
   8841         // pack expansion.
   8842         if (Key.get()->containsUnexpandedParameterPack() ||
   8843             Value.get()->containsUnexpandedParameterPack())
   8844           Element.EllipsisLoc = OrigElement.EllipsisLoc;
   8845 
   8846         Elements.push_back(Element);
   8847       }
   8848 
   8849       // We've finished with this pack expansion.
   8850       continue;
   8851     }
   8852 
   8853     // Transform and check key.
   8854     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
   8855     if (Key.isInvalid())
   8856       return ExprError();
   8857 
   8858     if (Key.get() != OrigElement.Key)
   8859       ArgChanged = true;
   8860 
   8861     // Transform and check value.
   8862     ExprResult Value
   8863       = getDerived().TransformExpr(OrigElement.Value);
   8864     if (Value.isInvalid())
   8865       return ExprError();
   8866 
   8867     if (Value.get() != OrigElement.Value)
   8868       ArgChanged = true;
   8869 
   8870     ObjCDictionaryElement Element = {
   8871       Key.get(), Value.get(), SourceLocation(), None
   8872     };
   8873     Elements.push_back(Element);
   8874   }
   8875 
   8876   if (!getDerived().AlwaysRebuild() && !ArgChanged)
   8877     return SemaRef.MaybeBindToTemporary(E);
   8878 
   8879   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
   8880                                                    Elements.data(),
   8881                                                    Elements.size());
   8882 }
   8883 
   8884 template<typename Derived>
   8885 ExprResult
   8886 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
   8887   TypeSourceInfo *EncodedTypeInfo
   8888     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
   8889   if (!EncodedTypeInfo)
   8890     return ExprError();
   8891 
   8892   if (!getDerived().AlwaysRebuild() &&
   8893       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
   8894     return SemaRef.Owned(E);
   8895 
   8896   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
   8897                                             EncodedTypeInfo,
   8898                                             E->getRParenLoc());
   8899 }
   8900 
   8901 template<typename Derived>
   8902 ExprResult TreeTransform<Derived>::
   8903 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
   8904   // This is a kind of implicit conversion, and it needs to get dropped
   8905   // and recomputed for the same general reasons that ImplicitCastExprs
   8906   // do, as well a more specific one: this expression is only valid when
   8907   // it appears *immediately* as an argument expression.
   8908   return getDerived().TransformExpr(E->getSubExpr());
   8909 }
   8910 
   8911 template<typename Derived>
   8912 ExprResult TreeTransform<Derived>::
   8913 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
   8914   TypeSourceInfo *TSInfo
   8915     = getDerived().TransformType(E->getTypeInfoAsWritten());
   8916   if (!TSInfo)
   8917     return ExprError();
   8918 
   8919   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
   8920   if (Result.isInvalid())
   8921     return ExprError();
   8922 
   8923   if (!getDerived().AlwaysRebuild() &&
   8924       TSInfo == E->getTypeInfoAsWritten() &&
   8925       Result.get() == E->getSubExpr())
   8926     return SemaRef.Owned(E);
   8927 
   8928   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
   8929                                       E->getBridgeKeywordLoc(), TSInfo,
   8930                                       Result.get());
   8931 }
   8932 
   8933 template<typename Derived>
   8934 ExprResult
   8935 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
   8936   // Transform arguments.
   8937   bool ArgChanged = false;
   8938   SmallVector<Expr*, 8> Args;
   8939   Args.reserve(E->getNumArgs());
   8940   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
   8941                                   &ArgChanged))
   8942     return ExprError();
   8943 
   8944   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
   8945     // Class message: transform the receiver type.
   8946     TypeSourceInfo *ReceiverTypeInfo
   8947       = getDerived().TransformType(E->getClassReceiverTypeInfo());
   8948     if (!ReceiverTypeInfo)
   8949       return ExprError();
   8950 
   8951     // If nothing changed, just retain the existing message send.
   8952     if (!getDerived().AlwaysRebuild() &&
   8953         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
   8954       return SemaRef.MaybeBindToTemporary(E);
   8955 
   8956     // Build a new class message send.
   8957     SmallVector<SourceLocation, 16> SelLocs;
   8958     E->getSelectorLocs(SelLocs);
   8959     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
   8960                                                E->getSelector(),
   8961                                                SelLocs,
   8962                                                E->getMethodDecl(),
   8963                                                E->getLeftLoc(),
   8964                                                Args,
   8965                                                E->getRightLoc());
   8966   }
   8967 
   8968   // Instance message: transform the receiver
   8969   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
   8970          "Only class and instance messages may be instantiated");
   8971   ExprResult Receiver
   8972     = getDerived().TransformExpr(E->getInstanceReceiver());
   8973   if (Receiver.isInvalid())
   8974     return ExprError();
   8975 
   8976   // If nothing changed, just retain the existing message send.
   8977   if (!getDerived().AlwaysRebuild() &&
   8978       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
   8979     return SemaRef.MaybeBindToTemporary(E);
   8980 
   8981   // Build a new instance message send.
   8982   SmallVector<SourceLocation, 16> SelLocs;
   8983   E->getSelectorLocs(SelLocs);
   8984   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
   8985                                              E->getSelector(),
   8986                                              SelLocs,
   8987                                              E->getMethodDecl(),
   8988                                              E->getLeftLoc(),
   8989                                              Args,
   8990                                              E->getRightLoc());
   8991 }
   8992 
   8993 template<typename Derived>
   8994 ExprResult
   8995 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
   8996   return SemaRef.Owned(E);
   8997 }
   8998 
   8999 template<typename Derived>
   9000 ExprResult
   9001 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
   9002   return SemaRef.Owned(E);
   9003 }
   9004 
   9005 template<typename Derived>
   9006 ExprResult
   9007 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
   9008   // Transform the base expression.
   9009   ExprResult Base = getDerived().TransformExpr(E->getBase());
   9010   if (Base.isInvalid())
   9011     return ExprError();
   9012 
   9013   // We don't need to transform the ivar; it will never change.
   9014 
   9015   // If nothing changed, just retain the existing expression.
   9016   if (!getDerived().AlwaysRebuild() &&
   9017       Base.get() == E->getBase())
   9018     return SemaRef.Owned(E);
   9019 
   9020   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
   9021                                              E->getLocation(),
   9022                                              E->isArrow(), E->isFreeIvar());
   9023 }
   9024 
   9025 template<typename Derived>
   9026 ExprResult
   9027 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
   9028   // 'super' and types never change. Property never changes. Just
   9029   // retain the existing expression.
   9030   if (!E->isObjectReceiver())
   9031     return SemaRef.Owned(E);
   9032 
   9033   // Transform the base expression.
   9034   ExprResult Base = getDerived().TransformExpr(E->getBase());
   9035   if (Base.isInvalid())
   9036     return ExprError();
   9037 
   9038   // We don't need to transform the property; it will never change.
   9039 
   9040   // If nothing changed, just retain the existing expression.
   9041   if (!getDerived().AlwaysRebuild() &&
   9042       Base.get() == E->getBase())
   9043     return SemaRef.Owned(E);
   9044 
   9045   if (E->isExplicitProperty())
   9046     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
   9047                                                    E->getExplicitProperty(),
   9048                                                    E->getLocation());
   9049 
   9050   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
   9051                                                  SemaRef.Context.PseudoObjectTy,
   9052                                                  E->getImplicitPropertyGetter(),
   9053                                                  E->getImplicitPropertySetter(),
   9054                                                  E->getLocation());
   9055 }
   9056 
   9057 template<typename Derived>
   9058 ExprResult
   9059 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
   9060   // Transform the base expression.
   9061   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
   9062   if (Base.isInvalid())
   9063     return ExprError();
   9064 
   9065   // Transform the key expression.
   9066   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
   9067   if (Key.isInvalid())
   9068     return ExprError();
   9069 
   9070   // If nothing changed, just retain the existing expression.
   9071   if (!getDerived().AlwaysRebuild() &&
   9072       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
   9073     return SemaRef.Owned(E);
   9074 
   9075   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
   9076                                                   Base.get(), Key.get(),
   9077                                                   E->getAtIndexMethodDecl(),
   9078                                                   E->setAtIndexMethodDecl());
   9079 }
   9080 
   9081 template<typename Derived>
   9082 ExprResult
   9083 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
   9084   // Transform the base expression.
   9085   ExprResult Base = getDerived().TransformExpr(E->getBase());
   9086   if (Base.isInvalid())
   9087     return ExprError();
   9088 
   9089   // If nothing changed, just retain the existing expression.
   9090   if (!getDerived().AlwaysRebuild() &&
   9091       Base.get() == E->getBase())
   9092     return SemaRef.Owned(E);
   9093 
   9094   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
   9095                                          E->getOpLoc(),
   9096                                          E->isArrow());
   9097 }
   9098 
   9099 template<typename Derived>
   9100 ExprResult
   9101 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
   9102   bool ArgumentChanged = false;
   9103   SmallVector<Expr*, 8> SubExprs;
   9104   SubExprs.reserve(E->getNumSubExprs());
   9105   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
   9106                                   SubExprs, &ArgumentChanged))
   9107     return ExprError();
   9108 
   9109   if (!getDerived().AlwaysRebuild() &&
   9110       !ArgumentChanged)
   9111     return SemaRef.Owned(E);
   9112 
   9113   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
   9114                                                SubExprs,
   9115                                                E->getRParenLoc());
   9116 }
   9117 
   9118 template<typename Derived>
   9119 ExprResult
   9120 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
   9121   BlockDecl *oldBlock = E->getBlockDecl();
   9122 
   9123   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/0);
   9124   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
   9125 
   9126   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
   9127   blockScope->TheDecl->setBlockMissingReturnType(
   9128                          oldBlock->blockMissingReturnType());
   9129 
   9130   SmallVector<ParmVarDecl*, 4> params;
   9131   SmallVector<QualType, 4> paramTypes;
   9132 
   9133   // Parameter substitution.
   9134   if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
   9135                                                oldBlock->param_begin(),
   9136                                                oldBlock->param_size(),
   9137                                                0, paramTypes, &params)) {
   9138     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/0);
   9139     return ExprError();
   9140   }
   9141 
   9142   const FunctionProtoType *exprFunctionType = E->getFunctionType();
   9143   QualType exprResultType =
   9144       getDerived().TransformType(exprFunctionType->getResultType());
   9145 
   9146   QualType functionType =
   9147     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes,
   9148                                           exprFunctionType->getExtProtoInfo());
   9149   blockScope->FunctionType = functionType;
   9150 
   9151   // Set the parameters on the block decl.
   9152   if (!params.empty())
   9153     blockScope->TheDecl->setParams(params);
   9154 
   9155   if (!oldBlock->blockMissingReturnType()) {
   9156     blockScope->HasImplicitReturnType = false;
   9157     blockScope->ReturnType = exprResultType;
   9158   }
   9159 
   9160   // Transform the body
   9161   StmtResult body = getDerived().TransformStmt(E->getBody());
   9162   if (body.isInvalid()) {
   9163     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/0);
   9164     return ExprError();
   9165   }
   9166 
   9167 #ifndef NDEBUG
   9168   // In builds with assertions, make sure that we captured everything we
   9169   // captured before.
   9170   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
   9171     for (BlockDecl::capture_iterator i = oldBlock->capture_begin(),
   9172            e = oldBlock->capture_end(); i != e; ++i) {
   9173       VarDecl *oldCapture = i->getVariable();
   9174 
   9175       // Ignore parameter packs.
   9176       if (isa<ParmVarDecl>(oldCapture) &&
   9177           cast<ParmVarDecl>(oldCapture)->isParameterPack())
   9178         continue;
   9179 
   9180       VarDecl *newCapture =
   9181         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
   9182                                                  oldCapture));
   9183       assert(blockScope->CaptureMap.count(newCapture));
   9184     }
   9185     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
   9186   }
   9187 #endif
   9188 
   9189   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
   9190                                     /*Scope=*/0);
   9191 }
   9192 
   9193 template<typename Derived>
   9194 ExprResult
   9195 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
   9196   llvm_unreachable("Cannot transform asType expressions yet");
   9197 }
   9198 
   9199 template<typename Derived>
   9200 ExprResult
   9201 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
   9202   QualType RetTy = getDerived().TransformType(E->getType());
   9203   bool ArgumentChanged = false;
   9204   SmallVector<Expr*, 8> SubExprs;
   9205   SubExprs.reserve(E->getNumSubExprs());
   9206   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
   9207                                   SubExprs, &ArgumentChanged))
   9208     return ExprError();
   9209 
   9210   if (!getDerived().AlwaysRebuild() &&
   9211       !ArgumentChanged)
   9212     return SemaRef.Owned(E);
   9213 
   9214   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
   9215                                         RetTy, E->getOp(), E->getRParenLoc());
   9216 }
   9217 
   9218 //===----------------------------------------------------------------------===//
   9219 // Type reconstruction
   9220 //===----------------------------------------------------------------------===//
   9221 
   9222 template<typename Derived>
   9223 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
   9224                                                     SourceLocation Star) {
   9225   return SemaRef.BuildPointerType(PointeeType, Star,
   9226                                   getDerived().getBaseEntity());
   9227 }
   9228 
   9229 template<typename Derived>
   9230 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
   9231                                                          SourceLocation Star) {
   9232   return SemaRef.BuildBlockPointerType(PointeeType, Star,
   9233                                        getDerived().getBaseEntity());
   9234 }
   9235 
   9236 template<typename Derived>
   9237 QualType
   9238 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
   9239                                              bool WrittenAsLValue,
   9240                                              SourceLocation Sigil) {
   9241   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
   9242                                     Sigil, getDerived().getBaseEntity());
   9243 }
   9244 
   9245 template<typename Derived>
   9246 QualType
   9247 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
   9248                                                  QualType ClassType,
   9249                                                  SourceLocation Sigil) {
   9250   return SemaRef.BuildMemberPointerType(PointeeType, ClassType,
   9251                                         Sigil, getDerived().getBaseEntity());
   9252 }
   9253 
   9254 template<typename Derived>
   9255 QualType
   9256 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
   9257                                          ArrayType::ArraySizeModifier SizeMod,
   9258                                          const llvm::APInt *Size,
   9259                                          Expr *SizeExpr,
   9260                                          unsigned IndexTypeQuals,
   9261                                          SourceRange BracketsRange) {
   9262   if (SizeExpr || !Size)
   9263     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
   9264                                   IndexTypeQuals, BracketsRange,
   9265                                   getDerived().getBaseEntity());
   9266 
   9267   QualType Types[] = {
   9268     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
   9269     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
   9270     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
   9271   };
   9272   const unsigned NumTypes = llvm::array_lengthof(Types);
   9273   QualType SizeType;
   9274   for (unsigned I = 0; I != NumTypes; ++I)
   9275     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
   9276       SizeType = Types[I];
   9277       break;
   9278     }
   9279 
   9280   // Note that we can return a VariableArrayType here in the case where
   9281   // the element type was a dependent VariableArrayType.
   9282   IntegerLiteral *ArraySize
   9283       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
   9284                                /*FIXME*/BracketsRange.getBegin());
   9285   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
   9286                                 IndexTypeQuals, BracketsRange,
   9287                                 getDerived().getBaseEntity());
   9288 }
   9289 
   9290 template<typename Derived>
   9291 QualType
   9292 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
   9293                                                  ArrayType::ArraySizeModifier SizeMod,
   9294                                                  const llvm::APInt &Size,
   9295                                                  unsigned IndexTypeQuals,
   9296                                                  SourceRange BracketsRange) {
   9297   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, 0,
   9298                                         IndexTypeQuals, BracketsRange);
   9299 }
   9300 
   9301 template<typename Derived>
   9302 QualType
   9303 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
   9304                                           ArrayType::ArraySizeModifier SizeMod,
   9305                                                  unsigned IndexTypeQuals,
   9306                                                    SourceRange BracketsRange) {
   9307   return getDerived().RebuildArrayType(ElementType, SizeMod, 0, 0,
   9308                                        IndexTypeQuals, BracketsRange);
   9309 }
   9310 
   9311 template<typename Derived>
   9312 QualType
   9313 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
   9314                                           ArrayType::ArraySizeModifier SizeMod,
   9315                                                  Expr *SizeExpr,
   9316                                                  unsigned IndexTypeQuals,
   9317                                                  SourceRange BracketsRange) {
   9318   return getDerived().RebuildArrayType(ElementType, SizeMod, 0,
   9319                                        SizeExpr,
   9320                                        IndexTypeQuals, BracketsRange);
   9321 }
   9322 
   9323 template<typename Derived>
   9324 QualType
   9325 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
   9326                                           ArrayType::ArraySizeModifier SizeMod,
   9327                                                        Expr *SizeExpr,
   9328                                                        unsigned IndexTypeQuals,
   9329                                                    SourceRange BracketsRange) {
   9330   return getDerived().RebuildArrayType(ElementType, SizeMod, 0,
   9331                                        SizeExpr,
   9332                                        IndexTypeQuals, BracketsRange);
   9333 }
   9334 
   9335 template<typename Derived>
   9336 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
   9337                                                unsigned NumElements,
   9338                                                VectorType::VectorKind VecKind) {
   9339   // FIXME: semantic checking!
   9340   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
   9341 }
   9342 
   9343 template<typename Derived>
   9344 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
   9345                                                       unsigned NumElements,
   9346                                                  SourceLocation AttributeLoc) {
   9347   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
   9348                           NumElements, true);
   9349   IntegerLiteral *VectorSize
   9350     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
   9351                              AttributeLoc);
   9352   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
   9353 }
   9354 
   9355 template<typename Derived>
   9356 QualType
   9357 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
   9358                                                            Expr *SizeExpr,
   9359                                                   SourceLocation AttributeLoc) {
   9360   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
   9361 }
   9362 
   9363 template<typename Derived>
   9364 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
   9365     QualType T,
   9366     llvm::MutableArrayRef<QualType> ParamTypes,
   9367     const FunctionProtoType::ExtProtoInfo &EPI) {
   9368   return SemaRef.BuildFunctionType(T, ParamTypes,
   9369                                    getDerived().getBaseLocation(),
   9370                                    getDerived().getBaseEntity(),
   9371                                    EPI);
   9372 }
   9373 
   9374 template<typename Derived>
   9375 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
   9376   return SemaRef.Context.getFunctionNoProtoType(T);
   9377 }
   9378 
   9379 template<typename Derived>
   9380 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
   9381   assert(D && "no decl found");
   9382   if (D->isInvalidDecl()) return QualType();
   9383 
   9384   // FIXME: Doesn't account for ObjCInterfaceDecl!
   9385   TypeDecl *Ty;
   9386   if (isa<UsingDecl>(D)) {
   9387     UsingDecl *Using = cast<UsingDecl>(D);
   9388     assert(Using->hasTypename() &&
   9389            "UnresolvedUsingTypenameDecl transformed to non-typename using");
   9390 
   9391     // A valid resolved using typename decl points to exactly one type decl.
   9392     assert(++Using->shadow_begin() == Using->shadow_end());
   9393     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
   9394 
   9395   } else {
   9396     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
   9397            "UnresolvedUsingTypenameDecl transformed to non-using decl");
   9398     Ty = cast<UnresolvedUsingTypenameDecl>(D);
   9399   }
   9400 
   9401   return SemaRef.Context.getTypeDeclType(Ty);
   9402 }
   9403 
   9404 template<typename Derived>
   9405 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
   9406                                                        SourceLocation Loc) {
   9407   return SemaRef.BuildTypeofExprType(E, Loc);
   9408 }
   9409 
   9410 template<typename Derived>
   9411 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
   9412   return SemaRef.Context.getTypeOfType(Underlying);
   9413 }
   9414 
   9415 template<typename Derived>
   9416 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
   9417                                                      SourceLocation Loc) {
   9418   return SemaRef.BuildDecltypeType(E, Loc);
   9419 }
   9420 
   9421 template<typename Derived>
   9422 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
   9423                                             UnaryTransformType::UTTKind UKind,
   9424                                             SourceLocation Loc) {
   9425   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
   9426 }
   9427 
   9428 template<typename Derived>
   9429 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
   9430                                                       TemplateName Template,
   9431                                              SourceLocation TemplateNameLoc,
   9432                                      TemplateArgumentListInfo &TemplateArgs) {
   9433   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
   9434 }
   9435 
   9436 template<typename Derived>
   9437 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
   9438                                                    SourceLocation KWLoc) {
   9439   return SemaRef.BuildAtomicType(ValueType, KWLoc);
   9440 }
   9441 
   9442 template<typename Derived>
   9443 TemplateName
   9444 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
   9445                                             bool TemplateKW,
   9446                                             TemplateDecl *Template) {
   9447   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
   9448                                                   Template);
   9449 }
   9450 
   9451 template<typename Derived>
   9452 TemplateName
   9453 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
   9454                                             const IdentifierInfo &Name,
   9455                                             SourceLocation NameLoc,
   9456                                             QualType ObjectType,
   9457                                             NamedDecl *FirstQualifierInScope) {
   9458   UnqualifiedId TemplateName;
   9459   TemplateName.setIdentifier(&Name, NameLoc);
   9460   Sema::TemplateTy Template;
   9461   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
   9462   getSema().ActOnDependentTemplateName(/*Scope=*/0,
   9463                                        SS, TemplateKWLoc, TemplateName,
   9464                                        ParsedType::make(ObjectType),
   9465                                        /*EnteringContext=*/false,
   9466                                        Template);
   9467   return Template.get();
   9468 }
   9469 
   9470 template<typename Derived>
   9471 TemplateName
   9472 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
   9473                                             OverloadedOperatorKind Operator,
   9474                                             SourceLocation NameLoc,
   9475                                             QualType ObjectType) {
   9476   UnqualifiedId Name;
   9477   // FIXME: Bogus location information.
   9478   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
   9479   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
   9480   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
   9481   Sema::TemplateTy Template;
   9482   getSema().ActOnDependentTemplateName(/*Scope=*/0,
   9483                                        SS, TemplateKWLoc, Name,
   9484                                        ParsedType::make(ObjectType),
   9485                                        /*EnteringContext=*/false,
   9486                                        Template);
   9487   return Template.template getAsVal<TemplateName>();
   9488 }
   9489 
   9490 template<typename Derived>
   9491 ExprResult
   9492 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
   9493                                                    SourceLocation OpLoc,
   9494                                                    Expr *OrigCallee,
   9495                                                    Expr *First,
   9496                                                    Expr *Second) {
   9497   Expr *Callee = OrigCallee->IgnoreParenCasts();
   9498   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
   9499 
   9500   // Determine whether this should be a builtin operation.
   9501   if (Op == OO_Subscript) {
   9502     if (!First->getType()->isOverloadableType() &&
   9503         !Second->getType()->isOverloadableType())
   9504       return getSema().CreateBuiltinArraySubscriptExpr(First,
   9505                                                        Callee->getLocStart(),
   9506                                                        Second, OpLoc);
   9507   } else if (Op == OO_Arrow) {
   9508     // -> is never a builtin operation.
   9509     return SemaRef.BuildOverloadedArrowExpr(0, First, OpLoc);
   9510   } else if (Second == 0 || isPostIncDec) {
   9511     if (!First->getType()->isOverloadableType()) {
   9512       // The argument is not of overloadable type, so try to create a
   9513       // built-in unary operation.
   9514       UnaryOperatorKind Opc
   9515         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
   9516 
   9517       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
   9518     }
   9519   } else {
   9520     if (!First->getType()->isOverloadableType() &&
   9521         !Second->getType()->isOverloadableType()) {
   9522       // Neither of the arguments is an overloadable type, so try to
   9523       // create a built-in binary operation.
   9524       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
   9525       ExprResult Result
   9526         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
   9527       if (Result.isInvalid())
   9528         return ExprError();
   9529 
   9530       return Result;
   9531     }
   9532   }
   9533 
   9534   // Compute the transformed set of functions (and function templates) to be
   9535   // used during overload resolution.
   9536   UnresolvedSet<16> Functions;
   9537 
   9538   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
   9539     assert(ULE->requiresADL());
   9540 
   9541     // FIXME: Do we have to check
   9542     // IsAcceptableNonMemberOperatorCandidate for each of these?
   9543     Functions.append(ULE->decls_begin(), ULE->decls_end());
   9544   } else {
   9545     // If we've resolved this to a particular non-member function, just call
   9546     // that function. If we resolved it to a member function,
   9547     // CreateOverloaded* will find that function for us.
   9548     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
   9549     if (!isa<CXXMethodDecl>(ND))
   9550       Functions.addDecl(ND);
   9551   }
   9552 
   9553   // Add any functions found via argument-dependent lookup.
   9554   Expr *Args[2] = { First, Second };
   9555   unsigned NumArgs = 1 + (Second != 0);
   9556 
   9557   // Create the overloaded operator invocation for unary operators.
   9558   if (NumArgs == 1 || isPostIncDec) {
   9559     UnaryOperatorKind Opc
   9560       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
   9561     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
   9562   }
   9563 
   9564   if (Op == OO_Subscript) {
   9565     SourceLocation LBrace;
   9566     SourceLocation RBrace;
   9567 
   9568     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
   9569         DeclarationNameLoc &NameLoc = DRE->getNameInfo().getInfo();
   9570         LBrace = SourceLocation::getFromRawEncoding(
   9571                     NameLoc.CXXOperatorName.BeginOpNameLoc);
   9572         RBrace = SourceLocation::getFromRawEncoding(
   9573                     NameLoc.CXXOperatorName.EndOpNameLoc);
   9574     } else {
   9575         LBrace = Callee->getLocStart();
   9576         RBrace = OpLoc;
   9577     }
   9578 
   9579     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
   9580                                                       First, Second);
   9581   }
   9582 
   9583   // Create the overloaded operator invocation for binary operators.
   9584   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
   9585   ExprResult Result
   9586     = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
   9587   if (Result.isInvalid())
   9588     return ExprError();
   9589 
   9590   return Result;
   9591 }
   9592 
   9593 template<typename Derived>
   9594 ExprResult
   9595 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
   9596                                                      SourceLocation OperatorLoc,
   9597                                                        bool isArrow,
   9598                                                        CXXScopeSpec &SS,
   9599                                                      TypeSourceInfo *ScopeType,
   9600                                                        SourceLocation CCLoc,
   9601                                                        SourceLocation TildeLoc,
   9602                                         PseudoDestructorTypeStorage Destroyed) {
   9603   QualType BaseType = Base->getType();
   9604   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
   9605       (!isArrow && !BaseType->getAs<RecordType>()) ||
   9606       (isArrow && BaseType->getAs<PointerType>() &&
   9607        !BaseType->getAs<PointerType>()->getPointeeType()
   9608                                               ->template getAs<RecordType>())){
   9609     // This pseudo-destructor expression is still a pseudo-destructor.
   9610     return SemaRef.BuildPseudoDestructorExpr(Base, OperatorLoc,
   9611                                              isArrow? tok::arrow : tok::period,
   9612                                              SS, ScopeType, CCLoc, TildeLoc,
   9613                                              Destroyed,
   9614                                              /*FIXME?*/true);
   9615   }
   9616 
   9617   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
   9618   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
   9619                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
   9620   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
   9621   NameInfo.setNamedTypeInfo(DestroyedType);
   9622 
   9623   // The scope type is now known to be a valid nested name specifier
   9624   // component. Tack it on to the end of the nested name specifier.
   9625   if (ScopeType)
   9626     SS.Extend(SemaRef.Context, SourceLocation(),
   9627               ScopeType->getTypeLoc(), CCLoc);
   9628 
   9629   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
   9630   return getSema().BuildMemberReferenceExpr(Base, BaseType,
   9631                                             OperatorLoc, isArrow,
   9632                                             SS, TemplateKWLoc,
   9633                                             /*FIXME: FirstQualifier*/ 0,
   9634                                             NameInfo,
   9635                                             /*TemplateArgs*/ 0);
   9636 }
   9637 
   9638 template<typename Derived>
   9639 StmtResult
   9640 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
   9641   SourceLocation Loc = S->getLocStart();
   9642   unsigned NumParams = S->getCapturedDecl()->getNumParams();
   9643   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/0,
   9644                                      S->getCapturedRegionKind(), NumParams);
   9645   StmtResult Body = getDerived().TransformStmt(S->getCapturedStmt());
   9646 
   9647   if (Body.isInvalid()) {
   9648     getSema().ActOnCapturedRegionError();
   9649     return StmtError();
   9650   }
   9651 
   9652   return getSema().ActOnCapturedRegionEnd(Body.take());
   9653 }
   9654 
   9655 } // end namespace clang
   9656 
   9657 #endif // LLVM_CLANG_SEMA_TREETRANSFORM_H
   9658