TreeTransform.h revision 63c00d7f35fa060c0a446c9df3a4402d9c7757fe
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#ifndef LLVM_CLANG_SEMA_TREETRANSFORM_H
14#define LLVM_CLANG_SEMA_TREETRANSFORM_H
15
16#include "clang/Sema/SemaInternal.h"
17#include "clang/Sema/Lookup.h"
18#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/SemaDiagnostic.h"
20#include "clang/Sema/ScopeInfo.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/Stmt.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/AST/StmtObjC.h"
29#include "clang/Sema/Ownership.h"
30#include "clang/Sema/Designator.h"
31#include "clang/Lex/Preprocessor.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "TypeLocBuilder.h"
34#include <algorithm>
35
36namespace clang {
37using namespace sema;
38
39/// \brief A semantic tree transformation that allows one to transform one
40/// abstract syntax tree into another.
41///
42/// A new tree transformation is defined by creating a new subclass \c X of
43/// \c TreeTransform<X> and then overriding certain operations to provide
44/// behavior specific to that transformation. For example, template
45/// instantiation is implemented as a tree transformation where the
46/// transformation of TemplateTypeParmType nodes involves substituting the
47/// template arguments for their corresponding template parameters; a similar
48/// transformation is performed for non-type template parameters and
49/// template template parameters.
50///
51/// This tree-transformation template uses static polymorphism to allow
52/// subclasses to customize any of its operations. Thus, a subclass can
53/// override any of the transformation or rebuild operators by providing an
54/// operation with the same signature as the default implementation. The
55/// overridding function should not be virtual.
56///
57/// Semantic tree transformations are split into two stages, either of which
58/// can be replaced by a subclass. The "transform" step transforms an AST node
59/// or the parts of an AST node using the various transformation functions,
60/// then passes the pieces on to the "rebuild" step, which constructs a new AST
61/// node of the appropriate kind from the pieces. The default transformation
62/// routines recursively transform the operands to composite AST nodes (e.g.,
63/// the pointee type of a PointerType node) and, if any of those operand nodes
64/// were changed by the transformation, invokes the rebuild operation to create
65/// a new AST node.
66///
67/// Subclasses can customize the transformation at various levels. The
68/// most coarse-grained transformations involve replacing TransformType(),
69/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifier(),
70/// TransformTemplateName(), or TransformTemplateArgument() with entirely
71/// new implementations.
72///
73/// For more fine-grained transformations, subclasses can replace any of the
74/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
75/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
76/// replacing TransformTemplateTypeParmType() allows template instantiation
77/// to substitute template arguments for their corresponding template
78/// parameters. Additionally, subclasses can override the \c RebuildXXX
79/// functions to control how AST nodes are rebuilt when their operands change.
80/// By default, \c TreeTransform will invoke semantic analysis to rebuild
81/// AST nodes. However, certain other tree transformations (e.g, cloning) may
82/// be able to use more efficient rebuild steps.
83///
84/// There are a handful of other functions that can be overridden, allowing one
85/// to avoid traversing nodes that don't need any transformation
86/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
87/// operands have not changed (\c AlwaysRebuild()), and customize the
88/// default locations and entity names used for type-checking
89/// (\c getBaseLocation(), \c getBaseEntity()).
90template<typename Derived>
91class TreeTransform {
92  /// \brief Private RAII object that helps us forget and then re-remember
93  /// the template argument corresponding to a partially-substituted parameter
94  /// pack.
95  class ForgetPartiallySubstitutedPackRAII {
96    Derived &Self;
97    TemplateArgument Old;
98
99  public:
100    ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
101      Old = Self.ForgetPartiallySubstitutedPack();
102    }
103
104    ~ForgetPartiallySubstitutedPackRAII() {
105      Self.RememberPartiallySubstitutedPack(Old);
106    }
107  };
108
109protected:
110  Sema &SemaRef;
111
112public:
113  /// \brief Initializes a new tree transformer.
114  TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
115
116  /// \brief Retrieves a reference to the derived class.
117  Derived &getDerived() { return static_cast<Derived&>(*this); }
118
119  /// \brief Retrieves a reference to the derived class.
120  const Derived &getDerived() const {
121    return static_cast<const Derived&>(*this);
122  }
123
124  static inline ExprResult Owned(Expr *E) { return E; }
125  static inline StmtResult Owned(Stmt *S) { return S; }
126
127  /// \brief Retrieves a reference to the semantic analysis object used for
128  /// this tree transform.
129  Sema &getSema() const { return SemaRef; }
130
131  /// \brief Whether the transformation should always rebuild AST nodes, even
132  /// if none of the children have changed.
133  ///
134  /// Subclasses may override this function to specify when the transformation
135  /// should rebuild all AST nodes.
136  bool AlwaysRebuild() { return false; }
137
138  /// \brief Returns the location of the entity being transformed, if that
139  /// information was not available elsewhere in the AST.
140  ///
141  /// By default, returns no source-location information. Subclasses can
142  /// provide an alternative implementation that provides better location
143  /// information.
144  SourceLocation getBaseLocation() { return SourceLocation(); }
145
146  /// \brief Returns the name of the entity being transformed, if that
147  /// information was not available elsewhere in the AST.
148  ///
149  /// By default, returns an empty name. Subclasses can provide an alternative
150  /// implementation with a more precise name.
151  DeclarationName getBaseEntity() { return DeclarationName(); }
152
153  /// \brief Sets the "base" location and entity when that
154  /// information is known based on another transformation.
155  ///
156  /// By default, the source location and entity are ignored. Subclasses can
157  /// override this function to provide a customized implementation.
158  void setBase(SourceLocation Loc, DeclarationName Entity) { }
159
160  /// \brief RAII object that temporarily sets the base location and entity
161  /// used for reporting diagnostics in types.
162  class TemporaryBase {
163    TreeTransform &Self;
164    SourceLocation OldLocation;
165    DeclarationName OldEntity;
166
167  public:
168    TemporaryBase(TreeTransform &Self, SourceLocation Location,
169                  DeclarationName Entity) : Self(Self) {
170      OldLocation = Self.getDerived().getBaseLocation();
171      OldEntity = Self.getDerived().getBaseEntity();
172
173      if (Location.isValid())
174        Self.getDerived().setBase(Location, Entity);
175    }
176
177    ~TemporaryBase() {
178      Self.getDerived().setBase(OldLocation, OldEntity);
179    }
180  };
181
182  /// \brief Determine whether the given type \p T has already been
183  /// transformed.
184  ///
185  /// Subclasses can provide an alternative implementation of this routine
186  /// to short-circuit evaluation when it is known that a given type will
187  /// not change. For example, template instantiation need not traverse
188  /// non-dependent types.
189  bool AlreadyTransformed(QualType T) {
190    return T.isNull();
191  }
192
193  /// \brief Determine whether the given call argument should be dropped, e.g.,
194  /// because it is a default argument.
195  ///
196  /// Subclasses can provide an alternative implementation of this routine to
197  /// determine which kinds of call arguments get dropped. By default,
198  /// CXXDefaultArgument nodes are dropped (prior to transformation).
199  bool DropCallArgument(Expr *E) {
200    return E->isDefaultArgument();
201  }
202
203  /// \brief Determine whether we should expand a pack expansion with the
204  /// given set of parameter packs into separate arguments by repeatedly
205  /// transforming the pattern.
206  ///
207  /// By default, the transformer never tries to expand pack expansions.
208  /// Subclasses can override this routine to provide different behavior.
209  ///
210  /// \param EllipsisLoc The location of the ellipsis that identifies the
211  /// pack expansion.
212  ///
213  /// \param PatternRange The source range that covers the entire pattern of
214  /// the pack expansion.
215  ///
216  /// \param Unexpanded The set of unexpanded parameter packs within the
217  /// pattern.
218  ///
219  /// \param NumUnexpanded The number of unexpanded parameter packs in
220  /// \p Unexpanded.
221  ///
222  /// \param ShouldExpand Will be set to \c true if the transformer should
223  /// expand the corresponding pack expansions into separate arguments. When
224  /// set, \c NumExpansions must also be set.
225  ///
226  /// \param RetainExpansion Whether the caller should add an unexpanded
227  /// pack expansion after all of the expanded arguments. This is used
228  /// when extending explicitly-specified template argument packs per
229  /// C++0x [temp.arg.explicit]p9.
230  ///
231  /// \param NumExpansions The number of separate arguments that will be in
232  /// the expanded form of the corresponding pack expansion. This is both an
233  /// input and an output parameter, which can be set by the caller if the
234  /// number of expansions is known a priori (e.g., due to a prior substitution)
235  /// and will be set by the callee when the number of expansions is known.
236  /// The callee must set this value when \c ShouldExpand is \c true; it may
237  /// set this value in other cases.
238  ///
239  /// \returns true if an error occurred (e.g., because the parameter packs
240  /// are to be instantiated with arguments of different lengths), false
241  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
242  /// must be set.
243  bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
244                               SourceRange PatternRange,
245                               const UnexpandedParameterPack *Unexpanded,
246                               unsigned NumUnexpanded,
247                               bool &ShouldExpand,
248                               bool &RetainExpansion,
249                               llvm::Optional<unsigned> &NumExpansions) {
250    ShouldExpand = false;
251    return false;
252  }
253
254  /// \brief "Forget" about the partially-substituted pack template argument,
255  /// when performing an instantiation that must preserve the parameter pack
256  /// use.
257  ///
258  /// This routine is meant to be overridden by the template instantiator.
259  TemplateArgument ForgetPartiallySubstitutedPack() {
260    return TemplateArgument();
261  }
262
263  /// \brief "Remember" the partially-substituted pack template argument
264  /// after performing an instantiation that must preserve the parameter pack
265  /// use.
266  ///
267  /// This routine is meant to be overridden by the template instantiator.
268  void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
269
270  /// \brief Note to the derived class when a function parameter pack is
271  /// being expanded.
272  void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
273
274  /// \brief Transforms the given type into another type.
275  ///
276  /// By default, this routine transforms a type by creating a
277  /// TypeSourceInfo for it and delegating to the appropriate
278  /// function.  This is expensive, but we don't mind, because
279  /// this method is deprecated anyway;  all users should be
280  /// switched to storing TypeSourceInfos.
281  ///
282  /// \returns the transformed type.
283  QualType TransformType(QualType T);
284
285  /// \brief Transforms the given type-with-location into a new
286  /// type-with-location.
287  ///
288  /// By default, this routine transforms a type by delegating to the
289  /// appropriate TransformXXXType to build a new type.  Subclasses
290  /// may override this function (to take over all type
291  /// transformations) or some set of the TransformXXXType functions
292  /// to alter the transformation.
293  TypeSourceInfo *TransformType(TypeSourceInfo *DI);
294
295  /// \brief Transform the given type-with-location into a new
296  /// type, collecting location information in the given builder
297  /// as necessary.
298  ///
299  QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
300
301  /// \brief Transform the given statement.
302  ///
303  /// By default, this routine transforms a statement by delegating to the
304  /// appropriate TransformXXXStmt function to transform a specific kind of
305  /// statement or the TransformExpr() function to transform an expression.
306  /// Subclasses may override this function to transform statements using some
307  /// other mechanism.
308  ///
309  /// \returns the transformed statement.
310  StmtResult TransformStmt(Stmt *S);
311
312  /// \brief Transform the given expression.
313  ///
314  /// By default, this routine transforms an expression by delegating to the
315  /// appropriate TransformXXXExpr function to build a new expression.
316  /// Subclasses may override this function to transform expressions using some
317  /// other mechanism.
318  ///
319  /// \returns the transformed expression.
320  ExprResult TransformExpr(Expr *E);
321
322  /// \brief Transform the given list of expressions.
323  ///
324  /// This routine transforms a list of expressions by invoking
325  /// \c TransformExpr() for each subexpression. However, it also provides
326  /// support for variadic templates by expanding any pack expansions (if the
327  /// derived class permits such expansion) along the way. When pack expansions
328  /// are present, the number of outputs may not equal the number of inputs.
329  ///
330  /// \param Inputs The set of expressions to be transformed.
331  ///
332  /// \param NumInputs The number of expressions in \c Inputs.
333  ///
334  /// \param IsCall If \c true, then this transform is being performed on
335  /// function-call arguments, and any arguments that should be dropped, will
336  /// be.
337  ///
338  /// \param Outputs The transformed input expressions will be added to this
339  /// vector.
340  ///
341  /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
342  /// due to transformation.
343  ///
344  /// \returns true if an error occurred, false otherwise.
345  bool TransformExprs(Expr **Inputs, unsigned NumInputs, bool IsCall,
346                      llvm::SmallVectorImpl<Expr *> &Outputs,
347                      bool *ArgChanged = 0);
348
349  /// \brief Transform the given declaration, which is referenced from a type
350  /// or expression.
351  ///
352  /// By default, acts as the identity function on declarations. Subclasses
353  /// may override this function to provide alternate behavior.
354  Decl *TransformDecl(SourceLocation Loc, Decl *D) { return D; }
355
356  /// \brief Transform the definition of the given declaration.
357  ///
358  /// By default, invokes TransformDecl() to transform the declaration.
359  /// Subclasses may override this function to provide alternate behavior.
360  Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
361    return getDerived().TransformDecl(Loc, D);
362  }
363
364  /// \brief Transform the given declaration, which was the first part of a
365  /// nested-name-specifier in a member access expression.
366  ///
367  /// This specific declaration transformation only applies to the first
368  /// identifier in a nested-name-specifier of a member access expression, e.g.,
369  /// the \c T in \c x->T::member
370  ///
371  /// By default, invokes TransformDecl() to transform the declaration.
372  /// Subclasses may override this function to provide alternate behavior.
373  NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
374    return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
375  }
376
377  /// \brief Transform the given nested-name-specifier.
378  ///
379  /// By default, transforms all of the types and declarations within the
380  /// nested-name-specifier. Subclasses may override this function to provide
381  /// alternate behavior.
382  NestedNameSpecifier *TransformNestedNameSpecifier(NestedNameSpecifier *NNS,
383                                                    SourceRange Range,
384                                              QualType ObjectType = QualType(),
385                                          NamedDecl *FirstQualifierInScope = 0);
386
387  /// \brief Transform the given declaration name.
388  ///
389  /// By default, transforms the types of conversion function, constructor,
390  /// and destructor names and then (if needed) rebuilds the declaration name.
391  /// Identifiers and selectors are returned unmodified. Sublcasses may
392  /// override this function to provide alternate behavior.
393  DeclarationNameInfo
394  TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
395
396  /// \brief Transform the given template name.
397  ///
398  /// By default, transforms the template name by transforming the declarations
399  /// and nested-name-specifiers that occur within the template name.
400  /// Subclasses may override this function to provide alternate behavior.
401  TemplateName TransformTemplateName(TemplateName Name,
402                                     QualType ObjectType = QualType(),
403                                     NamedDecl *FirstQualifierInScope = 0);
404
405  /// \brief Transform the given template argument.
406  ///
407  /// By default, this operation transforms the type, expression, or
408  /// declaration stored within the template argument and constructs a
409  /// new template argument from the transformed result. Subclasses may
410  /// override this function to provide alternate behavior.
411  ///
412  /// Returns true if there was an error.
413  bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
414                                 TemplateArgumentLoc &Output);
415
416  /// \brief Transform the given set of template arguments.
417  ///
418  /// By default, this operation transforms all of the template arguments
419  /// in the input set using \c TransformTemplateArgument(), and appends
420  /// the transformed arguments to the output list.
421  ///
422  /// Note that this overload of \c TransformTemplateArguments() is merely
423  /// a convenience function. Subclasses that wish to override this behavior
424  /// should override the iterator-based member template version.
425  ///
426  /// \param Inputs The set of template arguments to be transformed.
427  ///
428  /// \param NumInputs The number of template arguments in \p Inputs.
429  ///
430  /// \param Outputs The set of transformed template arguments output by this
431  /// routine.
432  ///
433  /// Returns true if an error occurred.
434  bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
435                                  unsigned NumInputs,
436                                  TemplateArgumentListInfo &Outputs) {
437    return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs);
438  }
439
440  /// \brief Transform the given set of template arguments.
441  ///
442  /// By default, this operation transforms all of the template arguments
443  /// in the input set using \c TransformTemplateArgument(), and appends
444  /// the transformed arguments to the output list.
445  ///
446  /// \param First An iterator to the first template argument.
447  ///
448  /// \param Last An iterator one step past the last template argument.
449  ///
450  /// \param Outputs The set of transformed template arguments output by this
451  /// routine.
452  ///
453  /// Returns true if an error occurred.
454  template<typename InputIterator>
455  bool TransformTemplateArguments(InputIterator First,
456                                  InputIterator Last,
457                                  TemplateArgumentListInfo &Outputs);
458
459  /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
460  void InventTemplateArgumentLoc(const TemplateArgument &Arg,
461                                 TemplateArgumentLoc &ArgLoc);
462
463  /// \brief Fakes up a TypeSourceInfo for a type.
464  TypeSourceInfo *InventTypeSourceInfo(QualType T) {
465    return SemaRef.Context.getTrivialTypeSourceInfo(T,
466                       getDerived().getBaseLocation());
467  }
468
469#define ABSTRACT_TYPELOC(CLASS, PARENT)
470#define TYPELOC(CLASS, PARENT)                                   \
471  QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
472#include "clang/AST/TypeLocNodes.def"
473
474  QualType
475  TransformTemplateSpecializationType(TypeLocBuilder &TLB,
476                                      TemplateSpecializationTypeLoc TL,
477                                      TemplateName Template);
478
479  QualType
480  TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
481                                      DependentTemplateSpecializationTypeLoc TL,
482                                               NestedNameSpecifier *Prefix);
483
484  /// \brief Transforms the parameters of a function type into the
485  /// given vectors.
486  ///
487  /// The result vectors should be kept in sync; null entries in the
488  /// variables vector are acceptable.
489  ///
490  /// Return true on error.
491  bool TransformFunctionTypeParams(SourceLocation Loc,
492                                   ParmVarDecl **Params, unsigned NumParams,
493                                   const QualType *ParamTypes,
494                                   llvm::SmallVectorImpl<QualType> &PTypes,
495                                   llvm::SmallVectorImpl<ParmVarDecl*> *PVars);
496
497  /// \brief Transforms a single function-type parameter.  Return null
498  /// on error.
499  ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
500                                        llvm::Optional<unsigned> NumExpansions);
501
502  QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
503
504  StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
505  ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
506
507#define STMT(Node, Parent)                        \
508  StmtResult Transform##Node(Node *S);
509#define EXPR(Node, Parent)                        \
510  ExprResult Transform##Node(Node *E);
511#define ABSTRACT_STMT(Stmt)
512#include "clang/AST/StmtNodes.inc"
513
514  /// \brief Build a new pointer type given its pointee type.
515  ///
516  /// By default, performs semantic analysis when building the pointer type.
517  /// Subclasses may override this routine to provide different behavior.
518  QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
519
520  /// \brief Build a new block pointer type given its pointee type.
521  ///
522  /// By default, performs semantic analysis when building the block pointer
523  /// type. Subclasses may override this routine to provide different behavior.
524  QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
525
526  /// \brief Build a new reference type given the type it references.
527  ///
528  /// By default, performs semantic analysis when building the
529  /// reference type. Subclasses may override this routine to provide
530  /// different behavior.
531  ///
532  /// \param LValue whether the type was written with an lvalue sigil
533  /// or an rvalue sigil.
534  QualType RebuildReferenceType(QualType ReferentType,
535                                bool LValue,
536                                SourceLocation Sigil);
537
538  /// \brief Build a new member pointer type given the pointee type and the
539  /// class type it refers into.
540  ///
541  /// By default, performs semantic analysis when building the member pointer
542  /// type. Subclasses may override this routine to provide different behavior.
543  QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
544                                    SourceLocation Sigil);
545
546  /// \brief Build a new array type given the element type, size
547  /// modifier, size of the array (if known), size expression, and index type
548  /// qualifiers.
549  ///
550  /// By default, performs semantic analysis when building the array type.
551  /// Subclasses may override this routine to provide different behavior.
552  /// Also by default, all of the other Rebuild*Array
553  QualType RebuildArrayType(QualType ElementType,
554                            ArrayType::ArraySizeModifier SizeMod,
555                            const llvm::APInt *Size,
556                            Expr *SizeExpr,
557                            unsigned IndexTypeQuals,
558                            SourceRange BracketsRange);
559
560  /// \brief Build a new constant array type given the element type, size
561  /// modifier, (known) size of the array, and index type qualifiers.
562  ///
563  /// By default, performs semantic analysis when building the array type.
564  /// Subclasses may override this routine to provide different behavior.
565  QualType RebuildConstantArrayType(QualType ElementType,
566                                    ArrayType::ArraySizeModifier SizeMod,
567                                    const llvm::APInt &Size,
568                                    unsigned IndexTypeQuals,
569                                    SourceRange BracketsRange);
570
571  /// \brief Build a new incomplete array type given the element type, size
572  /// modifier, and index type qualifiers.
573  ///
574  /// By default, performs semantic analysis when building the array type.
575  /// Subclasses may override this routine to provide different behavior.
576  QualType RebuildIncompleteArrayType(QualType ElementType,
577                                      ArrayType::ArraySizeModifier SizeMod,
578                                      unsigned IndexTypeQuals,
579                                      SourceRange BracketsRange);
580
581  /// \brief Build a new variable-length array type given the element type,
582  /// size modifier, size expression, and index type qualifiers.
583  ///
584  /// By default, performs semantic analysis when building the array type.
585  /// Subclasses may override this routine to provide different behavior.
586  QualType RebuildVariableArrayType(QualType ElementType,
587                                    ArrayType::ArraySizeModifier SizeMod,
588                                    Expr *SizeExpr,
589                                    unsigned IndexTypeQuals,
590                                    SourceRange BracketsRange);
591
592  /// \brief Build a new dependent-sized array type given the element type,
593  /// size modifier, size expression, and index type qualifiers.
594  ///
595  /// By default, performs semantic analysis when building the array type.
596  /// Subclasses may override this routine to provide different behavior.
597  QualType RebuildDependentSizedArrayType(QualType ElementType,
598                                          ArrayType::ArraySizeModifier SizeMod,
599                                          Expr *SizeExpr,
600                                          unsigned IndexTypeQuals,
601                                          SourceRange BracketsRange);
602
603  /// \brief Build a new vector type given the element type and
604  /// number of elements.
605  ///
606  /// By default, performs semantic analysis when building the vector type.
607  /// Subclasses may override this routine to provide different behavior.
608  QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
609                             VectorType::VectorKind VecKind);
610
611  /// \brief Build a new extended vector type given the element type and
612  /// number of elements.
613  ///
614  /// By default, performs semantic analysis when building the vector type.
615  /// Subclasses may override this routine to provide different behavior.
616  QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
617                                SourceLocation AttributeLoc);
618
619  /// \brief Build a new potentially dependently-sized extended vector type
620  /// given the element type and number of elements.
621  ///
622  /// By default, performs semantic analysis when building the vector type.
623  /// Subclasses may override this routine to provide different behavior.
624  QualType RebuildDependentSizedExtVectorType(QualType ElementType,
625                                              Expr *SizeExpr,
626                                              SourceLocation AttributeLoc);
627
628  /// \brief Build a new function type.
629  ///
630  /// By default, performs semantic analysis when building the function type.
631  /// Subclasses may override this routine to provide different behavior.
632  QualType RebuildFunctionProtoType(QualType T,
633                                    QualType *ParamTypes,
634                                    unsigned NumParamTypes,
635                                    bool Variadic, unsigned Quals,
636                                    RefQualifierKind RefQualifier,
637                                    const FunctionType::ExtInfo &Info);
638
639  /// \brief Build a new unprototyped function type.
640  QualType RebuildFunctionNoProtoType(QualType ResultType);
641
642  /// \brief Rebuild an unresolved typename type, given the decl that
643  /// the UnresolvedUsingTypenameDecl was transformed to.
644  QualType RebuildUnresolvedUsingType(Decl *D);
645
646  /// \brief Build a new typedef type.
647  QualType RebuildTypedefType(TypedefDecl *Typedef) {
648    return SemaRef.Context.getTypeDeclType(Typedef);
649  }
650
651  /// \brief Build a new class/struct/union type.
652  QualType RebuildRecordType(RecordDecl *Record) {
653    return SemaRef.Context.getTypeDeclType(Record);
654  }
655
656  /// \brief Build a new Enum type.
657  QualType RebuildEnumType(EnumDecl *Enum) {
658    return SemaRef.Context.getTypeDeclType(Enum);
659  }
660
661  /// \brief Build a new typeof(expr) type.
662  ///
663  /// By default, performs semantic analysis when building the typeof type.
664  /// Subclasses may override this routine to provide different behavior.
665  QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
666
667  /// \brief Build a new typeof(type) type.
668  ///
669  /// By default, builds a new TypeOfType with the given underlying type.
670  QualType RebuildTypeOfType(QualType Underlying);
671
672  /// \brief Build a new C++0x decltype type.
673  ///
674  /// By default, performs semantic analysis when building the decltype type.
675  /// Subclasses may override this routine to provide different behavior.
676  QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
677
678  /// \brief Build a new template specialization type.
679  ///
680  /// By default, performs semantic analysis when building the template
681  /// specialization type. Subclasses may override this routine to provide
682  /// different behavior.
683  QualType RebuildTemplateSpecializationType(TemplateName Template,
684                                             SourceLocation TemplateLoc,
685                                       const TemplateArgumentListInfo &Args);
686
687  /// \brief Build a new parenthesized type.
688  ///
689  /// By default, builds a new ParenType type from the inner type.
690  /// Subclasses may override this routine to provide different behavior.
691  QualType RebuildParenType(QualType InnerType) {
692    return SemaRef.Context.getParenType(InnerType);
693  }
694
695  /// \brief Build a new qualified name type.
696  ///
697  /// By default, builds a new ElaboratedType type from the keyword,
698  /// the nested-name-specifier and the named type.
699  /// Subclasses may override this routine to provide different behavior.
700  QualType RebuildElaboratedType(SourceLocation KeywordLoc,
701                                 ElaboratedTypeKeyword Keyword,
702                                 NestedNameSpecifier *NNS, QualType Named) {
703    return SemaRef.Context.getElaboratedType(Keyword, NNS, Named);
704  }
705
706  /// \brief Build a new typename type that refers to a template-id.
707  ///
708  /// By default, builds a new DependentNameType type from the
709  /// nested-name-specifier and the given type. Subclasses may override
710  /// this routine to provide different behavior.
711  QualType RebuildDependentTemplateSpecializationType(
712                                    ElaboratedTypeKeyword Keyword,
713                                    NestedNameSpecifier *Qualifier,
714                                    SourceRange QualifierRange,
715                                    const IdentifierInfo *Name,
716                                    SourceLocation NameLoc,
717                                    const TemplateArgumentListInfo &Args) {
718    // Rebuild the template name.
719    // TODO: avoid TemplateName abstraction
720    TemplateName InstName =
721      getDerived().RebuildTemplateName(Qualifier, QualifierRange, *Name,
722                                       QualType(), 0);
723
724    if (InstName.isNull())
725      return QualType();
726
727    // If it's still dependent, make a dependent specialization.
728    if (InstName.getAsDependentTemplateName())
729      return SemaRef.Context.getDependentTemplateSpecializationType(
730                                          Keyword, Qualifier, Name, Args);
731
732    // Otherwise, make an elaborated type wrapping a non-dependent
733    // specialization.
734    QualType T =
735      getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
736    if (T.isNull()) return QualType();
737
738    // NOTE: NNS is already recorded in template specialization type T.
739    return SemaRef.Context.getElaboratedType(Keyword, /*NNS=*/0, T);
740  }
741
742  /// \brief Build a new typename type that refers to an identifier.
743  ///
744  /// By default, performs semantic analysis when building the typename type
745  /// (or elaborated type). Subclasses may override this routine to provide
746  /// different behavior.
747  QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
748                                    NestedNameSpecifier *NNS,
749                                    const IdentifierInfo *Id,
750                                    SourceLocation KeywordLoc,
751                                    SourceRange NNSRange,
752                                    SourceLocation IdLoc) {
753    CXXScopeSpec SS;
754    SS.setScopeRep(NNS);
755    SS.setRange(NNSRange);
756
757    if (NNS->isDependent()) {
758      // If the name is still dependent, just build a new dependent name type.
759      if (!SemaRef.computeDeclContext(SS))
760        return SemaRef.Context.getDependentNameType(Keyword, NNS, Id);
761    }
762
763    if (Keyword == ETK_None || Keyword == ETK_Typename)
764      return SemaRef.CheckTypenameType(Keyword, NNS, *Id,
765                                       KeywordLoc, NNSRange, IdLoc);
766
767    TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
768
769    // We had a dependent elaborated-type-specifier that has been transformed
770    // into a non-dependent elaborated-type-specifier. Find the tag we're
771    // referring to.
772    LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
773    DeclContext *DC = SemaRef.computeDeclContext(SS, false);
774    if (!DC)
775      return QualType();
776
777    if (SemaRef.RequireCompleteDeclContext(SS, DC))
778      return QualType();
779
780    TagDecl *Tag = 0;
781    SemaRef.LookupQualifiedName(Result, DC);
782    switch (Result.getResultKind()) {
783      case LookupResult::NotFound:
784      case LookupResult::NotFoundInCurrentInstantiation:
785        break;
786
787      case LookupResult::Found:
788        Tag = Result.getAsSingle<TagDecl>();
789        break;
790
791      case LookupResult::FoundOverloaded:
792      case LookupResult::FoundUnresolvedValue:
793        llvm_unreachable("Tag lookup cannot find non-tags");
794        return QualType();
795
796      case LookupResult::Ambiguous:
797        // Let the LookupResult structure handle ambiguities.
798        return QualType();
799    }
800
801    if (!Tag) {
802      // Check where the name exists but isn't a tag type and use that to emit
803      // better diagnostics.
804      LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
805      SemaRef.LookupQualifiedName(Result, DC);
806      switch (Result.getResultKind()) {
807        case LookupResult::Found:
808        case LookupResult::FoundOverloaded:
809        case LookupResult::FoundUnresolvedValue: {
810	  NamedDecl *SomeDecl = Result.getRepresentativeDecl();
811          unsigned Kind = 0;
812          if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
813          else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 2;
814          SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
815          SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
816          break;
817	}
818        default:
819          // FIXME: Would be nice to highlight just the source range.
820          SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
821            << Kind << Id << DC;
822          break;
823      }
824      return QualType();
825    }
826
827    if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, IdLoc, *Id)) {
828      SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
829      SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
830      return QualType();
831    }
832
833    // Build the elaborated-type-specifier type.
834    QualType T = SemaRef.Context.getTypeDeclType(Tag);
835    return SemaRef.Context.getElaboratedType(Keyword, NNS, T);
836  }
837
838  /// \brief Build a new pack expansion type.
839  ///
840  /// By default, builds a new PackExpansionType type from the given pattern.
841  /// Subclasses may override this routine to provide different behavior.
842  QualType RebuildPackExpansionType(QualType Pattern,
843                                    SourceRange PatternRange,
844                                    SourceLocation EllipsisLoc,
845                                    llvm::Optional<unsigned> NumExpansions) {
846    return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
847                                        NumExpansions);
848  }
849
850  /// \brief Build a new nested-name-specifier given the prefix and an
851  /// identifier that names the next step in the nested-name-specifier.
852  ///
853  /// By default, performs semantic analysis when building the new
854  /// nested-name-specifier. Subclasses may override this routine to provide
855  /// different behavior.
856  NestedNameSpecifier *RebuildNestedNameSpecifier(NestedNameSpecifier *Prefix,
857                                                  SourceRange Range,
858                                                  IdentifierInfo &II,
859                                                  QualType ObjectType,
860                                              NamedDecl *FirstQualifierInScope);
861
862  /// \brief Build a new nested-name-specifier given the prefix and the
863  /// namespace named in the next step in the nested-name-specifier.
864  ///
865  /// By default, performs semantic analysis when building the new
866  /// nested-name-specifier. Subclasses may override this routine to provide
867  /// different behavior.
868  NestedNameSpecifier *RebuildNestedNameSpecifier(NestedNameSpecifier *Prefix,
869                                                  SourceRange Range,
870                                                  NamespaceDecl *NS);
871
872  /// \brief Build a new nested-name-specifier given the prefix and the
873  /// type named in the next step in the nested-name-specifier.
874  ///
875  /// By default, performs semantic analysis when building the new
876  /// nested-name-specifier. Subclasses may override this routine to provide
877  /// different behavior.
878  NestedNameSpecifier *RebuildNestedNameSpecifier(NestedNameSpecifier *Prefix,
879                                                  SourceRange Range,
880                                                  bool TemplateKW,
881                                                  QualType T);
882
883  /// \brief Build a new template name given a nested name specifier, a flag
884  /// indicating whether the "template" keyword was provided, and the template
885  /// that the template name refers to.
886  ///
887  /// By default, builds the new template name directly. Subclasses may override
888  /// this routine to provide different behavior.
889  TemplateName RebuildTemplateName(NestedNameSpecifier *Qualifier,
890                                   bool TemplateKW,
891                                   TemplateDecl *Template);
892
893  /// \brief Build a new template name given a nested name specifier and the
894  /// name that is referred to as a template.
895  ///
896  /// By default, performs semantic analysis to determine whether the name can
897  /// be resolved to a specific template, then builds the appropriate kind of
898  /// template name. Subclasses may override this routine to provide different
899  /// behavior.
900  TemplateName RebuildTemplateName(NestedNameSpecifier *Qualifier,
901                                   SourceRange QualifierRange,
902                                   const IdentifierInfo &II,
903                                   QualType ObjectType,
904                                   NamedDecl *FirstQualifierInScope);
905
906  /// \brief Build a new template name given a nested name specifier and the
907  /// overloaded operator name that is referred to as a template.
908  ///
909  /// By default, performs semantic analysis to determine whether the name can
910  /// be resolved to a specific template, then builds the appropriate kind of
911  /// template name. Subclasses may override this routine to provide different
912  /// behavior.
913  TemplateName RebuildTemplateName(NestedNameSpecifier *Qualifier,
914                                   OverloadedOperatorKind Operator,
915                                   QualType ObjectType);
916
917  /// \brief Build a new template name given a template template parameter pack
918  /// and the
919  ///
920  /// By default, performs semantic analysis to determine whether the name can
921  /// be resolved to a specific template, then builds the appropriate kind of
922  /// template name. Subclasses may override this routine to provide different
923  /// behavior.
924  TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
925                                   const TemplateArgument &ArgPack) {
926    return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
927  }
928
929  /// \brief Build a new compound statement.
930  ///
931  /// By default, performs semantic analysis to build the new statement.
932  /// Subclasses may override this routine to provide different behavior.
933  StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
934                                       MultiStmtArg Statements,
935                                       SourceLocation RBraceLoc,
936                                       bool IsStmtExpr) {
937    return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
938                                       IsStmtExpr);
939  }
940
941  /// \brief Build a new case statement.
942  ///
943  /// By default, performs semantic analysis to build the new statement.
944  /// Subclasses may override this routine to provide different behavior.
945  StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
946                                   Expr *LHS,
947                                   SourceLocation EllipsisLoc,
948                                   Expr *RHS,
949                                   SourceLocation ColonLoc) {
950    return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
951                                   ColonLoc);
952  }
953
954  /// \brief Attach the body to a new case statement.
955  ///
956  /// By default, performs semantic analysis to build the new statement.
957  /// Subclasses may override this routine to provide different behavior.
958  StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
959    getSema().ActOnCaseStmtBody(S, Body);
960    return S;
961  }
962
963  /// \brief Build a new default statement.
964  ///
965  /// By default, performs semantic analysis to build the new statement.
966  /// Subclasses may override this routine to provide different behavior.
967  StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
968                                      SourceLocation ColonLoc,
969                                      Stmt *SubStmt) {
970    return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
971                                      /*CurScope=*/0);
972  }
973
974  /// \brief Build a new label statement.
975  ///
976  /// By default, performs semantic analysis to build the new statement.
977  /// Subclasses may override this routine to provide different behavior.
978  StmtResult RebuildLabelStmt(SourceLocation IdentLoc,
979                                    IdentifierInfo *Id,
980                                    SourceLocation ColonLoc,
981                                    Stmt *SubStmt, bool HasUnusedAttr) {
982    return SemaRef.ActOnLabelStmt(IdentLoc, Id, ColonLoc, SubStmt,
983                                  HasUnusedAttr);
984  }
985
986  /// \brief Build a new "if" statement.
987  ///
988  /// By default, performs semantic analysis to build the new statement.
989  /// Subclasses may override this routine to provide different behavior.
990  StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
991                                 VarDecl *CondVar, Stmt *Then,
992                                 SourceLocation ElseLoc, Stmt *Else) {
993    return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
994  }
995
996  /// \brief Start building a new switch statement.
997  ///
998  /// By default, performs semantic analysis to build the new statement.
999  /// Subclasses may override this routine to provide different behavior.
1000  StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1001                                          Expr *Cond, VarDecl *CondVar) {
1002    return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
1003                                            CondVar);
1004  }
1005
1006  /// \brief Attach the body to the switch statement.
1007  ///
1008  /// By default, performs semantic analysis to build the new statement.
1009  /// Subclasses may override this routine to provide different behavior.
1010  StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1011                                         Stmt *Switch, Stmt *Body) {
1012    return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1013  }
1014
1015  /// \brief Build a new while statement.
1016  ///
1017  /// By default, performs semantic analysis to build the new statement.
1018  /// Subclasses may override this routine to provide different behavior.
1019  StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1020                                    Sema::FullExprArg Cond,
1021                                    VarDecl *CondVar,
1022                                    Stmt *Body) {
1023    return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
1024  }
1025
1026  /// \brief Build a new do-while statement.
1027  ///
1028  /// By default, performs semantic analysis to build the new statement.
1029  /// Subclasses may override this routine to provide different behavior.
1030  StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1031                                 SourceLocation WhileLoc,
1032                                 SourceLocation LParenLoc,
1033                                 Expr *Cond,
1034                                 SourceLocation RParenLoc) {
1035    return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1036                                 Cond, RParenLoc);
1037  }
1038
1039  /// \brief Build a new for statement.
1040  ///
1041  /// By default, performs semantic analysis to build the new statement.
1042  /// Subclasses may override this routine to provide different behavior.
1043  StmtResult RebuildForStmt(SourceLocation ForLoc,
1044                                  SourceLocation LParenLoc,
1045                                  Stmt *Init, Sema::FullExprArg Cond,
1046                                  VarDecl *CondVar, Sema::FullExprArg Inc,
1047                                  SourceLocation RParenLoc, Stmt *Body) {
1048    return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1049                                  CondVar,
1050                                  Inc, RParenLoc, Body);
1051  }
1052
1053  /// \brief Build a new goto statement.
1054  ///
1055  /// By default, performs semantic analysis to build the new statement.
1056  /// Subclasses may override this routine to provide different behavior.
1057  StmtResult RebuildGotoStmt(SourceLocation GotoLoc,
1058                                   SourceLocation LabelLoc,
1059                                   LabelStmt *Label) {
1060    return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label->getID());
1061  }
1062
1063  /// \brief Build a new indirect goto statement.
1064  ///
1065  /// By default, performs semantic analysis to build the new statement.
1066  /// Subclasses may override this routine to provide different behavior.
1067  StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1068                                           SourceLocation StarLoc,
1069                                           Expr *Target) {
1070    return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1071  }
1072
1073  /// \brief Build a new return 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 RebuildReturnStmt(SourceLocation ReturnLoc,
1078                                     Expr *Result) {
1079
1080    return getSema().ActOnReturnStmt(ReturnLoc, Result);
1081  }
1082
1083  /// \brief Build a new declaration statement.
1084  ///
1085  /// By default, performs semantic analysis to build the new statement.
1086  /// Subclasses may override this routine to provide different behavior.
1087  StmtResult RebuildDeclStmt(Decl **Decls, unsigned NumDecls,
1088                                   SourceLocation StartLoc,
1089                                   SourceLocation EndLoc) {
1090    return getSema().Owned(
1091             new (getSema().Context) DeclStmt(
1092                                        DeclGroupRef::Create(getSema().Context,
1093                                                             Decls, NumDecls),
1094                                              StartLoc, EndLoc));
1095  }
1096
1097  /// \brief Build a new inline asm statement.
1098  ///
1099  /// By default, performs semantic analysis to build the new statement.
1100  /// Subclasses may override this routine to provide different behavior.
1101  StmtResult RebuildAsmStmt(SourceLocation AsmLoc,
1102                                  bool IsSimple,
1103                                  bool IsVolatile,
1104                                  unsigned NumOutputs,
1105                                  unsigned NumInputs,
1106                                  IdentifierInfo **Names,
1107                                  MultiExprArg Constraints,
1108                                  MultiExprArg Exprs,
1109                                  Expr *AsmString,
1110                                  MultiExprArg Clobbers,
1111                                  SourceLocation RParenLoc,
1112                                  bool MSAsm) {
1113    return getSema().ActOnAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1114                                  NumInputs, Names, move(Constraints),
1115                                  Exprs, AsmString, Clobbers,
1116                                  RParenLoc, MSAsm);
1117  }
1118
1119  /// \brief Build a new Objective-C @try statement.
1120  ///
1121  /// By default, performs semantic analysis to build the new statement.
1122  /// Subclasses may override this routine to provide different behavior.
1123  StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1124                                        Stmt *TryBody,
1125                                        MultiStmtArg CatchStmts,
1126                                        Stmt *Finally) {
1127    return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, move(CatchStmts),
1128                                        Finally);
1129  }
1130
1131  /// \brief Rebuild an Objective-C exception declaration.
1132  ///
1133  /// By default, performs semantic analysis to build the new declaration.
1134  /// Subclasses may override this routine to provide different behavior.
1135  VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1136                                    TypeSourceInfo *TInfo, QualType T) {
1137    return getSema().BuildObjCExceptionDecl(TInfo, T,
1138                                            ExceptionDecl->getIdentifier(),
1139                                            ExceptionDecl->getLocation());
1140  }
1141
1142  /// \brief Build a new Objective-C @catch statement.
1143  ///
1144  /// By default, performs semantic analysis to build the new statement.
1145  /// Subclasses may override this routine to provide different behavior.
1146  StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1147                                          SourceLocation RParenLoc,
1148                                          VarDecl *Var,
1149                                          Stmt *Body) {
1150    return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1151                                          Var, Body);
1152  }
1153
1154  /// \brief Build a new Objective-C @finally statement.
1155  ///
1156  /// By default, performs semantic analysis to build the new statement.
1157  /// Subclasses may override this routine to provide different behavior.
1158  StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1159                                            Stmt *Body) {
1160    return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1161  }
1162
1163  /// \brief Build a new Objective-C @throw statement.
1164  ///
1165  /// By default, performs semantic analysis to build the new statement.
1166  /// Subclasses may override this routine to provide different behavior.
1167  StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1168                                          Expr *Operand) {
1169    return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1170  }
1171
1172  /// \brief Build a new Objective-C @synchronized statement.
1173  ///
1174  /// By default, performs semantic analysis to build the new statement.
1175  /// Subclasses may override this routine to provide different behavior.
1176  StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1177                                                 Expr *Object,
1178                                                 Stmt *Body) {
1179    return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object,
1180                                                 Body);
1181  }
1182
1183  /// \brief Build a new Objective-C fast enumeration statement.
1184  ///
1185  /// By default, performs semantic analysis to build the new statement.
1186  /// Subclasses may override this routine to provide different behavior.
1187  StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1188                                          SourceLocation LParenLoc,
1189                                          Stmt *Element,
1190                                          Expr *Collection,
1191                                          SourceLocation RParenLoc,
1192                                          Stmt *Body) {
1193    return getSema().ActOnObjCForCollectionStmt(ForLoc, LParenLoc,
1194                                                Element,
1195                                                Collection,
1196                                                RParenLoc,
1197                                                Body);
1198  }
1199
1200  /// \brief Build a new C++ exception declaration.
1201  ///
1202  /// By default, performs semantic analysis to build the new decaration.
1203  /// Subclasses may override this routine to provide different behavior.
1204  VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1205                                TypeSourceInfo *Declarator,
1206                                IdentifierInfo *Name,
1207                                SourceLocation Loc) {
1208    return getSema().BuildExceptionDeclaration(0, Declarator, Name, Loc);
1209  }
1210
1211  /// \brief Build a new C++ catch statement.
1212  ///
1213  /// By default, performs semantic analysis to build the new statement.
1214  /// Subclasses may override this routine to provide different behavior.
1215  StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
1216                                 VarDecl *ExceptionDecl,
1217                                 Stmt *Handler) {
1218    return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
1219                                                      Handler));
1220  }
1221
1222  /// \brief Build a new C++ try statement.
1223  ///
1224  /// By default, performs semantic analysis to build the new statement.
1225  /// Subclasses may override this routine to provide different behavior.
1226  StmtResult RebuildCXXTryStmt(SourceLocation TryLoc,
1227                               Stmt *TryBlock,
1228                               MultiStmtArg Handlers) {
1229    return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, move(Handlers));
1230  }
1231
1232  /// \brief Build a new expression that references a declaration.
1233  ///
1234  /// By default, performs semantic analysis to build the new expression.
1235  /// Subclasses may override this routine to provide different behavior.
1236  ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
1237                                        LookupResult &R,
1238                                        bool RequiresADL) {
1239    return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
1240  }
1241
1242
1243  /// \brief Build a new expression that references a declaration.
1244  ///
1245  /// By default, performs semantic analysis to build the new expression.
1246  /// Subclasses may override this routine to provide different behavior.
1247  ExprResult RebuildDeclRefExpr(NestedNameSpecifier *Qualifier,
1248                                SourceRange QualifierRange,
1249                                ValueDecl *VD,
1250                                const DeclarationNameInfo &NameInfo,
1251                                TemplateArgumentListInfo *TemplateArgs) {
1252    CXXScopeSpec SS;
1253    SS.setScopeRep(Qualifier);
1254    SS.setRange(QualifierRange);
1255
1256    // FIXME: loses template args.
1257
1258    return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
1259  }
1260
1261  /// \brief Build a new expression in parentheses.
1262  ///
1263  /// By default, performs semantic analysis to build the new expression.
1264  /// Subclasses may override this routine to provide different behavior.
1265  ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
1266                                    SourceLocation RParen) {
1267    return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
1268  }
1269
1270  /// \brief Build a new pseudo-destructor expression.
1271  ///
1272  /// By default, performs semantic analysis to build the new expression.
1273  /// Subclasses may override this routine to provide different behavior.
1274  ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
1275                                                  SourceLocation OperatorLoc,
1276                                                  bool isArrow,
1277                                                NestedNameSpecifier *Qualifier,
1278                                                  SourceRange QualifierRange,
1279                                                  TypeSourceInfo *ScopeType,
1280                                                  SourceLocation CCLoc,
1281                                                  SourceLocation TildeLoc,
1282                                        PseudoDestructorTypeStorage Destroyed);
1283
1284  /// \brief Build a new unary operator expression.
1285  ///
1286  /// By default, performs semantic analysis to build the new expression.
1287  /// Subclasses may override this routine to provide different behavior.
1288  ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
1289                                        UnaryOperatorKind Opc,
1290                                        Expr *SubExpr) {
1291    return getSema().BuildUnaryOp(/*Scope=*/0, OpLoc, Opc, SubExpr);
1292  }
1293
1294  /// \brief Build a new builtin offsetof expression.
1295  ///
1296  /// By default, performs semantic analysis to build the new expression.
1297  /// Subclasses may override this routine to provide different behavior.
1298  ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
1299                                       TypeSourceInfo *Type,
1300                                       Sema::OffsetOfComponent *Components,
1301                                       unsigned NumComponents,
1302                                       SourceLocation RParenLoc) {
1303    return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
1304                                          NumComponents, RParenLoc);
1305  }
1306
1307  /// \brief Build a new sizeof or alignof expression with a type argument.
1308  ///
1309  /// By default, performs semantic analysis to build the new expression.
1310  /// Subclasses may override this routine to provide different behavior.
1311  ExprResult RebuildSizeOfAlignOf(TypeSourceInfo *TInfo,
1312                                        SourceLocation OpLoc,
1313                                        bool isSizeOf, SourceRange R) {
1314    return getSema().CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeOf, R);
1315  }
1316
1317  /// \brief Build a new sizeof or alignof expression with an expression
1318  /// argument.
1319  ///
1320  /// By default, performs semantic analysis to build the new expression.
1321  /// Subclasses may override this routine to provide different behavior.
1322  ExprResult RebuildSizeOfAlignOf(Expr *SubExpr, SourceLocation OpLoc,
1323                                        bool isSizeOf, SourceRange R) {
1324    ExprResult Result
1325      = getSema().CreateSizeOfAlignOfExpr(SubExpr, OpLoc, isSizeOf, R);
1326    if (Result.isInvalid())
1327      return ExprError();
1328
1329    return move(Result);
1330  }
1331
1332  /// \brief Build a new array subscript expression.
1333  ///
1334  /// By default, performs semantic analysis to build the new expression.
1335  /// Subclasses may override this routine to provide different behavior.
1336  ExprResult RebuildArraySubscriptExpr(Expr *LHS,
1337                                             SourceLocation LBracketLoc,
1338                                             Expr *RHS,
1339                                             SourceLocation RBracketLoc) {
1340    return getSema().ActOnArraySubscriptExpr(/*Scope=*/0, LHS,
1341                                             LBracketLoc, RHS,
1342                                             RBracketLoc);
1343  }
1344
1345  /// \brief Build a new call expression.
1346  ///
1347  /// By default, performs semantic analysis to build the new expression.
1348  /// Subclasses may override this routine to provide different behavior.
1349  ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
1350                                   MultiExprArg Args,
1351                                   SourceLocation RParenLoc) {
1352    return getSema().ActOnCallExpr(/*Scope=*/0, Callee, LParenLoc,
1353                                   move(Args), RParenLoc);
1354  }
1355
1356  /// \brief Build a new member access expression.
1357  ///
1358  /// By default, performs semantic analysis to build the new expression.
1359  /// Subclasses may override this routine to provide different behavior.
1360  ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
1361                               bool isArrow,
1362                               NestedNameSpecifier *Qualifier,
1363                               SourceRange QualifierRange,
1364                               const DeclarationNameInfo &MemberNameInfo,
1365                               ValueDecl *Member,
1366                               NamedDecl *FoundDecl,
1367                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
1368                               NamedDecl *FirstQualifierInScope) {
1369    if (!Member->getDeclName()) {
1370      // We have a reference to an unnamed field.  This is always the
1371      // base of an anonymous struct/union member access, i.e. the
1372      // field is always of record type.
1373      assert(!Qualifier && "Can't have an unnamed field with a qualifier!");
1374      assert(Member->getType()->isRecordType() &&
1375             "unnamed member not of record type?");
1376
1377      if (getSema().PerformObjectMemberConversion(Base, Qualifier,
1378                                                  FoundDecl, Member))
1379        return ExprError();
1380
1381      ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
1382      MemberExpr *ME =
1383        new (getSema().Context) MemberExpr(Base, isArrow,
1384                                           Member, MemberNameInfo,
1385                                           cast<FieldDecl>(Member)->getType(),
1386                                           VK, OK_Ordinary);
1387      return getSema().Owned(ME);
1388    }
1389
1390    CXXScopeSpec SS;
1391    if (Qualifier) {
1392      SS.setRange(QualifierRange);
1393      SS.setScopeRep(Qualifier);
1394    }
1395
1396    getSema().DefaultFunctionArrayConversion(Base);
1397    QualType BaseType = Base->getType();
1398
1399    // FIXME: this involves duplicating earlier analysis in a lot of
1400    // cases; we should avoid this when possible.
1401    LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
1402    R.addDecl(FoundDecl);
1403    R.resolveKind();
1404
1405    return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
1406                                              SS, FirstQualifierInScope,
1407                                              R, ExplicitTemplateArgs);
1408  }
1409
1410  /// \brief Build a new binary operator expression.
1411  ///
1412  /// By default, performs semantic analysis to build the new expression.
1413  /// Subclasses may override this routine to provide different behavior.
1414  ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
1415                                         BinaryOperatorKind Opc,
1416                                         Expr *LHS, Expr *RHS) {
1417    return getSema().BuildBinOp(/*Scope=*/0, OpLoc, Opc, LHS, RHS);
1418  }
1419
1420  /// \brief Build a new conditional operator expression.
1421  ///
1422  /// By default, performs semantic analysis to build the new expression.
1423  /// Subclasses may override this routine to provide different behavior.
1424  ExprResult RebuildConditionalOperator(Expr *Cond,
1425                                              SourceLocation QuestionLoc,
1426                                              Expr *LHS,
1427                                              SourceLocation ColonLoc,
1428                                              Expr *RHS) {
1429    return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
1430                                        LHS, RHS);
1431  }
1432
1433  /// \brief Build a new C-style cast expression.
1434  ///
1435  /// By default, performs semantic analysis to build the new expression.
1436  /// Subclasses may override this routine to provide different behavior.
1437  ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
1438                                         TypeSourceInfo *TInfo,
1439                                         SourceLocation RParenLoc,
1440                                         Expr *SubExpr) {
1441    return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
1442                                         SubExpr);
1443  }
1444
1445  /// \brief Build a new compound literal expression.
1446  ///
1447  /// By default, performs semantic analysis to build the new expression.
1448  /// Subclasses may override this routine to provide different behavior.
1449  ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
1450                                              TypeSourceInfo *TInfo,
1451                                              SourceLocation RParenLoc,
1452                                              Expr *Init) {
1453    return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
1454                                              Init);
1455  }
1456
1457  /// \brief Build a new extended vector element access expression.
1458  ///
1459  /// By default, performs semantic analysis to build the new expression.
1460  /// Subclasses may override this routine to provide different behavior.
1461  ExprResult RebuildExtVectorElementExpr(Expr *Base,
1462                                               SourceLocation OpLoc,
1463                                               SourceLocation AccessorLoc,
1464                                               IdentifierInfo &Accessor) {
1465
1466    CXXScopeSpec SS;
1467    DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
1468    return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
1469                                              OpLoc, /*IsArrow*/ false,
1470                                              SS, /*FirstQualifierInScope*/ 0,
1471                                              NameInfo,
1472                                              /* TemplateArgs */ 0);
1473  }
1474
1475  /// \brief Build a new initializer list expression.
1476  ///
1477  /// By default, performs semantic analysis to build the new expression.
1478  /// Subclasses may override this routine to provide different behavior.
1479  ExprResult RebuildInitList(SourceLocation LBraceLoc,
1480                                   MultiExprArg Inits,
1481                                   SourceLocation RBraceLoc,
1482                                   QualType ResultTy) {
1483    ExprResult Result
1484      = SemaRef.ActOnInitList(LBraceLoc, move(Inits), RBraceLoc);
1485    if (Result.isInvalid() || ResultTy->isDependentType())
1486      return move(Result);
1487
1488    // Patch in the result type we were given, which may have been computed
1489    // when the initial InitListExpr was built.
1490    InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
1491    ILE->setType(ResultTy);
1492    return move(Result);
1493  }
1494
1495  /// \brief Build a new designated initializer expression.
1496  ///
1497  /// By default, performs semantic analysis to build the new expression.
1498  /// Subclasses may override this routine to provide different behavior.
1499  ExprResult RebuildDesignatedInitExpr(Designation &Desig,
1500                                             MultiExprArg ArrayExprs,
1501                                             SourceLocation EqualOrColonLoc,
1502                                             bool GNUSyntax,
1503                                             Expr *Init) {
1504    ExprResult Result
1505      = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
1506                                           Init);
1507    if (Result.isInvalid())
1508      return ExprError();
1509
1510    ArrayExprs.release();
1511    return move(Result);
1512  }
1513
1514  /// \brief Build a new value-initialized expression.
1515  ///
1516  /// By default, builds the implicit value initialization without performing
1517  /// any semantic analysis. Subclasses may override this routine to provide
1518  /// different behavior.
1519  ExprResult RebuildImplicitValueInitExpr(QualType T) {
1520    return SemaRef.Owned(new (SemaRef.Context) ImplicitValueInitExpr(T));
1521  }
1522
1523  /// \brief Build a new \c va_arg expression.
1524  ///
1525  /// By default, performs semantic analysis to build the new expression.
1526  /// Subclasses may override this routine to provide different behavior.
1527  ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
1528                                    Expr *SubExpr, TypeSourceInfo *TInfo,
1529                                    SourceLocation RParenLoc) {
1530    return getSema().BuildVAArgExpr(BuiltinLoc,
1531                                    SubExpr, TInfo,
1532                                    RParenLoc);
1533  }
1534
1535  /// \brief Build a new expression list in parentheses.
1536  ///
1537  /// By default, performs semantic analysis to build the new expression.
1538  /// Subclasses may override this routine to provide different behavior.
1539  ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
1540                                        MultiExprArg SubExprs,
1541                                        SourceLocation RParenLoc) {
1542    return getSema().ActOnParenOrParenListExpr(LParenLoc, RParenLoc,
1543                                               move(SubExprs));
1544  }
1545
1546  /// \brief Build a new address-of-label expression.
1547  ///
1548  /// By default, performs semantic analysis, using the name of the label
1549  /// rather than attempting to map the label statement itself.
1550  /// Subclasses may override this routine to provide different behavior.
1551  ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
1552                                        SourceLocation LabelLoc,
1553                                        LabelStmt *Label) {
1554    return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label->getID());
1555  }
1556
1557  /// \brief Build a new GNU statement expression.
1558  ///
1559  /// By default, performs semantic analysis to build the new expression.
1560  /// Subclasses may override this routine to provide different behavior.
1561  ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
1562                                   Stmt *SubStmt,
1563                                   SourceLocation RParenLoc) {
1564    return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
1565  }
1566
1567  /// \brief Build a new __builtin_choose_expr expression.
1568  ///
1569  /// By default, performs semantic analysis to build the new expression.
1570  /// Subclasses may override this routine to provide different behavior.
1571  ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
1572                                     Expr *Cond, Expr *LHS, Expr *RHS,
1573                                     SourceLocation RParenLoc) {
1574    return SemaRef.ActOnChooseExpr(BuiltinLoc,
1575                                   Cond, LHS, RHS,
1576                                   RParenLoc);
1577  }
1578
1579  /// \brief Build a new overloaded operator call expression.
1580  ///
1581  /// By default, performs semantic analysis to build the new expression.
1582  /// The semantic analysis provides the behavior of template instantiation,
1583  /// copying with transformations that turn what looks like an overloaded
1584  /// operator call into a use of a builtin operator, performing
1585  /// argument-dependent lookup, etc. Subclasses may override this routine to
1586  /// provide different behavior.
1587  ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
1588                                              SourceLocation OpLoc,
1589                                              Expr *Callee,
1590                                              Expr *First,
1591                                              Expr *Second);
1592
1593  /// \brief Build a new C++ "named" cast expression, such as static_cast or
1594  /// reinterpret_cast.
1595  ///
1596  /// By default, this routine dispatches to one of the more-specific routines
1597  /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
1598  /// Subclasses may override this routine to provide different behavior.
1599  ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
1600                                           Stmt::StmtClass Class,
1601                                           SourceLocation LAngleLoc,
1602                                           TypeSourceInfo *TInfo,
1603                                           SourceLocation RAngleLoc,
1604                                           SourceLocation LParenLoc,
1605                                           Expr *SubExpr,
1606                                           SourceLocation RParenLoc) {
1607    switch (Class) {
1608    case Stmt::CXXStaticCastExprClass:
1609      return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
1610                                                   RAngleLoc, LParenLoc,
1611                                                   SubExpr, RParenLoc);
1612
1613    case Stmt::CXXDynamicCastExprClass:
1614      return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
1615                                                    RAngleLoc, LParenLoc,
1616                                                    SubExpr, RParenLoc);
1617
1618    case Stmt::CXXReinterpretCastExprClass:
1619      return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
1620                                                        RAngleLoc, LParenLoc,
1621                                                        SubExpr,
1622                                                        RParenLoc);
1623
1624    case Stmt::CXXConstCastExprClass:
1625      return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
1626                                                   RAngleLoc, LParenLoc,
1627                                                   SubExpr, RParenLoc);
1628
1629    default:
1630      assert(false && "Invalid C++ named cast");
1631      break;
1632    }
1633
1634    return ExprError();
1635  }
1636
1637  /// \brief Build a new C++ static_cast expression.
1638  ///
1639  /// By default, performs semantic analysis to build the new expression.
1640  /// Subclasses may override this routine to provide different behavior.
1641  ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
1642                                            SourceLocation LAngleLoc,
1643                                            TypeSourceInfo *TInfo,
1644                                            SourceLocation RAngleLoc,
1645                                            SourceLocation LParenLoc,
1646                                            Expr *SubExpr,
1647                                            SourceLocation RParenLoc) {
1648    return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
1649                                       TInfo, SubExpr,
1650                                       SourceRange(LAngleLoc, RAngleLoc),
1651                                       SourceRange(LParenLoc, RParenLoc));
1652  }
1653
1654  /// \brief Build a new C++ dynamic_cast expression.
1655  ///
1656  /// By default, performs semantic analysis to build the new expression.
1657  /// Subclasses may override this routine to provide different behavior.
1658  ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
1659                                             SourceLocation LAngleLoc,
1660                                             TypeSourceInfo *TInfo,
1661                                             SourceLocation RAngleLoc,
1662                                             SourceLocation LParenLoc,
1663                                             Expr *SubExpr,
1664                                             SourceLocation RParenLoc) {
1665    return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
1666                                       TInfo, SubExpr,
1667                                       SourceRange(LAngleLoc, RAngleLoc),
1668                                       SourceRange(LParenLoc, RParenLoc));
1669  }
1670
1671  /// \brief Build a new C++ reinterpret_cast expression.
1672  ///
1673  /// By default, performs semantic analysis to build the new expression.
1674  /// Subclasses may override this routine to provide different behavior.
1675  ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
1676                                                 SourceLocation LAngleLoc,
1677                                                 TypeSourceInfo *TInfo,
1678                                                 SourceLocation RAngleLoc,
1679                                                 SourceLocation LParenLoc,
1680                                                 Expr *SubExpr,
1681                                                 SourceLocation RParenLoc) {
1682    return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
1683                                       TInfo, SubExpr,
1684                                       SourceRange(LAngleLoc, RAngleLoc),
1685                                       SourceRange(LParenLoc, RParenLoc));
1686  }
1687
1688  /// \brief Build a new C++ const_cast expression.
1689  ///
1690  /// By default, performs semantic analysis to build the new expression.
1691  /// Subclasses may override this routine to provide different behavior.
1692  ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
1693                                           SourceLocation LAngleLoc,
1694                                           TypeSourceInfo *TInfo,
1695                                           SourceLocation RAngleLoc,
1696                                           SourceLocation LParenLoc,
1697                                           Expr *SubExpr,
1698                                           SourceLocation RParenLoc) {
1699    return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
1700                                       TInfo, SubExpr,
1701                                       SourceRange(LAngleLoc, RAngleLoc),
1702                                       SourceRange(LParenLoc, RParenLoc));
1703  }
1704
1705  /// \brief Build a new C++ functional-style cast expression.
1706  ///
1707  /// By default, performs semantic analysis to build the new expression.
1708  /// Subclasses may override this routine to provide different behavior.
1709  ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
1710                                          SourceLocation LParenLoc,
1711                                          Expr *Sub,
1712                                          SourceLocation RParenLoc) {
1713    return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
1714                                               MultiExprArg(&Sub, 1),
1715                                               RParenLoc);
1716  }
1717
1718  /// \brief Build a new C++ typeid(type) expression.
1719  ///
1720  /// By default, performs semantic analysis to build the new expression.
1721  /// Subclasses may override this routine to provide different behavior.
1722  ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
1723                                        SourceLocation TypeidLoc,
1724                                        TypeSourceInfo *Operand,
1725                                        SourceLocation RParenLoc) {
1726    return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
1727                                    RParenLoc);
1728  }
1729
1730
1731  /// \brief Build a new C++ typeid(expr) expression.
1732  ///
1733  /// By default, performs semantic analysis to build the new expression.
1734  /// Subclasses may override this routine to provide different behavior.
1735  ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
1736                                        SourceLocation TypeidLoc,
1737                                        Expr *Operand,
1738                                        SourceLocation RParenLoc) {
1739    return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
1740                                    RParenLoc);
1741  }
1742
1743  /// \brief Build a new C++ __uuidof(type) expression.
1744  ///
1745  /// By default, performs semantic analysis to build the new expression.
1746  /// Subclasses may override this routine to provide different behavior.
1747  ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
1748                                        SourceLocation TypeidLoc,
1749                                        TypeSourceInfo *Operand,
1750                                        SourceLocation RParenLoc) {
1751    return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
1752                                    RParenLoc);
1753  }
1754
1755  /// \brief Build a new C++ __uuidof(expr) expression.
1756  ///
1757  /// By default, performs semantic analysis to build the new expression.
1758  /// Subclasses may override this routine to provide different behavior.
1759  ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
1760                                        SourceLocation TypeidLoc,
1761                                        Expr *Operand,
1762                                        SourceLocation RParenLoc) {
1763    return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
1764                                    RParenLoc);
1765  }
1766
1767  /// \brief Build a new C++ "this" expression.
1768  ///
1769  /// By default, builds a new "this" expression without performing any
1770  /// semantic analysis. Subclasses may override this routine to provide
1771  /// different behavior.
1772  ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
1773                                QualType ThisType,
1774                                bool isImplicit) {
1775    return getSema().Owned(
1776                      new (getSema().Context) CXXThisExpr(ThisLoc, ThisType,
1777                                                          isImplicit));
1778  }
1779
1780  /// \brief Build a new C++ throw expression.
1781  ///
1782  /// By default, performs semantic analysis to build the new expression.
1783  /// Subclasses may override this routine to provide different behavior.
1784  ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub) {
1785    return getSema().ActOnCXXThrow(ThrowLoc, Sub);
1786  }
1787
1788  /// \brief Build a new C++ default-argument expression.
1789  ///
1790  /// By default, builds a new default-argument expression, which does not
1791  /// require any semantic analysis. Subclasses may override this routine to
1792  /// provide different behavior.
1793  ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
1794                                            ParmVarDecl *Param) {
1795    return getSema().Owned(CXXDefaultArgExpr::Create(getSema().Context, Loc,
1796                                                     Param));
1797  }
1798
1799  /// \brief Build a new C++ zero-initialization expression.
1800  ///
1801  /// By default, performs semantic analysis to build the new expression.
1802  /// Subclasses may override this routine to provide different behavior.
1803  ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
1804                                           SourceLocation LParenLoc,
1805                                           SourceLocation RParenLoc) {
1806    return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
1807                                               MultiExprArg(getSema(), 0, 0),
1808                                               RParenLoc);
1809  }
1810
1811  /// \brief Build a new C++ "new" expression.
1812  ///
1813  /// By default, performs semantic analysis to build the new expression.
1814  /// Subclasses may override this routine to provide different behavior.
1815  ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
1816                               bool UseGlobal,
1817                               SourceLocation PlacementLParen,
1818                               MultiExprArg PlacementArgs,
1819                               SourceLocation PlacementRParen,
1820                               SourceRange TypeIdParens,
1821                               QualType AllocatedType,
1822                               TypeSourceInfo *AllocatedTypeInfo,
1823                               Expr *ArraySize,
1824                               SourceLocation ConstructorLParen,
1825                               MultiExprArg ConstructorArgs,
1826                               SourceLocation ConstructorRParen) {
1827    return getSema().BuildCXXNew(StartLoc, UseGlobal,
1828                                 PlacementLParen,
1829                                 move(PlacementArgs),
1830                                 PlacementRParen,
1831                                 TypeIdParens,
1832                                 AllocatedType,
1833                                 AllocatedTypeInfo,
1834                                 ArraySize,
1835                                 ConstructorLParen,
1836                                 move(ConstructorArgs),
1837                                 ConstructorRParen);
1838  }
1839
1840  /// \brief Build a new C++ "delete" 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 RebuildCXXDeleteExpr(SourceLocation StartLoc,
1845                                        bool IsGlobalDelete,
1846                                        bool IsArrayForm,
1847                                        Expr *Operand) {
1848    return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
1849                                    Operand);
1850  }
1851
1852  /// \brief Build a new unary type trait expression.
1853  ///
1854  /// By default, performs semantic analysis to build the new expression.
1855  /// Subclasses may override this routine to provide different behavior.
1856  ExprResult RebuildUnaryTypeTrait(UnaryTypeTrait Trait,
1857                                   SourceLocation StartLoc,
1858                                   TypeSourceInfo *T,
1859                                   SourceLocation RParenLoc) {
1860    return getSema().BuildUnaryTypeTrait(Trait, StartLoc, T, RParenLoc);
1861  }
1862
1863  /// \brief Build a new binary type trait 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 RebuildBinaryTypeTrait(BinaryTypeTrait Trait,
1868                                    SourceLocation StartLoc,
1869                                    TypeSourceInfo *LhsT,
1870                                    TypeSourceInfo *RhsT,
1871                                    SourceLocation RParenLoc) {
1872    return getSema().BuildBinaryTypeTrait(Trait, StartLoc, LhsT, RhsT, RParenLoc);
1873  }
1874
1875  /// \brief Build a new (previously unresolved) declaration reference
1876  /// expression.
1877  ///
1878  /// By default, performs semantic analysis to build the new expression.
1879  /// Subclasses may override this routine to provide different behavior.
1880  ExprResult RebuildDependentScopeDeclRefExpr(NestedNameSpecifier *NNS,
1881                                                SourceRange QualifierRange,
1882                                       const DeclarationNameInfo &NameInfo,
1883                              const TemplateArgumentListInfo *TemplateArgs) {
1884    CXXScopeSpec SS;
1885    SS.setRange(QualifierRange);
1886    SS.setScopeRep(NNS);
1887
1888    if (TemplateArgs)
1889      return getSema().BuildQualifiedTemplateIdExpr(SS, NameInfo,
1890                                                    *TemplateArgs);
1891
1892    return getSema().BuildQualifiedDeclarationNameExpr(SS, NameInfo);
1893  }
1894
1895  /// \brief Build a new template-id expression.
1896  ///
1897  /// By default, performs semantic analysis to build the new expression.
1898  /// Subclasses may override this routine to provide different behavior.
1899  ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
1900                                         LookupResult &R,
1901                                         bool RequiresADL,
1902                              const TemplateArgumentListInfo &TemplateArgs) {
1903    return getSema().BuildTemplateIdExpr(SS, R, RequiresADL, TemplateArgs);
1904  }
1905
1906  /// \brief Build a new object-construction 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 RebuildCXXConstructExpr(QualType T,
1911                                           SourceLocation Loc,
1912                                           CXXConstructorDecl *Constructor,
1913                                           bool IsElidable,
1914                                           MultiExprArg Args,
1915                                           bool RequiresZeroInit,
1916                             CXXConstructExpr::ConstructionKind ConstructKind,
1917                                           SourceRange ParenRange) {
1918    ASTOwningVector<Expr*> ConvertedArgs(SemaRef);
1919    if (getSema().CompleteConstructorCall(Constructor, move(Args), Loc,
1920                                          ConvertedArgs))
1921      return ExprError();
1922
1923    return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
1924                                           move_arg(ConvertedArgs),
1925                                           RequiresZeroInit, ConstructKind,
1926                                           ParenRange);
1927  }
1928
1929  /// \brief Build a new object-construction expression.
1930  ///
1931  /// By default, performs semantic analysis to build the new expression.
1932  /// Subclasses may override this routine to provide different behavior.
1933  ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
1934                                           SourceLocation LParenLoc,
1935                                           MultiExprArg Args,
1936                                           SourceLocation RParenLoc) {
1937    return getSema().BuildCXXTypeConstructExpr(TSInfo,
1938                                               LParenLoc,
1939                                               move(Args),
1940                                               RParenLoc);
1941  }
1942
1943  /// \brief Build a new object-construction expression.
1944  ///
1945  /// By default, performs semantic analysis to build the new expression.
1946  /// Subclasses may override this routine to provide different behavior.
1947  ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
1948                                               SourceLocation LParenLoc,
1949                                               MultiExprArg Args,
1950                                               SourceLocation RParenLoc) {
1951    return getSema().BuildCXXTypeConstructExpr(TSInfo,
1952                                               LParenLoc,
1953                                               move(Args),
1954                                               RParenLoc);
1955  }
1956
1957  /// \brief Build a new member reference expression.
1958  ///
1959  /// By default, performs semantic analysis to build the new expression.
1960  /// Subclasses may override this routine to provide different behavior.
1961  ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
1962                                                  QualType BaseType,
1963                                                  bool IsArrow,
1964                                                  SourceLocation OperatorLoc,
1965                                              NestedNameSpecifier *Qualifier,
1966                                                  SourceRange QualifierRange,
1967                                            NamedDecl *FirstQualifierInScope,
1968                                   const DeclarationNameInfo &MemberNameInfo,
1969                              const TemplateArgumentListInfo *TemplateArgs) {
1970    CXXScopeSpec SS;
1971    SS.setRange(QualifierRange);
1972    SS.setScopeRep(Qualifier);
1973
1974    return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
1975                                            OperatorLoc, IsArrow,
1976                                            SS, FirstQualifierInScope,
1977                                            MemberNameInfo,
1978                                            TemplateArgs);
1979  }
1980
1981  /// \brief Build a new member reference expression.
1982  ///
1983  /// By default, performs semantic analysis to build the new expression.
1984  /// Subclasses may override this routine to provide different behavior.
1985  ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE,
1986                                               QualType BaseType,
1987                                               SourceLocation OperatorLoc,
1988                                               bool IsArrow,
1989                                               NestedNameSpecifier *Qualifier,
1990                                               SourceRange QualifierRange,
1991                                               NamedDecl *FirstQualifierInScope,
1992                                               LookupResult &R,
1993                                const TemplateArgumentListInfo *TemplateArgs) {
1994    CXXScopeSpec SS;
1995    SS.setRange(QualifierRange);
1996    SS.setScopeRep(Qualifier);
1997
1998    return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
1999                                            OperatorLoc, IsArrow,
2000                                            SS, FirstQualifierInScope,
2001                                            R, TemplateArgs);
2002  }
2003
2004  /// \brief Build a new noexcept expression.
2005  ///
2006  /// By default, performs semantic analysis to build the new expression.
2007  /// Subclasses may override this routine to provide different behavior.
2008  ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2009    return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2010  }
2011
2012  /// \brief Build a new expression to compute the length of a parameter pack.
2013  ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
2014                                   SourceLocation PackLoc,
2015                                   SourceLocation RParenLoc,
2016                                   unsigned Length) {
2017    return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2018                                                OperatorLoc, Pack, PackLoc,
2019                                                RParenLoc, Length);
2020  }
2021
2022  /// \brief Build a new Objective-C @encode expression.
2023  ///
2024  /// By default, performs semantic analysis to build the new expression.
2025  /// Subclasses may override this routine to provide different behavior.
2026  ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
2027                                         TypeSourceInfo *EncodeTypeInfo,
2028                                         SourceLocation RParenLoc) {
2029    return SemaRef.Owned(SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo,
2030                                                           RParenLoc));
2031  }
2032
2033  /// \brief Build a new Objective-C class message.
2034  ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
2035                                          Selector Sel,
2036                                          SourceLocation SelectorLoc,
2037                                          ObjCMethodDecl *Method,
2038                                          SourceLocation LBracLoc,
2039                                          MultiExprArg Args,
2040                                          SourceLocation RBracLoc) {
2041    return SemaRef.BuildClassMessage(ReceiverTypeInfo,
2042                                     ReceiverTypeInfo->getType(),
2043                                     /*SuperLoc=*/SourceLocation(),
2044                                     Sel, Method, LBracLoc, SelectorLoc,
2045                                     RBracLoc, move(Args));
2046  }
2047
2048  /// \brief Build a new Objective-C instance message.
2049  ExprResult RebuildObjCMessageExpr(Expr *Receiver,
2050                                          Selector Sel,
2051                                          SourceLocation SelectorLoc,
2052                                          ObjCMethodDecl *Method,
2053                                          SourceLocation LBracLoc,
2054                                          MultiExprArg Args,
2055                                          SourceLocation RBracLoc) {
2056    return SemaRef.BuildInstanceMessage(Receiver,
2057                                        Receiver->getType(),
2058                                        /*SuperLoc=*/SourceLocation(),
2059                                        Sel, Method, LBracLoc, SelectorLoc,
2060                                        RBracLoc, move(Args));
2061  }
2062
2063  /// \brief Build a new Objective-C ivar reference expression.
2064  ///
2065  /// By default, performs semantic analysis to build the new expression.
2066  /// Subclasses may override this routine to provide different behavior.
2067  ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
2068                                          SourceLocation IvarLoc,
2069                                          bool IsArrow, bool IsFreeIvar) {
2070    // FIXME: We lose track of the IsFreeIvar bit.
2071    CXXScopeSpec SS;
2072    Expr *Base = BaseArg;
2073    LookupResult R(getSema(), Ivar->getDeclName(), IvarLoc,
2074                   Sema::LookupMemberName);
2075    ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
2076                                                         /*FIME:*/IvarLoc,
2077                                                         SS, 0,
2078                                                         false);
2079    if (Result.isInvalid())
2080      return ExprError();
2081
2082    if (Result.get())
2083      return move(Result);
2084
2085    return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2086                                              /*FIXME:*/IvarLoc, IsArrow, SS,
2087                                              /*FirstQualifierInScope=*/0,
2088                                              R,
2089                                              /*TemplateArgs=*/0);
2090  }
2091
2092  /// \brief Build a new Objective-C property reference expression.
2093  ///
2094  /// By default, performs semantic analysis to build the new expression.
2095  /// Subclasses may override this routine to provide different behavior.
2096  ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
2097                                              ObjCPropertyDecl *Property,
2098                                              SourceLocation PropertyLoc) {
2099    CXXScopeSpec SS;
2100    Expr *Base = BaseArg;
2101    LookupResult R(getSema(), Property->getDeclName(), PropertyLoc,
2102                   Sema::LookupMemberName);
2103    bool IsArrow = false;
2104    ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
2105                                                         /*FIME:*/PropertyLoc,
2106                                                         SS, 0, false);
2107    if (Result.isInvalid())
2108      return ExprError();
2109
2110    if (Result.get())
2111      return move(Result);
2112
2113    return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2114                                              /*FIXME:*/PropertyLoc, IsArrow,
2115                                              SS,
2116                                              /*FirstQualifierInScope=*/0,
2117                                              R,
2118                                              /*TemplateArgs=*/0);
2119  }
2120
2121  /// \brief Build a new Objective-C property reference expression.
2122  ///
2123  /// By default, performs semantic analysis to build the new expression.
2124  /// Subclasses may override this routine to provide different behavior.
2125  ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
2126                                        ObjCMethodDecl *Getter,
2127                                        ObjCMethodDecl *Setter,
2128                                        SourceLocation PropertyLoc) {
2129    // Since these expressions can only be value-dependent, we do not
2130    // need to perform semantic analysis again.
2131    return Owned(
2132      new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
2133                                                  VK_LValue, OK_ObjCProperty,
2134                                                  PropertyLoc, Base));
2135  }
2136
2137  /// \brief Build a new Objective-C "isa" expression.
2138  ///
2139  /// By default, performs semantic analysis to build the new expression.
2140  /// Subclasses may override this routine to provide different behavior.
2141  ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
2142                                      bool IsArrow) {
2143    CXXScopeSpec SS;
2144    Expr *Base = BaseArg;
2145    LookupResult R(getSema(), &getSema().Context.Idents.get("isa"), IsaLoc,
2146                   Sema::LookupMemberName);
2147    ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
2148                                                         /*FIME:*/IsaLoc,
2149                                                         SS, 0, false);
2150    if (Result.isInvalid())
2151      return ExprError();
2152
2153    if (Result.get())
2154      return move(Result);
2155
2156    return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2157                                              /*FIXME:*/IsaLoc, IsArrow, SS,
2158                                              /*FirstQualifierInScope=*/0,
2159                                              R,
2160                                              /*TemplateArgs=*/0);
2161  }
2162
2163  /// \brief Build a new shuffle vector expression.
2164  ///
2165  /// By default, performs semantic analysis to build the new expression.
2166  /// Subclasses may override this routine to provide different behavior.
2167  ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
2168                                      MultiExprArg SubExprs,
2169                                      SourceLocation RParenLoc) {
2170    // Find the declaration for __builtin_shufflevector
2171    const IdentifierInfo &Name
2172      = SemaRef.Context.Idents.get("__builtin_shufflevector");
2173    TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
2174    DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
2175    assert(Lookup.first != Lookup.second && "No __builtin_shufflevector?");
2176
2177    // Build a reference to the __builtin_shufflevector builtin
2178    FunctionDecl *Builtin = cast<FunctionDecl>(*Lookup.first);
2179    Expr *Callee
2180      = new (SemaRef.Context) DeclRefExpr(Builtin, Builtin->getType(),
2181                                          VK_LValue, BuiltinLoc);
2182    SemaRef.UsualUnaryConversions(Callee);
2183
2184    // Build the CallExpr
2185    unsigned NumSubExprs = SubExprs.size();
2186    Expr **Subs = (Expr **)SubExprs.release();
2187    CallExpr *TheCall = new (SemaRef.Context) CallExpr(SemaRef.Context, Callee,
2188                                                       Subs, NumSubExprs,
2189                                                   Builtin->getCallResultType(),
2190                            Expr::getValueKindForType(Builtin->getResultType()),
2191                                                       RParenLoc);
2192    ExprResult OwnedCall(SemaRef.Owned(TheCall));
2193
2194    // Type-check the __builtin_shufflevector expression.
2195    ExprResult Result = SemaRef.SemaBuiltinShuffleVector(TheCall);
2196    if (Result.isInvalid())
2197      return ExprError();
2198
2199    OwnedCall.release();
2200    return move(Result);
2201  }
2202
2203  /// \brief Build a new template argument pack expansion.
2204  ///
2205  /// By default, performs semantic analysis to build a new pack expansion
2206  /// for a template argument. Subclasses may override this routine to provide
2207  /// different behavior.
2208  TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
2209                                           SourceLocation EllipsisLoc,
2210                                       llvm::Optional<unsigned> NumExpansions) {
2211    switch (Pattern.getArgument().getKind()) {
2212    case TemplateArgument::Expression: {
2213      ExprResult Result
2214        = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
2215                                       EllipsisLoc, NumExpansions);
2216      if (Result.isInvalid())
2217        return TemplateArgumentLoc();
2218
2219      return TemplateArgumentLoc(Result.get(), Result.get());
2220    }
2221
2222    case TemplateArgument::Template:
2223      return TemplateArgumentLoc(TemplateArgument(
2224                                          Pattern.getArgument().getAsTemplate(),
2225                                                  NumExpansions),
2226                                 Pattern.getTemplateQualifierRange(),
2227                                 Pattern.getTemplateNameLoc(),
2228                                 EllipsisLoc);
2229
2230    case TemplateArgument::Null:
2231    case TemplateArgument::Integral:
2232    case TemplateArgument::Declaration:
2233    case TemplateArgument::Pack:
2234    case TemplateArgument::TemplateExpansion:
2235      llvm_unreachable("Pack expansion pattern has no parameter packs");
2236
2237    case TemplateArgument::Type:
2238      if (TypeSourceInfo *Expansion
2239            = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
2240                                           EllipsisLoc,
2241                                           NumExpansions))
2242        return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
2243                                   Expansion);
2244      break;
2245    }
2246
2247    return TemplateArgumentLoc();
2248  }
2249
2250  /// \brief Build a new expression pack expansion.
2251  ///
2252  /// By default, performs semantic analysis to build a new pack expansion
2253  /// for an expression. Subclasses may override this routine to provide
2254  /// different behavior.
2255  ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
2256                                  llvm::Optional<unsigned> NumExpansions) {
2257    return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
2258  }
2259
2260private:
2261  QualType TransformTypeInObjectScope(QualType T,
2262                                      QualType ObjectType,
2263                                      NamedDecl *FirstQualifierInScope,
2264                                      NestedNameSpecifier *Prefix);
2265
2266  TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *T,
2267                                             QualType ObjectType,
2268                                             NamedDecl *FirstQualifierInScope,
2269                                             NestedNameSpecifier *Prefix);
2270};
2271
2272template<typename Derived>
2273StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
2274  if (!S)
2275    return SemaRef.Owned(S);
2276
2277  switch (S->getStmtClass()) {
2278  case Stmt::NoStmtClass: break;
2279
2280  // Transform individual statement nodes
2281#define STMT(Node, Parent)                                              \
2282  case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
2283#define ABSTRACT_STMT(Node)
2284#define EXPR(Node, Parent)
2285#include "clang/AST/StmtNodes.inc"
2286
2287  // Transform expressions by calling TransformExpr.
2288#define STMT(Node, Parent)
2289#define ABSTRACT_STMT(Stmt)
2290#define EXPR(Node, Parent) case Stmt::Node##Class:
2291#include "clang/AST/StmtNodes.inc"
2292    {
2293      ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
2294      if (E.isInvalid())
2295        return StmtError();
2296
2297      return getSema().ActOnExprStmt(getSema().MakeFullExpr(E.take()));
2298    }
2299  }
2300
2301  return SemaRef.Owned(S);
2302}
2303
2304
2305template<typename Derived>
2306ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
2307  if (!E)
2308    return SemaRef.Owned(E);
2309
2310  switch (E->getStmtClass()) {
2311    case Stmt::NoStmtClass: break;
2312#define STMT(Node, Parent) case Stmt::Node##Class: break;
2313#define ABSTRACT_STMT(Stmt)
2314#define EXPR(Node, Parent)                                              \
2315    case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
2316#include "clang/AST/StmtNodes.inc"
2317  }
2318
2319  return SemaRef.Owned(E);
2320}
2321
2322template<typename Derived>
2323bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
2324                                            unsigned NumInputs,
2325                                            bool IsCall,
2326                                      llvm::SmallVectorImpl<Expr *> &Outputs,
2327                                            bool *ArgChanged) {
2328  for (unsigned I = 0; I != NumInputs; ++I) {
2329    // If requested, drop call arguments that need to be dropped.
2330    if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
2331      if (ArgChanged)
2332        *ArgChanged = true;
2333
2334      break;
2335    }
2336
2337    if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
2338      Expr *Pattern = Expansion->getPattern();
2339
2340      llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2341      getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
2342      assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
2343
2344      // Determine whether the set of unexpanded parameter packs can and should
2345      // be expanded.
2346      bool Expand = true;
2347      bool RetainExpansion = false;
2348      llvm::Optional<unsigned> OrigNumExpansions
2349        = Expansion->getNumExpansions();
2350      llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
2351      if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
2352                                               Pattern->getSourceRange(),
2353                                               Unexpanded.data(),
2354                                               Unexpanded.size(),
2355                                               Expand, RetainExpansion,
2356                                               NumExpansions))
2357        return true;
2358
2359      if (!Expand) {
2360        // The transform has determined that we should perform a simple
2361        // transformation on the pack expansion, producing another pack
2362        // expansion.
2363        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
2364        ExprResult OutPattern = getDerived().TransformExpr(Pattern);
2365        if (OutPattern.isInvalid())
2366          return true;
2367
2368        ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
2369                                                Expansion->getEllipsisLoc(),
2370                                                           NumExpansions);
2371        if (Out.isInvalid())
2372          return true;
2373
2374        if (ArgChanged)
2375          *ArgChanged = true;
2376        Outputs.push_back(Out.get());
2377        continue;
2378      }
2379
2380      // The transform has determined that we should perform an elementwise
2381      // expansion of the pattern. Do so.
2382      for (unsigned I = 0; I != *NumExpansions; ++I) {
2383        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
2384        ExprResult Out = getDerived().TransformExpr(Pattern);
2385        if (Out.isInvalid())
2386          return true;
2387
2388        if (Out.get()->containsUnexpandedParameterPack()) {
2389          Out = RebuildPackExpansion(Out.get(), Expansion->getEllipsisLoc(),
2390                                     OrigNumExpansions);
2391          if (Out.isInvalid())
2392            return true;
2393        }
2394
2395        if (ArgChanged)
2396          *ArgChanged = true;
2397        Outputs.push_back(Out.get());
2398      }
2399
2400      continue;
2401    }
2402
2403    ExprResult Result = getDerived().TransformExpr(Inputs[I]);
2404    if (Result.isInvalid())
2405      return true;
2406
2407    if (Result.get() != Inputs[I] && ArgChanged)
2408      *ArgChanged = true;
2409
2410    Outputs.push_back(Result.get());
2411  }
2412
2413  return false;
2414}
2415
2416template<typename Derived>
2417NestedNameSpecifier *
2418TreeTransform<Derived>::TransformNestedNameSpecifier(NestedNameSpecifier *NNS,
2419                                                     SourceRange Range,
2420                                                     QualType ObjectType,
2421                                             NamedDecl *FirstQualifierInScope) {
2422  NestedNameSpecifier *Prefix = NNS->getPrefix();
2423
2424  // Transform the prefix of this nested name specifier.
2425  if (Prefix) {
2426    Prefix = getDerived().TransformNestedNameSpecifier(Prefix, Range,
2427                                                       ObjectType,
2428                                                       FirstQualifierInScope);
2429    if (!Prefix)
2430      return 0;
2431  }
2432
2433  switch (NNS->getKind()) {
2434  case NestedNameSpecifier::Identifier:
2435    if (Prefix) {
2436      // The object type and qualifier-in-scope really apply to the
2437      // leftmost entity.
2438      ObjectType = QualType();
2439      FirstQualifierInScope = 0;
2440    }
2441
2442    assert((Prefix || !ObjectType.isNull()) &&
2443            "Identifier nested-name-specifier with no prefix or object type");
2444    if (!getDerived().AlwaysRebuild() && Prefix == NNS->getPrefix() &&
2445        ObjectType.isNull())
2446      return NNS;
2447
2448    return getDerived().RebuildNestedNameSpecifier(Prefix, Range,
2449                                                   *NNS->getAsIdentifier(),
2450                                                   ObjectType,
2451                                                   FirstQualifierInScope);
2452
2453  case NestedNameSpecifier::Namespace: {
2454    NamespaceDecl *NS
2455      = cast_or_null<NamespaceDecl>(
2456                                    getDerived().TransformDecl(Range.getBegin(),
2457                                                       NNS->getAsNamespace()));
2458    if (!getDerived().AlwaysRebuild() &&
2459        Prefix == NNS->getPrefix() &&
2460        NS == NNS->getAsNamespace())
2461      return NNS;
2462
2463    return getDerived().RebuildNestedNameSpecifier(Prefix, Range, NS);
2464  }
2465
2466  case NestedNameSpecifier::Global:
2467    // There is no meaningful transformation that one could perform on the
2468    // global scope.
2469    return NNS;
2470
2471  case NestedNameSpecifier::TypeSpecWithTemplate:
2472  case NestedNameSpecifier::TypeSpec: {
2473    TemporaryBase Rebase(*this, Range.getBegin(), DeclarationName());
2474    QualType T = TransformTypeInObjectScope(QualType(NNS->getAsType(), 0),
2475                                            ObjectType,
2476                                            FirstQualifierInScope,
2477                                            Prefix);
2478    if (T.isNull())
2479      return 0;
2480
2481    if (!getDerived().AlwaysRebuild() &&
2482        Prefix == NNS->getPrefix() &&
2483        T == QualType(NNS->getAsType(), 0))
2484      return NNS;
2485
2486    return getDerived().RebuildNestedNameSpecifier(Prefix, Range,
2487                  NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2488                                                   T);
2489  }
2490  }
2491
2492  // Required to silence a GCC warning
2493  return 0;
2494}
2495
2496template<typename Derived>
2497DeclarationNameInfo
2498TreeTransform<Derived>
2499::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
2500  DeclarationName Name = NameInfo.getName();
2501  if (!Name)
2502    return DeclarationNameInfo();
2503
2504  switch (Name.getNameKind()) {
2505  case DeclarationName::Identifier:
2506  case DeclarationName::ObjCZeroArgSelector:
2507  case DeclarationName::ObjCOneArgSelector:
2508  case DeclarationName::ObjCMultiArgSelector:
2509  case DeclarationName::CXXOperatorName:
2510  case DeclarationName::CXXLiteralOperatorName:
2511  case DeclarationName::CXXUsingDirective:
2512    return NameInfo;
2513
2514  case DeclarationName::CXXConstructorName:
2515  case DeclarationName::CXXDestructorName:
2516  case DeclarationName::CXXConversionFunctionName: {
2517    TypeSourceInfo *NewTInfo;
2518    CanQualType NewCanTy;
2519    if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
2520      NewTInfo = getDerived().TransformType(OldTInfo);
2521      if (!NewTInfo)
2522        return DeclarationNameInfo();
2523      NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
2524    }
2525    else {
2526      NewTInfo = 0;
2527      TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
2528      QualType NewT = getDerived().TransformType(Name.getCXXNameType());
2529      if (NewT.isNull())
2530        return DeclarationNameInfo();
2531      NewCanTy = SemaRef.Context.getCanonicalType(NewT);
2532    }
2533
2534    DeclarationName NewName
2535      = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
2536                                                           NewCanTy);
2537    DeclarationNameInfo NewNameInfo(NameInfo);
2538    NewNameInfo.setName(NewName);
2539    NewNameInfo.setNamedTypeInfo(NewTInfo);
2540    return NewNameInfo;
2541  }
2542  }
2543
2544  assert(0 && "Unknown name kind.");
2545  return DeclarationNameInfo();
2546}
2547
2548template<typename Derived>
2549TemplateName
2550TreeTransform<Derived>::TransformTemplateName(TemplateName Name,
2551                                              QualType ObjectType,
2552                                              NamedDecl *FirstQualifierInScope) {
2553  SourceLocation Loc = getDerived().getBaseLocation();
2554
2555  if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
2556    NestedNameSpecifier *NNS
2557      = getDerived().TransformNestedNameSpecifier(QTN->getQualifier(),
2558                                                  /*FIXME*/ SourceRange(Loc),
2559                                                  ObjectType,
2560                                                  FirstQualifierInScope);
2561    if (!NNS)
2562      return TemplateName();
2563
2564    if (TemplateDecl *Template = QTN->getTemplateDecl()) {
2565      TemplateDecl *TransTemplate
2566        = cast_or_null<TemplateDecl>(getDerived().TransformDecl(Loc, Template));
2567      if (!TransTemplate)
2568        return TemplateName();
2569
2570      if (!getDerived().AlwaysRebuild() &&
2571          NNS == QTN->getQualifier() &&
2572          TransTemplate == Template)
2573        return Name;
2574
2575      return getDerived().RebuildTemplateName(NNS, QTN->hasTemplateKeyword(),
2576                                              TransTemplate);
2577    }
2578
2579    // These should be getting filtered out before they make it into the AST.
2580    llvm_unreachable("overloaded template name survived to here");
2581  }
2582
2583  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2584    NestedNameSpecifier *NNS = DTN->getQualifier();
2585    if (NNS) {
2586      NNS = getDerived().TransformNestedNameSpecifier(NNS,
2587                                                  /*FIXME:*/SourceRange(Loc),
2588                                                      ObjectType,
2589                                                      FirstQualifierInScope);
2590      if (!NNS) return TemplateName();
2591
2592      // These apply to the scope specifier, not the template.
2593      ObjectType = QualType();
2594      FirstQualifierInScope = 0;
2595    }
2596
2597    if (!getDerived().AlwaysRebuild() &&
2598        NNS == DTN->getQualifier() &&
2599        ObjectType.isNull())
2600      return Name;
2601
2602    if (DTN->isIdentifier()) {
2603      // FIXME: Bad range
2604      SourceRange QualifierRange(getDerived().getBaseLocation());
2605      return getDerived().RebuildTemplateName(NNS, QualifierRange,
2606                                              *DTN->getIdentifier(),
2607                                              ObjectType,
2608                                              FirstQualifierInScope);
2609    }
2610
2611    return getDerived().RebuildTemplateName(NNS, DTN->getOperator(),
2612                                            ObjectType);
2613  }
2614
2615  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2616    TemplateDecl *TransTemplate
2617      = cast_or_null<TemplateDecl>(getDerived().TransformDecl(Loc, Template));
2618    if (!TransTemplate)
2619      return TemplateName();
2620
2621    if (!getDerived().AlwaysRebuild() &&
2622        TransTemplate == Template)
2623      return Name;
2624
2625    return TemplateName(TransTemplate);
2626  }
2627
2628  if (SubstTemplateTemplateParmPackStorage *SubstPack
2629                                 = Name.getAsSubstTemplateTemplateParmPack()) {
2630    TemplateTemplateParmDecl *TransParam
2631      = cast_or_null<TemplateTemplateParmDecl>(
2632               getDerived().TransformDecl(Loc, SubstPack->getParameterPack()));
2633    if (!TransParam)
2634      return TemplateName();
2635
2636    if (!getDerived().AlwaysRebuild() &&
2637        TransParam == SubstPack->getParameterPack())
2638      return Name;
2639
2640    return getDerived().RebuildTemplateName(TransParam,
2641                                            SubstPack->getArgumentPack());
2642  }
2643
2644  // These should be getting filtered out before they reach the AST.
2645  llvm_unreachable("overloaded function decl survived to here");
2646  return TemplateName();
2647}
2648
2649template<typename Derived>
2650void TreeTransform<Derived>::InventTemplateArgumentLoc(
2651                                         const TemplateArgument &Arg,
2652                                         TemplateArgumentLoc &Output) {
2653  SourceLocation Loc = getDerived().getBaseLocation();
2654  switch (Arg.getKind()) {
2655  case TemplateArgument::Null:
2656    llvm_unreachable("null template argument in TreeTransform");
2657    break;
2658
2659  case TemplateArgument::Type:
2660    Output = TemplateArgumentLoc(Arg,
2661               SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2662
2663    break;
2664
2665  case TemplateArgument::Template:
2666    Output = TemplateArgumentLoc(Arg, SourceRange(), Loc);
2667    break;
2668
2669  case TemplateArgument::TemplateExpansion:
2670    Output = TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
2671    break;
2672
2673  case TemplateArgument::Expression:
2674    Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
2675    break;
2676
2677  case TemplateArgument::Declaration:
2678  case TemplateArgument::Integral:
2679  case TemplateArgument::Pack:
2680    Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2681    break;
2682  }
2683}
2684
2685template<typename Derived>
2686bool TreeTransform<Derived>::TransformTemplateArgument(
2687                                         const TemplateArgumentLoc &Input,
2688                                         TemplateArgumentLoc &Output) {
2689  const TemplateArgument &Arg = Input.getArgument();
2690  switch (Arg.getKind()) {
2691  case TemplateArgument::Null:
2692  case TemplateArgument::Integral:
2693    Output = Input;
2694    return false;
2695
2696  case TemplateArgument::Type: {
2697    TypeSourceInfo *DI = Input.getTypeSourceInfo();
2698    if (DI == NULL)
2699      DI = InventTypeSourceInfo(Input.getArgument().getAsType());
2700
2701    DI = getDerived().TransformType(DI);
2702    if (!DI) return true;
2703
2704    Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2705    return false;
2706  }
2707
2708  case TemplateArgument::Declaration: {
2709    // FIXME: we should never have to transform one of these.
2710    DeclarationName Name;
2711    if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl()))
2712      Name = ND->getDeclName();
2713    TemporaryBase Rebase(*this, Input.getLocation(), Name);
2714    Decl *D = getDerived().TransformDecl(Input.getLocation(), Arg.getAsDecl());
2715    if (!D) return true;
2716
2717    Expr *SourceExpr = Input.getSourceDeclExpression();
2718    if (SourceExpr) {
2719      EnterExpressionEvaluationContext Unevaluated(getSema(),
2720                                                   Sema::Unevaluated);
2721      ExprResult E = getDerived().TransformExpr(SourceExpr);
2722      SourceExpr = (E.isInvalid() ? 0 : E.take());
2723    }
2724
2725    Output = TemplateArgumentLoc(TemplateArgument(D), SourceExpr);
2726    return false;
2727  }
2728
2729  case TemplateArgument::Template: {
2730    TemporaryBase Rebase(*this, Input.getLocation(), DeclarationName());
2731    TemplateName Template
2732      = getDerived().TransformTemplateName(Arg.getAsTemplate());
2733    if (Template.isNull())
2734      return true;
2735
2736    Output = TemplateArgumentLoc(TemplateArgument(Template),
2737                                 Input.getTemplateQualifierRange(),
2738                                 Input.getTemplateNameLoc());
2739    return false;
2740  }
2741
2742  case TemplateArgument::TemplateExpansion:
2743    llvm_unreachable("Caller should expand pack expansions");
2744
2745  case TemplateArgument::Expression: {
2746    // Template argument expressions are not potentially evaluated.
2747    EnterExpressionEvaluationContext Unevaluated(getSema(),
2748                                                 Sema::Unevaluated);
2749
2750    Expr *InputExpr = Input.getSourceExpression();
2751    if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
2752
2753    ExprResult E
2754      = getDerived().TransformExpr(InputExpr);
2755    if (E.isInvalid()) return true;
2756    Output = TemplateArgumentLoc(TemplateArgument(E.take()), E.take());
2757    return false;
2758  }
2759
2760  case TemplateArgument::Pack: {
2761    llvm::SmallVector<TemplateArgument, 4> TransformedArgs;
2762    TransformedArgs.reserve(Arg.pack_size());
2763    for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2764                                      AEnd = Arg.pack_end();
2765         A != AEnd; ++A) {
2766
2767      // FIXME: preserve source information here when we start
2768      // caring about parameter packs.
2769
2770      TemplateArgumentLoc InputArg;
2771      TemplateArgumentLoc OutputArg;
2772      getDerived().InventTemplateArgumentLoc(*A, InputArg);
2773      if (getDerived().TransformTemplateArgument(InputArg, OutputArg))
2774        return true;
2775
2776      TransformedArgs.push_back(OutputArg.getArgument());
2777    }
2778
2779    TemplateArgument *TransformedArgsPtr
2780      = new (getSema().Context) TemplateArgument[TransformedArgs.size()];
2781    std::copy(TransformedArgs.begin(), TransformedArgs.end(),
2782              TransformedArgsPtr);
2783    Output = TemplateArgumentLoc(TemplateArgument(TransformedArgsPtr,
2784                                                  TransformedArgs.size()),
2785                                 Input.getLocInfo());
2786    return false;
2787  }
2788  }
2789
2790  // Work around bogus GCC warning
2791  return true;
2792}
2793
2794/// \brief Iterator adaptor that invents template argument location information
2795/// for each of the template arguments in its underlying iterator.
2796template<typename Derived, typename InputIterator>
2797class TemplateArgumentLocInventIterator {
2798  TreeTransform<Derived> &Self;
2799  InputIterator Iter;
2800
2801public:
2802  typedef TemplateArgumentLoc value_type;
2803  typedef TemplateArgumentLoc reference;
2804  typedef typename std::iterator_traits<InputIterator>::difference_type
2805    difference_type;
2806  typedef std::input_iterator_tag iterator_category;
2807
2808  class pointer {
2809    TemplateArgumentLoc Arg;
2810
2811  public:
2812    explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
2813
2814    const TemplateArgumentLoc *operator->() const { return &Arg; }
2815  };
2816
2817  TemplateArgumentLocInventIterator() { }
2818
2819  explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
2820                                             InputIterator Iter)
2821    : Self(Self), Iter(Iter) { }
2822
2823  TemplateArgumentLocInventIterator &operator++() {
2824    ++Iter;
2825    return *this;
2826  }
2827
2828  TemplateArgumentLocInventIterator operator++(int) {
2829    TemplateArgumentLocInventIterator Old(*this);
2830    ++(*this);
2831    return Old;
2832  }
2833
2834  reference operator*() const {
2835    TemplateArgumentLoc Result;
2836    Self.InventTemplateArgumentLoc(*Iter, Result);
2837    return Result;
2838  }
2839
2840  pointer operator->() const { return pointer(**this); }
2841
2842  friend bool operator==(const TemplateArgumentLocInventIterator &X,
2843                         const TemplateArgumentLocInventIterator &Y) {
2844    return X.Iter == Y.Iter;
2845  }
2846
2847  friend bool operator!=(const TemplateArgumentLocInventIterator &X,
2848                         const TemplateArgumentLocInventIterator &Y) {
2849    return X.Iter != Y.Iter;
2850  }
2851};
2852
2853template<typename Derived>
2854template<typename InputIterator>
2855bool TreeTransform<Derived>::TransformTemplateArguments(InputIterator First,
2856                                                        InputIterator Last,
2857                                            TemplateArgumentListInfo &Outputs) {
2858  for (; First != Last; ++First) {
2859    TemplateArgumentLoc Out;
2860    TemplateArgumentLoc In = *First;
2861
2862    if (In.getArgument().getKind() == TemplateArgument::Pack) {
2863      // Unpack argument packs, which we translate them into separate
2864      // arguments.
2865      // FIXME: We could do much better if we could guarantee that the
2866      // TemplateArgumentLocInfo for the pack expansion would be usable for
2867      // all of the template arguments in the argument pack.
2868      typedef TemplateArgumentLocInventIterator<Derived,
2869                                                TemplateArgument::pack_iterator>
2870        PackLocIterator;
2871      if (TransformTemplateArguments(PackLocIterator(*this,
2872                                                 In.getArgument().pack_begin()),
2873                                     PackLocIterator(*this,
2874                                                   In.getArgument().pack_end()),
2875                                     Outputs))
2876        return true;
2877
2878      continue;
2879    }
2880
2881    if (In.getArgument().isPackExpansion()) {
2882      // We have a pack expansion, for which we will be substituting into
2883      // the pattern.
2884      SourceLocation Ellipsis;
2885      llvm::Optional<unsigned> OrigNumExpansions;
2886      TemplateArgumentLoc Pattern
2887        = In.getPackExpansionPattern(Ellipsis, OrigNumExpansions,
2888                                     getSema().Context);
2889
2890      llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2891      getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
2892      assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
2893
2894      // Determine whether the set of unexpanded parameter packs can and should
2895      // be expanded.
2896      bool Expand = true;
2897      bool RetainExpansion = false;
2898      llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
2899      if (getDerived().TryExpandParameterPacks(Ellipsis,
2900                                               Pattern.getSourceRange(),
2901                                               Unexpanded.data(),
2902                                               Unexpanded.size(),
2903                                               Expand,
2904                                               RetainExpansion,
2905                                               NumExpansions))
2906        return true;
2907
2908      if (!Expand) {
2909        // The transform has determined that we should perform a simple
2910        // transformation on the pack expansion, producing another pack
2911        // expansion.
2912        TemplateArgumentLoc OutPattern;
2913        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
2914        if (getDerived().TransformTemplateArgument(Pattern, OutPattern))
2915          return true;
2916
2917        Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
2918                                                NumExpansions);
2919        if (Out.getArgument().isNull())
2920          return true;
2921
2922        Outputs.addArgument(Out);
2923        continue;
2924      }
2925
2926      // The transform has determined that we should perform an elementwise
2927      // expansion of the pattern. Do so.
2928      for (unsigned I = 0; I != *NumExpansions; ++I) {
2929        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
2930
2931        if (getDerived().TransformTemplateArgument(Pattern, Out))
2932          return true;
2933
2934        if (Out.getArgument().containsUnexpandedParameterPack()) {
2935          Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
2936                                                  OrigNumExpansions);
2937          if (Out.getArgument().isNull())
2938            return true;
2939        }
2940
2941        Outputs.addArgument(Out);
2942      }
2943
2944      // If we're supposed to retain a pack expansion, do so by temporarily
2945      // forgetting the partially-substituted parameter pack.
2946      if (RetainExpansion) {
2947        ForgetPartiallySubstitutedPackRAII Forget(getDerived());
2948
2949        if (getDerived().TransformTemplateArgument(Pattern, Out))
2950          return true;
2951
2952        Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
2953                                                OrigNumExpansions);
2954        if (Out.getArgument().isNull())
2955          return true;
2956
2957        Outputs.addArgument(Out);
2958      }
2959
2960      continue;
2961    }
2962
2963    // The simple case:
2964    if (getDerived().TransformTemplateArgument(In, Out))
2965      return true;
2966
2967    Outputs.addArgument(Out);
2968  }
2969
2970  return false;
2971
2972}
2973
2974//===----------------------------------------------------------------------===//
2975// Type transformation
2976//===----------------------------------------------------------------------===//
2977
2978template<typename Derived>
2979QualType TreeTransform<Derived>::TransformType(QualType T) {
2980  if (getDerived().AlreadyTransformed(T))
2981    return T;
2982
2983  // Temporary workaround.  All of these transformations should
2984  // eventually turn into transformations on TypeLocs.
2985  TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
2986                                                getDerived().getBaseLocation());
2987
2988  TypeSourceInfo *NewDI = getDerived().TransformType(DI);
2989
2990  if (!NewDI)
2991    return QualType();
2992
2993  return NewDI->getType();
2994}
2995
2996template<typename Derived>
2997TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
2998  if (getDerived().AlreadyTransformed(DI->getType()))
2999    return DI;
3000
3001  TypeLocBuilder TLB;
3002
3003  TypeLoc TL = DI->getTypeLoc();
3004  TLB.reserve(TL.getFullDataSize());
3005
3006  QualType Result = getDerived().TransformType(TLB, TL);
3007  if (Result.isNull())
3008    return 0;
3009
3010  return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3011}
3012
3013template<typename Derived>
3014QualType
3015TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
3016  switch (T.getTypeLocClass()) {
3017#define ABSTRACT_TYPELOC(CLASS, PARENT)
3018#define TYPELOC(CLASS, PARENT) \
3019  case TypeLoc::CLASS: \
3020    return getDerived().Transform##CLASS##Type(TLB, cast<CLASS##TypeLoc>(T));
3021#include "clang/AST/TypeLocNodes.def"
3022  }
3023
3024  llvm_unreachable("unhandled type loc!");
3025  return QualType();
3026}
3027
3028/// FIXME: By default, this routine adds type qualifiers only to types
3029/// that can have qualifiers, and silently suppresses those qualifiers
3030/// that are not permitted (e.g., qualifiers on reference or function
3031/// types). This is the right thing for template instantiation, but
3032/// probably not for other clients.
3033template<typename Derived>
3034QualType
3035TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
3036                                               QualifiedTypeLoc T) {
3037  Qualifiers Quals = T.getType().getLocalQualifiers();
3038
3039  QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
3040  if (Result.isNull())
3041    return QualType();
3042
3043  // Silently suppress qualifiers if the result type can't be qualified.
3044  // FIXME: this is the right thing for template instantiation, but
3045  // probably not for other clients.
3046  if (Result->isFunctionType() || Result->isReferenceType())
3047    return Result;
3048
3049  if (!Quals.empty()) {
3050    Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
3051    TLB.push<QualifiedTypeLoc>(Result);
3052    // No location information to preserve.
3053  }
3054
3055  return Result;
3056}
3057
3058/// \brief Transforms a type that was written in a scope specifier,
3059/// given an object type, the results of unqualified lookup, and
3060/// an already-instantiated prefix.
3061///
3062/// The object type is provided iff the scope specifier qualifies the
3063/// member of a dependent member-access expression.  The prefix is
3064/// provided iff the the scope specifier in which this appears has a
3065/// prefix.
3066///
3067/// This is private to TreeTransform.
3068template<typename Derived>
3069QualType
3070TreeTransform<Derived>::TransformTypeInObjectScope(QualType T,
3071                                                   QualType ObjectType,
3072                                                   NamedDecl *UnqualLookup,
3073                                                  NestedNameSpecifier *Prefix) {
3074  if (getDerived().AlreadyTransformed(T))
3075    return T;
3076
3077  TypeSourceInfo *TSI =
3078    SemaRef.Context.getTrivialTypeSourceInfo(T, getDerived().getBaseLocation());
3079
3080  TSI = getDerived().TransformTypeInObjectScope(TSI, ObjectType,
3081                                                UnqualLookup, Prefix);
3082  if (!TSI) return QualType();
3083  return TSI->getType();
3084}
3085
3086template<typename Derived>
3087TypeSourceInfo *
3088TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSI,
3089                                                   QualType ObjectType,
3090                                                   NamedDecl *UnqualLookup,
3091                                                  NestedNameSpecifier *Prefix) {
3092  // TODO: in some cases, we might be some verification to do here.
3093  if (ObjectType.isNull())
3094    return getDerived().TransformType(TSI);
3095
3096  QualType T = TSI->getType();
3097  if (getDerived().AlreadyTransformed(T))
3098    return TSI;
3099
3100  TypeLocBuilder TLB;
3101  QualType Result;
3102
3103  if (isa<TemplateSpecializationType>(T)) {
3104    TemplateSpecializationTypeLoc TL
3105      = cast<TemplateSpecializationTypeLoc>(TSI->getTypeLoc());
3106
3107    TemplateName Template =
3108      getDerived().TransformTemplateName(TL.getTypePtr()->getTemplateName(),
3109                                         ObjectType, UnqualLookup);
3110    if (Template.isNull()) return 0;
3111
3112    Result = getDerived()
3113      .TransformTemplateSpecializationType(TLB, TL, Template);
3114  } else if (isa<DependentTemplateSpecializationType>(T)) {
3115    DependentTemplateSpecializationTypeLoc TL
3116      = cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
3117
3118    Result = getDerived()
3119      .TransformDependentTemplateSpecializationType(TLB, TL, Prefix);
3120  } else {
3121    // Nothing special needs to be done for these.
3122    Result = getDerived().TransformType(TLB, TSI->getTypeLoc());
3123  }
3124
3125  if (Result.isNull()) return 0;
3126  return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3127}
3128
3129template <class TyLoc> static inline
3130QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
3131  TyLoc NewT = TLB.push<TyLoc>(T.getType());
3132  NewT.setNameLoc(T.getNameLoc());
3133  return T.getType();
3134}
3135
3136template<typename Derived>
3137QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
3138                                                      BuiltinTypeLoc T) {
3139  BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
3140  NewT.setBuiltinLoc(T.getBuiltinLoc());
3141  if (T.needsExtraLocalData())
3142    NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
3143  return T.getType();
3144}
3145
3146template<typename Derived>
3147QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
3148                                                      ComplexTypeLoc T) {
3149  // FIXME: recurse?
3150  return TransformTypeSpecType(TLB, T);
3151}
3152
3153template<typename Derived>
3154QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
3155                                                      PointerTypeLoc TL) {
3156  QualType PointeeType
3157    = getDerived().TransformType(TLB, TL.getPointeeLoc());
3158  if (PointeeType.isNull())
3159    return QualType();
3160
3161  QualType Result = TL.getType();
3162  if (PointeeType->getAs<ObjCObjectType>()) {
3163    // A dependent pointer type 'T *' has is being transformed such
3164    // that an Objective-C class type is being replaced for 'T'. The
3165    // resulting pointer type is an ObjCObjectPointerType, not a
3166    // PointerType.
3167    Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
3168
3169    ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
3170    NewT.setStarLoc(TL.getStarLoc());
3171    return Result;
3172  }
3173
3174  if (getDerived().AlwaysRebuild() ||
3175      PointeeType != TL.getPointeeLoc().getType()) {
3176    Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
3177    if (Result.isNull())
3178      return QualType();
3179  }
3180
3181  PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
3182  NewT.setSigilLoc(TL.getSigilLoc());
3183  return Result;
3184}
3185
3186template<typename Derived>
3187QualType
3188TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
3189                                                  BlockPointerTypeLoc TL) {
3190  QualType PointeeType
3191    = getDerived().TransformType(TLB, TL.getPointeeLoc());
3192  if (PointeeType.isNull())
3193    return QualType();
3194
3195  QualType Result = TL.getType();
3196  if (getDerived().AlwaysRebuild() ||
3197      PointeeType != TL.getPointeeLoc().getType()) {
3198    Result = getDerived().RebuildBlockPointerType(PointeeType,
3199                                                  TL.getSigilLoc());
3200    if (Result.isNull())
3201      return QualType();
3202  }
3203
3204  BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
3205  NewT.setSigilLoc(TL.getSigilLoc());
3206  return Result;
3207}
3208
3209/// Transforms a reference type.  Note that somewhat paradoxically we
3210/// don't care whether the type itself is an l-value type or an r-value
3211/// type;  we only care if the type was *written* as an l-value type
3212/// or an r-value type.
3213template<typename Derived>
3214QualType
3215TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
3216                                               ReferenceTypeLoc TL) {
3217  const ReferenceType *T = TL.getTypePtr();
3218
3219  // Note that this works with the pointee-as-written.
3220  QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
3221  if (PointeeType.isNull())
3222    return QualType();
3223
3224  QualType Result = TL.getType();
3225  if (getDerived().AlwaysRebuild() ||
3226      PointeeType != T->getPointeeTypeAsWritten()) {
3227    Result = getDerived().RebuildReferenceType(PointeeType,
3228                                               T->isSpelledAsLValue(),
3229                                               TL.getSigilLoc());
3230    if (Result.isNull())
3231      return QualType();
3232  }
3233
3234  // r-value references can be rebuilt as l-value references.
3235  ReferenceTypeLoc NewTL;
3236  if (isa<LValueReferenceType>(Result))
3237    NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
3238  else
3239    NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
3240  NewTL.setSigilLoc(TL.getSigilLoc());
3241
3242  return Result;
3243}
3244
3245template<typename Derived>
3246QualType
3247TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
3248                                                 LValueReferenceTypeLoc TL) {
3249  return TransformReferenceType(TLB, TL);
3250}
3251
3252template<typename Derived>
3253QualType
3254TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
3255                                                 RValueReferenceTypeLoc TL) {
3256  return TransformReferenceType(TLB, TL);
3257}
3258
3259template<typename Derived>
3260QualType
3261TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
3262                                                   MemberPointerTypeLoc TL) {
3263  const MemberPointerType *T = TL.getTypePtr();
3264
3265  QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
3266  if (PointeeType.isNull())
3267    return QualType();
3268
3269  // TODO: preserve source information for this.
3270  QualType ClassType
3271    = getDerived().TransformType(QualType(T->getClass(), 0));
3272  if (ClassType.isNull())
3273    return QualType();
3274
3275  QualType Result = TL.getType();
3276  if (getDerived().AlwaysRebuild() ||
3277      PointeeType != T->getPointeeType() ||
3278      ClassType != QualType(T->getClass(), 0)) {
3279    Result = getDerived().RebuildMemberPointerType(PointeeType, ClassType,
3280                                                   TL.getStarLoc());
3281    if (Result.isNull())
3282      return QualType();
3283  }
3284
3285  MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
3286  NewTL.setSigilLoc(TL.getSigilLoc());
3287
3288  return Result;
3289}
3290
3291template<typename Derived>
3292QualType
3293TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
3294                                                   ConstantArrayTypeLoc TL) {
3295  const ConstantArrayType *T = TL.getTypePtr();
3296  QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
3297  if (ElementType.isNull())
3298    return QualType();
3299
3300  QualType Result = TL.getType();
3301  if (getDerived().AlwaysRebuild() ||
3302      ElementType != T->getElementType()) {
3303    Result = getDerived().RebuildConstantArrayType(ElementType,
3304                                                   T->getSizeModifier(),
3305                                                   T->getSize(),
3306                                             T->getIndexTypeCVRQualifiers(),
3307                                                   TL.getBracketsRange());
3308    if (Result.isNull())
3309      return QualType();
3310  }
3311
3312  ConstantArrayTypeLoc NewTL = TLB.push<ConstantArrayTypeLoc>(Result);
3313  NewTL.setLBracketLoc(TL.getLBracketLoc());
3314  NewTL.setRBracketLoc(TL.getRBracketLoc());
3315
3316  Expr *Size = TL.getSizeExpr();
3317  if (Size) {
3318    EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3319    Size = getDerived().TransformExpr(Size).template takeAs<Expr>();
3320  }
3321  NewTL.setSizeExpr(Size);
3322
3323  return Result;
3324}
3325
3326template<typename Derived>
3327QualType TreeTransform<Derived>::TransformIncompleteArrayType(
3328                                              TypeLocBuilder &TLB,
3329                                              IncompleteArrayTypeLoc TL) {
3330  const IncompleteArrayType *T = TL.getTypePtr();
3331  QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
3332  if (ElementType.isNull())
3333    return QualType();
3334
3335  QualType Result = TL.getType();
3336  if (getDerived().AlwaysRebuild() ||
3337      ElementType != T->getElementType()) {
3338    Result = getDerived().RebuildIncompleteArrayType(ElementType,
3339                                                     T->getSizeModifier(),
3340                                           T->getIndexTypeCVRQualifiers(),
3341                                                     TL.getBracketsRange());
3342    if (Result.isNull())
3343      return QualType();
3344  }
3345
3346  IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
3347  NewTL.setLBracketLoc(TL.getLBracketLoc());
3348  NewTL.setRBracketLoc(TL.getRBracketLoc());
3349  NewTL.setSizeExpr(0);
3350
3351  return Result;
3352}
3353
3354template<typename Derived>
3355QualType
3356TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
3357                                                   VariableArrayTypeLoc TL) {
3358  const VariableArrayType *T = TL.getTypePtr();
3359  QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
3360  if (ElementType.isNull())
3361    return QualType();
3362
3363  // Array bounds are not potentially evaluated contexts
3364  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3365
3366  ExprResult SizeResult
3367    = getDerived().TransformExpr(T->getSizeExpr());
3368  if (SizeResult.isInvalid())
3369    return QualType();
3370
3371  Expr *Size = SizeResult.take();
3372
3373  QualType Result = TL.getType();
3374  if (getDerived().AlwaysRebuild() ||
3375      ElementType != T->getElementType() ||
3376      Size != T->getSizeExpr()) {
3377    Result = getDerived().RebuildVariableArrayType(ElementType,
3378                                                   T->getSizeModifier(),
3379                                                   Size,
3380                                             T->getIndexTypeCVRQualifiers(),
3381                                                   TL.getBracketsRange());
3382    if (Result.isNull())
3383      return QualType();
3384  }
3385
3386  VariableArrayTypeLoc NewTL = TLB.push<VariableArrayTypeLoc>(Result);
3387  NewTL.setLBracketLoc(TL.getLBracketLoc());
3388  NewTL.setRBracketLoc(TL.getRBracketLoc());
3389  NewTL.setSizeExpr(Size);
3390
3391  return Result;
3392}
3393
3394template<typename Derived>
3395QualType
3396TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
3397                                             DependentSizedArrayTypeLoc TL) {
3398  const DependentSizedArrayType *T = TL.getTypePtr();
3399  QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
3400  if (ElementType.isNull())
3401    return QualType();
3402
3403  // Array bounds are not potentially evaluated contexts
3404  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3405
3406  // Prefer the expression from the TypeLoc;  the other may have been uniqued.
3407  Expr *origSize = TL.getSizeExpr();
3408  if (!origSize) origSize = T->getSizeExpr();
3409
3410  ExprResult sizeResult
3411    = getDerived().TransformExpr(origSize);
3412  if (sizeResult.isInvalid())
3413    return QualType();
3414
3415  Expr *size = sizeResult.get();
3416
3417  QualType Result = TL.getType();
3418  if (getDerived().AlwaysRebuild() ||
3419      ElementType != T->getElementType() ||
3420      size != origSize) {
3421    Result = getDerived().RebuildDependentSizedArrayType(ElementType,
3422                                                         T->getSizeModifier(),
3423                                                         size,
3424                                                T->getIndexTypeCVRQualifiers(),
3425                                                        TL.getBracketsRange());
3426    if (Result.isNull())
3427      return QualType();
3428  }
3429
3430  // We might have any sort of array type now, but fortunately they
3431  // all have the same location layout.
3432  ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
3433  NewTL.setLBracketLoc(TL.getLBracketLoc());
3434  NewTL.setRBracketLoc(TL.getRBracketLoc());
3435  NewTL.setSizeExpr(size);
3436
3437  return Result;
3438}
3439
3440template<typename Derived>
3441QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
3442                                      TypeLocBuilder &TLB,
3443                                      DependentSizedExtVectorTypeLoc TL) {
3444  const DependentSizedExtVectorType *T = TL.getTypePtr();
3445
3446  // FIXME: ext vector locs should be nested
3447  QualType ElementType = getDerived().TransformType(T->getElementType());
3448  if (ElementType.isNull())
3449    return QualType();
3450
3451  // Vector sizes are not potentially evaluated contexts
3452  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3453
3454  ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
3455  if (Size.isInvalid())
3456    return QualType();
3457
3458  QualType Result = TL.getType();
3459  if (getDerived().AlwaysRebuild() ||
3460      ElementType != T->getElementType() ||
3461      Size.get() != T->getSizeExpr()) {
3462    Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
3463                                                             Size.take(),
3464                                                         T->getAttributeLoc());
3465    if (Result.isNull())
3466      return QualType();
3467  }
3468
3469  // Result might be dependent or not.
3470  if (isa<DependentSizedExtVectorType>(Result)) {
3471    DependentSizedExtVectorTypeLoc NewTL
3472      = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
3473    NewTL.setNameLoc(TL.getNameLoc());
3474  } else {
3475    ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
3476    NewTL.setNameLoc(TL.getNameLoc());
3477  }
3478
3479  return Result;
3480}
3481
3482template<typename Derived>
3483QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
3484                                                     VectorTypeLoc TL) {
3485  const VectorType *T = TL.getTypePtr();
3486  QualType ElementType = getDerived().TransformType(T->getElementType());
3487  if (ElementType.isNull())
3488    return QualType();
3489
3490  QualType Result = TL.getType();
3491  if (getDerived().AlwaysRebuild() ||
3492      ElementType != T->getElementType()) {
3493    Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
3494                                            T->getVectorKind());
3495    if (Result.isNull())
3496      return QualType();
3497  }
3498
3499  VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
3500  NewTL.setNameLoc(TL.getNameLoc());
3501
3502  return Result;
3503}
3504
3505template<typename Derived>
3506QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
3507                                                        ExtVectorTypeLoc TL) {
3508  const VectorType *T = TL.getTypePtr();
3509  QualType ElementType = getDerived().TransformType(T->getElementType());
3510  if (ElementType.isNull())
3511    return QualType();
3512
3513  QualType Result = TL.getType();
3514  if (getDerived().AlwaysRebuild() ||
3515      ElementType != T->getElementType()) {
3516    Result = getDerived().RebuildExtVectorType(ElementType,
3517                                               T->getNumElements(),
3518                                               /*FIXME*/ SourceLocation());
3519    if (Result.isNull())
3520      return QualType();
3521  }
3522
3523  ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
3524  NewTL.setNameLoc(TL.getNameLoc());
3525
3526  return Result;
3527}
3528
3529template<typename Derived>
3530ParmVarDecl *
3531TreeTransform<Derived>::TransformFunctionTypeParam(ParmVarDecl *OldParm,
3532                                       llvm::Optional<unsigned> NumExpansions) {
3533  TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3534  TypeSourceInfo *NewDI = 0;
3535
3536  if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
3537    // If we're substituting into a pack expansion type and we know the
3538    TypeLoc OldTL = OldDI->getTypeLoc();
3539    PackExpansionTypeLoc OldExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
3540
3541    TypeLocBuilder TLB;
3542    TypeLoc NewTL = OldDI->getTypeLoc();
3543    TLB.reserve(NewTL.getFullDataSize());
3544
3545    QualType Result = getDerived().TransformType(TLB,
3546                                               OldExpansionTL.getPatternLoc());
3547    if (Result.isNull())
3548      return 0;
3549
3550    Result = RebuildPackExpansionType(Result,
3551                                OldExpansionTL.getPatternLoc().getSourceRange(),
3552                                      OldExpansionTL.getEllipsisLoc(),
3553                                      NumExpansions);
3554    if (Result.isNull())
3555      return 0;
3556
3557    PackExpansionTypeLoc NewExpansionTL
3558      = TLB.push<PackExpansionTypeLoc>(Result);
3559    NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
3560    NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
3561  } else
3562    NewDI = getDerived().TransformType(OldDI);
3563  if (!NewDI)
3564    return 0;
3565
3566  if (NewDI == OldDI)
3567    return OldParm;
3568  else
3569    return ParmVarDecl::Create(SemaRef.Context,
3570                               OldParm->getDeclContext(),
3571                               OldParm->getLocation(),
3572                               OldParm->getIdentifier(),
3573                               NewDI->getType(),
3574                               NewDI,
3575                               OldParm->getStorageClass(),
3576                               OldParm->getStorageClassAsWritten(),
3577                               /* DefArg */ NULL);
3578}
3579
3580template<typename Derived>
3581bool TreeTransform<Derived>::
3582  TransformFunctionTypeParams(SourceLocation Loc,
3583                              ParmVarDecl **Params, unsigned NumParams,
3584                              const QualType *ParamTypes,
3585                              llvm::SmallVectorImpl<QualType> &OutParamTypes,
3586                              llvm::SmallVectorImpl<ParmVarDecl*> *PVars) {
3587  for (unsigned i = 0; i != NumParams; ++i) {
3588    if (ParmVarDecl *OldParm = Params[i]) {
3589      llvm::Optional<unsigned> NumExpansions;
3590      if (OldParm->isParameterPack()) {
3591        // We have a function parameter pack that may need to be expanded.
3592        llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3593
3594        // Find the parameter packs that could be expanded.
3595        TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
3596        PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(TL);
3597        TypeLoc Pattern = ExpansionTL.getPatternLoc();
3598        SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
3599
3600        // Determine whether we should expand the parameter packs.
3601        bool ShouldExpand = false;
3602        bool RetainExpansion = false;
3603        llvm::Optional<unsigned> OrigNumExpansions
3604          = ExpansionTL.getTypePtr()->getNumExpansions();
3605        NumExpansions = OrigNumExpansions;
3606        if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
3607                                                 Pattern.getSourceRange(),
3608                                                 Unexpanded.data(),
3609                                                 Unexpanded.size(),
3610                                                 ShouldExpand,
3611                                                 RetainExpansion,
3612                                                 NumExpansions)) {
3613          return true;
3614        }
3615
3616        if (ShouldExpand) {
3617          // Expand the function parameter pack into multiple, separate
3618          // parameters.
3619          getDerived().ExpandingFunctionParameterPack(OldParm);
3620          for (unsigned I = 0; I != *NumExpansions; ++I) {
3621            Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3622            ParmVarDecl *NewParm
3623              = getDerived().TransformFunctionTypeParam(OldParm,
3624                                                        OrigNumExpansions);
3625            if (!NewParm)
3626              return true;
3627
3628            OutParamTypes.push_back(NewParm->getType());
3629            if (PVars)
3630              PVars->push_back(NewParm);
3631          }
3632
3633          // If we're supposed to retain a pack expansion, do so by temporarily
3634          // forgetting the partially-substituted parameter pack.
3635          if (RetainExpansion) {
3636            ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3637            ParmVarDecl *NewParm
3638              = getDerived().TransformFunctionTypeParam(OldParm,
3639                                                        OrigNumExpansions);
3640            if (!NewParm)
3641              return true;
3642
3643            OutParamTypes.push_back(NewParm->getType());
3644            if (PVars)
3645              PVars->push_back(NewParm);
3646          }
3647
3648          // We're done with the pack expansion.
3649          continue;
3650        }
3651
3652        // We'll substitute the parameter now without expanding the pack
3653        // expansion.
3654      }
3655
3656      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3657      ParmVarDecl *NewParm = getDerived().TransformFunctionTypeParam(OldParm,
3658                                                                 NumExpansions);
3659      if (!NewParm)
3660        return true;
3661
3662      OutParamTypes.push_back(NewParm->getType());
3663      if (PVars)
3664        PVars->push_back(NewParm);
3665      continue;
3666    }
3667
3668    // Deal with the possibility that we don't have a parameter
3669    // declaration for this parameter.
3670    QualType OldType = ParamTypes[i];
3671    bool IsPackExpansion = false;
3672    llvm::Optional<unsigned> NumExpansions;
3673    if (const PackExpansionType *Expansion
3674                                       = dyn_cast<PackExpansionType>(OldType)) {
3675      // We have a function parameter pack that may need to be expanded.
3676      QualType Pattern = Expansion->getPattern();
3677      llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3678      getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3679
3680      // Determine whether we should expand the parameter packs.
3681      bool ShouldExpand = false;
3682      bool RetainExpansion = false;
3683      if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
3684                                               Unexpanded.data(),
3685                                               Unexpanded.size(),
3686                                               ShouldExpand,
3687                                               RetainExpansion,
3688                                               NumExpansions)) {
3689        return true;
3690      }
3691
3692      if (ShouldExpand) {
3693        // Expand the function parameter pack into multiple, separate
3694        // parameters.
3695        for (unsigned I = 0; I != *NumExpansions; ++I) {
3696          Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3697          QualType NewType = getDerived().TransformType(Pattern);
3698          if (NewType.isNull())
3699            return true;
3700
3701          OutParamTypes.push_back(NewType);
3702          if (PVars)
3703            PVars->push_back(0);
3704        }
3705
3706        // We're done with the pack expansion.
3707        continue;
3708      }
3709
3710      // If we're supposed to retain a pack expansion, do so by temporarily
3711      // forgetting the partially-substituted parameter pack.
3712      if (RetainExpansion) {
3713        ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3714        QualType NewType = getDerived().TransformType(Pattern);
3715        if (NewType.isNull())
3716          return true;
3717
3718        OutParamTypes.push_back(NewType);
3719        if (PVars)
3720          PVars->push_back(0);
3721      }
3722
3723      // We'll substitute the parameter now without expanding the pack
3724      // expansion.
3725      OldType = Expansion->getPattern();
3726      IsPackExpansion = true;
3727    }
3728
3729    Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3730    QualType NewType = getDerived().TransformType(OldType);
3731    if (NewType.isNull())
3732      return true;
3733
3734    if (IsPackExpansion)
3735      NewType = getSema().Context.getPackExpansionType(NewType,
3736                                                       NumExpansions);
3737
3738    OutParamTypes.push_back(NewType);
3739    if (PVars)
3740      PVars->push_back(0);
3741  }
3742
3743  return false;
3744  }
3745
3746template<typename Derived>
3747QualType
3748TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
3749                                                   FunctionProtoTypeLoc TL) {
3750  // Transform the parameters and return type.
3751  //
3752  // We instantiate in source order, with the return type first followed by
3753  // the parameters, because users tend to expect this (even if they shouldn't
3754  // rely on it!).
3755  //
3756  // When the function has a trailing return type, we instantiate the
3757  // parameters before the return type,  since the return type can then refer
3758  // to the parameters themselves (via decltype, sizeof, etc.).
3759  //
3760  llvm::SmallVector<QualType, 4> ParamTypes;
3761  llvm::SmallVector<ParmVarDecl*, 4> ParamDecls;
3762  const FunctionProtoType *T = TL.getTypePtr();
3763
3764  QualType ResultType;
3765
3766  if (TL.getTrailingReturn()) {
3767    if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
3768                                                 TL.getParmArray(),
3769                                                 TL.getNumArgs(),
3770                                             TL.getTypePtr()->arg_type_begin(),
3771                                                 ParamTypes, &ParamDecls))
3772      return QualType();
3773
3774    ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
3775    if (ResultType.isNull())
3776      return QualType();
3777  }
3778  else {
3779    ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
3780    if (ResultType.isNull())
3781      return QualType();
3782
3783    if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
3784                                                 TL.getParmArray(),
3785                                                 TL.getNumArgs(),
3786                                             TL.getTypePtr()->arg_type_begin(),
3787                                                 ParamTypes, &ParamDecls))
3788      return QualType();
3789  }
3790
3791  QualType Result = TL.getType();
3792  if (getDerived().AlwaysRebuild() ||
3793      ResultType != T->getResultType() ||
3794      T->getNumArgs() != ParamTypes.size() ||
3795      !std::equal(T->arg_type_begin(), T->arg_type_end(), ParamTypes.begin())) {
3796    Result = getDerived().RebuildFunctionProtoType(ResultType,
3797                                                   ParamTypes.data(),
3798                                                   ParamTypes.size(),
3799                                                   T->isVariadic(),
3800                                                   T->getTypeQuals(),
3801                                                   T->getRefQualifier(),
3802                                                   T->getExtInfo());
3803    if (Result.isNull())
3804      return QualType();
3805  }
3806
3807  FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
3808  NewTL.setLParenLoc(TL.getLParenLoc());
3809  NewTL.setRParenLoc(TL.getRParenLoc());
3810  NewTL.setTrailingReturn(TL.getTrailingReturn());
3811  for (unsigned i = 0, e = NewTL.getNumArgs(); i != e; ++i)
3812    NewTL.setArg(i, ParamDecls[i]);
3813
3814  return Result;
3815}
3816
3817template<typename Derived>
3818QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
3819                                                 TypeLocBuilder &TLB,
3820                                                 FunctionNoProtoTypeLoc TL) {
3821  const FunctionNoProtoType *T = TL.getTypePtr();
3822  QualType ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
3823  if (ResultType.isNull())
3824    return QualType();
3825
3826  QualType Result = TL.getType();
3827  if (getDerived().AlwaysRebuild() ||
3828      ResultType != T->getResultType())
3829    Result = getDerived().RebuildFunctionNoProtoType(ResultType);
3830
3831  FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
3832  NewTL.setLParenLoc(TL.getLParenLoc());
3833  NewTL.setRParenLoc(TL.getRParenLoc());
3834  NewTL.setTrailingReturn(false);
3835
3836  return Result;
3837}
3838
3839template<typename Derived> QualType
3840TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
3841                                                 UnresolvedUsingTypeLoc TL) {
3842  const UnresolvedUsingType *T = TL.getTypePtr();
3843  Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
3844  if (!D)
3845    return QualType();
3846
3847  QualType Result = TL.getType();
3848  if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
3849    Result = getDerived().RebuildUnresolvedUsingType(D);
3850    if (Result.isNull())
3851      return QualType();
3852  }
3853
3854  // We might get an arbitrary type spec type back.  We should at
3855  // least always get a type spec type, though.
3856  TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
3857  NewTL.setNameLoc(TL.getNameLoc());
3858
3859  return Result;
3860}
3861
3862template<typename Derived>
3863QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
3864                                                      TypedefTypeLoc TL) {
3865  const TypedefType *T = TL.getTypePtr();
3866  TypedefDecl *Typedef
3867    = cast_or_null<TypedefDecl>(getDerived().TransformDecl(TL.getNameLoc(),
3868                                                           T->getDecl()));
3869  if (!Typedef)
3870    return QualType();
3871
3872  QualType Result = TL.getType();
3873  if (getDerived().AlwaysRebuild() ||
3874      Typedef != T->getDecl()) {
3875    Result = getDerived().RebuildTypedefType(Typedef);
3876    if (Result.isNull())
3877      return QualType();
3878  }
3879
3880  TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
3881  NewTL.setNameLoc(TL.getNameLoc());
3882
3883  return Result;
3884}
3885
3886template<typename Derived>
3887QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
3888                                                      TypeOfExprTypeLoc TL) {
3889  // typeof expressions are not potentially evaluated contexts
3890  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3891
3892  ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
3893  if (E.isInvalid())
3894    return QualType();
3895
3896  QualType Result = TL.getType();
3897  if (getDerived().AlwaysRebuild() ||
3898      E.get() != TL.getUnderlyingExpr()) {
3899    Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
3900    if (Result.isNull())
3901      return QualType();
3902  }
3903  else E.take();
3904
3905  TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
3906  NewTL.setTypeofLoc(TL.getTypeofLoc());
3907  NewTL.setLParenLoc(TL.getLParenLoc());
3908  NewTL.setRParenLoc(TL.getRParenLoc());
3909
3910  return Result;
3911}
3912
3913template<typename Derived>
3914QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
3915                                                     TypeOfTypeLoc TL) {
3916  TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
3917  TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
3918  if (!New_Under_TI)
3919    return QualType();
3920
3921  QualType Result = TL.getType();
3922  if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
3923    Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
3924    if (Result.isNull())
3925      return QualType();
3926  }
3927
3928  TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
3929  NewTL.setTypeofLoc(TL.getTypeofLoc());
3930  NewTL.setLParenLoc(TL.getLParenLoc());
3931  NewTL.setRParenLoc(TL.getRParenLoc());
3932  NewTL.setUnderlyingTInfo(New_Under_TI);
3933
3934  return Result;
3935}
3936
3937template<typename Derived>
3938QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
3939                                                       DecltypeTypeLoc TL) {
3940  const DecltypeType *T = TL.getTypePtr();
3941
3942  // decltype expressions are not potentially evaluated contexts
3943  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3944
3945  ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
3946  if (E.isInvalid())
3947    return QualType();
3948
3949  QualType Result = TL.getType();
3950  if (getDerived().AlwaysRebuild() ||
3951      E.get() != T->getUnderlyingExpr()) {
3952    Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
3953    if (Result.isNull())
3954      return QualType();
3955  }
3956  else E.take();
3957
3958  DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
3959  NewTL.setNameLoc(TL.getNameLoc());
3960
3961  return Result;
3962}
3963
3964template<typename Derived>
3965QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
3966                                                     RecordTypeLoc TL) {
3967  const RecordType *T = TL.getTypePtr();
3968  RecordDecl *Record
3969    = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
3970                                                          T->getDecl()));
3971  if (!Record)
3972    return QualType();
3973
3974  QualType Result = TL.getType();
3975  if (getDerived().AlwaysRebuild() ||
3976      Record != T->getDecl()) {
3977    Result = getDerived().RebuildRecordType(Record);
3978    if (Result.isNull())
3979      return QualType();
3980  }
3981
3982  RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
3983  NewTL.setNameLoc(TL.getNameLoc());
3984
3985  return Result;
3986}
3987
3988template<typename Derived>
3989QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
3990                                                   EnumTypeLoc TL) {
3991  const EnumType *T = TL.getTypePtr();
3992  EnumDecl *Enum
3993    = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
3994                                                        T->getDecl()));
3995  if (!Enum)
3996    return QualType();
3997
3998  QualType Result = TL.getType();
3999  if (getDerived().AlwaysRebuild() ||
4000      Enum != T->getDecl()) {
4001    Result = getDerived().RebuildEnumType(Enum);
4002    if (Result.isNull())
4003      return QualType();
4004  }
4005
4006  EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
4007  NewTL.setNameLoc(TL.getNameLoc());
4008
4009  return Result;
4010}
4011
4012template<typename Derived>
4013QualType TreeTransform<Derived>::TransformInjectedClassNameType(
4014                                         TypeLocBuilder &TLB,
4015                                         InjectedClassNameTypeLoc TL) {
4016  Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
4017                                       TL.getTypePtr()->getDecl());
4018  if (!D) return QualType();
4019
4020  QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
4021  TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
4022  return T;
4023}
4024
4025template<typename Derived>
4026QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
4027                                                TypeLocBuilder &TLB,
4028                                                TemplateTypeParmTypeLoc TL) {
4029  return TransformTypeSpecType(TLB, TL);
4030}
4031
4032template<typename Derived>
4033QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
4034                                         TypeLocBuilder &TLB,
4035                                         SubstTemplateTypeParmTypeLoc TL) {
4036  return TransformTypeSpecType(TLB, TL);
4037}
4038
4039template<typename Derived>
4040QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
4041                                          TypeLocBuilder &TLB,
4042                                          SubstTemplateTypeParmPackTypeLoc TL) {
4043  return TransformTypeSpecType(TLB, TL);
4044}
4045
4046template<typename Derived>
4047QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
4048                                                        TypeLocBuilder &TLB,
4049                                           TemplateSpecializationTypeLoc TL) {
4050  const TemplateSpecializationType *T = TL.getTypePtr();
4051
4052  TemplateName Template
4053    = getDerived().TransformTemplateName(T->getTemplateName());
4054  if (Template.isNull())
4055    return QualType();
4056
4057  return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
4058}
4059
4060namespace {
4061  /// \brief Simple iterator that traverses the template arguments in a
4062  /// container that provides a \c getArgLoc() member function.
4063  ///
4064  /// This iterator is intended to be used with the iterator form of
4065  /// \c TreeTransform<Derived>::TransformTemplateArguments().
4066  template<typename ArgLocContainer>
4067  class TemplateArgumentLocContainerIterator {
4068    ArgLocContainer *Container;
4069    unsigned Index;
4070
4071  public:
4072    typedef TemplateArgumentLoc value_type;
4073    typedef TemplateArgumentLoc reference;
4074    typedef int difference_type;
4075    typedef std::input_iterator_tag iterator_category;
4076
4077    class pointer {
4078      TemplateArgumentLoc Arg;
4079
4080    public:
4081      explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4082
4083      const TemplateArgumentLoc *operator->() const {
4084        return &Arg;
4085      }
4086    };
4087
4088
4089    TemplateArgumentLocContainerIterator() {}
4090
4091    TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
4092                                 unsigned Index)
4093      : Container(&Container), Index(Index) { }
4094
4095    TemplateArgumentLocContainerIterator &operator++() {
4096      ++Index;
4097      return *this;
4098    }
4099
4100    TemplateArgumentLocContainerIterator operator++(int) {
4101      TemplateArgumentLocContainerIterator Old(*this);
4102      ++(*this);
4103      return Old;
4104    }
4105
4106    TemplateArgumentLoc operator*() const {
4107      return Container->getArgLoc(Index);
4108    }
4109
4110    pointer operator->() const {
4111      return pointer(Container->getArgLoc(Index));
4112    }
4113
4114    friend bool operator==(const TemplateArgumentLocContainerIterator &X,
4115                           const TemplateArgumentLocContainerIterator &Y) {
4116      return X.Container == Y.Container && X.Index == Y.Index;
4117    }
4118
4119    friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
4120                           const TemplateArgumentLocContainerIterator &Y) {
4121      return !(X == Y);
4122    }
4123  };
4124}
4125
4126
4127template <typename Derived>
4128QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
4129                                                        TypeLocBuilder &TLB,
4130                                           TemplateSpecializationTypeLoc TL,
4131                                                      TemplateName Template) {
4132  TemplateArgumentListInfo NewTemplateArgs;
4133  NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
4134  NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
4135  typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
4136    ArgIterator;
4137  if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
4138                                              ArgIterator(TL, TL.getNumArgs()),
4139                                              NewTemplateArgs))
4140    return QualType();
4141
4142  // FIXME: maybe don't rebuild if all the template arguments are the same.
4143
4144  QualType Result =
4145    getDerived().RebuildTemplateSpecializationType(Template,
4146                                                   TL.getTemplateNameLoc(),
4147                                                   NewTemplateArgs);
4148
4149  if (!Result.isNull()) {
4150    TemplateSpecializationTypeLoc NewTL
4151      = TLB.push<TemplateSpecializationTypeLoc>(Result);
4152    NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
4153    NewTL.setLAngleLoc(TL.getLAngleLoc());
4154    NewTL.setRAngleLoc(TL.getRAngleLoc());
4155    for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
4156      NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
4157  }
4158
4159  return Result;
4160}
4161
4162template<typename Derived>
4163QualType
4164TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
4165                                                ElaboratedTypeLoc TL) {
4166  const ElaboratedType *T = TL.getTypePtr();
4167
4168  NestedNameSpecifier *NNS = 0;
4169  // NOTE: the qualifier in an ElaboratedType is optional.
4170  if (T->getQualifier() != 0) {
4171    NNS = getDerived().TransformNestedNameSpecifier(T->getQualifier(),
4172                                                    TL.getQualifierRange());
4173    if (!NNS)
4174      return QualType();
4175  }
4176
4177  QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
4178  if (NamedT.isNull())
4179    return QualType();
4180
4181  QualType Result = TL.getType();
4182  if (getDerived().AlwaysRebuild() ||
4183      NNS != T->getQualifier() ||
4184      NamedT != T->getNamedType()) {
4185    Result = getDerived().RebuildElaboratedType(TL.getKeywordLoc(),
4186                                                T->getKeyword(), NNS, NamedT);
4187    if (Result.isNull())
4188      return QualType();
4189  }
4190
4191  ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
4192  NewTL.setKeywordLoc(TL.getKeywordLoc());
4193  NewTL.setQualifierRange(TL.getQualifierRange());
4194
4195  return Result;
4196}
4197
4198template<typename Derived>
4199QualType TreeTransform<Derived>::TransformAttributedType(
4200                                                TypeLocBuilder &TLB,
4201                                                AttributedTypeLoc TL) {
4202  const AttributedType *oldType = TL.getTypePtr();
4203  QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
4204  if (modifiedType.isNull())
4205    return QualType();
4206
4207  QualType result = TL.getType();
4208
4209  // FIXME: dependent operand expressions?
4210  if (getDerived().AlwaysRebuild() ||
4211      modifiedType != oldType->getModifiedType()) {
4212    // TODO: this is really lame; we should really be rebuilding the
4213    // equivalent type from first principles.
4214    QualType equivalentType
4215      = getDerived().TransformType(oldType->getEquivalentType());
4216    if (equivalentType.isNull())
4217      return QualType();
4218    result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
4219                                               modifiedType,
4220                                               equivalentType);
4221  }
4222
4223  AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
4224  newTL.setAttrNameLoc(TL.getAttrNameLoc());
4225  if (TL.hasAttrOperand())
4226    newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
4227  if (TL.hasAttrExprOperand())
4228    newTL.setAttrExprOperand(TL.getAttrExprOperand());
4229  else if (TL.hasAttrEnumOperand())
4230    newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
4231
4232  return result;
4233}
4234
4235template<typename Derived>
4236QualType
4237TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
4238                                           ParenTypeLoc TL) {
4239  QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
4240  if (Inner.isNull())
4241    return QualType();
4242
4243  QualType Result = TL.getType();
4244  if (getDerived().AlwaysRebuild() ||
4245      Inner != TL.getInnerLoc().getType()) {
4246    Result = getDerived().RebuildParenType(Inner);
4247    if (Result.isNull())
4248      return QualType();
4249  }
4250
4251  ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
4252  NewTL.setLParenLoc(TL.getLParenLoc());
4253  NewTL.setRParenLoc(TL.getRParenLoc());
4254  return Result;
4255}
4256
4257template<typename Derived>
4258QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
4259                                                      DependentNameTypeLoc TL) {
4260  const DependentNameType *T = TL.getTypePtr();
4261
4262  NestedNameSpecifier *NNS
4263    = getDerived().TransformNestedNameSpecifier(T->getQualifier(),
4264                                                TL.getQualifierRange());
4265  if (!NNS)
4266    return QualType();
4267
4268  QualType Result
4269    = getDerived().RebuildDependentNameType(T->getKeyword(), NNS,
4270                                            T->getIdentifier(),
4271                                            TL.getKeywordLoc(),
4272                                            TL.getQualifierRange(),
4273                                            TL.getNameLoc());
4274  if (Result.isNull())
4275    return QualType();
4276
4277  if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
4278    QualType NamedT = ElabT->getNamedType();
4279    TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
4280
4281    ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
4282    NewTL.setKeywordLoc(TL.getKeywordLoc());
4283    NewTL.setQualifierRange(TL.getQualifierRange());
4284  } else {
4285    DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
4286    NewTL.setKeywordLoc(TL.getKeywordLoc());
4287    NewTL.setQualifierRange(TL.getQualifierRange());
4288    NewTL.setNameLoc(TL.getNameLoc());
4289  }
4290  return Result;
4291}
4292
4293template<typename Derived>
4294QualType TreeTransform<Derived>::
4295          TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
4296                                 DependentTemplateSpecializationTypeLoc TL) {
4297  const DependentTemplateSpecializationType *T = TL.getTypePtr();
4298
4299  NestedNameSpecifier *NNS
4300    = getDerived().TransformNestedNameSpecifier(T->getQualifier(),
4301                                                TL.getQualifierRange());
4302  if (!NNS)
4303    return QualType();
4304
4305  return getDerived()
4306           .TransformDependentTemplateSpecializationType(TLB, TL, NNS);
4307}
4308
4309template<typename Derived>
4310QualType TreeTransform<Derived>::
4311          TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
4312                                 DependentTemplateSpecializationTypeLoc TL,
4313                                                  NestedNameSpecifier *NNS) {
4314  const DependentTemplateSpecializationType *T = TL.getTypePtr();
4315
4316  TemplateArgumentListInfo NewTemplateArgs;
4317  NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
4318  NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
4319
4320  typedef TemplateArgumentLocContainerIterator<
4321                            DependentTemplateSpecializationTypeLoc> ArgIterator;
4322  if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
4323                                              ArgIterator(TL, TL.getNumArgs()),
4324                                              NewTemplateArgs))
4325    return QualType();
4326
4327  QualType Result
4328    = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
4329                                                              NNS,
4330                                                        TL.getQualifierRange(),
4331                                                            T->getIdentifier(),
4332                                                              TL.getNameLoc(),
4333                                                              NewTemplateArgs);
4334  if (Result.isNull())
4335    return QualType();
4336
4337  if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
4338    QualType NamedT = ElabT->getNamedType();
4339
4340    // Copy information relevant to the template specialization.
4341    TemplateSpecializationTypeLoc NamedTL
4342      = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
4343    NamedTL.setLAngleLoc(TL.getLAngleLoc());
4344    NamedTL.setRAngleLoc(TL.getRAngleLoc());
4345    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
4346      NamedTL.setArgLocInfo(I, TL.getArgLocInfo(I));
4347
4348    // Copy information relevant to the elaborated type.
4349    ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
4350    NewTL.setKeywordLoc(TL.getKeywordLoc());
4351    NewTL.setQualifierRange(TL.getQualifierRange());
4352  } else {
4353    TypeLoc NewTL(Result, TL.getOpaqueData());
4354    TLB.pushFullCopy(NewTL);
4355  }
4356  return Result;
4357}
4358
4359template<typename Derived>
4360QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
4361                                                      PackExpansionTypeLoc TL) {
4362  QualType Pattern
4363    = getDerived().TransformType(TLB, TL.getPatternLoc());
4364  if (Pattern.isNull())
4365    return QualType();
4366
4367  QualType Result = TL.getType();
4368  if (getDerived().AlwaysRebuild() ||
4369      Pattern != TL.getPatternLoc().getType()) {
4370    Result = getDerived().RebuildPackExpansionType(Pattern,
4371                                           TL.getPatternLoc().getSourceRange(),
4372                                                   TL.getEllipsisLoc(),
4373                                           TL.getTypePtr()->getNumExpansions());
4374    if (Result.isNull())
4375      return QualType();
4376  }
4377
4378  PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
4379  NewT.setEllipsisLoc(TL.getEllipsisLoc());
4380  return Result;
4381}
4382
4383template<typename Derived>
4384QualType
4385TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
4386                                                   ObjCInterfaceTypeLoc TL) {
4387  // ObjCInterfaceType is never dependent.
4388  TLB.pushFullCopy(TL);
4389  return TL.getType();
4390}
4391
4392template<typename Derived>
4393QualType
4394TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
4395                                                ObjCObjectTypeLoc TL) {
4396  // ObjCObjectType is never dependent.
4397  TLB.pushFullCopy(TL);
4398  return TL.getType();
4399}
4400
4401template<typename Derived>
4402QualType
4403TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
4404                                               ObjCObjectPointerTypeLoc TL) {
4405  // ObjCObjectPointerType is never dependent.
4406  TLB.pushFullCopy(TL);
4407  return TL.getType();
4408}
4409
4410//===----------------------------------------------------------------------===//
4411// Statement transformation
4412//===----------------------------------------------------------------------===//
4413template<typename Derived>
4414StmtResult
4415TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
4416  return SemaRef.Owned(S);
4417}
4418
4419template<typename Derived>
4420StmtResult
4421TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
4422  return getDerived().TransformCompoundStmt(S, false);
4423}
4424
4425template<typename Derived>
4426StmtResult
4427TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
4428                                              bool IsStmtExpr) {
4429  bool SubStmtInvalid = false;
4430  bool SubStmtChanged = false;
4431  ASTOwningVector<Stmt*> Statements(getSema());
4432  for (CompoundStmt::body_iterator B = S->body_begin(), BEnd = S->body_end();
4433       B != BEnd; ++B) {
4434    StmtResult Result = getDerived().TransformStmt(*B);
4435    if (Result.isInvalid()) {
4436      // Immediately fail if this was a DeclStmt, since it's very
4437      // likely that this will cause problems for future statements.
4438      if (isa<DeclStmt>(*B))
4439        return StmtError();
4440
4441      // Otherwise, just keep processing substatements and fail later.
4442      SubStmtInvalid = true;
4443      continue;
4444    }
4445
4446    SubStmtChanged = SubStmtChanged || Result.get() != *B;
4447    Statements.push_back(Result.takeAs<Stmt>());
4448  }
4449
4450  if (SubStmtInvalid)
4451    return StmtError();
4452
4453  if (!getDerived().AlwaysRebuild() &&
4454      !SubStmtChanged)
4455    return SemaRef.Owned(S);
4456
4457  return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
4458                                          move_arg(Statements),
4459                                          S->getRBracLoc(),
4460                                          IsStmtExpr);
4461}
4462
4463template<typename Derived>
4464StmtResult
4465TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
4466  ExprResult LHS, RHS;
4467  {
4468    // The case value expressions are not potentially evaluated.
4469    EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
4470
4471    // Transform the left-hand case value.
4472    LHS = getDerived().TransformExpr(S->getLHS());
4473    if (LHS.isInvalid())
4474      return StmtError();
4475
4476    // Transform the right-hand case value (for the GNU case-range extension).
4477    RHS = getDerived().TransformExpr(S->getRHS());
4478    if (RHS.isInvalid())
4479      return StmtError();
4480  }
4481
4482  // Build the case statement.
4483  // Case statements are always rebuilt so that they will attached to their
4484  // transformed switch statement.
4485  StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
4486                                                       LHS.get(),
4487                                                       S->getEllipsisLoc(),
4488                                                       RHS.get(),
4489                                                       S->getColonLoc());
4490  if (Case.isInvalid())
4491    return StmtError();
4492
4493  // Transform the statement following the case
4494  StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
4495  if (SubStmt.isInvalid())
4496    return StmtError();
4497
4498  // Attach the body to the case statement
4499  return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
4500}
4501
4502template<typename Derived>
4503StmtResult
4504TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
4505  // Transform the statement following the default case
4506  StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
4507  if (SubStmt.isInvalid())
4508    return StmtError();
4509
4510  // Default statements are always rebuilt
4511  return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
4512                                         SubStmt.get());
4513}
4514
4515template<typename Derived>
4516StmtResult
4517TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
4518  StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
4519  if (SubStmt.isInvalid())
4520    return StmtError();
4521
4522  // FIXME: Pass the real colon location in.
4523  SourceLocation ColonLoc = SemaRef.PP.getLocForEndOfToken(S->getIdentLoc());
4524  return getDerived().RebuildLabelStmt(S->getIdentLoc(), S->getID(), ColonLoc,
4525                                       SubStmt.get(), S->HasUnusedAttribute());
4526}
4527
4528template<typename Derived>
4529StmtResult
4530TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
4531  // Transform the condition
4532  ExprResult Cond;
4533  VarDecl *ConditionVar = 0;
4534  if (S->getConditionVariable()) {
4535    ConditionVar
4536      = cast_or_null<VarDecl>(
4537                   getDerived().TransformDefinition(
4538                                      S->getConditionVariable()->getLocation(),
4539                                                    S->getConditionVariable()));
4540    if (!ConditionVar)
4541      return StmtError();
4542  } else {
4543    Cond = getDerived().TransformExpr(S->getCond());
4544
4545    if (Cond.isInvalid())
4546      return StmtError();
4547
4548    // Convert the condition to a boolean value.
4549    if (S->getCond()) {
4550      ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getIfLoc(),
4551                                                         Cond.get());
4552      if (CondE.isInvalid())
4553        return StmtError();
4554
4555      Cond = CondE.get();
4556    }
4557  }
4558
4559  Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
4560  if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
4561    return StmtError();
4562
4563  // Transform the "then" branch.
4564  StmtResult Then = getDerived().TransformStmt(S->getThen());
4565  if (Then.isInvalid())
4566    return StmtError();
4567
4568  // Transform the "else" branch.
4569  StmtResult Else = getDerived().TransformStmt(S->getElse());
4570  if (Else.isInvalid())
4571    return StmtError();
4572
4573  if (!getDerived().AlwaysRebuild() &&
4574      FullCond.get() == S->getCond() &&
4575      ConditionVar == S->getConditionVariable() &&
4576      Then.get() == S->getThen() &&
4577      Else.get() == S->getElse())
4578    return SemaRef.Owned(S);
4579
4580  return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
4581                                    Then.get(),
4582                                    S->getElseLoc(), Else.get());
4583}
4584
4585template<typename Derived>
4586StmtResult
4587TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
4588  // Transform the condition.
4589  ExprResult Cond;
4590  VarDecl *ConditionVar = 0;
4591  if (S->getConditionVariable()) {
4592    ConditionVar
4593      = cast_or_null<VarDecl>(
4594                   getDerived().TransformDefinition(
4595                                      S->getConditionVariable()->getLocation(),
4596                                                    S->getConditionVariable()));
4597    if (!ConditionVar)
4598      return StmtError();
4599  } else {
4600    Cond = getDerived().TransformExpr(S->getCond());
4601
4602    if (Cond.isInvalid())
4603      return StmtError();
4604  }
4605
4606  // Rebuild the switch statement.
4607  StmtResult Switch
4608    = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
4609                                          ConditionVar);
4610  if (Switch.isInvalid())
4611    return StmtError();
4612
4613  // Transform the body of the switch statement.
4614  StmtResult Body = getDerived().TransformStmt(S->getBody());
4615  if (Body.isInvalid())
4616    return StmtError();
4617
4618  // Complete the switch statement.
4619  return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
4620                                            Body.get());
4621}
4622
4623template<typename Derived>
4624StmtResult
4625TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
4626  // Transform the condition
4627  ExprResult Cond;
4628  VarDecl *ConditionVar = 0;
4629  if (S->getConditionVariable()) {
4630    ConditionVar
4631      = cast_or_null<VarDecl>(
4632                   getDerived().TransformDefinition(
4633                                      S->getConditionVariable()->getLocation(),
4634                                                    S->getConditionVariable()));
4635    if (!ConditionVar)
4636      return StmtError();
4637  } else {
4638    Cond = getDerived().TransformExpr(S->getCond());
4639
4640    if (Cond.isInvalid())
4641      return StmtError();
4642
4643    if (S->getCond()) {
4644      // Convert the condition to a boolean value.
4645      ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getWhileLoc(),
4646                                                         Cond.get());
4647      if (CondE.isInvalid())
4648        return StmtError();
4649      Cond = CondE;
4650    }
4651  }
4652
4653  Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
4654  if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
4655    return StmtError();
4656
4657  // Transform the body
4658  StmtResult Body = getDerived().TransformStmt(S->getBody());
4659  if (Body.isInvalid())
4660    return StmtError();
4661
4662  if (!getDerived().AlwaysRebuild() &&
4663      FullCond.get() == S->getCond() &&
4664      ConditionVar == S->getConditionVariable() &&
4665      Body.get() == S->getBody())
4666    return Owned(S);
4667
4668  return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
4669                                       ConditionVar, Body.get());
4670}
4671
4672template<typename Derived>
4673StmtResult
4674TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
4675  // Transform the body
4676  StmtResult Body = getDerived().TransformStmt(S->getBody());
4677  if (Body.isInvalid())
4678    return StmtError();
4679
4680  // Transform the condition
4681  ExprResult Cond = getDerived().TransformExpr(S->getCond());
4682  if (Cond.isInvalid())
4683    return StmtError();
4684
4685  if (!getDerived().AlwaysRebuild() &&
4686      Cond.get() == S->getCond() &&
4687      Body.get() == S->getBody())
4688    return SemaRef.Owned(S);
4689
4690  return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
4691                                    /*FIXME:*/S->getWhileLoc(), Cond.get(),
4692                                    S->getRParenLoc());
4693}
4694
4695template<typename Derived>
4696StmtResult
4697TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
4698  // Transform the initialization statement
4699  StmtResult Init = getDerived().TransformStmt(S->getInit());
4700  if (Init.isInvalid())
4701    return StmtError();
4702
4703  // Transform the condition
4704  ExprResult Cond;
4705  VarDecl *ConditionVar = 0;
4706  if (S->getConditionVariable()) {
4707    ConditionVar
4708      = cast_or_null<VarDecl>(
4709                   getDerived().TransformDefinition(
4710                                      S->getConditionVariable()->getLocation(),
4711                                                    S->getConditionVariable()));
4712    if (!ConditionVar)
4713      return StmtError();
4714  } else {
4715    Cond = getDerived().TransformExpr(S->getCond());
4716
4717    if (Cond.isInvalid())
4718      return StmtError();
4719
4720    if (S->getCond()) {
4721      // Convert the condition to a boolean value.
4722      ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getForLoc(),
4723                                                         Cond.get());
4724      if (CondE.isInvalid())
4725        return StmtError();
4726
4727      Cond = CondE.get();
4728    }
4729  }
4730
4731  Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
4732  if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
4733    return StmtError();
4734
4735  // Transform the increment
4736  ExprResult Inc = getDerived().TransformExpr(S->getInc());
4737  if (Inc.isInvalid())
4738    return StmtError();
4739
4740  Sema::FullExprArg FullInc(getSema().MakeFullExpr(Inc.get()));
4741  if (S->getInc() && !FullInc.get())
4742    return StmtError();
4743
4744  // Transform the body
4745  StmtResult Body = getDerived().TransformStmt(S->getBody());
4746  if (Body.isInvalid())
4747    return StmtError();
4748
4749  if (!getDerived().AlwaysRebuild() &&
4750      Init.get() == S->getInit() &&
4751      FullCond.get() == S->getCond() &&
4752      Inc.get() == S->getInc() &&
4753      Body.get() == S->getBody())
4754    return SemaRef.Owned(S);
4755
4756  return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
4757                                     Init.get(), FullCond, ConditionVar,
4758                                     FullInc, S->getRParenLoc(), Body.get());
4759}
4760
4761template<typename Derived>
4762StmtResult
4763TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
4764  // Goto statements must always be rebuilt, to resolve the label.
4765  return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
4766                                      S->getLabel());
4767}
4768
4769template<typename Derived>
4770StmtResult
4771TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
4772  ExprResult Target = getDerived().TransformExpr(S->getTarget());
4773  if (Target.isInvalid())
4774    return StmtError();
4775
4776  if (!getDerived().AlwaysRebuild() &&
4777      Target.get() == S->getTarget())
4778    return SemaRef.Owned(S);
4779
4780  return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
4781                                              Target.get());
4782}
4783
4784template<typename Derived>
4785StmtResult
4786TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
4787  return SemaRef.Owned(S);
4788}
4789
4790template<typename Derived>
4791StmtResult
4792TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
4793  return SemaRef.Owned(S);
4794}
4795
4796template<typename Derived>
4797StmtResult
4798TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
4799  ExprResult Result = getDerived().TransformExpr(S->getRetValue());
4800  if (Result.isInvalid())
4801    return StmtError();
4802
4803  // FIXME: We always rebuild the return statement because there is no way
4804  // to tell whether the return type of the function has changed.
4805  return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
4806}
4807
4808template<typename Derived>
4809StmtResult
4810TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
4811  bool DeclChanged = false;
4812  llvm::SmallVector<Decl *, 4> Decls;
4813  for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
4814       D != DEnd; ++D) {
4815    Decl *Transformed = getDerived().TransformDefinition((*D)->getLocation(),
4816                                                         *D);
4817    if (!Transformed)
4818      return StmtError();
4819
4820    if (Transformed != *D)
4821      DeclChanged = true;
4822
4823    Decls.push_back(Transformed);
4824  }
4825
4826  if (!getDerived().AlwaysRebuild() && !DeclChanged)
4827    return SemaRef.Owned(S);
4828
4829  return getDerived().RebuildDeclStmt(Decls.data(), Decls.size(),
4830                                      S->getStartLoc(), S->getEndLoc());
4831}
4832
4833template<typename Derived>
4834StmtResult
4835TreeTransform<Derived>::TransformAsmStmt(AsmStmt *S) {
4836
4837  ASTOwningVector<Expr*> Constraints(getSema());
4838  ASTOwningVector<Expr*> Exprs(getSema());
4839  llvm::SmallVector<IdentifierInfo *, 4> Names;
4840
4841  ExprResult AsmString;
4842  ASTOwningVector<Expr*> Clobbers(getSema());
4843
4844  bool ExprsChanged = false;
4845
4846  // Go through the outputs.
4847  for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
4848    Names.push_back(S->getOutputIdentifier(I));
4849
4850    // No need to transform the constraint literal.
4851    Constraints.push_back(S->getOutputConstraintLiteral(I));
4852
4853    // Transform the output expr.
4854    Expr *OutputExpr = S->getOutputExpr(I);
4855    ExprResult Result = getDerived().TransformExpr(OutputExpr);
4856    if (Result.isInvalid())
4857      return StmtError();
4858
4859    ExprsChanged |= Result.get() != OutputExpr;
4860
4861    Exprs.push_back(Result.get());
4862  }
4863
4864  // Go through the inputs.
4865  for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
4866    Names.push_back(S->getInputIdentifier(I));
4867
4868    // No need to transform the constraint literal.
4869    Constraints.push_back(S->getInputConstraintLiteral(I));
4870
4871    // Transform the input expr.
4872    Expr *InputExpr = S->getInputExpr(I);
4873    ExprResult Result = getDerived().TransformExpr(InputExpr);
4874    if (Result.isInvalid())
4875      return StmtError();
4876
4877    ExprsChanged |= Result.get() != InputExpr;
4878
4879    Exprs.push_back(Result.get());
4880  }
4881
4882  if (!getDerived().AlwaysRebuild() && !ExprsChanged)
4883    return SemaRef.Owned(S);
4884
4885  // Go through the clobbers.
4886  for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
4887    Clobbers.push_back(S->getClobber(I));
4888
4889  // No need to transform the asm string literal.
4890  AsmString = SemaRef.Owned(S->getAsmString());
4891
4892  return getDerived().RebuildAsmStmt(S->getAsmLoc(),
4893                                     S->isSimple(),
4894                                     S->isVolatile(),
4895                                     S->getNumOutputs(),
4896                                     S->getNumInputs(),
4897                                     Names.data(),
4898                                     move_arg(Constraints),
4899                                     move_arg(Exprs),
4900                                     AsmString.get(),
4901                                     move_arg(Clobbers),
4902                                     S->getRParenLoc(),
4903                                     S->isMSAsm());
4904}
4905
4906
4907template<typename Derived>
4908StmtResult
4909TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
4910  // Transform the body of the @try.
4911  StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
4912  if (TryBody.isInvalid())
4913    return StmtError();
4914
4915  // Transform the @catch statements (if present).
4916  bool AnyCatchChanged = false;
4917  ASTOwningVector<Stmt*> CatchStmts(SemaRef);
4918  for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
4919    StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
4920    if (Catch.isInvalid())
4921      return StmtError();
4922    if (Catch.get() != S->getCatchStmt(I))
4923      AnyCatchChanged = true;
4924    CatchStmts.push_back(Catch.release());
4925  }
4926
4927  // Transform the @finally statement (if present).
4928  StmtResult Finally;
4929  if (S->getFinallyStmt()) {
4930    Finally = getDerived().TransformStmt(S->getFinallyStmt());
4931    if (Finally.isInvalid())
4932      return StmtError();
4933  }
4934
4935  // If nothing changed, just retain this statement.
4936  if (!getDerived().AlwaysRebuild() &&
4937      TryBody.get() == S->getTryBody() &&
4938      !AnyCatchChanged &&
4939      Finally.get() == S->getFinallyStmt())
4940    return SemaRef.Owned(S);
4941
4942  // Build a new statement.
4943  return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
4944                                           move_arg(CatchStmts), Finally.get());
4945}
4946
4947template<typename Derived>
4948StmtResult
4949TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
4950  // Transform the @catch parameter, if there is one.
4951  VarDecl *Var = 0;
4952  if (VarDecl *FromVar = S->getCatchParamDecl()) {
4953    TypeSourceInfo *TSInfo = 0;
4954    if (FromVar->getTypeSourceInfo()) {
4955      TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
4956      if (!TSInfo)
4957        return StmtError();
4958    }
4959
4960    QualType T;
4961    if (TSInfo)
4962      T = TSInfo->getType();
4963    else {
4964      T = getDerived().TransformType(FromVar->getType());
4965      if (T.isNull())
4966        return StmtError();
4967    }
4968
4969    Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
4970    if (!Var)
4971      return StmtError();
4972  }
4973
4974  StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
4975  if (Body.isInvalid())
4976    return StmtError();
4977
4978  return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
4979                                             S->getRParenLoc(),
4980                                             Var, Body.get());
4981}
4982
4983template<typename Derived>
4984StmtResult
4985TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
4986  // Transform the body.
4987  StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
4988  if (Body.isInvalid())
4989    return StmtError();
4990
4991  // If nothing changed, just retain this statement.
4992  if (!getDerived().AlwaysRebuild() &&
4993      Body.get() == S->getFinallyBody())
4994    return SemaRef.Owned(S);
4995
4996  // Build a new statement.
4997  return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
4998                                               Body.get());
4999}
5000
5001template<typename Derived>
5002StmtResult
5003TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5004  ExprResult Operand;
5005  if (S->getThrowExpr()) {
5006    Operand = getDerived().TransformExpr(S->getThrowExpr());
5007    if (Operand.isInvalid())
5008      return StmtError();
5009  }
5010
5011  if (!getDerived().AlwaysRebuild() &&
5012      Operand.get() == S->getThrowExpr())
5013    return getSema().Owned(S);
5014
5015  return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
5016}
5017
5018template<typename Derived>
5019StmtResult
5020TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
5021                                                  ObjCAtSynchronizedStmt *S) {
5022  // Transform the object we are locking.
5023  ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
5024  if (Object.isInvalid())
5025    return StmtError();
5026
5027  // Transform the body.
5028  StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
5029  if (Body.isInvalid())
5030    return StmtError();
5031
5032  // If nothing change, just retain the current statement.
5033  if (!getDerived().AlwaysRebuild() &&
5034      Object.get() == S->getSynchExpr() &&
5035      Body.get() == S->getSynchBody())
5036    return SemaRef.Owned(S);
5037
5038  // Build a new statement.
5039  return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
5040                                                    Object.get(), Body.get());
5041}
5042
5043template<typename Derived>
5044StmtResult
5045TreeTransform<Derived>::TransformObjCForCollectionStmt(
5046                                                  ObjCForCollectionStmt *S) {
5047  // Transform the element statement.
5048  StmtResult Element = getDerived().TransformStmt(S->getElement());
5049  if (Element.isInvalid())
5050    return StmtError();
5051
5052  // Transform the collection expression.
5053  ExprResult Collection = getDerived().TransformExpr(S->getCollection());
5054  if (Collection.isInvalid())
5055    return StmtError();
5056
5057  // Transform the body.
5058  StmtResult Body = getDerived().TransformStmt(S->getBody());
5059  if (Body.isInvalid())
5060    return StmtError();
5061
5062  // If nothing changed, just retain this statement.
5063  if (!getDerived().AlwaysRebuild() &&
5064      Element.get() == S->getElement() &&
5065      Collection.get() == S->getCollection() &&
5066      Body.get() == S->getBody())
5067    return SemaRef.Owned(S);
5068
5069  // Build a new statement.
5070  return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
5071                                                   /*FIXME:*/S->getForLoc(),
5072                                                   Element.get(),
5073                                                   Collection.get(),
5074                                                   S->getRParenLoc(),
5075                                                   Body.get());
5076}
5077
5078
5079template<typename Derived>
5080StmtResult
5081TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
5082  // Transform the exception declaration, if any.
5083  VarDecl *Var = 0;
5084  if (S->getExceptionDecl()) {
5085    VarDecl *ExceptionDecl = S->getExceptionDecl();
5086    TypeSourceInfo *T = getDerived().TransformType(
5087                                            ExceptionDecl->getTypeSourceInfo());
5088    if (!T)
5089      return StmtError();
5090
5091    Var = getDerived().RebuildExceptionDecl(ExceptionDecl, T,
5092                                            ExceptionDecl->getIdentifier(),
5093                                            ExceptionDecl->getLocation());
5094    if (!Var || Var->isInvalidDecl())
5095      return StmtError();
5096  }
5097
5098  // Transform the actual exception handler.
5099  StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
5100  if (Handler.isInvalid())
5101    return StmtError();
5102
5103  if (!getDerived().AlwaysRebuild() &&
5104      !Var &&
5105      Handler.get() == S->getHandlerBlock())
5106    return SemaRef.Owned(S);
5107
5108  return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(),
5109                                          Var,
5110                                          Handler.get());
5111}
5112
5113template<typename Derived>
5114StmtResult
5115TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
5116  // Transform the try block itself.
5117  StmtResult TryBlock
5118    = getDerived().TransformCompoundStmt(S->getTryBlock());
5119  if (TryBlock.isInvalid())
5120    return StmtError();
5121
5122  // Transform the handlers.
5123  bool HandlerChanged = false;
5124  ASTOwningVector<Stmt*> Handlers(SemaRef);
5125  for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
5126    StmtResult Handler
5127      = getDerived().TransformCXXCatchStmt(S->getHandler(I));
5128    if (Handler.isInvalid())
5129      return StmtError();
5130
5131    HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
5132    Handlers.push_back(Handler.takeAs<Stmt>());
5133  }
5134
5135  if (!getDerived().AlwaysRebuild() &&
5136      TryBlock.get() == S->getTryBlock() &&
5137      !HandlerChanged)
5138    return SemaRef.Owned(S);
5139
5140  return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
5141                                        move_arg(Handlers));
5142}
5143
5144//===----------------------------------------------------------------------===//
5145// Expression transformation
5146//===----------------------------------------------------------------------===//
5147template<typename Derived>
5148ExprResult
5149TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
5150  return SemaRef.Owned(E);
5151}
5152
5153template<typename Derived>
5154ExprResult
5155TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
5156  NestedNameSpecifier *Qualifier = 0;
5157  if (E->getQualifier()) {
5158    Qualifier = getDerived().TransformNestedNameSpecifier(E->getQualifier(),
5159                                                       E->getQualifierRange());
5160    if (!Qualifier)
5161      return ExprError();
5162  }
5163
5164  ValueDecl *ND
5165    = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
5166                                                         E->getDecl()));
5167  if (!ND)
5168    return ExprError();
5169
5170  DeclarationNameInfo NameInfo = E->getNameInfo();
5171  if (NameInfo.getName()) {
5172    NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
5173    if (!NameInfo.getName())
5174      return ExprError();
5175  }
5176
5177  if (!getDerived().AlwaysRebuild() &&
5178      Qualifier == E->getQualifier() &&
5179      ND == E->getDecl() &&
5180      NameInfo.getName() == E->getDecl()->getDeclName() &&
5181      !E->hasExplicitTemplateArgs()) {
5182
5183    // Mark it referenced in the new context regardless.
5184    // FIXME: this is a bit instantiation-specific.
5185    SemaRef.MarkDeclarationReferenced(E->getLocation(), ND);
5186
5187    return SemaRef.Owned(E);
5188  }
5189
5190  TemplateArgumentListInfo TransArgs, *TemplateArgs = 0;
5191  if (E->hasExplicitTemplateArgs()) {
5192    TemplateArgs = &TransArgs;
5193    TransArgs.setLAngleLoc(E->getLAngleLoc());
5194    TransArgs.setRAngleLoc(E->getRAngleLoc());
5195    if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
5196                                                E->getNumTemplateArgs(),
5197                                                TransArgs))
5198      return ExprError();
5199  }
5200
5201  return getDerived().RebuildDeclRefExpr(Qualifier, E->getQualifierRange(),
5202                                         ND, NameInfo, TemplateArgs);
5203}
5204
5205template<typename Derived>
5206ExprResult
5207TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
5208  return SemaRef.Owned(E);
5209}
5210
5211template<typename Derived>
5212ExprResult
5213TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
5214  return SemaRef.Owned(E);
5215}
5216
5217template<typename Derived>
5218ExprResult
5219TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
5220  return SemaRef.Owned(E);
5221}
5222
5223template<typename Derived>
5224ExprResult
5225TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
5226  return SemaRef.Owned(E);
5227}
5228
5229template<typename Derived>
5230ExprResult
5231TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
5232  return SemaRef.Owned(E);
5233}
5234
5235template<typename Derived>
5236ExprResult
5237TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
5238  ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
5239  if (SubExpr.isInvalid())
5240    return ExprError();
5241
5242  if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
5243    return SemaRef.Owned(E);
5244
5245  return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
5246                                       E->getRParen());
5247}
5248
5249template<typename Derived>
5250ExprResult
5251TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
5252  ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
5253  if (SubExpr.isInvalid())
5254    return ExprError();
5255
5256  if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
5257    return SemaRef.Owned(E);
5258
5259  return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
5260                                           E->getOpcode(),
5261                                           SubExpr.get());
5262}
5263
5264template<typename Derived>
5265ExprResult
5266TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
5267  // Transform the type.
5268  TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
5269  if (!Type)
5270    return ExprError();
5271
5272  // Transform all of the components into components similar to what the
5273  // parser uses.
5274  // FIXME: It would be slightly more efficient in the non-dependent case to
5275  // just map FieldDecls, rather than requiring the rebuilder to look for
5276  // the fields again. However, __builtin_offsetof is rare enough in
5277  // template code that we don't care.
5278  bool ExprChanged = false;
5279  typedef Sema::OffsetOfComponent Component;
5280  typedef OffsetOfExpr::OffsetOfNode Node;
5281  llvm::SmallVector<Component, 4> Components;
5282  for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
5283    const Node &ON = E->getComponent(I);
5284    Component Comp;
5285    Comp.isBrackets = true;
5286    Comp.LocStart = ON.getRange().getBegin();
5287    Comp.LocEnd = ON.getRange().getEnd();
5288    switch (ON.getKind()) {
5289    case Node::Array: {
5290      Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
5291      ExprResult Index = getDerived().TransformExpr(FromIndex);
5292      if (Index.isInvalid())
5293        return ExprError();
5294
5295      ExprChanged = ExprChanged || Index.get() != FromIndex;
5296      Comp.isBrackets = true;
5297      Comp.U.E = Index.get();
5298      break;
5299    }
5300
5301    case Node::Field:
5302    case Node::Identifier:
5303      Comp.isBrackets = false;
5304      Comp.U.IdentInfo = ON.getFieldName();
5305      if (!Comp.U.IdentInfo)
5306        continue;
5307
5308      break;
5309
5310    case Node::Base:
5311      // Will be recomputed during the rebuild.
5312      continue;
5313    }
5314
5315    Components.push_back(Comp);
5316  }
5317
5318  // If nothing changed, retain the existing expression.
5319  if (!getDerived().AlwaysRebuild() &&
5320      Type == E->getTypeSourceInfo() &&
5321      !ExprChanged)
5322    return SemaRef.Owned(E);
5323
5324  // Build a new offsetof expression.
5325  return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
5326                                          Components.data(), Components.size(),
5327                                          E->getRParenLoc());
5328}
5329
5330template<typename Derived>
5331ExprResult
5332TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
5333  assert(getDerived().AlreadyTransformed(E->getType()) &&
5334         "opaque value expression requires transformation");
5335  return SemaRef.Owned(E);
5336}
5337
5338template<typename Derived>
5339ExprResult
5340TreeTransform<Derived>::TransformSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
5341  if (E->isArgumentType()) {
5342    TypeSourceInfo *OldT = E->getArgumentTypeInfo();
5343
5344    TypeSourceInfo *NewT = getDerived().TransformType(OldT);
5345    if (!NewT)
5346      return ExprError();
5347
5348    if (!getDerived().AlwaysRebuild() && OldT == NewT)
5349      return SemaRef.Owned(E);
5350
5351    return getDerived().RebuildSizeOfAlignOf(NewT, E->getOperatorLoc(),
5352                                             E->isSizeOf(),
5353                                             E->getSourceRange());
5354  }
5355
5356  ExprResult SubExpr;
5357  {
5358    // C++0x [expr.sizeof]p1:
5359    //   The operand is either an expression, which is an unevaluated operand
5360    //   [...]
5361    EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
5362
5363    SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
5364    if (SubExpr.isInvalid())
5365      return ExprError();
5366
5367    if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
5368      return SemaRef.Owned(E);
5369  }
5370
5371  return getDerived().RebuildSizeOfAlignOf(SubExpr.get(), E->getOperatorLoc(),
5372                                           E->isSizeOf(),
5373                                           E->getSourceRange());
5374}
5375
5376template<typename Derived>
5377ExprResult
5378TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
5379  ExprResult LHS = getDerived().TransformExpr(E->getLHS());
5380  if (LHS.isInvalid())
5381    return ExprError();
5382
5383  ExprResult RHS = getDerived().TransformExpr(E->getRHS());
5384  if (RHS.isInvalid())
5385    return ExprError();
5386
5387
5388  if (!getDerived().AlwaysRebuild() &&
5389      LHS.get() == E->getLHS() &&
5390      RHS.get() == E->getRHS())
5391    return SemaRef.Owned(E);
5392
5393  return getDerived().RebuildArraySubscriptExpr(LHS.get(),
5394                                           /*FIXME:*/E->getLHS()->getLocStart(),
5395                                                RHS.get(),
5396                                                E->getRBracketLoc());
5397}
5398
5399template<typename Derived>
5400ExprResult
5401TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
5402  // Transform the callee.
5403  ExprResult Callee = getDerived().TransformExpr(E->getCallee());
5404  if (Callee.isInvalid())
5405    return ExprError();
5406
5407  // Transform arguments.
5408  bool ArgChanged = false;
5409  ASTOwningVector<Expr*> Args(SemaRef);
5410  if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
5411                                  &ArgChanged))
5412    return ExprError();
5413
5414  if (!getDerived().AlwaysRebuild() &&
5415      Callee.get() == E->getCallee() &&
5416      !ArgChanged)
5417    return SemaRef.Owned(E);
5418
5419  // FIXME: Wrong source location information for the '('.
5420  SourceLocation FakeLParenLoc
5421    = ((Expr *)Callee.get())->getSourceRange().getBegin();
5422  return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
5423                                      move_arg(Args),
5424                                      E->getRParenLoc());
5425}
5426
5427template<typename Derived>
5428ExprResult
5429TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
5430  ExprResult Base = getDerived().TransformExpr(E->getBase());
5431  if (Base.isInvalid())
5432    return ExprError();
5433
5434  NestedNameSpecifier *Qualifier = 0;
5435  if (E->hasQualifier()) {
5436    Qualifier
5437      = getDerived().TransformNestedNameSpecifier(E->getQualifier(),
5438                                                  E->getQualifierRange());
5439    if (Qualifier == 0)
5440      return ExprError();
5441  }
5442
5443  ValueDecl *Member
5444    = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
5445                                                         E->getMemberDecl()));
5446  if (!Member)
5447    return ExprError();
5448
5449  NamedDecl *FoundDecl = E->getFoundDecl();
5450  if (FoundDecl == E->getMemberDecl()) {
5451    FoundDecl = Member;
5452  } else {
5453    FoundDecl = cast_or_null<NamedDecl>(
5454                   getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
5455    if (!FoundDecl)
5456      return ExprError();
5457  }
5458
5459  if (!getDerived().AlwaysRebuild() &&
5460      Base.get() == E->getBase() &&
5461      Qualifier == E->getQualifier() &&
5462      Member == E->getMemberDecl() &&
5463      FoundDecl == E->getFoundDecl() &&
5464      !E->hasExplicitTemplateArgs()) {
5465
5466    // Mark it referenced in the new context regardless.
5467    // FIXME: this is a bit instantiation-specific.
5468    SemaRef.MarkDeclarationReferenced(E->getMemberLoc(), Member);
5469    return SemaRef.Owned(E);
5470  }
5471
5472  TemplateArgumentListInfo TransArgs;
5473  if (E->hasExplicitTemplateArgs()) {
5474    TransArgs.setLAngleLoc(E->getLAngleLoc());
5475    TransArgs.setRAngleLoc(E->getRAngleLoc());
5476    if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
5477                                                E->getNumTemplateArgs(),
5478                                                TransArgs))
5479      return ExprError();
5480  }
5481
5482  // FIXME: Bogus source location for the operator
5483  SourceLocation FakeOperatorLoc
5484    = SemaRef.PP.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
5485
5486  // FIXME: to do this check properly, we will need to preserve the
5487  // first-qualifier-in-scope here, just in case we had a dependent
5488  // base (and therefore couldn't do the check) and a
5489  // nested-name-qualifier (and therefore could do the lookup).
5490  NamedDecl *FirstQualifierInScope = 0;
5491
5492  return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
5493                                        E->isArrow(),
5494                                        Qualifier,
5495                                        E->getQualifierRange(),
5496                                        E->getMemberNameInfo(),
5497                                        Member,
5498                                        FoundDecl,
5499                                        (E->hasExplicitTemplateArgs()
5500                                           ? &TransArgs : 0),
5501                                        FirstQualifierInScope);
5502}
5503
5504template<typename Derived>
5505ExprResult
5506TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
5507  ExprResult LHS = getDerived().TransformExpr(E->getLHS());
5508  if (LHS.isInvalid())
5509    return ExprError();
5510
5511  ExprResult RHS = getDerived().TransformExpr(E->getRHS());
5512  if (RHS.isInvalid())
5513    return ExprError();
5514
5515  if (!getDerived().AlwaysRebuild() &&
5516      LHS.get() == E->getLHS() &&
5517      RHS.get() == E->getRHS())
5518    return SemaRef.Owned(E);
5519
5520  return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
5521                                            LHS.get(), RHS.get());
5522}
5523
5524template<typename Derived>
5525ExprResult
5526TreeTransform<Derived>::TransformCompoundAssignOperator(
5527                                                      CompoundAssignOperator *E) {
5528  return getDerived().TransformBinaryOperator(E);
5529}
5530
5531template<typename Derived>
5532ExprResult
5533TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
5534  ExprResult Cond = getDerived().TransformExpr(E->getCond());
5535  if (Cond.isInvalid())
5536    return ExprError();
5537
5538  ExprResult LHS = getDerived().TransformExpr(E->getLHS());
5539  if (LHS.isInvalid())
5540    return ExprError();
5541
5542  ExprResult RHS = getDerived().TransformExpr(E->getRHS());
5543  if (RHS.isInvalid())
5544    return ExprError();
5545
5546  if (!getDerived().AlwaysRebuild() &&
5547      Cond.get() == E->getCond() &&
5548      LHS.get() == E->getLHS() &&
5549      RHS.get() == E->getRHS())
5550    return SemaRef.Owned(E);
5551
5552  return getDerived().RebuildConditionalOperator(Cond.get(),
5553                                                 E->getQuestionLoc(),
5554                                                 LHS.get(),
5555                                                 E->getColonLoc(),
5556                                                 RHS.get());
5557}
5558
5559template<typename Derived>
5560ExprResult
5561TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
5562  // Implicit casts are eliminated during transformation, since they
5563  // will be recomputed by semantic analysis after transformation.
5564  return getDerived().TransformExpr(E->getSubExprAsWritten());
5565}
5566
5567template<typename Derived>
5568ExprResult
5569TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
5570  TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
5571  if (!Type)
5572    return ExprError();
5573
5574  ExprResult SubExpr
5575    = getDerived().TransformExpr(E->getSubExprAsWritten());
5576  if (SubExpr.isInvalid())
5577    return ExprError();
5578
5579  if (!getDerived().AlwaysRebuild() &&
5580      Type == E->getTypeInfoAsWritten() &&
5581      SubExpr.get() == E->getSubExpr())
5582    return SemaRef.Owned(E);
5583
5584  return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
5585                                            Type,
5586                                            E->getRParenLoc(),
5587                                            SubExpr.get());
5588}
5589
5590template<typename Derived>
5591ExprResult
5592TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
5593  TypeSourceInfo *OldT = E->getTypeSourceInfo();
5594  TypeSourceInfo *NewT = getDerived().TransformType(OldT);
5595  if (!NewT)
5596    return ExprError();
5597
5598  ExprResult Init = getDerived().TransformExpr(E->getInitializer());
5599  if (Init.isInvalid())
5600    return ExprError();
5601
5602  if (!getDerived().AlwaysRebuild() &&
5603      OldT == NewT &&
5604      Init.get() == E->getInitializer())
5605    return SemaRef.Owned(E);
5606
5607  // Note: the expression type doesn't necessarily match the
5608  // type-as-written, but that's okay, because it should always be
5609  // derivable from the initializer.
5610
5611  return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
5612                                   /*FIXME:*/E->getInitializer()->getLocEnd(),
5613                                                 Init.get());
5614}
5615
5616template<typename Derived>
5617ExprResult
5618TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
5619  ExprResult Base = getDerived().TransformExpr(E->getBase());
5620  if (Base.isInvalid())
5621    return ExprError();
5622
5623  if (!getDerived().AlwaysRebuild() &&
5624      Base.get() == E->getBase())
5625    return SemaRef.Owned(E);
5626
5627  // FIXME: Bad source location
5628  SourceLocation FakeOperatorLoc
5629    = SemaRef.PP.getLocForEndOfToken(E->getBase()->getLocEnd());
5630  return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
5631                                                  E->getAccessorLoc(),
5632                                                  E->getAccessor());
5633}
5634
5635template<typename Derived>
5636ExprResult
5637TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
5638  bool InitChanged = false;
5639
5640  ASTOwningVector<Expr*, 4> Inits(SemaRef);
5641  if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
5642                                  Inits, &InitChanged))
5643    return ExprError();
5644
5645  if (!getDerived().AlwaysRebuild() && !InitChanged)
5646    return SemaRef.Owned(E);
5647
5648  return getDerived().RebuildInitList(E->getLBraceLoc(), move_arg(Inits),
5649                                      E->getRBraceLoc(), E->getType());
5650}
5651
5652template<typename Derived>
5653ExprResult
5654TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
5655  Designation Desig;
5656
5657  // transform the initializer value
5658  ExprResult Init = getDerived().TransformExpr(E->getInit());
5659  if (Init.isInvalid())
5660    return ExprError();
5661
5662  // transform the designators.
5663  ASTOwningVector<Expr*, 4> ArrayExprs(SemaRef);
5664  bool ExprChanged = false;
5665  for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
5666                                             DEnd = E->designators_end();
5667       D != DEnd; ++D) {
5668    if (D->isFieldDesignator()) {
5669      Desig.AddDesignator(Designator::getField(D->getFieldName(),
5670                                               D->getDotLoc(),
5671                                               D->getFieldLoc()));
5672      continue;
5673    }
5674
5675    if (D->isArrayDesignator()) {
5676      ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
5677      if (Index.isInvalid())
5678        return ExprError();
5679
5680      Desig.AddDesignator(Designator::getArray(Index.get(),
5681                                               D->getLBracketLoc()));
5682
5683      ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
5684      ArrayExprs.push_back(Index.release());
5685      continue;
5686    }
5687
5688    assert(D->isArrayRangeDesignator() && "New kind of designator?");
5689    ExprResult Start
5690      = getDerived().TransformExpr(E->getArrayRangeStart(*D));
5691    if (Start.isInvalid())
5692      return ExprError();
5693
5694    ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
5695    if (End.isInvalid())
5696      return ExprError();
5697
5698    Desig.AddDesignator(Designator::getArrayRange(Start.get(),
5699                                                  End.get(),
5700                                                  D->getLBracketLoc(),
5701                                                  D->getEllipsisLoc()));
5702
5703    ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
5704      End.get() != E->getArrayRangeEnd(*D);
5705
5706    ArrayExprs.push_back(Start.release());
5707    ArrayExprs.push_back(End.release());
5708  }
5709
5710  if (!getDerived().AlwaysRebuild() &&
5711      Init.get() == E->getInit() &&
5712      !ExprChanged)
5713    return SemaRef.Owned(E);
5714
5715  return getDerived().RebuildDesignatedInitExpr(Desig, move_arg(ArrayExprs),
5716                                                E->getEqualOrColonLoc(),
5717                                                E->usesGNUSyntax(), Init.get());
5718}
5719
5720template<typename Derived>
5721ExprResult
5722TreeTransform<Derived>::TransformImplicitValueInitExpr(
5723                                                     ImplicitValueInitExpr *E) {
5724  TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
5725
5726  // FIXME: Will we ever have proper type location here? Will we actually
5727  // need to transform the type?
5728  QualType T = getDerived().TransformType(E->getType());
5729  if (T.isNull())
5730    return ExprError();
5731
5732  if (!getDerived().AlwaysRebuild() &&
5733      T == E->getType())
5734    return SemaRef.Owned(E);
5735
5736  return getDerived().RebuildImplicitValueInitExpr(T);
5737}
5738
5739template<typename Derived>
5740ExprResult
5741TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
5742  TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
5743  if (!TInfo)
5744    return ExprError();
5745
5746  ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
5747  if (SubExpr.isInvalid())
5748    return ExprError();
5749
5750  if (!getDerived().AlwaysRebuild() &&
5751      TInfo == E->getWrittenTypeInfo() &&
5752      SubExpr.get() == E->getSubExpr())
5753    return SemaRef.Owned(E);
5754
5755  return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
5756                                       TInfo, E->getRParenLoc());
5757}
5758
5759template<typename Derived>
5760ExprResult
5761TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
5762  bool ArgumentChanged = false;
5763  ASTOwningVector<Expr*, 4> Inits(SemaRef);
5764  if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
5765                     &ArgumentChanged))
5766    return ExprError();
5767
5768  return getDerived().RebuildParenListExpr(E->getLParenLoc(),
5769                                           move_arg(Inits),
5770                                           E->getRParenLoc());
5771}
5772
5773/// \brief Transform an address-of-label expression.
5774///
5775/// By default, the transformation of an address-of-label expression always
5776/// rebuilds the expression, so that the label identifier can be resolved to
5777/// the corresponding label statement by semantic analysis.
5778template<typename Derived>
5779ExprResult
5780TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
5781  return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
5782                                           E->getLabel());
5783}
5784
5785template<typename Derived>
5786ExprResult
5787TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
5788  StmtResult SubStmt
5789    = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
5790  if (SubStmt.isInvalid())
5791    return ExprError();
5792
5793  if (!getDerived().AlwaysRebuild() &&
5794      SubStmt.get() == E->getSubStmt())
5795    return SemaRef.Owned(E);
5796
5797  return getDerived().RebuildStmtExpr(E->getLParenLoc(),
5798                                      SubStmt.get(),
5799                                      E->getRParenLoc());
5800}
5801
5802template<typename Derived>
5803ExprResult
5804TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
5805  ExprResult Cond = getDerived().TransformExpr(E->getCond());
5806  if (Cond.isInvalid())
5807    return ExprError();
5808
5809  ExprResult LHS = getDerived().TransformExpr(E->getLHS());
5810  if (LHS.isInvalid())
5811    return ExprError();
5812
5813  ExprResult RHS = getDerived().TransformExpr(E->getRHS());
5814  if (RHS.isInvalid())
5815    return ExprError();
5816
5817  if (!getDerived().AlwaysRebuild() &&
5818      Cond.get() == E->getCond() &&
5819      LHS.get() == E->getLHS() &&
5820      RHS.get() == E->getRHS())
5821    return SemaRef.Owned(E);
5822
5823  return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
5824                                        Cond.get(), LHS.get(), RHS.get(),
5825                                        E->getRParenLoc());
5826}
5827
5828template<typename Derived>
5829ExprResult
5830TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
5831  return SemaRef.Owned(E);
5832}
5833
5834template<typename Derived>
5835ExprResult
5836TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
5837  switch (E->getOperator()) {
5838  case OO_New:
5839  case OO_Delete:
5840  case OO_Array_New:
5841  case OO_Array_Delete:
5842    llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
5843    return ExprError();
5844
5845  case OO_Call: {
5846    // This is a call to an object's operator().
5847    assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
5848
5849    // Transform the object itself.
5850    ExprResult Object = getDerived().TransformExpr(E->getArg(0));
5851    if (Object.isInvalid())
5852      return ExprError();
5853
5854    // FIXME: Poor location information
5855    SourceLocation FakeLParenLoc
5856      = SemaRef.PP.getLocForEndOfToken(
5857                              static_cast<Expr *>(Object.get())->getLocEnd());
5858
5859    // Transform the call arguments.
5860    ASTOwningVector<Expr*> Args(SemaRef);
5861    if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
5862                                    Args))
5863      return ExprError();
5864
5865    return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
5866                                        move_arg(Args),
5867                                        E->getLocEnd());
5868  }
5869
5870#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5871  case OO_##Name:
5872#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
5873#include "clang/Basic/OperatorKinds.def"
5874  case OO_Subscript:
5875    // Handled below.
5876    break;
5877
5878  case OO_Conditional:
5879    llvm_unreachable("conditional operator is not actually overloadable");
5880    return ExprError();
5881
5882  case OO_None:
5883  case NUM_OVERLOADED_OPERATORS:
5884    llvm_unreachable("not an overloaded operator?");
5885    return ExprError();
5886  }
5887
5888  ExprResult Callee = getDerived().TransformExpr(E->getCallee());
5889  if (Callee.isInvalid())
5890    return ExprError();
5891
5892  ExprResult First = getDerived().TransformExpr(E->getArg(0));
5893  if (First.isInvalid())
5894    return ExprError();
5895
5896  ExprResult Second;
5897  if (E->getNumArgs() == 2) {
5898    Second = getDerived().TransformExpr(E->getArg(1));
5899    if (Second.isInvalid())
5900      return ExprError();
5901  }
5902
5903  if (!getDerived().AlwaysRebuild() &&
5904      Callee.get() == E->getCallee() &&
5905      First.get() == E->getArg(0) &&
5906      (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
5907    return SemaRef.Owned(E);
5908
5909  return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
5910                                                 E->getOperatorLoc(),
5911                                                 Callee.get(),
5912                                                 First.get(),
5913                                                 Second.get());
5914}
5915
5916template<typename Derived>
5917ExprResult
5918TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
5919  return getDerived().TransformCallExpr(E);
5920}
5921
5922template<typename Derived>
5923ExprResult
5924TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
5925  TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
5926  if (!Type)
5927    return ExprError();
5928
5929  ExprResult SubExpr
5930    = getDerived().TransformExpr(E->getSubExprAsWritten());
5931  if (SubExpr.isInvalid())
5932    return ExprError();
5933
5934  if (!getDerived().AlwaysRebuild() &&
5935      Type == E->getTypeInfoAsWritten() &&
5936      SubExpr.get() == E->getSubExpr())
5937    return SemaRef.Owned(E);
5938
5939  // FIXME: Poor source location information here.
5940  SourceLocation FakeLAngleLoc
5941    = SemaRef.PP.getLocForEndOfToken(E->getOperatorLoc());
5942  SourceLocation FakeRAngleLoc = E->getSubExpr()->getSourceRange().getBegin();
5943  SourceLocation FakeRParenLoc
5944    = SemaRef.PP.getLocForEndOfToken(
5945                                  E->getSubExpr()->getSourceRange().getEnd());
5946  return getDerived().RebuildCXXNamedCastExpr(E->getOperatorLoc(),
5947                                              E->getStmtClass(),
5948                                              FakeLAngleLoc,
5949                                              Type,
5950                                              FakeRAngleLoc,
5951                                              FakeRAngleLoc,
5952                                              SubExpr.get(),
5953                                              FakeRParenLoc);
5954}
5955
5956template<typename Derived>
5957ExprResult
5958TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
5959  return getDerived().TransformCXXNamedCastExpr(E);
5960}
5961
5962template<typename Derived>
5963ExprResult
5964TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
5965  return getDerived().TransformCXXNamedCastExpr(E);
5966}
5967
5968template<typename Derived>
5969ExprResult
5970TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
5971                                                      CXXReinterpretCastExpr *E) {
5972  return getDerived().TransformCXXNamedCastExpr(E);
5973}
5974
5975template<typename Derived>
5976ExprResult
5977TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
5978  return getDerived().TransformCXXNamedCastExpr(E);
5979}
5980
5981template<typename Derived>
5982ExprResult
5983TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
5984                                                     CXXFunctionalCastExpr *E) {
5985  TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
5986  if (!Type)
5987    return ExprError();
5988
5989  ExprResult SubExpr
5990    = getDerived().TransformExpr(E->getSubExprAsWritten());
5991  if (SubExpr.isInvalid())
5992    return ExprError();
5993
5994  if (!getDerived().AlwaysRebuild() &&
5995      Type == E->getTypeInfoAsWritten() &&
5996      SubExpr.get() == E->getSubExpr())
5997    return SemaRef.Owned(E);
5998
5999  return getDerived().RebuildCXXFunctionalCastExpr(Type,
6000                                      /*FIXME:*/E->getSubExpr()->getLocStart(),
6001                                                   SubExpr.get(),
6002                                                   E->getRParenLoc());
6003}
6004
6005template<typename Derived>
6006ExprResult
6007TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
6008  if (E->isTypeOperand()) {
6009    TypeSourceInfo *TInfo
6010      = getDerived().TransformType(E->getTypeOperandSourceInfo());
6011    if (!TInfo)
6012      return ExprError();
6013
6014    if (!getDerived().AlwaysRebuild() &&
6015        TInfo == E->getTypeOperandSourceInfo())
6016      return SemaRef.Owned(E);
6017
6018    return getDerived().RebuildCXXTypeidExpr(E->getType(),
6019                                             E->getLocStart(),
6020                                             TInfo,
6021                                             E->getLocEnd());
6022  }
6023
6024  // We don't know whether the expression is potentially evaluated until
6025  // after we perform semantic analysis, so the expression is potentially
6026  // potentially evaluated.
6027  EnterExpressionEvaluationContext Unevaluated(SemaRef,
6028                                      Sema::PotentiallyPotentiallyEvaluated);
6029
6030  ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
6031  if (SubExpr.isInvalid())
6032    return ExprError();
6033
6034  if (!getDerived().AlwaysRebuild() &&
6035      SubExpr.get() == E->getExprOperand())
6036    return SemaRef.Owned(E);
6037
6038  return getDerived().RebuildCXXTypeidExpr(E->getType(),
6039                                           E->getLocStart(),
6040                                           SubExpr.get(),
6041                                           E->getLocEnd());
6042}
6043
6044template<typename Derived>
6045ExprResult
6046TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
6047  if (E->isTypeOperand()) {
6048    TypeSourceInfo *TInfo
6049      = getDerived().TransformType(E->getTypeOperandSourceInfo());
6050    if (!TInfo)
6051      return ExprError();
6052
6053    if (!getDerived().AlwaysRebuild() &&
6054        TInfo == E->getTypeOperandSourceInfo())
6055      return SemaRef.Owned(E);
6056
6057    return getDerived().RebuildCXXTypeidExpr(E->getType(),
6058                                             E->getLocStart(),
6059                                             TInfo,
6060                                             E->getLocEnd());
6061  }
6062
6063  // We don't know whether the expression is potentially evaluated until
6064  // after we perform semantic analysis, so the expression is potentially
6065  // potentially evaluated.
6066  EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
6067
6068  ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
6069  if (SubExpr.isInvalid())
6070    return ExprError();
6071
6072  if (!getDerived().AlwaysRebuild() &&
6073      SubExpr.get() == E->getExprOperand())
6074    return SemaRef.Owned(E);
6075
6076  return getDerived().RebuildCXXUuidofExpr(E->getType(),
6077                                           E->getLocStart(),
6078                                           SubExpr.get(),
6079                                           E->getLocEnd());
6080}
6081
6082template<typename Derived>
6083ExprResult
6084TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
6085  return SemaRef.Owned(E);
6086}
6087
6088template<typename Derived>
6089ExprResult
6090TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
6091                                                     CXXNullPtrLiteralExpr *E) {
6092  return SemaRef.Owned(E);
6093}
6094
6095template<typename Derived>
6096ExprResult
6097TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
6098  DeclContext *DC = getSema().getFunctionLevelDeclContext();
6099  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC);
6100  QualType T = MD->getThisType(getSema().Context);
6101
6102  if (!getDerived().AlwaysRebuild() && T == E->getType())
6103    return SemaRef.Owned(E);
6104
6105  return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
6106}
6107
6108template<typename Derived>
6109ExprResult
6110TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
6111  ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
6112  if (SubExpr.isInvalid())
6113    return ExprError();
6114
6115  if (!getDerived().AlwaysRebuild() &&
6116      SubExpr.get() == E->getSubExpr())
6117    return SemaRef.Owned(E);
6118
6119  return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get());
6120}
6121
6122template<typename Derived>
6123ExprResult
6124TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
6125  ParmVarDecl *Param
6126    = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
6127                                                           E->getParam()));
6128  if (!Param)
6129    return ExprError();
6130
6131  if (!getDerived().AlwaysRebuild() &&
6132      Param == E->getParam())
6133    return SemaRef.Owned(E);
6134
6135  return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
6136}
6137
6138template<typename Derived>
6139ExprResult
6140TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
6141                                                    CXXScalarValueInitExpr *E) {
6142  TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
6143  if (!T)
6144    return ExprError();
6145
6146  if (!getDerived().AlwaysRebuild() &&
6147      T == E->getTypeSourceInfo())
6148    return SemaRef.Owned(E);
6149
6150  return getDerived().RebuildCXXScalarValueInitExpr(T,
6151                                          /*FIXME:*/T->getTypeLoc().getEndLoc(),
6152                                                    E->getRParenLoc());
6153}
6154
6155template<typename Derived>
6156ExprResult
6157TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
6158  // Transform the type that we're allocating
6159  TypeSourceInfo *AllocTypeInfo
6160    = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
6161  if (!AllocTypeInfo)
6162    return ExprError();
6163
6164  // Transform the size of the array we're allocating (if any).
6165  ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
6166  if (ArraySize.isInvalid())
6167    return ExprError();
6168
6169  // Transform the placement arguments (if any).
6170  bool ArgumentChanged = false;
6171  ASTOwningVector<Expr*> PlacementArgs(SemaRef);
6172  if (getDerived().TransformExprs(E->getPlacementArgs(),
6173                                  E->getNumPlacementArgs(), true,
6174                                  PlacementArgs, &ArgumentChanged))
6175    return ExprError();
6176
6177  // transform the constructor arguments (if any).
6178  ASTOwningVector<Expr*> ConstructorArgs(SemaRef);
6179  if (TransformExprs(E->getConstructorArgs(), E->getNumConstructorArgs(), true,
6180                     ConstructorArgs, &ArgumentChanged))
6181    return ExprError();
6182
6183  // Transform constructor, new operator, and delete operator.
6184  CXXConstructorDecl *Constructor = 0;
6185  if (E->getConstructor()) {
6186    Constructor = cast_or_null<CXXConstructorDecl>(
6187                                   getDerived().TransformDecl(E->getLocStart(),
6188                                                         E->getConstructor()));
6189    if (!Constructor)
6190      return ExprError();
6191  }
6192
6193  FunctionDecl *OperatorNew = 0;
6194  if (E->getOperatorNew()) {
6195    OperatorNew = cast_or_null<FunctionDecl>(
6196                                 getDerived().TransformDecl(E->getLocStart(),
6197                                                         E->getOperatorNew()));
6198    if (!OperatorNew)
6199      return ExprError();
6200  }
6201
6202  FunctionDecl *OperatorDelete = 0;
6203  if (E->getOperatorDelete()) {
6204    OperatorDelete = cast_or_null<FunctionDecl>(
6205                                   getDerived().TransformDecl(E->getLocStart(),
6206                                                       E->getOperatorDelete()));
6207    if (!OperatorDelete)
6208      return ExprError();
6209  }
6210
6211  if (!getDerived().AlwaysRebuild() &&
6212      AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
6213      ArraySize.get() == E->getArraySize() &&
6214      Constructor == E->getConstructor() &&
6215      OperatorNew == E->getOperatorNew() &&
6216      OperatorDelete == E->getOperatorDelete() &&
6217      !ArgumentChanged) {
6218    // Mark any declarations we need as referenced.
6219    // FIXME: instantiation-specific.
6220    if (Constructor)
6221      SemaRef.MarkDeclarationReferenced(E->getLocStart(), Constructor);
6222    if (OperatorNew)
6223      SemaRef.MarkDeclarationReferenced(E->getLocStart(), OperatorNew);
6224    if (OperatorDelete)
6225      SemaRef.MarkDeclarationReferenced(E->getLocStart(), OperatorDelete);
6226    return SemaRef.Owned(E);
6227  }
6228
6229  QualType AllocType = AllocTypeInfo->getType();
6230  if (!ArraySize.get()) {
6231    // If no array size was specified, but the new expression was
6232    // instantiated with an array type (e.g., "new T" where T is
6233    // instantiated with "int[4]"), extract the outer bound from the
6234    // array type as our array size. We do this with constant and
6235    // dependently-sized array types.
6236    const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
6237    if (!ArrayT) {
6238      // Do nothing
6239    } else if (const ConstantArrayType *ConsArrayT
6240                                     = dyn_cast<ConstantArrayType>(ArrayT)) {
6241      ArraySize
6242        = SemaRef.Owned(IntegerLiteral::Create(SemaRef.Context,
6243                                               ConsArrayT->getSize(),
6244                                               SemaRef.Context.getSizeType(),
6245                                               /*FIXME:*/E->getLocStart()));
6246      AllocType = ConsArrayT->getElementType();
6247    } else if (const DependentSizedArrayType *DepArrayT
6248                              = dyn_cast<DependentSizedArrayType>(ArrayT)) {
6249      if (DepArrayT->getSizeExpr()) {
6250        ArraySize = SemaRef.Owned(DepArrayT->getSizeExpr());
6251        AllocType = DepArrayT->getElementType();
6252      }
6253    }
6254  }
6255
6256  return getDerived().RebuildCXXNewExpr(E->getLocStart(),
6257                                        E->isGlobalNew(),
6258                                        /*FIXME:*/E->getLocStart(),
6259                                        move_arg(PlacementArgs),
6260                                        /*FIXME:*/E->getLocStart(),
6261                                        E->getTypeIdParens(),
6262                                        AllocType,
6263                                        AllocTypeInfo,
6264                                        ArraySize.get(),
6265                                        /*FIXME:*/E->getLocStart(),
6266                                        move_arg(ConstructorArgs),
6267                                        E->getLocEnd());
6268}
6269
6270template<typename Derived>
6271ExprResult
6272TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
6273  ExprResult Operand = getDerived().TransformExpr(E->getArgument());
6274  if (Operand.isInvalid())
6275    return ExprError();
6276
6277  // Transform the delete operator, if known.
6278  FunctionDecl *OperatorDelete = 0;
6279  if (E->getOperatorDelete()) {
6280    OperatorDelete = cast_or_null<FunctionDecl>(
6281                                   getDerived().TransformDecl(E->getLocStart(),
6282                                                       E->getOperatorDelete()));
6283    if (!OperatorDelete)
6284      return ExprError();
6285  }
6286
6287  if (!getDerived().AlwaysRebuild() &&
6288      Operand.get() == E->getArgument() &&
6289      OperatorDelete == E->getOperatorDelete()) {
6290    // Mark any declarations we need as referenced.
6291    // FIXME: instantiation-specific.
6292    if (OperatorDelete)
6293      SemaRef.MarkDeclarationReferenced(E->getLocStart(), OperatorDelete);
6294
6295    if (!E->getArgument()->isTypeDependent()) {
6296      QualType Destroyed = SemaRef.Context.getBaseElementType(
6297                                                         E->getDestroyedType());
6298      if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
6299        CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
6300        SemaRef.MarkDeclarationReferenced(E->getLocStart(),
6301                                          SemaRef.LookupDestructor(Record));
6302      }
6303    }
6304
6305    return SemaRef.Owned(E);
6306  }
6307
6308  return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
6309                                           E->isGlobalDelete(),
6310                                           E->isArrayForm(),
6311                                           Operand.get());
6312}
6313
6314template<typename Derived>
6315ExprResult
6316TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
6317                                                     CXXPseudoDestructorExpr *E) {
6318  ExprResult Base = getDerived().TransformExpr(E->getBase());
6319  if (Base.isInvalid())
6320    return ExprError();
6321
6322  ParsedType ObjectTypePtr;
6323  bool MayBePseudoDestructor = false;
6324  Base = SemaRef.ActOnStartCXXMemberReference(0, Base.get(),
6325                                              E->getOperatorLoc(),
6326                                        E->isArrow()? tok::arrow : tok::period,
6327                                              ObjectTypePtr,
6328                                              MayBePseudoDestructor);
6329  if (Base.isInvalid())
6330    return ExprError();
6331
6332  QualType ObjectType = ObjectTypePtr.get();
6333  NestedNameSpecifier *Qualifier = E->getQualifier();
6334  if (Qualifier) {
6335    Qualifier
6336      = getDerived().TransformNestedNameSpecifier(E->getQualifier(),
6337                                                  E->getQualifierRange(),
6338                                                  ObjectType);
6339    if (!Qualifier)
6340      return ExprError();
6341  }
6342
6343  PseudoDestructorTypeStorage Destroyed;
6344  if (E->getDestroyedTypeInfo()) {
6345    TypeSourceInfo *DestroyedTypeInfo
6346      = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
6347                                                ObjectType, 0, Qualifier);
6348    if (!DestroyedTypeInfo)
6349      return ExprError();
6350    Destroyed = DestroyedTypeInfo;
6351  } else if (ObjectType->isDependentType()) {
6352    // We aren't likely to be able to resolve the identifier down to a type
6353    // now anyway, so just retain the identifier.
6354    Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
6355                                            E->getDestroyedTypeLoc());
6356  } else {
6357    // Look for a destructor known with the given name.
6358    CXXScopeSpec SS;
6359    if (Qualifier) {
6360      SS.setScopeRep(Qualifier);
6361      SS.setRange(E->getQualifierRange());
6362    }
6363
6364    ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
6365                                              *E->getDestroyedTypeIdentifier(),
6366                                                E->getDestroyedTypeLoc(),
6367                                                /*Scope=*/0,
6368                                                SS, ObjectTypePtr,
6369                                                false);
6370    if (!T)
6371      return ExprError();
6372
6373    Destroyed
6374      = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
6375                                                 E->getDestroyedTypeLoc());
6376  }
6377
6378  TypeSourceInfo *ScopeTypeInfo = 0;
6379  if (E->getScopeTypeInfo()) {
6380    ScopeTypeInfo = getDerived().TransformType(E->getScopeTypeInfo());
6381    if (!ScopeTypeInfo)
6382      return ExprError();
6383  }
6384
6385  return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
6386                                                     E->getOperatorLoc(),
6387                                                     E->isArrow(),
6388                                                     Qualifier,
6389                                                     E->getQualifierRange(),
6390                                                     ScopeTypeInfo,
6391                                                     E->getColonColonLoc(),
6392                                                     E->getTildeLoc(),
6393                                                     Destroyed);
6394}
6395
6396template<typename Derived>
6397ExprResult
6398TreeTransform<Derived>::TransformUnresolvedLookupExpr(
6399                                                  UnresolvedLookupExpr *Old) {
6400  TemporaryBase Rebase(*this, Old->getNameLoc(), DeclarationName());
6401
6402  LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
6403                 Sema::LookupOrdinaryName);
6404
6405  // Transform all the decls.
6406  for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
6407         E = Old->decls_end(); I != E; ++I) {
6408    NamedDecl *InstD = static_cast<NamedDecl*>(
6409                                 getDerived().TransformDecl(Old->getNameLoc(),
6410                                                            *I));
6411    if (!InstD) {
6412      // Silently ignore these if a UsingShadowDecl instantiated to nothing.
6413      // This can happen because of dependent hiding.
6414      if (isa<UsingShadowDecl>(*I))
6415        continue;
6416      else
6417        return ExprError();
6418    }
6419
6420    // Expand using declarations.
6421    if (isa<UsingDecl>(InstD)) {
6422      UsingDecl *UD = cast<UsingDecl>(InstD);
6423      for (UsingDecl::shadow_iterator I = UD->shadow_begin(),
6424             E = UD->shadow_end(); I != E; ++I)
6425        R.addDecl(*I);
6426      continue;
6427    }
6428
6429    R.addDecl(InstD);
6430  }
6431
6432  // Resolve a kind, but don't do any further analysis.  If it's
6433  // ambiguous, the callee needs to deal with it.
6434  R.resolveKind();
6435
6436  // Rebuild the nested-name qualifier, if present.
6437  CXXScopeSpec SS;
6438  NestedNameSpecifier *Qualifier = 0;
6439  if (Old->getQualifier()) {
6440    Qualifier = getDerived().TransformNestedNameSpecifier(Old->getQualifier(),
6441                                                    Old->getQualifierRange());
6442    if (!Qualifier)
6443      return ExprError();
6444
6445    SS.setScopeRep(Qualifier);
6446    SS.setRange(Old->getQualifierRange());
6447  }
6448
6449  if (Old->getNamingClass()) {
6450    CXXRecordDecl *NamingClass
6451      = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
6452                                                            Old->getNameLoc(),
6453                                                        Old->getNamingClass()));
6454    if (!NamingClass)
6455      return ExprError();
6456
6457    R.setNamingClass(NamingClass);
6458  }
6459
6460  // If we have no template arguments, it's a normal declaration name.
6461  if (!Old->hasExplicitTemplateArgs())
6462    return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
6463
6464  // If we have template arguments, rebuild them, then rebuild the
6465  // templateid expression.
6466  TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
6467  if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
6468                                              Old->getNumTemplateArgs(),
6469                                              TransArgs))
6470    return ExprError();
6471
6472  return getDerived().RebuildTemplateIdExpr(SS, R, Old->requiresADL(),
6473                                            TransArgs);
6474}
6475
6476template<typename Derived>
6477ExprResult
6478TreeTransform<Derived>::TransformUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
6479  TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
6480  if (!T)
6481    return ExprError();
6482
6483  if (!getDerived().AlwaysRebuild() &&
6484      T == E->getQueriedTypeSourceInfo())
6485    return SemaRef.Owned(E);
6486
6487  return getDerived().RebuildUnaryTypeTrait(E->getTrait(),
6488                                            E->getLocStart(),
6489                                            T,
6490                                            E->getLocEnd());
6491}
6492
6493template<typename Derived>
6494ExprResult
6495TreeTransform<Derived>::TransformBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
6496  TypeSourceInfo *LhsT = getDerived().TransformType(E->getLhsTypeSourceInfo());
6497  if (!LhsT)
6498    return ExprError();
6499
6500  TypeSourceInfo *RhsT = getDerived().TransformType(E->getRhsTypeSourceInfo());
6501  if (!RhsT)
6502    return ExprError();
6503
6504  if (!getDerived().AlwaysRebuild() &&
6505      LhsT == E->getLhsTypeSourceInfo() && RhsT == E->getRhsTypeSourceInfo())
6506    return SemaRef.Owned(E);
6507
6508  return getDerived().RebuildBinaryTypeTrait(E->getTrait(),
6509                                            E->getLocStart(),
6510                                            LhsT, RhsT,
6511                                            E->getLocEnd());
6512}
6513
6514template<typename Derived>
6515ExprResult
6516TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
6517                                               DependentScopeDeclRefExpr *E) {
6518  NestedNameSpecifier *NNS
6519    = getDerived().TransformNestedNameSpecifier(E->getQualifier(),
6520                                                E->getQualifierRange());
6521  if (!NNS)
6522    return ExprError();
6523
6524  // TODO: If this is a conversion-function-id, verify that the
6525  // destination type name (if present) resolves the same way after
6526  // instantiation as it did in the local scope.
6527
6528  DeclarationNameInfo NameInfo
6529    = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
6530  if (!NameInfo.getName())
6531    return ExprError();
6532
6533  if (!E->hasExplicitTemplateArgs()) {
6534    if (!getDerived().AlwaysRebuild() &&
6535        NNS == E->getQualifier() &&
6536        // Note: it is sufficient to compare the Name component of NameInfo:
6537        // if name has not changed, DNLoc has not changed either.
6538        NameInfo.getName() == E->getDeclName())
6539      return SemaRef.Owned(E);
6540
6541    return getDerived().RebuildDependentScopeDeclRefExpr(NNS,
6542                                                         E->getQualifierRange(),
6543                                                         NameInfo,
6544                                                         /*TemplateArgs*/ 0);
6545  }
6546
6547  TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
6548  if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
6549                                              E->getNumTemplateArgs(),
6550                                              TransArgs))
6551    return ExprError();
6552
6553  return getDerived().RebuildDependentScopeDeclRefExpr(NNS,
6554                                                       E->getQualifierRange(),
6555                                                       NameInfo,
6556                                                       &TransArgs);
6557}
6558
6559template<typename Derived>
6560ExprResult
6561TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
6562  // CXXConstructExprs are always implicit, so when we have a
6563  // 1-argument construction we just transform that argument.
6564  if (E->getNumArgs() == 1 ||
6565      (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1))))
6566    return getDerived().TransformExpr(E->getArg(0));
6567
6568  TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
6569
6570  QualType T = getDerived().TransformType(E->getType());
6571  if (T.isNull())
6572    return ExprError();
6573
6574  CXXConstructorDecl *Constructor
6575    = cast_or_null<CXXConstructorDecl>(
6576                                getDerived().TransformDecl(E->getLocStart(),
6577                                                         E->getConstructor()));
6578  if (!Constructor)
6579    return ExprError();
6580
6581  bool ArgumentChanged = false;
6582  ASTOwningVector<Expr*> Args(SemaRef);
6583  if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
6584                                  &ArgumentChanged))
6585    return ExprError();
6586
6587  if (!getDerived().AlwaysRebuild() &&
6588      T == E->getType() &&
6589      Constructor == E->getConstructor() &&
6590      !ArgumentChanged) {
6591    // Mark the constructor as referenced.
6592    // FIXME: Instantiation-specific
6593    SemaRef.MarkDeclarationReferenced(E->getLocStart(), Constructor);
6594    return SemaRef.Owned(E);
6595  }
6596
6597  return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
6598                                              Constructor, E->isElidable(),
6599                                              move_arg(Args),
6600                                              E->requiresZeroInitialization(),
6601                                              E->getConstructionKind(),
6602                                              E->getParenRange());
6603}
6604
6605/// \brief Transform a C++ temporary-binding expression.
6606///
6607/// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
6608/// transform the subexpression and return that.
6609template<typename Derived>
6610ExprResult
6611TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
6612  return getDerived().TransformExpr(E->getSubExpr());
6613}
6614
6615/// \brief Transform a C++ expression that contains cleanups that should
6616/// be run after the expression is evaluated.
6617///
6618/// Since ExprWithCleanups nodes are implicitly generated, we
6619/// just transform the subexpression and return that.
6620template<typename Derived>
6621ExprResult
6622TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
6623  return getDerived().TransformExpr(E->getSubExpr());
6624}
6625
6626template<typename Derived>
6627ExprResult
6628TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
6629                                                    CXXTemporaryObjectExpr *E) {
6630  TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
6631  if (!T)
6632    return ExprError();
6633
6634  CXXConstructorDecl *Constructor
6635    = cast_or_null<CXXConstructorDecl>(
6636                                  getDerived().TransformDecl(E->getLocStart(),
6637                                                         E->getConstructor()));
6638  if (!Constructor)
6639    return ExprError();
6640
6641  bool ArgumentChanged = false;
6642  ASTOwningVector<Expr*> Args(SemaRef);
6643  Args.reserve(E->getNumArgs());
6644  if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
6645                     &ArgumentChanged))
6646    return ExprError();
6647
6648  if (!getDerived().AlwaysRebuild() &&
6649      T == E->getTypeSourceInfo() &&
6650      Constructor == E->getConstructor() &&
6651      !ArgumentChanged) {
6652    // FIXME: Instantiation-specific
6653    SemaRef.MarkDeclarationReferenced(E->getLocStart(), Constructor);
6654    return SemaRef.MaybeBindToTemporary(E);
6655  }
6656
6657  return getDerived().RebuildCXXTemporaryObjectExpr(T,
6658                                          /*FIXME:*/T->getTypeLoc().getEndLoc(),
6659                                                    move_arg(Args),
6660                                                    E->getLocEnd());
6661}
6662
6663template<typename Derived>
6664ExprResult
6665TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
6666                                                  CXXUnresolvedConstructExpr *E) {
6667  TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
6668  if (!T)
6669    return ExprError();
6670
6671  bool ArgumentChanged = false;
6672  ASTOwningVector<Expr*> Args(SemaRef);
6673  Args.reserve(E->arg_size());
6674  if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
6675                                  &ArgumentChanged))
6676    return ExprError();
6677
6678  if (!getDerived().AlwaysRebuild() &&
6679      T == E->getTypeSourceInfo() &&
6680      !ArgumentChanged)
6681    return SemaRef.Owned(E);
6682
6683  // FIXME: we're faking the locations of the commas
6684  return getDerived().RebuildCXXUnresolvedConstructExpr(T,
6685                                                        E->getLParenLoc(),
6686                                                        move_arg(Args),
6687                                                        E->getRParenLoc());
6688}
6689
6690template<typename Derived>
6691ExprResult
6692TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
6693                                             CXXDependentScopeMemberExpr *E) {
6694  // Transform the base of the expression.
6695  ExprResult Base((Expr*) 0);
6696  Expr *OldBase;
6697  QualType BaseType;
6698  QualType ObjectType;
6699  if (!E->isImplicitAccess()) {
6700    OldBase = E->getBase();
6701    Base = getDerived().TransformExpr(OldBase);
6702    if (Base.isInvalid())
6703      return ExprError();
6704
6705    // Start the member reference and compute the object's type.
6706    ParsedType ObjectTy;
6707    bool MayBePseudoDestructor = false;
6708    Base = SemaRef.ActOnStartCXXMemberReference(0, Base.get(),
6709                                                E->getOperatorLoc(),
6710                                      E->isArrow()? tok::arrow : tok::period,
6711                                                ObjectTy,
6712                                                MayBePseudoDestructor);
6713    if (Base.isInvalid())
6714      return ExprError();
6715
6716    ObjectType = ObjectTy.get();
6717    BaseType = ((Expr*) Base.get())->getType();
6718  } else {
6719    OldBase = 0;
6720    BaseType = getDerived().TransformType(E->getBaseType());
6721    ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
6722  }
6723
6724  // Transform the first part of the nested-name-specifier that qualifies
6725  // the member name.
6726  NamedDecl *FirstQualifierInScope
6727    = getDerived().TransformFirstQualifierInScope(
6728                                          E->getFirstQualifierFoundInScope(),
6729                                          E->getQualifierRange().getBegin());
6730
6731  NestedNameSpecifier *Qualifier = 0;
6732  if (E->getQualifier()) {
6733    Qualifier = getDerived().TransformNestedNameSpecifier(E->getQualifier(),
6734                                                      E->getQualifierRange(),
6735                                                      ObjectType,
6736                                                      FirstQualifierInScope);
6737    if (!Qualifier)
6738      return ExprError();
6739  }
6740
6741  // TODO: If this is a conversion-function-id, verify that the
6742  // destination type name (if present) resolves the same way after
6743  // instantiation as it did in the local scope.
6744
6745  DeclarationNameInfo NameInfo
6746    = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
6747  if (!NameInfo.getName())
6748    return ExprError();
6749
6750  if (!E->hasExplicitTemplateArgs()) {
6751    // This is a reference to a member without an explicitly-specified
6752    // template argument list. Optimize for this common case.
6753    if (!getDerived().AlwaysRebuild() &&
6754        Base.get() == OldBase &&
6755        BaseType == E->getBaseType() &&
6756        Qualifier == E->getQualifier() &&
6757        NameInfo.getName() == E->getMember() &&
6758        FirstQualifierInScope == E->getFirstQualifierFoundInScope())
6759      return SemaRef.Owned(E);
6760
6761    return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
6762                                                       BaseType,
6763                                                       E->isArrow(),
6764                                                       E->getOperatorLoc(),
6765                                                       Qualifier,
6766                                                       E->getQualifierRange(),
6767                                                       FirstQualifierInScope,
6768                                                       NameInfo,
6769                                                       /*TemplateArgs*/ 0);
6770  }
6771
6772  TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
6773  if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
6774                                              E->getNumTemplateArgs(),
6775                                              TransArgs))
6776    return ExprError();
6777
6778  return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
6779                                                     BaseType,
6780                                                     E->isArrow(),
6781                                                     E->getOperatorLoc(),
6782                                                     Qualifier,
6783                                                     E->getQualifierRange(),
6784                                                     FirstQualifierInScope,
6785                                                     NameInfo,
6786                                                     &TransArgs);
6787}
6788
6789template<typename Derived>
6790ExprResult
6791TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
6792  // Transform the base of the expression.
6793  ExprResult Base((Expr*) 0);
6794  QualType BaseType;
6795  if (!Old->isImplicitAccess()) {
6796    Base = getDerived().TransformExpr(Old->getBase());
6797    if (Base.isInvalid())
6798      return ExprError();
6799    BaseType = ((Expr*) Base.get())->getType();
6800  } else {
6801    BaseType = getDerived().TransformType(Old->getBaseType());
6802  }
6803
6804  NestedNameSpecifier *Qualifier = 0;
6805  if (Old->getQualifier()) {
6806    Qualifier
6807      = getDerived().TransformNestedNameSpecifier(Old->getQualifier(),
6808                                                  Old->getQualifierRange());
6809    if (Qualifier == 0)
6810      return ExprError();
6811  }
6812
6813  LookupResult R(SemaRef, Old->getMemberNameInfo(),
6814                 Sema::LookupOrdinaryName);
6815
6816  // Transform all the decls.
6817  for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
6818         E = Old->decls_end(); I != E; ++I) {
6819    NamedDecl *InstD = static_cast<NamedDecl*>(
6820                                getDerived().TransformDecl(Old->getMemberLoc(),
6821                                                           *I));
6822    if (!InstD) {
6823      // Silently ignore these if a UsingShadowDecl instantiated to nothing.
6824      // This can happen because of dependent hiding.
6825      if (isa<UsingShadowDecl>(*I))
6826        continue;
6827      else
6828        return ExprError();
6829    }
6830
6831    // Expand using declarations.
6832    if (isa<UsingDecl>(InstD)) {
6833      UsingDecl *UD = cast<UsingDecl>(InstD);
6834      for (UsingDecl::shadow_iterator I = UD->shadow_begin(),
6835             E = UD->shadow_end(); I != E; ++I)
6836        R.addDecl(*I);
6837      continue;
6838    }
6839
6840    R.addDecl(InstD);
6841  }
6842
6843  R.resolveKind();
6844
6845  // Determine the naming class.
6846  if (Old->getNamingClass()) {
6847    CXXRecordDecl *NamingClass
6848      = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
6849                                                          Old->getMemberLoc(),
6850                                                        Old->getNamingClass()));
6851    if (!NamingClass)
6852      return ExprError();
6853
6854    R.setNamingClass(NamingClass);
6855  }
6856
6857  TemplateArgumentListInfo TransArgs;
6858  if (Old->hasExplicitTemplateArgs()) {
6859    TransArgs.setLAngleLoc(Old->getLAngleLoc());
6860    TransArgs.setRAngleLoc(Old->getRAngleLoc());
6861    if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
6862                                                Old->getNumTemplateArgs(),
6863                                                TransArgs))
6864      return ExprError();
6865  }
6866
6867  // FIXME: to do this check properly, we will need to preserve the
6868  // first-qualifier-in-scope here, just in case we had a dependent
6869  // base (and therefore couldn't do the check) and a
6870  // nested-name-qualifier (and therefore could do the lookup).
6871  NamedDecl *FirstQualifierInScope = 0;
6872
6873  return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
6874                                                  BaseType,
6875                                                  Old->getOperatorLoc(),
6876                                                  Old->isArrow(),
6877                                                  Qualifier,
6878                                                  Old->getQualifierRange(),
6879                                                  FirstQualifierInScope,
6880                                                  R,
6881                                              (Old->hasExplicitTemplateArgs()
6882                                                  ? &TransArgs : 0));
6883}
6884
6885template<typename Derived>
6886ExprResult
6887TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
6888  ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
6889  if (SubExpr.isInvalid())
6890    return ExprError();
6891
6892  if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
6893    return SemaRef.Owned(E);
6894
6895  return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
6896}
6897
6898template<typename Derived>
6899ExprResult
6900TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
6901  ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
6902  if (Pattern.isInvalid())
6903    return ExprError();
6904
6905  if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
6906    return SemaRef.Owned(E);
6907
6908  return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
6909                                           E->getNumExpansions());
6910}
6911
6912template<typename Derived>
6913ExprResult
6914TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
6915  // If E is not value-dependent, then nothing will change when we transform it.
6916  // Note: This is an instantiation-centric view.
6917  if (!E->isValueDependent())
6918    return SemaRef.Owned(E);
6919
6920  // Note: None of the implementations of TryExpandParameterPacks can ever
6921  // produce a diagnostic when given only a single unexpanded parameter pack,
6922  // so
6923  UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
6924  bool ShouldExpand = false;
6925  bool RetainExpansion = false;
6926  llvm::Optional<unsigned> NumExpansions;
6927  if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
6928                                           &Unexpanded, 1,
6929                                           ShouldExpand, RetainExpansion,
6930                                           NumExpansions))
6931    return ExprError();
6932
6933  if (!ShouldExpand || RetainExpansion)
6934    return SemaRef.Owned(E);
6935
6936  // We now know the length of the parameter pack, so build a new expression
6937  // that stores that length.
6938  return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
6939                                            E->getPackLoc(), E->getRParenLoc(),
6940                                            *NumExpansions);
6941}
6942
6943template<typename Derived>
6944ExprResult
6945TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
6946                                          SubstNonTypeTemplateParmPackExpr *E) {
6947  // Default behavior is to do nothing with this transformation.
6948  return SemaRef.Owned(E);
6949}
6950
6951template<typename Derived>
6952ExprResult
6953TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
6954  return SemaRef.Owned(E);
6955}
6956
6957template<typename Derived>
6958ExprResult
6959TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
6960  TypeSourceInfo *EncodedTypeInfo
6961    = getDerived().TransformType(E->getEncodedTypeSourceInfo());
6962  if (!EncodedTypeInfo)
6963    return ExprError();
6964
6965  if (!getDerived().AlwaysRebuild() &&
6966      EncodedTypeInfo == E->getEncodedTypeSourceInfo())
6967    return SemaRef.Owned(E);
6968
6969  return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
6970                                            EncodedTypeInfo,
6971                                            E->getRParenLoc());
6972}
6973
6974template<typename Derived>
6975ExprResult
6976TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
6977  // Transform arguments.
6978  bool ArgChanged = false;
6979  ASTOwningVector<Expr*> Args(SemaRef);
6980  Args.reserve(E->getNumArgs());
6981  if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
6982                                  &ArgChanged))
6983    return ExprError();
6984
6985  if (E->getReceiverKind() == ObjCMessageExpr::Class) {
6986    // Class message: transform the receiver type.
6987    TypeSourceInfo *ReceiverTypeInfo
6988      = getDerived().TransformType(E->getClassReceiverTypeInfo());
6989    if (!ReceiverTypeInfo)
6990      return ExprError();
6991
6992    // If nothing changed, just retain the existing message send.
6993    if (!getDerived().AlwaysRebuild() &&
6994        ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
6995      return SemaRef.Owned(E);
6996
6997    // Build a new class message send.
6998    return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
6999                                               E->getSelector(),
7000                                               E->getSelectorLoc(),
7001                                               E->getMethodDecl(),
7002                                               E->getLeftLoc(),
7003                                               move_arg(Args),
7004                                               E->getRightLoc());
7005  }
7006
7007  // Instance message: transform the receiver
7008  assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
7009         "Only class and instance messages may be instantiated");
7010  ExprResult Receiver
7011    = getDerived().TransformExpr(E->getInstanceReceiver());
7012  if (Receiver.isInvalid())
7013    return ExprError();
7014
7015  // If nothing changed, just retain the existing message send.
7016  if (!getDerived().AlwaysRebuild() &&
7017      Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
7018    return SemaRef.Owned(E);
7019
7020  // Build a new instance message send.
7021  return getDerived().RebuildObjCMessageExpr(Receiver.get(),
7022                                             E->getSelector(),
7023                                             E->getSelectorLoc(),
7024                                             E->getMethodDecl(),
7025                                             E->getLeftLoc(),
7026                                             move_arg(Args),
7027                                             E->getRightLoc());
7028}
7029
7030template<typename Derived>
7031ExprResult
7032TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
7033  return SemaRef.Owned(E);
7034}
7035
7036template<typename Derived>
7037ExprResult
7038TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
7039  return SemaRef.Owned(E);
7040}
7041
7042template<typename Derived>
7043ExprResult
7044TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
7045  // Transform the base expression.
7046  ExprResult Base = getDerived().TransformExpr(E->getBase());
7047  if (Base.isInvalid())
7048    return ExprError();
7049
7050  // We don't need to transform the ivar; it will never change.
7051
7052  // If nothing changed, just retain the existing expression.
7053  if (!getDerived().AlwaysRebuild() &&
7054      Base.get() == E->getBase())
7055    return SemaRef.Owned(E);
7056
7057  return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
7058                                             E->getLocation(),
7059                                             E->isArrow(), E->isFreeIvar());
7060}
7061
7062template<typename Derived>
7063ExprResult
7064TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
7065  // 'super' and types never change. Property never changes. Just
7066  // retain the existing expression.
7067  if (!E->isObjectReceiver())
7068    return SemaRef.Owned(E);
7069
7070  // Transform the base expression.
7071  ExprResult Base = getDerived().TransformExpr(E->getBase());
7072  if (Base.isInvalid())
7073    return ExprError();
7074
7075  // We don't need to transform the property; it will never change.
7076
7077  // If nothing changed, just retain the existing expression.
7078  if (!getDerived().AlwaysRebuild() &&
7079      Base.get() == E->getBase())
7080    return SemaRef.Owned(E);
7081
7082  if (E->isExplicitProperty())
7083    return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
7084                                                   E->getExplicitProperty(),
7085                                                   E->getLocation());
7086
7087  return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
7088                                                 E->getType(),
7089                                                 E->getImplicitPropertyGetter(),
7090                                                 E->getImplicitPropertySetter(),
7091                                                 E->getLocation());
7092}
7093
7094template<typename Derived>
7095ExprResult
7096TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
7097  // Transform the base expression.
7098  ExprResult Base = getDerived().TransformExpr(E->getBase());
7099  if (Base.isInvalid())
7100    return ExprError();
7101
7102  // If nothing changed, just retain the existing expression.
7103  if (!getDerived().AlwaysRebuild() &&
7104      Base.get() == E->getBase())
7105    return SemaRef.Owned(E);
7106
7107  return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
7108                                         E->isArrow());
7109}
7110
7111template<typename Derived>
7112ExprResult
7113TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
7114  bool ArgumentChanged = false;
7115  ASTOwningVector<Expr*> SubExprs(SemaRef);
7116  SubExprs.reserve(E->getNumSubExprs());
7117  if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
7118                                  SubExprs, &ArgumentChanged))
7119    return ExprError();
7120
7121  if (!getDerived().AlwaysRebuild() &&
7122      !ArgumentChanged)
7123    return SemaRef.Owned(E);
7124
7125  return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
7126                                               move_arg(SubExprs),
7127                                               E->getRParenLoc());
7128}
7129
7130template<typename Derived>
7131ExprResult
7132TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
7133  BlockDecl *oldBlock = E->getBlockDecl();
7134
7135  SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/0);
7136  BlockScopeInfo *blockScope = SemaRef.getCurBlock();
7137
7138  blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
7139  llvm::SmallVector<ParmVarDecl*, 4> params;
7140  llvm::SmallVector<QualType, 4> paramTypes;
7141
7142  // Parameter substitution.
7143  if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
7144                                               oldBlock->param_begin(),
7145                                               oldBlock->param_size(),
7146                                               0, paramTypes, &params))
7147    return true;
7148
7149  const FunctionType *exprFunctionType = E->getFunctionType();
7150  QualType exprResultType = exprFunctionType->getResultType();
7151  if (!exprResultType.isNull()) {
7152    if (!exprResultType->isDependentType())
7153      blockScope->ReturnType = exprResultType;
7154    else if (exprResultType != getSema().Context.DependentTy)
7155      blockScope->ReturnType = getDerived().TransformType(exprResultType);
7156  }
7157
7158  // If the return type has not been determined yet, leave it as a dependent
7159  // type; it'll get set when we process the body.
7160  if (blockScope->ReturnType.isNull())
7161    blockScope->ReturnType = getSema().Context.DependentTy;
7162
7163  // Don't allow returning a objc interface by value.
7164  if (blockScope->ReturnType->isObjCObjectType()) {
7165    getSema().Diag(E->getCaretLocation(),
7166                   diag::err_object_cannot_be_passed_returned_by_value)
7167      << 0 << blockScope->ReturnType;
7168    return ExprError();
7169  }
7170
7171  QualType functionType = getDerived().RebuildFunctionProtoType(
7172                                                        blockScope->ReturnType,
7173                                                        paramTypes.data(),
7174                                                        paramTypes.size(),
7175                                                        oldBlock->isVariadic(),
7176                                                        0, RQ_None,
7177                                               exprFunctionType->getExtInfo());
7178  blockScope->FunctionType = functionType;
7179
7180  // Set the parameters on the block decl.
7181  if (!params.empty())
7182    blockScope->TheDecl->setParams(params.data(), params.size());
7183
7184  // If the return type wasn't explicitly set, it will have been marked as a
7185  // dependent type (DependentTy); clear out the return type setting so
7186  // we will deduce the return type when type-checking the block's body.
7187  if (blockScope->ReturnType == getSema().Context.DependentTy)
7188    blockScope->ReturnType = QualType();
7189
7190  // Transform the body
7191  StmtResult body = getDerived().TransformStmt(E->getBody());
7192  if (body.isInvalid())
7193    return ExprError();
7194
7195#ifndef NDEBUG
7196  // In builds with assertions, make sure that we captured everything we
7197  // captured before.
7198
7199  if (oldBlock->capturesCXXThis()) assert(blockScope->CapturesCXXThis);
7200
7201  for (BlockDecl::capture_iterator i = oldBlock->capture_begin(),
7202         e = oldBlock->capture_end(); i != e; ++i) {
7203    VarDecl *oldCapture = i->getVariable();
7204
7205    // Ignore parameter packs.
7206    if (isa<ParmVarDecl>(oldCapture) &&
7207        cast<ParmVarDecl>(oldCapture)->isParameterPack())
7208      continue;
7209
7210    VarDecl *newCapture =
7211      cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
7212                                               oldCapture));
7213    assert(blockScope->CaptureMap.count(newCapture));
7214  }
7215#endif
7216
7217  return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
7218                                    /*Scope=*/0);
7219}
7220
7221template<typename Derived>
7222ExprResult
7223TreeTransform<Derived>::TransformBlockDeclRefExpr(BlockDeclRefExpr *E) {
7224  NestedNameSpecifier *Qualifier = 0;
7225
7226  ValueDecl *ND
7227  = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
7228                                                       E->getDecl()));
7229  if (!ND)
7230    return ExprError();
7231
7232  if (!getDerived().AlwaysRebuild() &&
7233      ND == E->getDecl()) {
7234    // Mark it referenced in the new context regardless.
7235    // FIXME: this is a bit instantiation-specific.
7236    SemaRef.MarkDeclarationReferenced(E->getLocation(), ND);
7237
7238    return SemaRef.Owned(E);
7239  }
7240
7241  DeclarationNameInfo NameInfo(E->getDecl()->getDeclName(), E->getLocation());
7242  return getDerived().RebuildDeclRefExpr(Qualifier, SourceLocation(),
7243                                         ND, NameInfo, 0);
7244}
7245
7246//===----------------------------------------------------------------------===//
7247// Type reconstruction
7248//===----------------------------------------------------------------------===//
7249
7250template<typename Derived>
7251QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
7252                                                    SourceLocation Star) {
7253  return SemaRef.BuildPointerType(PointeeType, Star,
7254                                  getDerived().getBaseEntity());
7255}
7256
7257template<typename Derived>
7258QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
7259                                                         SourceLocation Star) {
7260  return SemaRef.BuildBlockPointerType(PointeeType, Star,
7261                                       getDerived().getBaseEntity());
7262}
7263
7264template<typename Derived>
7265QualType
7266TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
7267                                             bool WrittenAsLValue,
7268                                             SourceLocation Sigil) {
7269  return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
7270                                    Sigil, getDerived().getBaseEntity());
7271}
7272
7273template<typename Derived>
7274QualType
7275TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
7276                                                 QualType ClassType,
7277                                                 SourceLocation Sigil) {
7278  return SemaRef.BuildMemberPointerType(PointeeType, ClassType,
7279                                        Sigil, getDerived().getBaseEntity());
7280}
7281
7282template<typename Derived>
7283QualType
7284TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
7285                                         ArrayType::ArraySizeModifier SizeMod,
7286                                         const llvm::APInt *Size,
7287                                         Expr *SizeExpr,
7288                                         unsigned IndexTypeQuals,
7289                                         SourceRange BracketsRange) {
7290  if (SizeExpr || !Size)
7291    return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
7292                                  IndexTypeQuals, BracketsRange,
7293                                  getDerived().getBaseEntity());
7294
7295  QualType Types[] = {
7296    SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
7297    SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
7298    SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
7299  };
7300  const unsigned NumTypes = sizeof(Types) / sizeof(QualType);
7301  QualType SizeType;
7302  for (unsigned I = 0; I != NumTypes; ++I)
7303    if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
7304      SizeType = Types[I];
7305      break;
7306    }
7307
7308  IntegerLiteral ArraySize(SemaRef.Context, *Size, SizeType,
7309                           /*FIXME*/BracketsRange.getBegin());
7310  return SemaRef.BuildArrayType(ElementType, SizeMod, &ArraySize,
7311                                IndexTypeQuals, BracketsRange,
7312                                getDerived().getBaseEntity());
7313}
7314
7315template<typename Derived>
7316QualType
7317TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
7318                                                 ArrayType::ArraySizeModifier SizeMod,
7319                                                 const llvm::APInt &Size,
7320                                                 unsigned IndexTypeQuals,
7321                                                 SourceRange BracketsRange) {
7322  return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, 0,
7323                                        IndexTypeQuals, BracketsRange);
7324}
7325
7326template<typename Derived>
7327QualType
7328TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
7329                                          ArrayType::ArraySizeModifier SizeMod,
7330                                                 unsigned IndexTypeQuals,
7331                                                   SourceRange BracketsRange) {
7332  return getDerived().RebuildArrayType(ElementType, SizeMod, 0, 0,
7333                                       IndexTypeQuals, BracketsRange);
7334}
7335
7336template<typename Derived>
7337QualType
7338TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
7339                                          ArrayType::ArraySizeModifier SizeMod,
7340                                                 Expr *SizeExpr,
7341                                                 unsigned IndexTypeQuals,
7342                                                 SourceRange BracketsRange) {
7343  return getDerived().RebuildArrayType(ElementType, SizeMod, 0,
7344                                       SizeExpr,
7345                                       IndexTypeQuals, BracketsRange);
7346}
7347
7348template<typename Derived>
7349QualType
7350TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
7351                                          ArrayType::ArraySizeModifier SizeMod,
7352                                                       Expr *SizeExpr,
7353                                                       unsigned IndexTypeQuals,
7354                                                   SourceRange BracketsRange) {
7355  return getDerived().RebuildArrayType(ElementType, SizeMod, 0,
7356                                       SizeExpr,
7357                                       IndexTypeQuals, BracketsRange);
7358}
7359
7360template<typename Derived>
7361QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
7362                                               unsigned NumElements,
7363                                               VectorType::VectorKind VecKind) {
7364  // FIXME: semantic checking!
7365  return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
7366}
7367
7368template<typename Derived>
7369QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
7370                                                      unsigned NumElements,
7371                                                 SourceLocation AttributeLoc) {
7372  llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
7373                          NumElements, true);
7374  IntegerLiteral *VectorSize
7375    = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
7376                             AttributeLoc);
7377  return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
7378}
7379
7380template<typename Derived>
7381QualType
7382TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
7383                                                           Expr *SizeExpr,
7384                                                  SourceLocation AttributeLoc) {
7385  return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
7386}
7387
7388template<typename Derived>
7389QualType TreeTransform<Derived>::RebuildFunctionProtoType(QualType T,
7390                                                          QualType *ParamTypes,
7391                                                        unsigned NumParamTypes,
7392                                                          bool Variadic,
7393                                                          unsigned Quals,
7394                                                  RefQualifierKind RefQualifier,
7395                                            const FunctionType::ExtInfo &Info) {
7396  return SemaRef.BuildFunctionType(T, ParamTypes, NumParamTypes, Variadic,
7397                                   Quals, RefQualifier,
7398                                   getDerived().getBaseLocation(),
7399                                   getDerived().getBaseEntity(),
7400                                   Info);
7401}
7402
7403template<typename Derived>
7404QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
7405  return SemaRef.Context.getFunctionNoProtoType(T);
7406}
7407
7408template<typename Derived>
7409QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
7410  assert(D && "no decl found");
7411  if (D->isInvalidDecl()) return QualType();
7412
7413  // FIXME: Doesn't account for ObjCInterfaceDecl!
7414  TypeDecl *Ty;
7415  if (isa<UsingDecl>(D)) {
7416    UsingDecl *Using = cast<UsingDecl>(D);
7417    assert(Using->isTypeName() &&
7418           "UnresolvedUsingTypenameDecl transformed to non-typename using");
7419
7420    // A valid resolved using typename decl points to exactly one type decl.
7421    assert(++Using->shadow_begin() == Using->shadow_end());
7422    Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
7423
7424  } else {
7425    assert(isa<UnresolvedUsingTypenameDecl>(D) &&
7426           "UnresolvedUsingTypenameDecl transformed to non-using decl");
7427    Ty = cast<UnresolvedUsingTypenameDecl>(D);
7428  }
7429
7430  return SemaRef.Context.getTypeDeclType(Ty);
7431}
7432
7433template<typename Derived>
7434QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
7435                                                       SourceLocation Loc) {
7436  return SemaRef.BuildTypeofExprType(E, Loc);
7437}
7438
7439template<typename Derived>
7440QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
7441  return SemaRef.Context.getTypeOfType(Underlying);
7442}
7443
7444template<typename Derived>
7445QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
7446                                                     SourceLocation Loc) {
7447  return SemaRef.BuildDecltypeType(E, Loc);
7448}
7449
7450template<typename Derived>
7451QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
7452                                                      TemplateName Template,
7453                                             SourceLocation TemplateNameLoc,
7454                               const TemplateArgumentListInfo &TemplateArgs) {
7455  return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7456}
7457
7458template<typename Derived>
7459NestedNameSpecifier *
7460TreeTransform<Derived>::RebuildNestedNameSpecifier(NestedNameSpecifier *Prefix,
7461                                                   SourceRange Range,
7462                                                   IdentifierInfo &II,
7463                                                   QualType ObjectType,
7464                                                   NamedDecl *FirstQualifierInScope) {
7465  CXXScopeSpec SS;
7466  // FIXME: The source location information is all wrong.
7467  SS.setRange(Range);
7468  SS.setScopeRep(Prefix);
7469  return static_cast<NestedNameSpecifier *>(
7470                    SemaRef.BuildCXXNestedNameSpecifier(0, SS, Range.getEnd(),
7471                                                        Range.getEnd(), II,
7472                                                        ObjectType,
7473                                                        FirstQualifierInScope,
7474                                                        false, false));
7475}
7476
7477template<typename Derived>
7478NestedNameSpecifier *
7479TreeTransform<Derived>::RebuildNestedNameSpecifier(NestedNameSpecifier *Prefix,
7480                                                   SourceRange Range,
7481                                                   NamespaceDecl *NS) {
7482  return NestedNameSpecifier::Create(SemaRef.Context, Prefix, NS);
7483}
7484
7485template<typename Derived>
7486NestedNameSpecifier *
7487TreeTransform<Derived>::RebuildNestedNameSpecifier(NestedNameSpecifier *Prefix,
7488                                                   SourceRange Range,
7489                                                   bool TemplateKW,
7490                                                   QualType T) {
7491  if (T->isDependentType() || T->isRecordType() ||
7492      (SemaRef.getLangOptions().CPlusPlus0x && T->isEnumeralType())) {
7493    assert(!T.hasLocalQualifiers() && "Can't get cv-qualifiers here");
7494    return NestedNameSpecifier::Create(SemaRef.Context, Prefix, TemplateKW,
7495                                       T.getTypePtr());
7496  }
7497
7498  SemaRef.Diag(Range.getBegin(), diag::err_nested_name_spec_non_tag) << T;
7499  return 0;
7500}
7501
7502template<typename Derived>
7503TemplateName
7504TreeTransform<Derived>::RebuildTemplateName(NestedNameSpecifier *Qualifier,
7505                                            bool TemplateKW,
7506                                            TemplateDecl *Template) {
7507  return SemaRef.Context.getQualifiedTemplateName(Qualifier, TemplateKW,
7508                                                  Template);
7509}
7510
7511template<typename Derived>
7512TemplateName
7513TreeTransform<Derived>::RebuildTemplateName(NestedNameSpecifier *Qualifier,
7514                                            SourceRange QualifierRange,
7515                                            const IdentifierInfo &II,
7516                                            QualType ObjectType,
7517                                            NamedDecl *FirstQualifierInScope) {
7518  CXXScopeSpec SS;
7519  SS.setRange(QualifierRange);
7520  SS.setScopeRep(Qualifier);
7521  UnqualifiedId Name;
7522  Name.setIdentifier(&II, /*FIXME:*/getDerived().getBaseLocation());
7523  Sema::TemplateTy Template;
7524  getSema().ActOnDependentTemplateName(/*Scope=*/0,
7525                                       /*FIXME:*/getDerived().getBaseLocation(),
7526                                       SS,
7527                                       Name,
7528                                       ParsedType::make(ObjectType),
7529                                       /*EnteringContext=*/false,
7530                                       Template);
7531  return Template.get();
7532}
7533
7534template<typename Derived>
7535TemplateName
7536TreeTransform<Derived>::RebuildTemplateName(NestedNameSpecifier *Qualifier,
7537                                            OverloadedOperatorKind Operator,
7538                                            QualType ObjectType) {
7539  CXXScopeSpec SS;
7540  SS.setRange(SourceRange(getDerived().getBaseLocation()));
7541  SS.setScopeRep(Qualifier);
7542  UnqualifiedId Name;
7543  SourceLocation SymbolLocations[3]; // FIXME: Bogus location information.
7544  Name.setOperatorFunctionId(/*FIXME:*/getDerived().getBaseLocation(),
7545                             Operator, SymbolLocations);
7546  Sema::TemplateTy Template;
7547  getSema().ActOnDependentTemplateName(/*Scope=*/0,
7548                                       /*FIXME:*/getDerived().getBaseLocation(),
7549                                       SS,
7550                                       Name,
7551                                       ParsedType::make(ObjectType),
7552                                       /*EnteringContext=*/false,
7553                                       Template);
7554  return Template.template getAsVal<TemplateName>();
7555}
7556
7557template<typename Derived>
7558ExprResult
7559TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
7560                                                   SourceLocation OpLoc,
7561                                                   Expr *OrigCallee,
7562                                                   Expr *First,
7563                                                   Expr *Second) {
7564  Expr *Callee = OrigCallee->IgnoreParenCasts();
7565  bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
7566
7567  // Determine whether this should be a builtin operation.
7568  if (Op == OO_Subscript) {
7569    if (!First->getType()->isOverloadableType() &&
7570        !Second->getType()->isOverloadableType())
7571      return getSema().CreateBuiltinArraySubscriptExpr(First,
7572                                                       Callee->getLocStart(),
7573                                                       Second, OpLoc);
7574  } else if (Op == OO_Arrow) {
7575    // -> is never a builtin operation.
7576    return SemaRef.BuildOverloadedArrowExpr(0, First, OpLoc);
7577  } else if (Second == 0 || isPostIncDec) {
7578    if (!First->getType()->isOverloadableType()) {
7579      // The argument is not of overloadable type, so try to create a
7580      // built-in unary operation.
7581      UnaryOperatorKind Opc
7582        = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
7583
7584      return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
7585    }
7586  } else {
7587    if (!First->getType()->isOverloadableType() &&
7588        !Second->getType()->isOverloadableType()) {
7589      // Neither of the arguments is an overloadable type, so try to
7590      // create a built-in binary operation.
7591      BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
7592      ExprResult Result
7593        = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
7594      if (Result.isInvalid())
7595        return ExprError();
7596
7597      return move(Result);
7598    }
7599  }
7600
7601  // Compute the transformed set of functions (and function templates) to be
7602  // used during overload resolution.
7603  UnresolvedSet<16> Functions;
7604
7605  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
7606    assert(ULE->requiresADL());
7607
7608    // FIXME: Do we have to check
7609    // IsAcceptableNonMemberOperatorCandidate for each of these?
7610    Functions.append(ULE->decls_begin(), ULE->decls_end());
7611  } else {
7612    Functions.addDecl(cast<DeclRefExpr>(Callee)->getDecl());
7613  }
7614
7615  // Add any functions found via argument-dependent lookup.
7616  Expr *Args[2] = { First, Second };
7617  unsigned NumArgs = 1 + (Second != 0);
7618
7619  // Create the overloaded operator invocation for unary operators.
7620  if (NumArgs == 1 || isPostIncDec) {
7621    UnaryOperatorKind Opc
7622      = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
7623    return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
7624  }
7625
7626  if (Op == OO_Subscript)
7627    return SemaRef.CreateOverloadedArraySubscriptExpr(Callee->getLocStart(),
7628                                                      OpLoc,
7629                                                      First,
7630                                                      Second);
7631
7632  // Create the overloaded operator invocation for binary operators.
7633  BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
7634  ExprResult Result
7635    = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
7636  if (Result.isInvalid())
7637    return ExprError();
7638
7639  return move(Result);
7640}
7641
7642template<typename Derived>
7643ExprResult
7644TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
7645                                                     SourceLocation OperatorLoc,
7646                                                       bool isArrow,
7647                                                 NestedNameSpecifier *Qualifier,
7648                                                     SourceRange QualifierRange,
7649                                                     TypeSourceInfo *ScopeType,
7650                                                       SourceLocation CCLoc,
7651                                                       SourceLocation TildeLoc,
7652                                        PseudoDestructorTypeStorage Destroyed) {
7653  CXXScopeSpec SS;
7654  if (Qualifier) {
7655    SS.setRange(QualifierRange);
7656    SS.setScopeRep(Qualifier);
7657  }
7658
7659  QualType BaseType = Base->getType();
7660  if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
7661      (!isArrow && !BaseType->getAs<RecordType>()) ||
7662      (isArrow && BaseType->getAs<PointerType>() &&
7663       !BaseType->getAs<PointerType>()->getPointeeType()
7664                                              ->template getAs<RecordType>())){
7665    // This pseudo-destructor expression is still a pseudo-destructor.
7666    return SemaRef.BuildPseudoDestructorExpr(Base, OperatorLoc,
7667                                             isArrow? tok::arrow : tok::period,
7668                                             SS, ScopeType, CCLoc, TildeLoc,
7669                                             Destroyed,
7670                                             /*FIXME?*/true);
7671  }
7672
7673  TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
7674  DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
7675                 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
7676  DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
7677  NameInfo.setNamedTypeInfo(DestroyedType);
7678
7679  // FIXME: the ScopeType should be tacked onto SS.
7680
7681  return getSema().BuildMemberReferenceExpr(Base, BaseType,
7682                                            OperatorLoc, isArrow,
7683                                            SS, /*FIXME: FirstQualifier*/ 0,
7684                                            NameInfo,
7685                                            /*TemplateArgs*/ 0);
7686}
7687
7688} // end namespace clang
7689
7690#endif // LLVM_CLANG_SEMA_TREETRANSFORM_H
7691