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