xref: /freebsd-src/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===//
7 //
8 //  This file implements a semantic tree transformation that takes a given
9 //  AST and rebuilds it, possibly transforming some nodes in the process.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14 #define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15 
16 #include "CoroutineStmtBuilder.h"
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/ExprOpenMP.h"
25 #include "clang/AST/OpenMPClause.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/StmtObjC.h"
29 #include "clang/AST/StmtOpenMP.h"
30 #include "clang/Sema/Designator.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Ownership.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaDiagnostic.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include <algorithm>
40 
41 using namespace llvm::omp;
42 
43 namespace clang {
44 using namespace sema;
45 
46 /// A semantic tree transformation that allows one to transform one
47 /// abstract syntax tree into another.
48 ///
49 /// A new tree transformation is defined by creating a new subclass \c X of
50 /// \c TreeTransform<X> and then overriding certain operations to provide
51 /// behavior specific to that transformation. For example, template
52 /// instantiation is implemented as a tree transformation where the
53 /// transformation of TemplateTypeParmType nodes involves substituting the
54 /// template arguments for their corresponding template parameters; a similar
55 /// transformation is performed for non-type template parameters and
56 /// template template parameters.
57 ///
58 /// This tree-transformation template uses static polymorphism to allow
59 /// subclasses to customize any of its operations. Thus, a subclass can
60 /// override any of the transformation or rebuild operators by providing an
61 /// operation with the same signature as the default implementation. The
62 /// overriding function should not be virtual.
63 ///
64 /// Semantic tree transformations are split into two stages, either of which
65 /// can be replaced by a subclass. The "transform" step transforms an AST node
66 /// or the parts of an AST node using the various transformation functions,
67 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
68 /// node of the appropriate kind from the pieces. The default transformation
69 /// routines recursively transform the operands to composite AST nodes (e.g.,
70 /// the pointee type of a PointerType node) and, if any of those operand nodes
71 /// were changed by the transformation, invokes the rebuild operation to create
72 /// a new AST node.
73 ///
74 /// Subclasses can customize the transformation at various levels. The
75 /// most coarse-grained transformations involve replacing TransformType(),
76 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
77 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
78 /// new implementations.
79 ///
80 /// For more fine-grained transformations, subclasses can replace any of the
81 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
82 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
83 /// replacing TransformTemplateTypeParmType() allows template instantiation
84 /// to substitute template arguments for their corresponding template
85 /// parameters. Additionally, subclasses can override the \c RebuildXXX
86 /// functions to control how AST nodes are rebuilt when their operands change.
87 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
88 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
89 /// be able to use more efficient rebuild steps.
90 ///
91 /// There are a handful of other functions that can be overridden, allowing one
92 /// to avoid traversing nodes that don't need any transformation
93 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
94 /// operands have not changed (\c AlwaysRebuild()), and customize the
95 /// default locations and entity names used for type-checking
96 /// (\c getBaseLocation(), \c getBaseEntity()).
97 template<typename Derived>
98 class TreeTransform {
99   /// Private RAII object that helps us forget and then re-remember
100   /// the template argument corresponding to a partially-substituted parameter
101   /// pack.
102   class ForgetPartiallySubstitutedPackRAII {
103     Derived &Self;
104     TemplateArgument Old;
105 
106   public:
107     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
108       Old = Self.ForgetPartiallySubstitutedPack();
109     }
110 
111     ~ForgetPartiallySubstitutedPackRAII() {
112       Self.RememberPartiallySubstitutedPack(Old);
113     }
114   };
115 
116 protected:
117   Sema &SemaRef;
118 
119   /// The set of local declarations that have been transformed, for
120   /// cases where we are forced to build new declarations within the transformer
121   /// rather than in the subclass (e.g., lambda closure types).
122   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
123 
124 public:
125   /// Initializes a new tree transformer.
126   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
127 
128   /// Retrieves a reference to the derived class.
129   Derived &getDerived() { return static_cast<Derived&>(*this); }
130 
131   /// Retrieves a reference to the derived class.
132   const Derived &getDerived() const {
133     return static_cast<const Derived&>(*this);
134   }
135 
136   static inline ExprResult Owned(Expr *E) { return E; }
137   static inline StmtResult Owned(Stmt *S) { return S; }
138 
139   /// Retrieves a reference to the semantic analysis object used for
140   /// this tree transform.
141   Sema &getSema() const { return SemaRef; }
142 
143   /// Whether the transformation should always rebuild AST nodes, even
144   /// if none of the children have changed.
145   ///
146   /// Subclasses may override this function to specify when the transformation
147   /// should rebuild all AST nodes.
148   ///
149   /// We must always rebuild all AST nodes when performing variadic template
150   /// pack expansion, in order to avoid violating the AST invariant that each
151   /// statement node appears at most once in its containing declaration.
152   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
153 
154   /// Whether the transformation is forming an expression or statement that
155   /// replaces the original. In this case, we'll reuse mangling numbers from
156   /// existing lambdas.
157   bool ReplacingOriginal() { return false; }
158 
159   /// Returns the location of the entity being transformed, if that
160   /// information was not available elsewhere in the AST.
161   ///
162   /// By default, returns no source-location information. Subclasses can
163   /// provide an alternative implementation that provides better location
164   /// information.
165   SourceLocation getBaseLocation() { return SourceLocation(); }
166 
167   /// Returns the name of the entity being transformed, if that
168   /// information was not available elsewhere in the AST.
169   ///
170   /// By default, returns an empty name. Subclasses can provide an alternative
171   /// implementation with a more precise name.
172   DeclarationName getBaseEntity() { return DeclarationName(); }
173 
174   /// Sets the "base" location and entity when that
175   /// information is known based on another transformation.
176   ///
177   /// By default, the source location and entity are ignored. Subclasses can
178   /// override this function to provide a customized implementation.
179   void setBase(SourceLocation Loc, DeclarationName Entity) { }
180 
181   /// RAII object that temporarily sets the base location and entity
182   /// used for reporting diagnostics in types.
183   class TemporaryBase {
184     TreeTransform &Self;
185     SourceLocation OldLocation;
186     DeclarationName OldEntity;
187 
188   public:
189     TemporaryBase(TreeTransform &Self, SourceLocation Location,
190                   DeclarationName Entity) : Self(Self) {
191       OldLocation = Self.getDerived().getBaseLocation();
192       OldEntity = Self.getDerived().getBaseEntity();
193 
194       if (Location.isValid())
195         Self.getDerived().setBase(Location, Entity);
196     }
197 
198     ~TemporaryBase() {
199       Self.getDerived().setBase(OldLocation, OldEntity);
200     }
201   };
202 
203   /// Determine whether the given type \p T has already been
204   /// transformed.
205   ///
206   /// Subclasses can provide an alternative implementation of this routine
207   /// to short-circuit evaluation when it is known that a given type will
208   /// not change. For example, template instantiation need not traverse
209   /// non-dependent types.
210   bool AlreadyTransformed(QualType T) {
211     return T.isNull();
212   }
213 
214   /// Determine whether the given call argument should be dropped, e.g.,
215   /// because it is a default argument.
216   ///
217   /// Subclasses can provide an alternative implementation of this routine to
218   /// determine which kinds of call arguments get dropped. By default,
219   /// CXXDefaultArgument nodes are dropped (prior to transformation).
220   bool DropCallArgument(Expr *E) {
221     return E->isDefaultArgument();
222   }
223 
224   /// Determine whether we should expand a pack expansion with the
225   /// given set of parameter packs into separate arguments by repeatedly
226   /// transforming the pattern.
227   ///
228   /// By default, the transformer never tries to expand pack expansions.
229   /// Subclasses can override this routine to provide different behavior.
230   ///
231   /// \param EllipsisLoc The location of the ellipsis that identifies the
232   /// pack expansion.
233   ///
234   /// \param PatternRange The source range that covers the entire pattern of
235   /// the pack expansion.
236   ///
237   /// \param Unexpanded The set of unexpanded parameter packs within the
238   /// pattern.
239   ///
240   /// \param ShouldExpand Will be set to \c true if the transformer should
241   /// expand the corresponding pack expansions into separate arguments. When
242   /// set, \c NumExpansions must also be set.
243   ///
244   /// \param RetainExpansion Whether the caller should add an unexpanded
245   /// pack expansion after all of the expanded arguments. This is used
246   /// when extending explicitly-specified template argument packs per
247   /// C++0x [temp.arg.explicit]p9.
248   ///
249   /// \param NumExpansions The number of separate arguments that will be in
250   /// the expanded form of the corresponding pack expansion. This is both an
251   /// input and an output parameter, which can be set by the caller if the
252   /// number of expansions is known a priori (e.g., due to a prior substitution)
253   /// and will be set by the callee when the number of expansions is known.
254   /// The callee must set this value when \c ShouldExpand is \c true; it may
255   /// set this value in other cases.
256   ///
257   /// \returns true if an error occurred (e.g., because the parameter packs
258   /// are to be instantiated with arguments of different lengths), false
259   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
260   /// must be set.
261   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
262                                SourceRange PatternRange,
263                                ArrayRef<UnexpandedParameterPack> Unexpanded,
264                                bool &ShouldExpand,
265                                bool &RetainExpansion,
266                                Optional<unsigned> &NumExpansions) {
267     ShouldExpand = false;
268     return false;
269   }
270 
271   /// "Forget" about the partially-substituted pack template argument,
272   /// when performing an instantiation that must preserve the parameter pack
273   /// use.
274   ///
275   /// This routine is meant to be overridden by the template instantiator.
276   TemplateArgument ForgetPartiallySubstitutedPack() {
277     return TemplateArgument();
278   }
279 
280   /// "Remember" the partially-substituted pack template argument
281   /// after performing an instantiation that must preserve the parameter pack
282   /// use.
283   ///
284   /// This routine is meant to be overridden by the template instantiator.
285   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
286 
287   /// Note to the derived class when a function parameter pack is
288   /// being expanded.
289   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
290 
291   /// Transforms the given type into another type.
292   ///
293   /// By default, this routine transforms a type by creating a
294   /// TypeSourceInfo for it and delegating to the appropriate
295   /// function.  This is expensive, but we don't mind, because
296   /// this method is deprecated anyway;  all users should be
297   /// switched to storing TypeSourceInfos.
298   ///
299   /// \returns the transformed type.
300   QualType TransformType(QualType T);
301 
302   /// Transforms the given type-with-location into a new
303   /// type-with-location.
304   ///
305   /// By default, this routine transforms a type by delegating to the
306   /// appropriate TransformXXXType to build a new type.  Subclasses
307   /// may override this function (to take over all type
308   /// transformations) or some set of the TransformXXXType functions
309   /// to alter the transformation.
310   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
311 
312   /// Transform the given type-with-location into a new
313   /// type, collecting location information in the given builder
314   /// as necessary.
315   ///
316   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
317 
318   /// Transform a type that is permitted to produce a
319   /// DeducedTemplateSpecializationType.
320   ///
321   /// This is used in the (relatively rare) contexts where it is acceptable
322   /// for transformation to produce a class template type with deduced
323   /// template arguments.
324   /// @{
325   QualType TransformTypeWithDeducedTST(QualType T);
326   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
327   /// @}
328 
329   /// The reason why the value of a statement is not discarded, if any.
330   enum StmtDiscardKind {
331     SDK_Discarded,
332     SDK_NotDiscarded,
333     SDK_StmtExprResult,
334   };
335 
336   /// Transform the given statement.
337   ///
338   /// By default, this routine transforms a statement by delegating to the
339   /// appropriate TransformXXXStmt function to transform a specific kind of
340   /// statement or the TransformExpr() function to transform an expression.
341   /// Subclasses may override this function to transform statements using some
342   /// other mechanism.
343   ///
344   /// \returns the transformed statement.
345   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
346 
347   /// Transform the given statement.
348   ///
349   /// By default, this routine transforms a statement by delegating to the
350   /// appropriate TransformOMPXXXClause function to transform a specific kind
351   /// of clause. Subclasses may override this function to transform statements
352   /// using some other mechanism.
353   ///
354   /// \returns the transformed OpenMP clause.
355   OMPClause *TransformOMPClause(OMPClause *S);
356 
357   /// Transform the given attribute.
358   ///
359   /// By default, this routine transforms a statement by delegating to the
360   /// appropriate TransformXXXAttr function to transform a specific kind
361   /// of attribute. Subclasses may override this function to transform
362   /// attributed statements using some other mechanism.
363   ///
364   /// \returns the transformed attribute
365   const Attr *TransformAttr(const Attr *S);
366 
367 /// Transform the specified attribute.
368 ///
369 /// Subclasses should override the transformation of attributes with a pragma
370 /// spelling to transform expressions stored within the attribute.
371 ///
372 /// \returns the transformed attribute.
373 #define ATTR(X)
374 #define PRAGMA_SPELLING_ATTR(X)                                                \
375   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
376 #include "clang/Basic/AttrList.inc"
377 
378   /// Transform the given expression.
379   ///
380   /// By default, this routine transforms an expression by delegating to the
381   /// appropriate TransformXXXExpr function to build a new expression.
382   /// Subclasses may override this function to transform expressions using some
383   /// other mechanism.
384   ///
385   /// \returns the transformed expression.
386   ExprResult TransformExpr(Expr *E);
387 
388   /// Transform the given initializer.
389   ///
390   /// By default, this routine transforms an initializer by stripping off the
391   /// semantic nodes added by initialization, then passing the result to
392   /// TransformExpr or TransformExprs.
393   ///
394   /// \returns the transformed initializer.
395   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
396 
397   /// Transform the given list of expressions.
398   ///
399   /// This routine transforms a list of expressions by invoking
400   /// \c TransformExpr() for each subexpression. However, it also provides
401   /// support for variadic templates by expanding any pack expansions (if the
402   /// derived class permits such expansion) along the way. When pack expansions
403   /// are present, the number of outputs may not equal the number of inputs.
404   ///
405   /// \param Inputs The set of expressions to be transformed.
406   ///
407   /// \param NumInputs The number of expressions in \c Inputs.
408   ///
409   /// \param IsCall If \c true, then this transform is being performed on
410   /// function-call arguments, and any arguments that should be dropped, will
411   /// be.
412   ///
413   /// \param Outputs The transformed input expressions will be added to this
414   /// vector.
415   ///
416   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
417   /// due to transformation.
418   ///
419   /// \returns true if an error occurred, false otherwise.
420   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
421                       SmallVectorImpl<Expr *> &Outputs,
422                       bool *ArgChanged = nullptr);
423 
424   /// Transform the given declaration, which is referenced from a type
425   /// or expression.
426   ///
427   /// By default, acts as the identity function on declarations, unless the
428   /// transformer has had to transform the declaration itself. Subclasses
429   /// may override this function to provide alternate behavior.
430   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
431     llvm::DenseMap<Decl *, Decl *>::iterator Known
432       = TransformedLocalDecls.find(D);
433     if (Known != TransformedLocalDecls.end())
434       return Known->second;
435 
436     return D;
437   }
438 
439   /// Transform the specified condition.
440   ///
441   /// By default, this transforms the variable and expression and rebuilds
442   /// the condition.
443   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
444                                            Expr *Expr,
445                                            Sema::ConditionKind Kind);
446 
447   /// Transform the attributes associated with the given declaration and
448   /// place them on the new declaration.
449   ///
450   /// By default, this operation does nothing. Subclasses may override this
451   /// behavior to transform attributes.
452   void transformAttrs(Decl *Old, Decl *New) { }
453 
454   /// Note that a local declaration has been transformed by this
455   /// transformer.
456   ///
457   /// Local declarations are typically transformed via a call to
458   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
459   /// the transformer itself has to transform the declarations. This routine
460   /// can be overridden by a subclass that keeps track of such mappings.
461   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
462     assert(New.size() == 1 &&
463            "must override transformedLocalDecl if performing pack expansion");
464     TransformedLocalDecls[Old] = New.front();
465   }
466 
467   /// Transform the definition of the given declaration.
468   ///
469   /// By default, invokes TransformDecl() to transform the declaration.
470   /// Subclasses may override this function to provide alternate behavior.
471   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
472     return getDerived().TransformDecl(Loc, D);
473   }
474 
475   /// Transform the given declaration, which was the first part of a
476   /// nested-name-specifier in a member access expression.
477   ///
478   /// This specific declaration transformation only applies to the first
479   /// identifier in a nested-name-specifier of a member access expression, e.g.,
480   /// the \c T in \c x->T::member
481   ///
482   /// By default, invokes TransformDecl() to transform the declaration.
483   /// Subclasses may override this function to provide alternate behavior.
484   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
485     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
486   }
487 
488   /// Transform the set of declarations in an OverloadExpr.
489   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
490                                   LookupResult &R);
491 
492   /// Transform the given nested-name-specifier with source-location
493   /// information.
494   ///
495   /// By default, transforms all of the types and declarations within the
496   /// nested-name-specifier. Subclasses may override this function to provide
497   /// alternate behavior.
498   NestedNameSpecifierLoc
499   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
500                                   QualType ObjectType = QualType(),
501                                   NamedDecl *FirstQualifierInScope = nullptr);
502 
503   /// Transform the given declaration name.
504   ///
505   /// By default, transforms the types of conversion function, constructor,
506   /// and destructor names and then (if needed) rebuilds the declaration name.
507   /// Identifiers and selectors are returned unmodified. Sublcasses may
508   /// override this function to provide alternate behavior.
509   DeclarationNameInfo
510   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
511 
512   /// Transform the given template name.
513   ///
514   /// \param SS The nested-name-specifier that qualifies the template
515   /// name. This nested-name-specifier must already have been transformed.
516   ///
517   /// \param Name The template name to transform.
518   ///
519   /// \param NameLoc The source location of the template name.
520   ///
521   /// \param ObjectType If we're translating a template name within a member
522   /// access expression, this is the type of the object whose member template
523   /// is being referenced.
524   ///
525   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
526   /// also refers to a name within the current (lexical) scope, this is the
527   /// declaration it refers to.
528   ///
529   /// By default, transforms the template name by transforming the declarations
530   /// and nested-name-specifiers that occur within the template name.
531   /// Subclasses may override this function to provide alternate behavior.
532   TemplateName
533   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
534                         SourceLocation NameLoc,
535                         QualType ObjectType = QualType(),
536                         NamedDecl *FirstQualifierInScope = nullptr,
537                         bool AllowInjectedClassName = false);
538 
539   /// Transform the given template argument.
540   ///
541   /// By default, this operation transforms the type, expression, or
542   /// declaration stored within the template argument and constructs a
543   /// new template argument from the transformed result. Subclasses may
544   /// override this function to provide alternate behavior.
545   ///
546   /// Returns true if there was an error.
547   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
548                                  TemplateArgumentLoc &Output,
549                                  bool Uneval = false);
550 
551   /// Transform the given set of template arguments.
552   ///
553   /// By default, this operation transforms all of the template arguments
554   /// in the input set using \c TransformTemplateArgument(), and appends
555   /// the transformed arguments to the output list.
556   ///
557   /// Note that this overload of \c TransformTemplateArguments() is merely
558   /// a convenience function. Subclasses that wish to override this behavior
559   /// should override the iterator-based member template version.
560   ///
561   /// \param Inputs The set of template arguments to be transformed.
562   ///
563   /// \param NumInputs The number of template arguments in \p Inputs.
564   ///
565   /// \param Outputs The set of transformed template arguments output by this
566   /// routine.
567   ///
568   /// Returns true if an error occurred.
569   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
570                                   unsigned NumInputs,
571                                   TemplateArgumentListInfo &Outputs,
572                                   bool Uneval = false) {
573     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
574                                       Uneval);
575   }
576 
577   /// Transform the given set of template arguments.
578   ///
579   /// By default, this operation transforms all of the template arguments
580   /// in the input set using \c TransformTemplateArgument(), and appends
581   /// the transformed arguments to the output list.
582   ///
583   /// \param First An iterator to the first template argument.
584   ///
585   /// \param Last An iterator one step past the last template argument.
586   ///
587   /// \param Outputs The set of transformed template arguments output by this
588   /// routine.
589   ///
590   /// Returns true if an error occurred.
591   template<typename InputIterator>
592   bool TransformTemplateArguments(InputIterator First,
593                                   InputIterator Last,
594                                   TemplateArgumentListInfo &Outputs,
595                                   bool Uneval = false);
596 
597   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
598   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
599                                  TemplateArgumentLoc &ArgLoc);
600 
601   /// Fakes up a TypeSourceInfo for a type.
602   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
603     return SemaRef.Context.getTrivialTypeSourceInfo(T,
604                        getDerived().getBaseLocation());
605   }
606 
607 #define ABSTRACT_TYPELOC(CLASS, PARENT)
608 #define TYPELOC(CLASS, PARENT)                                   \
609   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
610 #include "clang/AST/TypeLocNodes.def"
611 
612   template<typename Fn>
613   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
614                                       FunctionProtoTypeLoc TL,
615                                       CXXRecordDecl *ThisContext,
616                                       Qualifiers ThisTypeQuals,
617                                       Fn TransformExceptionSpec);
618 
619   bool TransformExceptionSpec(SourceLocation Loc,
620                               FunctionProtoType::ExceptionSpecInfo &ESI,
621                               SmallVectorImpl<QualType> &Exceptions,
622                               bool &Changed);
623 
624   StmtResult TransformSEHHandler(Stmt *Handler);
625 
626   QualType
627   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
628                                       TemplateSpecializationTypeLoc TL,
629                                       TemplateName Template);
630 
631   QualType
632   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
633                                       DependentTemplateSpecializationTypeLoc TL,
634                                                TemplateName Template,
635                                                CXXScopeSpec &SS);
636 
637   QualType TransformDependentTemplateSpecializationType(
638       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
639       NestedNameSpecifierLoc QualifierLoc);
640 
641   /// Transforms the parameters of a function type into the
642   /// given vectors.
643   ///
644   /// The result vectors should be kept in sync; null entries in the
645   /// variables vector are acceptable.
646   ///
647   /// Return true on error.
648   bool TransformFunctionTypeParams(
649       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
650       const QualType *ParamTypes,
651       const FunctionProtoType::ExtParameterInfo *ParamInfos,
652       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
653       Sema::ExtParameterInfoBuilder &PInfos);
654 
655   /// Transforms a single function-type parameter.  Return null
656   /// on error.
657   ///
658   /// \param indexAdjustment - A number to add to the parameter's
659   ///   scope index;  can be negative
660   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
661                                           int indexAdjustment,
662                                           Optional<unsigned> NumExpansions,
663                                           bool ExpectParameterPack);
664 
665   /// Transform the body of a lambda-expression.
666   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
667   /// Alternative implementation of TransformLambdaBody that skips transforming
668   /// the body.
669   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
670 
671   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
672 
673   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
674   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
675 
676   TemplateParameterList *TransformTemplateParameterList(
677         TemplateParameterList *TPL) {
678     return TPL;
679   }
680 
681   ExprResult TransformAddressOfOperand(Expr *E);
682 
683   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
684                                                 bool IsAddressOfOperand,
685                                                 TypeSourceInfo **RecoveryTSI);
686 
687   ExprResult TransformParenDependentScopeDeclRefExpr(
688       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
689       TypeSourceInfo **RecoveryTSI);
690 
691   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
692 
693 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
694 // amount of stack usage with clang.
695 #define STMT(Node, Parent)                        \
696   LLVM_ATTRIBUTE_NOINLINE \
697   StmtResult Transform##Node(Node *S);
698 #define VALUESTMT(Node, Parent)                   \
699   LLVM_ATTRIBUTE_NOINLINE \
700   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
701 #define EXPR(Node, Parent)                        \
702   LLVM_ATTRIBUTE_NOINLINE \
703   ExprResult Transform##Node(Node *E);
704 #define ABSTRACT_STMT(Stmt)
705 #include "clang/AST/StmtNodes.inc"
706 
707 #define OPENMP_CLAUSE(Name, Class)                        \
708   LLVM_ATTRIBUTE_NOINLINE \
709   OMPClause *Transform ## Class(Class *S);
710 #include "clang/Basic/OpenMPKinds.def"
711 
712   /// Build a new qualified type given its unqualified type and type location.
713   ///
714   /// By default, this routine adds type qualifiers only to types that can
715   /// have qualifiers, and silently suppresses those qualifiers that are not
716   /// permitted. Subclasses may override this routine to provide different
717   /// behavior.
718   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
719 
720   /// Build a new pointer type given its pointee type.
721   ///
722   /// By default, performs semantic analysis when building the pointer type.
723   /// Subclasses may override this routine to provide different behavior.
724   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
725 
726   /// Build a new block pointer type given its pointee type.
727   ///
728   /// By default, performs semantic analysis when building the block pointer
729   /// type. Subclasses may override this routine to provide different behavior.
730   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
731 
732   /// Build a new reference type given the type it references.
733   ///
734   /// By default, performs semantic analysis when building the
735   /// reference type. Subclasses may override this routine to provide
736   /// different behavior.
737   ///
738   /// \param LValue whether the type was written with an lvalue sigil
739   /// or an rvalue sigil.
740   QualType RebuildReferenceType(QualType ReferentType,
741                                 bool LValue,
742                                 SourceLocation Sigil);
743 
744   /// Build a new member pointer type given the pointee type and the
745   /// class type it refers into.
746   ///
747   /// By default, performs semantic analysis when building the member pointer
748   /// type. Subclasses may override this routine to provide different behavior.
749   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
750                                     SourceLocation Sigil);
751 
752   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
753                                     SourceLocation ProtocolLAngleLoc,
754                                     ArrayRef<ObjCProtocolDecl *> Protocols,
755                                     ArrayRef<SourceLocation> ProtocolLocs,
756                                     SourceLocation ProtocolRAngleLoc);
757 
758   /// Build an Objective-C object type.
759   ///
760   /// By default, performs semantic analysis when building the object type.
761   /// Subclasses may override this routine to provide different behavior.
762   QualType RebuildObjCObjectType(QualType BaseType,
763                                  SourceLocation Loc,
764                                  SourceLocation TypeArgsLAngleLoc,
765                                  ArrayRef<TypeSourceInfo *> TypeArgs,
766                                  SourceLocation TypeArgsRAngleLoc,
767                                  SourceLocation ProtocolLAngleLoc,
768                                  ArrayRef<ObjCProtocolDecl *> Protocols,
769                                  ArrayRef<SourceLocation> ProtocolLocs,
770                                  SourceLocation ProtocolRAngleLoc);
771 
772   /// Build a new Objective-C object pointer type given the pointee type.
773   ///
774   /// By default, directly builds the pointer type, with no additional semantic
775   /// analysis.
776   QualType RebuildObjCObjectPointerType(QualType PointeeType,
777                                         SourceLocation Star);
778 
779   /// Build a new array type given the element type, size
780   /// modifier, size of the array (if known), size expression, and index type
781   /// qualifiers.
782   ///
783   /// By default, performs semantic analysis when building the array type.
784   /// Subclasses may override this routine to provide different behavior.
785   /// Also by default, all of the other Rebuild*Array
786   QualType RebuildArrayType(QualType ElementType,
787                             ArrayType::ArraySizeModifier SizeMod,
788                             const llvm::APInt *Size,
789                             Expr *SizeExpr,
790                             unsigned IndexTypeQuals,
791                             SourceRange BracketsRange);
792 
793   /// Build a new constant array type given the element type, size
794   /// modifier, (known) size of the array, and index type qualifiers.
795   ///
796   /// By default, performs semantic analysis when building the array type.
797   /// Subclasses may override this routine to provide different behavior.
798   QualType RebuildConstantArrayType(QualType ElementType,
799                                     ArrayType::ArraySizeModifier SizeMod,
800                                     const llvm::APInt &Size,
801                                     Expr *SizeExpr,
802                                     unsigned IndexTypeQuals,
803                                     SourceRange BracketsRange);
804 
805   /// Build a new incomplete array type given the element type, size
806   /// modifier, and index type qualifiers.
807   ///
808   /// By default, performs semantic analysis when building the array type.
809   /// Subclasses may override this routine to provide different behavior.
810   QualType RebuildIncompleteArrayType(QualType ElementType,
811                                       ArrayType::ArraySizeModifier SizeMod,
812                                       unsigned IndexTypeQuals,
813                                       SourceRange BracketsRange);
814 
815   /// Build a new variable-length array type given the element type,
816   /// size modifier, size expression, and index type qualifiers.
817   ///
818   /// By default, performs semantic analysis when building the array type.
819   /// Subclasses may override this routine to provide different behavior.
820   QualType RebuildVariableArrayType(QualType ElementType,
821                                     ArrayType::ArraySizeModifier SizeMod,
822                                     Expr *SizeExpr,
823                                     unsigned IndexTypeQuals,
824                                     SourceRange BracketsRange);
825 
826   /// Build a new dependent-sized array type given the element type,
827   /// size modifier, size expression, and index type qualifiers.
828   ///
829   /// By default, performs semantic analysis when building the array type.
830   /// Subclasses may override this routine to provide different behavior.
831   QualType RebuildDependentSizedArrayType(QualType ElementType,
832                                           ArrayType::ArraySizeModifier SizeMod,
833                                           Expr *SizeExpr,
834                                           unsigned IndexTypeQuals,
835                                           SourceRange BracketsRange);
836 
837   /// Build a new vector type given the element type and
838   /// number of elements.
839   ///
840   /// By default, performs semantic analysis when building the vector type.
841   /// Subclasses may override this routine to provide different behavior.
842   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
843                              VectorType::VectorKind VecKind);
844 
845   /// Build a new potentially dependently-sized extended vector type
846   /// given the element type and number of elements.
847   ///
848   /// By default, performs semantic analysis when building the vector type.
849   /// Subclasses may override this routine to provide different behavior.
850   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
851                                            SourceLocation AttributeLoc,
852                                            VectorType::VectorKind);
853 
854   /// Build a new extended vector type given the element type and
855   /// number of elements.
856   ///
857   /// By default, performs semantic analysis when building the vector type.
858   /// Subclasses may override this routine to provide different behavior.
859   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
860                                 SourceLocation AttributeLoc);
861 
862   /// Build a new potentially dependently-sized extended vector type
863   /// given the element type and number of elements.
864   ///
865   /// By default, performs semantic analysis when building the vector type.
866   /// Subclasses may override this routine to provide different behavior.
867   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
868                                               Expr *SizeExpr,
869                                               SourceLocation AttributeLoc);
870 
871   /// Build a new DependentAddressSpaceType or return the pointee
872   /// type variable with the correct address space (retrieved from
873   /// AddrSpaceExpr) applied to it. The former will be returned in cases
874   /// where the address space remains dependent.
875   ///
876   /// By default, performs semantic analysis when building the type with address
877   /// space applied. Subclasses may override this routine to provide different
878   /// behavior.
879   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
880                                             Expr *AddrSpaceExpr,
881                                             SourceLocation AttributeLoc);
882 
883   /// Build a new function type.
884   ///
885   /// By default, performs semantic analysis when building the function type.
886   /// Subclasses may override this routine to provide different behavior.
887   QualType RebuildFunctionProtoType(QualType T,
888                                     MutableArrayRef<QualType> ParamTypes,
889                                     const FunctionProtoType::ExtProtoInfo &EPI);
890 
891   /// Build a new unprototyped function type.
892   QualType RebuildFunctionNoProtoType(QualType ResultType);
893 
894   /// Rebuild an unresolved typename type, given the decl that
895   /// the UnresolvedUsingTypenameDecl was transformed to.
896   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
897 
898   /// Build a new typedef type.
899   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
900     return SemaRef.Context.getTypeDeclType(Typedef);
901   }
902 
903   /// Build a new MacroDefined type.
904   QualType RebuildMacroQualifiedType(QualType T,
905                                      const IdentifierInfo *MacroII) {
906     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
907   }
908 
909   /// Build a new class/struct/union type.
910   QualType RebuildRecordType(RecordDecl *Record) {
911     return SemaRef.Context.getTypeDeclType(Record);
912   }
913 
914   /// Build a new Enum type.
915   QualType RebuildEnumType(EnumDecl *Enum) {
916     return SemaRef.Context.getTypeDeclType(Enum);
917   }
918 
919   /// Build a new typeof(expr) type.
920   ///
921   /// By default, performs semantic analysis when building the typeof type.
922   /// Subclasses may override this routine to provide different behavior.
923   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
924 
925   /// Build a new typeof(type) type.
926   ///
927   /// By default, builds a new TypeOfType with the given underlying type.
928   QualType RebuildTypeOfType(QualType Underlying);
929 
930   /// Build a new unary transform type.
931   QualType RebuildUnaryTransformType(QualType BaseType,
932                                      UnaryTransformType::UTTKind UKind,
933                                      SourceLocation Loc);
934 
935   /// Build a new C++11 decltype type.
936   ///
937   /// By default, performs semantic analysis when building the decltype type.
938   /// Subclasses may override this routine to provide different behavior.
939   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
940 
941   /// Build a new C++11 auto type.
942   ///
943   /// By default, builds a new AutoType with the given deduced type.
944   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
945     // Note, IsDependent is always false here: we implicitly convert an 'auto'
946     // which has been deduced to a dependent type into an undeduced 'auto', so
947     // that we'll retry deduction after the transformation.
948     return SemaRef.Context.getAutoType(Deduced, Keyword,
949                                        /*IsDependent*/ false);
950   }
951 
952   /// By default, builds a new DeducedTemplateSpecializationType with the given
953   /// deduced type.
954   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
955       QualType Deduced) {
956     return SemaRef.Context.getDeducedTemplateSpecializationType(
957         Template, Deduced, /*IsDependent*/ false);
958   }
959 
960   /// Build a new template specialization type.
961   ///
962   /// By default, performs semantic analysis when building the template
963   /// specialization type. Subclasses may override this routine to provide
964   /// different behavior.
965   QualType RebuildTemplateSpecializationType(TemplateName Template,
966                                              SourceLocation TemplateLoc,
967                                              TemplateArgumentListInfo &Args);
968 
969   /// Build a new parenthesized type.
970   ///
971   /// By default, builds a new ParenType type from the inner type.
972   /// Subclasses may override this routine to provide different behavior.
973   QualType RebuildParenType(QualType InnerType) {
974     return SemaRef.BuildParenType(InnerType);
975   }
976 
977   /// Build a new qualified name type.
978   ///
979   /// By default, builds a new ElaboratedType type from the keyword,
980   /// the nested-name-specifier and the named type.
981   /// Subclasses may override this routine to provide different behavior.
982   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
983                                  ElaboratedTypeKeyword Keyword,
984                                  NestedNameSpecifierLoc QualifierLoc,
985                                  QualType Named) {
986     return SemaRef.Context.getElaboratedType(Keyword,
987                                          QualifierLoc.getNestedNameSpecifier(),
988                                              Named);
989   }
990 
991   /// Build a new typename type that refers to a template-id.
992   ///
993   /// By default, builds a new DependentNameType type from the
994   /// nested-name-specifier and the given type. Subclasses may override
995   /// this routine to provide different behavior.
996   QualType RebuildDependentTemplateSpecializationType(
997                                           ElaboratedTypeKeyword Keyword,
998                                           NestedNameSpecifierLoc QualifierLoc,
999                                           SourceLocation TemplateKWLoc,
1000                                           const IdentifierInfo *Name,
1001                                           SourceLocation NameLoc,
1002                                           TemplateArgumentListInfo &Args,
1003                                           bool AllowInjectedClassName) {
1004     // Rebuild the template name.
1005     // TODO: avoid TemplateName abstraction
1006     CXXScopeSpec SS;
1007     SS.Adopt(QualifierLoc);
1008     TemplateName InstName = getDerived().RebuildTemplateName(
1009         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1010         AllowInjectedClassName);
1011 
1012     if (InstName.isNull())
1013       return QualType();
1014 
1015     // If it's still dependent, make a dependent specialization.
1016     if (InstName.getAsDependentTemplateName())
1017       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1018                                           QualifierLoc.getNestedNameSpecifier(),
1019                                                                     Name,
1020                                                                     Args);
1021 
1022     // Otherwise, make an elaborated type wrapping a non-dependent
1023     // specialization.
1024     QualType T =
1025     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1026     if (T.isNull()) return QualType();
1027 
1028     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1029       return T;
1030 
1031     return SemaRef.Context.getElaboratedType(Keyword,
1032                                        QualifierLoc.getNestedNameSpecifier(),
1033                                              T);
1034   }
1035 
1036   /// Build a new typename type that refers to an identifier.
1037   ///
1038   /// By default, performs semantic analysis when building the typename type
1039   /// (or elaborated type). Subclasses may override this routine to provide
1040   /// different behavior.
1041   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1042                                     SourceLocation KeywordLoc,
1043                                     NestedNameSpecifierLoc QualifierLoc,
1044                                     const IdentifierInfo *Id,
1045                                     SourceLocation IdLoc,
1046                                     bool DeducedTSTContext) {
1047     CXXScopeSpec SS;
1048     SS.Adopt(QualifierLoc);
1049 
1050     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1051       // If the name is still dependent, just build a new dependent name type.
1052       if (!SemaRef.computeDeclContext(SS))
1053         return SemaRef.Context.getDependentNameType(Keyword,
1054                                           QualifierLoc.getNestedNameSpecifier(),
1055                                                     Id);
1056     }
1057 
1058     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1059       QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1060                                              *Id, IdLoc);
1061       // If a dependent name resolves to a deduced template specialization type,
1062       // check that we're in one of the syntactic contexts permitting it.
1063       if (!DeducedTSTContext) {
1064         if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1065                 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1066           SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1067             << (int)SemaRef.getTemplateNameKindForDiagnostics(
1068                    Deduced->getTemplateName())
1069             << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1070           if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1071             SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1072           return QualType();
1073         }
1074       }
1075       return T;
1076     }
1077 
1078     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1079 
1080     // We had a dependent elaborated-type-specifier that has been transformed
1081     // into a non-dependent elaborated-type-specifier. Find the tag we're
1082     // referring to.
1083     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1084     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1085     if (!DC)
1086       return QualType();
1087 
1088     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1089       return QualType();
1090 
1091     TagDecl *Tag = nullptr;
1092     SemaRef.LookupQualifiedName(Result, DC);
1093     switch (Result.getResultKind()) {
1094       case LookupResult::NotFound:
1095       case LookupResult::NotFoundInCurrentInstantiation:
1096         break;
1097 
1098       case LookupResult::Found:
1099         Tag = Result.getAsSingle<TagDecl>();
1100         break;
1101 
1102       case LookupResult::FoundOverloaded:
1103       case LookupResult::FoundUnresolvedValue:
1104         llvm_unreachable("Tag lookup cannot find non-tags");
1105 
1106       case LookupResult::Ambiguous:
1107         // Let the LookupResult structure handle ambiguities.
1108         return QualType();
1109     }
1110 
1111     if (!Tag) {
1112       // Check where the name exists but isn't a tag type and use that to emit
1113       // better diagnostics.
1114       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1115       SemaRef.LookupQualifiedName(Result, DC);
1116       switch (Result.getResultKind()) {
1117         case LookupResult::Found:
1118         case LookupResult::FoundOverloaded:
1119         case LookupResult::FoundUnresolvedValue: {
1120           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1121           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1122           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1123                                                                << NTK << Kind;
1124           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1125           break;
1126         }
1127         default:
1128           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1129               << Kind << Id << DC << QualifierLoc.getSourceRange();
1130           break;
1131       }
1132       return QualType();
1133     }
1134 
1135     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1136                                               IdLoc, Id)) {
1137       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1138       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1139       return QualType();
1140     }
1141 
1142     // Build the elaborated-type-specifier type.
1143     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1144     return SemaRef.Context.getElaboratedType(Keyword,
1145                                          QualifierLoc.getNestedNameSpecifier(),
1146                                              T);
1147   }
1148 
1149   /// Build a new pack expansion type.
1150   ///
1151   /// By default, builds a new PackExpansionType type from the given pattern.
1152   /// Subclasses may override this routine to provide different behavior.
1153   QualType RebuildPackExpansionType(QualType Pattern,
1154                                     SourceRange PatternRange,
1155                                     SourceLocation EllipsisLoc,
1156                                     Optional<unsigned> NumExpansions) {
1157     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1158                                         NumExpansions);
1159   }
1160 
1161   /// Build a new atomic type given its value type.
1162   ///
1163   /// By default, performs semantic analysis when building the atomic type.
1164   /// Subclasses may override this routine to provide different behavior.
1165   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1166 
1167   /// Build a new pipe type given its value type.
1168   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1169                            bool isReadPipe);
1170 
1171   /// Build a new template name given a nested name specifier, a flag
1172   /// indicating whether the "template" keyword was provided, and the template
1173   /// that the template name refers to.
1174   ///
1175   /// By default, builds the new template name directly. Subclasses may override
1176   /// this routine to provide different behavior.
1177   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1178                                    bool TemplateKW,
1179                                    TemplateDecl *Template);
1180 
1181   /// Build a new template name given a nested name specifier and the
1182   /// name that is referred to as a template.
1183   ///
1184   /// By default, performs semantic analysis to determine whether the name can
1185   /// be resolved to a specific template, then builds the appropriate kind of
1186   /// template name. Subclasses may override this routine to provide different
1187   /// behavior.
1188   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1189                                    SourceLocation TemplateKWLoc,
1190                                    const IdentifierInfo &Name,
1191                                    SourceLocation NameLoc, QualType ObjectType,
1192                                    NamedDecl *FirstQualifierInScope,
1193                                    bool AllowInjectedClassName);
1194 
1195   /// Build a new template name given a nested name specifier and the
1196   /// overloaded operator name that is referred to as a template.
1197   ///
1198   /// By default, performs semantic analysis to determine whether the name can
1199   /// be resolved to a specific template, then builds the appropriate kind of
1200   /// template name. Subclasses may override this routine to provide different
1201   /// behavior.
1202   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1203                                    SourceLocation TemplateKWLoc,
1204                                    OverloadedOperatorKind Operator,
1205                                    SourceLocation NameLoc, QualType ObjectType,
1206                                    bool AllowInjectedClassName);
1207 
1208   /// Build a new template name given a template template parameter pack
1209   /// and the
1210   ///
1211   /// By default, performs semantic analysis to determine whether the name can
1212   /// be resolved to a specific template, then builds the appropriate kind of
1213   /// template name. Subclasses may override this routine to provide different
1214   /// behavior.
1215   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1216                                    const TemplateArgument &ArgPack) {
1217     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1218   }
1219 
1220   /// Build a new compound statement.
1221   ///
1222   /// By default, performs semantic analysis to build the new statement.
1223   /// Subclasses may override this routine to provide different behavior.
1224   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1225                                        MultiStmtArg Statements,
1226                                        SourceLocation RBraceLoc,
1227                                        bool IsStmtExpr) {
1228     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1229                                        IsStmtExpr);
1230   }
1231 
1232   /// Build a new case statement.
1233   ///
1234   /// By default, performs semantic analysis to build the new statement.
1235   /// Subclasses may override this routine to provide different behavior.
1236   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1237                                    Expr *LHS,
1238                                    SourceLocation EllipsisLoc,
1239                                    Expr *RHS,
1240                                    SourceLocation ColonLoc) {
1241     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1242                                    ColonLoc);
1243   }
1244 
1245   /// Attach the body to a new case statement.
1246   ///
1247   /// By default, performs semantic analysis to build the new statement.
1248   /// Subclasses may override this routine to provide different behavior.
1249   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1250     getSema().ActOnCaseStmtBody(S, Body);
1251     return S;
1252   }
1253 
1254   /// Build a new default statement.
1255   ///
1256   /// By default, performs semantic analysis to build the new statement.
1257   /// Subclasses may override this routine to provide different behavior.
1258   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1259                                       SourceLocation ColonLoc,
1260                                       Stmt *SubStmt) {
1261     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1262                                       /*CurScope=*/nullptr);
1263   }
1264 
1265   /// Build a new label statement.
1266   ///
1267   /// By default, performs semantic analysis to build the new statement.
1268   /// Subclasses may override this routine to provide different behavior.
1269   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1270                               SourceLocation ColonLoc, Stmt *SubStmt) {
1271     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1272   }
1273 
1274   /// Build a new label statement.
1275   ///
1276   /// By default, performs semantic analysis to build the new statement.
1277   /// Subclasses may override this routine to provide different behavior.
1278   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1279                                    ArrayRef<const Attr*> Attrs,
1280                                    Stmt *SubStmt) {
1281     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1282   }
1283 
1284   /// Build a new "if" statement.
1285   ///
1286   /// By default, performs semantic analysis to build the new statement.
1287   /// Subclasses may override this routine to provide different behavior.
1288   StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1289                            Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1290                            SourceLocation ElseLoc, Stmt *Else) {
1291     return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1292                                  ElseLoc, Else);
1293   }
1294 
1295   /// Start building a new switch statement.
1296   ///
1297   /// By default, performs semantic analysis to build the new statement.
1298   /// Subclasses may override this routine to provide different behavior.
1299   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1300                                     Sema::ConditionResult Cond) {
1301     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1302   }
1303 
1304   /// Attach the body to the switch statement.
1305   ///
1306   /// By default, performs semantic analysis to build the new statement.
1307   /// Subclasses may override this routine to provide different behavior.
1308   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1309                                    Stmt *Switch, Stmt *Body) {
1310     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1311   }
1312 
1313   /// Build a new while statement.
1314   ///
1315   /// By default, performs semantic analysis to build the new statement.
1316   /// Subclasses may override this routine to provide different behavior.
1317   StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1318                               Sema::ConditionResult Cond, Stmt *Body) {
1319     return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1320   }
1321 
1322   /// Build a new do-while statement.
1323   ///
1324   /// By default, performs semantic analysis to build the new statement.
1325   /// Subclasses may override this routine to provide different behavior.
1326   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1327                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1328                            Expr *Cond, SourceLocation RParenLoc) {
1329     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1330                                  Cond, RParenLoc);
1331   }
1332 
1333   /// Build a new for statement.
1334   ///
1335   /// By default, performs semantic analysis to build the new statement.
1336   /// Subclasses may override this routine to provide different behavior.
1337   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1338                             Stmt *Init, Sema::ConditionResult Cond,
1339                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1340                             Stmt *Body) {
1341     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1342                                   Inc, RParenLoc, Body);
1343   }
1344 
1345   /// Build a new goto statement.
1346   ///
1347   /// By default, performs semantic analysis to build the new statement.
1348   /// Subclasses may override this routine to provide different behavior.
1349   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1350                              LabelDecl *Label) {
1351     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1352   }
1353 
1354   /// Build a new indirect goto statement.
1355   ///
1356   /// By default, performs semantic analysis to build the new statement.
1357   /// Subclasses may override this routine to provide different behavior.
1358   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1359                                      SourceLocation StarLoc,
1360                                      Expr *Target) {
1361     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1362   }
1363 
1364   /// Build a new return statement.
1365   ///
1366   /// By default, performs semantic analysis to build the new statement.
1367   /// Subclasses may override this routine to provide different behavior.
1368   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1369     return getSema().BuildReturnStmt(ReturnLoc, Result);
1370   }
1371 
1372   /// Build a new declaration statement.
1373   ///
1374   /// By default, performs semantic analysis to build the new statement.
1375   /// Subclasses may override this routine to provide different behavior.
1376   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1377                              SourceLocation StartLoc, SourceLocation EndLoc) {
1378     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1379     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1380   }
1381 
1382   /// Build a new inline asm statement.
1383   ///
1384   /// By default, performs semantic analysis to build the new statement.
1385   /// Subclasses may override this routine to provide different behavior.
1386   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1387                                bool IsVolatile, unsigned NumOutputs,
1388                                unsigned NumInputs, IdentifierInfo **Names,
1389                                MultiExprArg Constraints, MultiExprArg Exprs,
1390                                Expr *AsmString, MultiExprArg Clobbers,
1391                                unsigned NumLabels,
1392                                SourceLocation RParenLoc) {
1393     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1394                                      NumInputs, Names, Constraints, Exprs,
1395                                      AsmString, Clobbers, NumLabels, RParenLoc);
1396   }
1397 
1398   /// Build a new MS style inline asm statement.
1399   ///
1400   /// By default, performs semantic analysis to build the new statement.
1401   /// Subclasses may override this routine to provide different behavior.
1402   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1403                               ArrayRef<Token> AsmToks,
1404                               StringRef AsmString,
1405                               unsigned NumOutputs, unsigned NumInputs,
1406                               ArrayRef<StringRef> Constraints,
1407                               ArrayRef<StringRef> Clobbers,
1408                               ArrayRef<Expr*> Exprs,
1409                               SourceLocation EndLoc) {
1410     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1411                                     NumOutputs, NumInputs,
1412                                     Constraints, Clobbers, Exprs, EndLoc);
1413   }
1414 
1415   /// Build a new co_return statement.
1416   ///
1417   /// By default, performs semantic analysis to build the new statement.
1418   /// Subclasses may override this routine to provide different behavior.
1419   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1420                                  bool IsImplicit) {
1421     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1422   }
1423 
1424   /// Build a new co_await expression.
1425   ///
1426   /// By default, performs semantic analysis to build the new expression.
1427   /// Subclasses may override this routine to provide different behavior.
1428   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1429                                 bool IsImplicit) {
1430     return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1431   }
1432 
1433   /// Build a new co_await 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 RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1438                                          Expr *Result,
1439                                          UnresolvedLookupExpr *Lookup) {
1440     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1441   }
1442 
1443   /// Build a new co_yield expression.
1444   ///
1445   /// By default, performs semantic analysis to build the new expression.
1446   /// Subclasses may override this routine to provide different behavior.
1447   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1448     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1449   }
1450 
1451   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1452     return getSema().BuildCoroutineBodyStmt(Args);
1453   }
1454 
1455   /// Build a new Objective-C \@try statement.
1456   ///
1457   /// By default, performs semantic analysis to build the new statement.
1458   /// Subclasses may override this routine to provide different behavior.
1459   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1460                                         Stmt *TryBody,
1461                                         MultiStmtArg CatchStmts,
1462                                         Stmt *Finally) {
1463     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1464                                         Finally);
1465   }
1466 
1467   /// Rebuild an Objective-C exception declaration.
1468   ///
1469   /// By default, performs semantic analysis to build the new declaration.
1470   /// Subclasses may override this routine to provide different behavior.
1471   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1472                                     TypeSourceInfo *TInfo, QualType T) {
1473     return getSema().BuildObjCExceptionDecl(TInfo, T,
1474                                             ExceptionDecl->getInnerLocStart(),
1475                                             ExceptionDecl->getLocation(),
1476                                             ExceptionDecl->getIdentifier());
1477   }
1478 
1479   /// Build a new Objective-C \@catch statement.
1480   ///
1481   /// By default, performs semantic analysis to build the new statement.
1482   /// Subclasses may override this routine to provide different behavior.
1483   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1484                                           SourceLocation RParenLoc,
1485                                           VarDecl *Var,
1486                                           Stmt *Body) {
1487     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1488                                           Var, Body);
1489   }
1490 
1491   /// Build a new Objective-C \@finally statement.
1492   ///
1493   /// By default, performs semantic analysis to build the new statement.
1494   /// Subclasses may override this routine to provide different behavior.
1495   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1496                                             Stmt *Body) {
1497     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1498   }
1499 
1500   /// Build a new Objective-C \@throw statement.
1501   ///
1502   /// By default, performs semantic analysis to build the new statement.
1503   /// Subclasses may override this routine to provide different behavior.
1504   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1505                                           Expr *Operand) {
1506     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1507   }
1508 
1509   /// Build a new OpenMP executable directive.
1510   ///
1511   /// By default, performs semantic analysis to build the new statement.
1512   /// Subclasses may override this routine to provide different behavior.
1513   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1514                                            DeclarationNameInfo DirName,
1515                                            OpenMPDirectiveKind CancelRegion,
1516                                            ArrayRef<OMPClause *> Clauses,
1517                                            Stmt *AStmt, SourceLocation StartLoc,
1518                                            SourceLocation EndLoc) {
1519     return getSema().ActOnOpenMPExecutableDirective(
1520         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1521   }
1522 
1523   /// Build a new OpenMP 'if' clause.
1524   ///
1525   /// By default, performs semantic analysis to build the new OpenMP clause.
1526   /// Subclasses may override this routine to provide different behavior.
1527   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1528                                 Expr *Condition, SourceLocation StartLoc,
1529                                 SourceLocation LParenLoc,
1530                                 SourceLocation NameModifierLoc,
1531                                 SourceLocation ColonLoc,
1532                                 SourceLocation EndLoc) {
1533     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1534                                          LParenLoc, NameModifierLoc, ColonLoc,
1535                                          EndLoc);
1536   }
1537 
1538   /// Build a new OpenMP 'final' clause.
1539   ///
1540   /// By default, performs semantic analysis to build the new OpenMP clause.
1541   /// Subclasses may override this routine to provide different behavior.
1542   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1543                                    SourceLocation LParenLoc,
1544                                    SourceLocation EndLoc) {
1545     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1546                                             EndLoc);
1547   }
1548 
1549   /// Build a new OpenMP 'num_threads' clause.
1550   ///
1551   /// By default, performs semantic analysis to build the new OpenMP clause.
1552   /// Subclasses may override this routine to provide different behavior.
1553   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1554                                         SourceLocation StartLoc,
1555                                         SourceLocation LParenLoc,
1556                                         SourceLocation EndLoc) {
1557     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1558                                                  LParenLoc, EndLoc);
1559   }
1560 
1561   /// Build a new OpenMP 'safelen' clause.
1562   ///
1563   /// By default, performs semantic analysis to build the new OpenMP clause.
1564   /// Subclasses may override this routine to provide different behavior.
1565   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1566                                      SourceLocation LParenLoc,
1567                                      SourceLocation EndLoc) {
1568     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1569   }
1570 
1571   /// Build a new OpenMP 'simdlen' clause.
1572   ///
1573   /// By default, performs semantic analysis to build the new OpenMP clause.
1574   /// Subclasses may override this routine to provide different behavior.
1575   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1576                                      SourceLocation LParenLoc,
1577                                      SourceLocation EndLoc) {
1578     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1579   }
1580 
1581   /// Build a new OpenMP 'allocator' clause.
1582   ///
1583   /// By default, performs semantic analysis to build the new OpenMP clause.
1584   /// Subclasses may override this routine to provide different behavior.
1585   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1586                                        SourceLocation LParenLoc,
1587                                        SourceLocation EndLoc) {
1588     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1589   }
1590 
1591   /// Build a new OpenMP 'collapse' clause.
1592   ///
1593   /// By default, performs semantic analysis to build the new OpenMP clause.
1594   /// Subclasses may override this routine to provide different behavior.
1595   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1596                                       SourceLocation LParenLoc,
1597                                       SourceLocation EndLoc) {
1598     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1599                                                EndLoc);
1600   }
1601 
1602   /// Build a new OpenMP 'default' clause.
1603   ///
1604   /// By default, performs semantic analysis to build the new OpenMP clause.
1605   /// Subclasses may override this routine to provide different behavior.
1606   OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1607                                      SourceLocation KindKwLoc,
1608                                      SourceLocation StartLoc,
1609                                      SourceLocation LParenLoc,
1610                                      SourceLocation EndLoc) {
1611     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1612                                               StartLoc, LParenLoc, EndLoc);
1613   }
1614 
1615   /// Build a new OpenMP 'proc_bind' clause.
1616   ///
1617   /// By default, performs semantic analysis to build the new OpenMP clause.
1618   /// Subclasses may override this routine to provide different behavior.
1619   OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1620                                       SourceLocation KindKwLoc,
1621                                       SourceLocation StartLoc,
1622                                       SourceLocation LParenLoc,
1623                                       SourceLocation EndLoc) {
1624     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1625                                                StartLoc, LParenLoc, EndLoc);
1626   }
1627 
1628   /// Build a new OpenMP 'schedule' clause.
1629   ///
1630   /// By default, performs semantic analysis to build the new OpenMP clause.
1631   /// Subclasses may override this routine to provide different behavior.
1632   OMPClause *RebuildOMPScheduleClause(
1633       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1634       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1635       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1636       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1637     return getSema().ActOnOpenMPScheduleClause(
1638         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1639         CommaLoc, EndLoc);
1640   }
1641 
1642   /// Build a new OpenMP 'ordered' clause.
1643   ///
1644   /// By default, performs semantic analysis to build the new OpenMP clause.
1645   /// Subclasses may override this routine to provide different behavior.
1646   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1647                                      SourceLocation EndLoc,
1648                                      SourceLocation LParenLoc, Expr *Num) {
1649     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1650   }
1651 
1652   /// Build a new OpenMP 'private' clause.
1653   ///
1654   /// By default, performs semantic analysis to build the new OpenMP clause.
1655   /// Subclasses may override this routine to provide different behavior.
1656   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1657                                      SourceLocation StartLoc,
1658                                      SourceLocation LParenLoc,
1659                                      SourceLocation EndLoc) {
1660     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1661                                               EndLoc);
1662   }
1663 
1664   /// Build a new OpenMP 'firstprivate' clause.
1665   ///
1666   /// By default, performs semantic analysis to build the new OpenMP clause.
1667   /// Subclasses may override this routine to provide different behavior.
1668   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1669                                           SourceLocation StartLoc,
1670                                           SourceLocation LParenLoc,
1671                                           SourceLocation EndLoc) {
1672     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1673                                                    EndLoc);
1674   }
1675 
1676   /// Build a new OpenMP 'lastprivate' clause.
1677   ///
1678   /// By default, performs semantic analysis to build the new OpenMP clause.
1679   /// Subclasses may override this routine to provide different behavior.
1680   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1681                                          OpenMPLastprivateModifier LPKind,
1682                                          SourceLocation LPKindLoc,
1683                                          SourceLocation ColonLoc,
1684                                          SourceLocation StartLoc,
1685                                          SourceLocation LParenLoc,
1686                                          SourceLocation EndLoc) {
1687     return getSema().ActOnOpenMPLastprivateClause(
1688         VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1689   }
1690 
1691   /// Build a new OpenMP 'shared' clause.
1692   ///
1693   /// By default, performs semantic analysis to build the new OpenMP clause.
1694   /// Subclasses may override this routine to provide different behavior.
1695   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1696                                     SourceLocation StartLoc,
1697                                     SourceLocation LParenLoc,
1698                                     SourceLocation EndLoc) {
1699     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1700                                              EndLoc);
1701   }
1702 
1703   /// Build a new OpenMP 'reduction' clause.
1704   ///
1705   /// By default, performs semantic analysis to build the new statement.
1706   /// Subclasses may override this routine to provide different behavior.
1707   OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1708                                        SourceLocation StartLoc,
1709                                        SourceLocation LParenLoc,
1710                                        SourceLocation ColonLoc,
1711                                        SourceLocation EndLoc,
1712                                        CXXScopeSpec &ReductionIdScopeSpec,
1713                                        const DeclarationNameInfo &ReductionId,
1714                                        ArrayRef<Expr *> UnresolvedReductions) {
1715     return getSema().ActOnOpenMPReductionClause(
1716         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1717         ReductionId, UnresolvedReductions);
1718   }
1719 
1720   /// Build a new OpenMP 'task_reduction' clause.
1721   ///
1722   /// By default, performs semantic analysis to build the new statement.
1723   /// Subclasses may override this routine to provide different behavior.
1724   OMPClause *RebuildOMPTaskReductionClause(
1725       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1726       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1727       CXXScopeSpec &ReductionIdScopeSpec,
1728       const DeclarationNameInfo &ReductionId,
1729       ArrayRef<Expr *> UnresolvedReductions) {
1730     return getSema().ActOnOpenMPTaskReductionClause(
1731         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1732         ReductionId, UnresolvedReductions);
1733   }
1734 
1735   /// Build a new OpenMP 'in_reduction' clause.
1736   ///
1737   /// By default, performs semantic analysis to build the new statement.
1738   /// Subclasses may override this routine to provide different behavior.
1739   OMPClause *
1740   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1741                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1742                               SourceLocation EndLoc,
1743                               CXXScopeSpec &ReductionIdScopeSpec,
1744                               const DeclarationNameInfo &ReductionId,
1745                               ArrayRef<Expr *> UnresolvedReductions) {
1746     return getSema().ActOnOpenMPInReductionClause(
1747         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1748         ReductionId, UnresolvedReductions);
1749   }
1750 
1751   /// Build a new OpenMP 'linear' clause.
1752   ///
1753   /// By default, performs semantic analysis to build the new OpenMP clause.
1754   /// Subclasses may override this routine to provide different behavior.
1755   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1756                                     SourceLocation StartLoc,
1757                                     SourceLocation LParenLoc,
1758                                     OpenMPLinearClauseKind Modifier,
1759                                     SourceLocation ModifierLoc,
1760                                     SourceLocation ColonLoc,
1761                                     SourceLocation EndLoc) {
1762     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1763                                              Modifier, ModifierLoc, ColonLoc,
1764                                              EndLoc);
1765   }
1766 
1767   /// Build a new OpenMP 'aligned' clause.
1768   ///
1769   /// By default, performs semantic analysis to build the new OpenMP clause.
1770   /// Subclasses may override this routine to provide different behavior.
1771   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1772                                      SourceLocation StartLoc,
1773                                      SourceLocation LParenLoc,
1774                                      SourceLocation ColonLoc,
1775                                      SourceLocation EndLoc) {
1776     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1777                                               LParenLoc, ColonLoc, EndLoc);
1778   }
1779 
1780   /// Build a new OpenMP 'copyin' clause.
1781   ///
1782   /// By default, performs semantic analysis to build the new OpenMP clause.
1783   /// Subclasses may override this routine to provide different behavior.
1784   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1785                                     SourceLocation StartLoc,
1786                                     SourceLocation LParenLoc,
1787                                     SourceLocation EndLoc) {
1788     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1789                                              EndLoc);
1790   }
1791 
1792   /// Build a new OpenMP 'copyprivate' clause.
1793   ///
1794   /// By default, performs semantic analysis to build the new OpenMP clause.
1795   /// Subclasses may override this routine to provide different behavior.
1796   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1797                                          SourceLocation StartLoc,
1798                                          SourceLocation LParenLoc,
1799                                          SourceLocation EndLoc) {
1800     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1801                                                   EndLoc);
1802   }
1803 
1804   /// Build a new OpenMP 'flush' pseudo clause.
1805   ///
1806   /// By default, performs semantic analysis to build the new OpenMP clause.
1807   /// Subclasses may override this routine to provide different behavior.
1808   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1809                                    SourceLocation StartLoc,
1810                                    SourceLocation LParenLoc,
1811                                    SourceLocation EndLoc) {
1812     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1813                                             EndLoc);
1814   }
1815 
1816   /// Build a new OpenMP 'depend' pseudo clause.
1817   ///
1818   /// By default, performs semantic analysis to build the new OpenMP clause.
1819   /// Subclasses may override this routine to provide different behavior.
1820   OMPClause *
1821   RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1822                          SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1823                          SourceLocation StartLoc, SourceLocation LParenLoc,
1824                          SourceLocation EndLoc) {
1825     return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1826                                              StartLoc, LParenLoc, EndLoc);
1827   }
1828 
1829   /// Build a new OpenMP 'device' clause.
1830   ///
1831   /// By default, performs semantic analysis to build the new statement.
1832   /// Subclasses may override this routine to provide different behavior.
1833   OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1834                                     SourceLocation LParenLoc,
1835                                     SourceLocation EndLoc) {
1836     return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1837                                              EndLoc);
1838   }
1839 
1840   /// Build a new OpenMP 'map' clause.
1841   ///
1842   /// By default, performs semantic analysis to build the new OpenMP clause.
1843   /// Subclasses may override this routine to provide different behavior.
1844   OMPClause *RebuildOMPMapClause(
1845       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1846       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1847       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1848       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1849       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1850       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1851     return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1852                                           MapperIdScopeSpec, MapperId, MapType,
1853                                           IsMapTypeImplicit, MapLoc, ColonLoc,
1854                                           VarList, Locs, UnresolvedMappers);
1855   }
1856 
1857   /// Build a new OpenMP 'allocate' clause.
1858   ///
1859   /// By default, performs semantic analysis to build the new OpenMP clause.
1860   /// Subclasses may override this routine to provide different behavior.
1861   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1862                                       SourceLocation StartLoc,
1863                                       SourceLocation LParenLoc,
1864                                       SourceLocation ColonLoc,
1865                                       SourceLocation EndLoc) {
1866     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1867                                                LParenLoc, ColonLoc, EndLoc);
1868   }
1869 
1870   /// Build a new OpenMP 'num_teams' clause.
1871   ///
1872   /// By default, performs semantic analysis to build the new statement.
1873   /// Subclasses may override this routine to provide different behavior.
1874   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1875                                       SourceLocation LParenLoc,
1876                                       SourceLocation EndLoc) {
1877     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1878                                                EndLoc);
1879   }
1880 
1881   /// Build a new OpenMP 'thread_limit' clause.
1882   ///
1883   /// By default, performs semantic analysis to build the new statement.
1884   /// Subclasses may override this routine to provide different behavior.
1885   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1886                                          SourceLocation StartLoc,
1887                                          SourceLocation LParenLoc,
1888                                          SourceLocation EndLoc) {
1889     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1890                                                   LParenLoc, EndLoc);
1891   }
1892 
1893   /// Build a new OpenMP 'priority' clause.
1894   ///
1895   /// By default, performs semantic analysis to build the new statement.
1896   /// Subclasses may override this routine to provide different behavior.
1897   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1898                                       SourceLocation LParenLoc,
1899                                       SourceLocation EndLoc) {
1900     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1901                                                EndLoc);
1902   }
1903 
1904   /// Build a new OpenMP 'grainsize' clause.
1905   ///
1906   /// By default, performs semantic analysis to build the new statement.
1907   /// Subclasses may override this routine to provide different behavior.
1908   OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1909                                        SourceLocation LParenLoc,
1910                                        SourceLocation EndLoc) {
1911     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1912                                                 EndLoc);
1913   }
1914 
1915   /// Build a new OpenMP 'num_tasks' clause.
1916   ///
1917   /// By default, performs semantic analysis to build the new statement.
1918   /// Subclasses may override this routine to provide different behavior.
1919   OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1920                                       SourceLocation LParenLoc,
1921                                       SourceLocation EndLoc) {
1922     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1923                                                EndLoc);
1924   }
1925 
1926   /// Build a new OpenMP 'hint' clause.
1927   ///
1928   /// By default, performs semantic analysis to build the new statement.
1929   /// Subclasses may override this routine to provide different behavior.
1930   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1931                                   SourceLocation LParenLoc,
1932                                   SourceLocation EndLoc) {
1933     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1934   }
1935 
1936   /// Build a new OpenMP 'dist_schedule' clause.
1937   ///
1938   /// By default, performs semantic analysis to build the new OpenMP clause.
1939   /// Subclasses may override this routine to provide different behavior.
1940   OMPClause *
1941   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1942                                Expr *ChunkSize, SourceLocation StartLoc,
1943                                SourceLocation LParenLoc, SourceLocation KindLoc,
1944                                SourceLocation CommaLoc, SourceLocation EndLoc) {
1945     return getSema().ActOnOpenMPDistScheduleClause(
1946         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1947   }
1948 
1949   /// Build a new OpenMP 'to' clause.
1950   ///
1951   /// By default, performs semantic analysis to build the new statement.
1952   /// Subclasses may override this routine to provide different behavior.
1953   OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1954                                 CXXScopeSpec &MapperIdScopeSpec,
1955                                 DeclarationNameInfo &MapperId,
1956                                 const OMPVarListLocTy &Locs,
1957                                 ArrayRef<Expr *> UnresolvedMappers) {
1958     return getSema().ActOnOpenMPToClause(VarList, MapperIdScopeSpec, MapperId,
1959                                          Locs, UnresolvedMappers);
1960   }
1961 
1962   /// Build a new OpenMP 'from' clause.
1963   ///
1964   /// By default, performs semantic analysis to build the new statement.
1965   /// Subclasses may override this routine to provide different behavior.
1966   OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1967                                   CXXScopeSpec &MapperIdScopeSpec,
1968                                   DeclarationNameInfo &MapperId,
1969                                   const OMPVarListLocTy &Locs,
1970                                   ArrayRef<Expr *> UnresolvedMappers) {
1971     return getSema().ActOnOpenMPFromClause(VarList, MapperIdScopeSpec, MapperId,
1972                                            Locs, UnresolvedMappers);
1973   }
1974 
1975   /// Build a new OpenMP 'use_device_ptr' clause.
1976   ///
1977   /// By default, performs semantic analysis to build the new OpenMP clause.
1978   /// Subclasses may override this routine to provide different behavior.
1979   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1980                                           const OMPVarListLocTy &Locs) {
1981     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
1982   }
1983 
1984   /// Build a new OpenMP 'is_device_ptr' clause.
1985   ///
1986   /// By default, performs semantic analysis to build the new OpenMP clause.
1987   /// Subclasses may override this routine to provide different behavior.
1988   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1989                                          const OMPVarListLocTy &Locs) {
1990     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
1991   }
1992 
1993   /// Build a new OpenMP 'defaultmap' clause.
1994   ///
1995   /// By default, performs semantic analysis to build the new OpenMP clause.
1996   /// Subclasses may override this routine to provide different behavior.
1997   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
1998                                         OpenMPDefaultmapClauseKind Kind,
1999                                         SourceLocation StartLoc,
2000                                         SourceLocation LParenLoc,
2001                                         SourceLocation MLoc,
2002                                         SourceLocation KindLoc,
2003                                         SourceLocation EndLoc) {
2004     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2005                                                  MLoc, KindLoc, EndLoc);
2006   }
2007 
2008   /// Build a new OpenMP 'nontemporal' clause.
2009   ///
2010   /// By default, performs semantic analysis to build the new OpenMP clause.
2011   /// Subclasses may override this routine to provide different behavior.
2012   OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2013                                          SourceLocation StartLoc,
2014                                          SourceLocation LParenLoc,
2015                                          SourceLocation EndLoc) {
2016     return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2017                                                   EndLoc);
2018   }
2019 
2020   /// Rebuild the operand to an Objective-C \@synchronized statement.
2021   ///
2022   /// By default, performs semantic analysis to build the new statement.
2023   /// Subclasses may override this routine to provide different behavior.
2024   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2025                                               Expr *object) {
2026     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2027   }
2028 
2029   /// Build a new Objective-C \@synchronized statement.
2030   ///
2031   /// By default, performs semantic analysis to build the new statement.
2032   /// Subclasses may override this routine to provide different behavior.
2033   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2034                                            Expr *Object, Stmt *Body) {
2035     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2036   }
2037 
2038   /// Build a new Objective-C \@autoreleasepool statement.
2039   ///
2040   /// By default, performs semantic analysis to build the new statement.
2041   /// Subclasses may override this routine to provide different behavior.
2042   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2043                                             Stmt *Body) {
2044     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2045   }
2046 
2047   /// Build a new Objective-C fast enumeration statement.
2048   ///
2049   /// By default, performs semantic analysis to build the new statement.
2050   /// Subclasses may override this routine to provide different behavior.
2051   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2052                                           Stmt *Element,
2053                                           Expr *Collection,
2054                                           SourceLocation RParenLoc,
2055                                           Stmt *Body) {
2056     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2057                                                 Element,
2058                                                 Collection,
2059                                                 RParenLoc);
2060     if (ForEachStmt.isInvalid())
2061       return StmtError();
2062 
2063     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2064   }
2065 
2066   /// Build a new C++ exception declaration.
2067   ///
2068   /// By default, performs semantic analysis to build the new decaration.
2069   /// Subclasses may override this routine to provide different behavior.
2070   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2071                                 TypeSourceInfo *Declarator,
2072                                 SourceLocation StartLoc,
2073                                 SourceLocation IdLoc,
2074                                 IdentifierInfo *Id) {
2075     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2076                                                        StartLoc, IdLoc, Id);
2077     if (Var)
2078       getSema().CurContext->addDecl(Var);
2079     return Var;
2080   }
2081 
2082   /// Build a new C++ catch statement.
2083   ///
2084   /// By default, performs semantic analysis to build the new statement.
2085   /// Subclasses may override this routine to provide different behavior.
2086   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2087                                  VarDecl *ExceptionDecl,
2088                                  Stmt *Handler) {
2089     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2090                                                       Handler));
2091   }
2092 
2093   /// Build a new C++ try statement.
2094   ///
2095   /// By default, performs semantic analysis to build the new statement.
2096   /// Subclasses may override this routine to provide different behavior.
2097   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2098                                ArrayRef<Stmt *> Handlers) {
2099     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2100   }
2101 
2102   /// Build a new C++0x range-based for statement.
2103   ///
2104   /// By default, performs semantic analysis to build the new statement.
2105   /// Subclasses may override this routine to provide different behavior.
2106   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2107                                     SourceLocation CoawaitLoc, Stmt *Init,
2108                                     SourceLocation ColonLoc, Stmt *Range,
2109                                     Stmt *Begin, Stmt *End, Expr *Cond,
2110                                     Expr *Inc, Stmt *LoopVar,
2111                                     SourceLocation RParenLoc) {
2112     // If we've just learned that the range is actually an Objective-C
2113     // collection, treat this as an Objective-C fast enumeration loop.
2114     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2115       if (RangeStmt->isSingleDecl()) {
2116         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2117           if (RangeVar->isInvalidDecl())
2118             return StmtError();
2119 
2120           Expr *RangeExpr = RangeVar->getInit();
2121           if (!RangeExpr->isTypeDependent() &&
2122               RangeExpr->getType()->isObjCObjectPointerType()) {
2123             // FIXME: Support init-statements in Objective-C++20 ranged for
2124             // statement.
2125             if (Init) {
2126               return SemaRef.Diag(Init->getBeginLoc(),
2127                                   diag::err_objc_for_range_init_stmt)
2128                          << Init->getSourceRange();
2129             }
2130             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2131                                                         RangeExpr, RParenLoc);
2132           }
2133         }
2134       }
2135     }
2136 
2137     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2138                                           Range, Begin, End, Cond, Inc, LoopVar,
2139                                           RParenLoc, Sema::BFRK_Rebuild);
2140   }
2141 
2142   /// Build a new C++0x range-based for statement.
2143   ///
2144   /// By default, performs semantic analysis to build the new statement.
2145   /// Subclasses may override this routine to provide different behavior.
2146   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2147                                           bool IsIfExists,
2148                                           NestedNameSpecifierLoc QualifierLoc,
2149                                           DeclarationNameInfo NameInfo,
2150                                           Stmt *Nested) {
2151     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2152                                                 QualifierLoc, NameInfo, Nested);
2153   }
2154 
2155   /// Attach body to a C++0x range-based for statement.
2156   ///
2157   /// By default, performs semantic analysis to finish the new statement.
2158   /// Subclasses may override this routine to provide different behavior.
2159   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2160     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2161   }
2162 
2163   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2164                                Stmt *TryBlock, Stmt *Handler) {
2165     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2166   }
2167 
2168   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2169                                   Stmt *Block) {
2170     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2171   }
2172 
2173   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2174     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2175   }
2176 
2177   /// Build a new predefined expression.
2178   ///
2179   /// By default, performs semantic analysis to build the new expression.
2180   /// Subclasses may override this routine to provide different behavior.
2181   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2182                                    PredefinedExpr::IdentKind IK) {
2183     return getSema().BuildPredefinedExpr(Loc, IK);
2184   }
2185 
2186   /// Build a new expression that references a declaration.
2187   ///
2188   /// By default, performs semantic analysis to build the new expression.
2189   /// Subclasses may override this routine to provide different behavior.
2190   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2191                                         LookupResult &R,
2192                                         bool RequiresADL) {
2193     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2194   }
2195 
2196 
2197   /// Build a new expression that references a declaration.
2198   ///
2199   /// By default, performs semantic analysis to build the new expression.
2200   /// Subclasses may override this routine to provide different behavior.
2201   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2202                                 ValueDecl *VD,
2203                                 const DeclarationNameInfo &NameInfo,
2204                                 NamedDecl *Found,
2205                                 TemplateArgumentListInfo *TemplateArgs) {
2206     CXXScopeSpec SS;
2207     SS.Adopt(QualifierLoc);
2208     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2209                                               TemplateArgs);
2210   }
2211 
2212   /// Build a new expression in parentheses.
2213   ///
2214   /// By default, performs semantic analysis to build the new expression.
2215   /// Subclasses may override this routine to provide different behavior.
2216   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2217                                     SourceLocation RParen) {
2218     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2219   }
2220 
2221   /// Build a new pseudo-destructor expression.
2222   ///
2223   /// By default, performs semantic analysis to build the new expression.
2224   /// Subclasses may override this routine to provide different behavior.
2225   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2226                                             SourceLocation OperatorLoc,
2227                                             bool isArrow,
2228                                             CXXScopeSpec &SS,
2229                                             TypeSourceInfo *ScopeType,
2230                                             SourceLocation CCLoc,
2231                                             SourceLocation TildeLoc,
2232                                         PseudoDestructorTypeStorage Destroyed);
2233 
2234   /// Build a new unary operator expression.
2235   ///
2236   /// By default, performs semantic analysis to build the new expression.
2237   /// Subclasses may override this routine to provide different behavior.
2238   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2239                                         UnaryOperatorKind Opc,
2240                                         Expr *SubExpr) {
2241     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2242   }
2243 
2244   /// Build a new builtin offsetof expression.
2245   ///
2246   /// By default, performs semantic analysis to build the new expression.
2247   /// Subclasses may override this routine to provide different behavior.
2248   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2249                                  TypeSourceInfo *Type,
2250                                  ArrayRef<Sema::OffsetOfComponent> Components,
2251                                  SourceLocation RParenLoc) {
2252     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2253                                           RParenLoc);
2254   }
2255 
2256   /// Build a new sizeof, alignof or vec_step expression with a
2257   /// type argument.
2258   ///
2259   /// By default, performs semantic analysis to build the new expression.
2260   /// Subclasses may override this routine to provide different behavior.
2261   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2262                                          SourceLocation OpLoc,
2263                                          UnaryExprOrTypeTrait ExprKind,
2264                                          SourceRange R) {
2265     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2266   }
2267 
2268   /// Build a new sizeof, alignof or vec step expression with an
2269   /// expression argument.
2270   ///
2271   /// By default, performs semantic analysis to build the new expression.
2272   /// Subclasses may override this routine to provide different behavior.
2273   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2274                                          UnaryExprOrTypeTrait ExprKind,
2275                                          SourceRange R) {
2276     ExprResult Result
2277       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2278     if (Result.isInvalid())
2279       return ExprError();
2280 
2281     return Result;
2282   }
2283 
2284   /// Build a new array subscript expression.
2285   ///
2286   /// By default, performs semantic analysis to build the new expression.
2287   /// Subclasses may override this routine to provide different behavior.
2288   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2289                                              SourceLocation LBracketLoc,
2290                                              Expr *RHS,
2291                                              SourceLocation RBracketLoc) {
2292     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2293                                              LBracketLoc, RHS,
2294                                              RBracketLoc);
2295   }
2296 
2297   /// Build a new array section expression.
2298   ///
2299   /// By default, performs semantic analysis to build the new expression.
2300   /// Subclasses may override this routine to provide different behavior.
2301   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2302                                         Expr *LowerBound,
2303                                         SourceLocation ColonLoc, Expr *Length,
2304                                         SourceLocation RBracketLoc) {
2305     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2306                                               ColonLoc, Length, RBracketLoc);
2307   }
2308 
2309   /// Build a new call expression.
2310   ///
2311   /// By default, performs semantic analysis to build the new expression.
2312   /// Subclasses may override this routine to provide different behavior.
2313   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2314                                    MultiExprArg Args,
2315                                    SourceLocation RParenLoc,
2316                                    Expr *ExecConfig = nullptr) {
2317     return getSema().BuildCallExpr(/*Scope=*/nullptr, Callee, LParenLoc, Args,
2318                                    RParenLoc, ExecConfig);
2319   }
2320 
2321   /// Build a new member access expression.
2322   ///
2323   /// By default, performs semantic analysis to build the new expression.
2324   /// Subclasses may override this routine to provide different behavior.
2325   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2326                                bool isArrow,
2327                                NestedNameSpecifierLoc QualifierLoc,
2328                                SourceLocation TemplateKWLoc,
2329                                const DeclarationNameInfo &MemberNameInfo,
2330                                ValueDecl *Member,
2331                                NamedDecl *FoundDecl,
2332                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2333                                NamedDecl *FirstQualifierInScope) {
2334     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2335                                                                       isArrow);
2336     if (!Member->getDeclName()) {
2337       // We have a reference to an unnamed field.  This is always the
2338       // base of an anonymous struct/union member access, i.e. the
2339       // field is always of record type.
2340       assert(Member->getType()->isRecordType() &&
2341              "unnamed member not of record type?");
2342 
2343       BaseResult =
2344         getSema().PerformObjectMemberConversion(BaseResult.get(),
2345                                                 QualifierLoc.getNestedNameSpecifier(),
2346                                                 FoundDecl, Member);
2347       if (BaseResult.isInvalid())
2348         return ExprError();
2349       Base = BaseResult.get();
2350 
2351       CXXScopeSpec EmptySS;
2352       return getSema().BuildFieldReferenceExpr(
2353           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2354           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2355     }
2356 
2357     CXXScopeSpec SS;
2358     SS.Adopt(QualifierLoc);
2359 
2360     Base = BaseResult.get();
2361     QualType BaseType = Base->getType();
2362 
2363     if (isArrow && !BaseType->isPointerType())
2364       return ExprError();
2365 
2366     // FIXME: this involves duplicating earlier analysis in a lot of
2367     // cases; we should avoid this when possible.
2368     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2369     R.addDecl(FoundDecl);
2370     R.resolveKind();
2371 
2372     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2373                                               SS, TemplateKWLoc,
2374                                               FirstQualifierInScope,
2375                                               R, ExplicitTemplateArgs,
2376                                               /*S*/nullptr);
2377   }
2378 
2379   /// Build a new binary operator expression.
2380   ///
2381   /// By default, performs semantic analysis to build the new expression.
2382   /// Subclasses may override this routine to provide different behavior.
2383   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2384                                          BinaryOperatorKind Opc,
2385                                          Expr *LHS, Expr *RHS) {
2386     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2387   }
2388 
2389   /// Build a new rewritten operator expression.
2390   ///
2391   /// By default, performs semantic analysis to build the new expression.
2392   /// Subclasses may override this routine to provide different behavior.
2393   ExprResult RebuildCXXRewrittenBinaryOperator(
2394       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2395       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2396     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2397                                            RHS, /*RequiresADL*/false);
2398   }
2399 
2400   /// Build a new conditional operator expression.
2401   ///
2402   /// By default, performs semantic analysis to build the new expression.
2403   /// Subclasses may override this routine to provide different behavior.
2404   ExprResult RebuildConditionalOperator(Expr *Cond,
2405                                         SourceLocation QuestionLoc,
2406                                         Expr *LHS,
2407                                         SourceLocation ColonLoc,
2408                                         Expr *RHS) {
2409     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2410                                         LHS, RHS);
2411   }
2412 
2413   /// Build a new C-style cast expression.
2414   ///
2415   /// By default, performs semantic analysis to build the new expression.
2416   /// Subclasses may override this routine to provide different behavior.
2417   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2418                                          TypeSourceInfo *TInfo,
2419                                          SourceLocation RParenLoc,
2420                                          Expr *SubExpr) {
2421     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2422                                          SubExpr);
2423   }
2424 
2425   /// Build a new compound literal expression.
2426   ///
2427   /// By default, performs semantic analysis to build the new expression.
2428   /// Subclasses may override this routine to provide different behavior.
2429   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2430                                               TypeSourceInfo *TInfo,
2431                                               SourceLocation RParenLoc,
2432                                               Expr *Init) {
2433     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2434                                               Init);
2435   }
2436 
2437   /// Build a new extended vector element access expression.
2438   ///
2439   /// By default, performs semantic analysis to build the new expression.
2440   /// Subclasses may override this routine to provide different behavior.
2441   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2442                                                SourceLocation OpLoc,
2443                                                SourceLocation AccessorLoc,
2444                                                IdentifierInfo &Accessor) {
2445 
2446     CXXScopeSpec SS;
2447     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2448     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2449                                               OpLoc, /*IsArrow*/ false,
2450                                               SS, SourceLocation(),
2451                                               /*FirstQualifierInScope*/ nullptr,
2452                                               NameInfo,
2453                                               /* TemplateArgs */ nullptr,
2454                                               /*S*/ nullptr);
2455   }
2456 
2457   /// Build a new initializer list expression.
2458   ///
2459   /// By default, performs semantic analysis to build the new expression.
2460   /// Subclasses may override this routine to provide different behavior.
2461   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2462                              MultiExprArg Inits,
2463                              SourceLocation RBraceLoc) {
2464     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2465   }
2466 
2467   /// Build a new designated initializer expression.
2468   ///
2469   /// By default, performs semantic analysis to build the new expression.
2470   /// Subclasses may override this routine to provide different behavior.
2471   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2472                                              MultiExprArg ArrayExprs,
2473                                              SourceLocation EqualOrColonLoc,
2474                                              bool GNUSyntax,
2475                                              Expr *Init) {
2476     ExprResult Result
2477       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2478                                            Init);
2479     if (Result.isInvalid())
2480       return ExprError();
2481 
2482     return Result;
2483   }
2484 
2485   /// Build a new value-initialized expression.
2486   ///
2487   /// By default, builds the implicit value initialization without performing
2488   /// any semantic analysis. Subclasses may override this routine to provide
2489   /// different behavior.
2490   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2491     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2492   }
2493 
2494   /// Build a new \c va_arg expression.
2495   ///
2496   /// By default, performs semantic analysis to build the new expression.
2497   /// Subclasses may override this routine to provide different behavior.
2498   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2499                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2500                                     SourceLocation RParenLoc) {
2501     return getSema().BuildVAArgExpr(BuiltinLoc,
2502                                     SubExpr, TInfo,
2503                                     RParenLoc);
2504   }
2505 
2506   /// Build a new expression list in parentheses.
2507   ///
2508   /// By default, performs semantic analysis to build the new expression.
2509   /// Subclasses may override this routine to provide different behavior.
2510   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2511                                   MultiExprArg SubExprs,
2512                                   SourceLocation RParenLoc) {
2513     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2514   }
2515 
2516   /// Build a new address-of-label expression.
2517   ///
2518   /// By default, performs semantic analysis, using the name of the label
2519   /// rather than attempting to map the label statement itself.
2520   /// Subclasses may override this routine to provide different behavior.
2521   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2522                                   SourceLocation LabelLoc, LabelDecl *Label) {
2523     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2524   }
2525 
2526   /// Build a new GNU statement expression.
2527   ///
2528   /// By default, performs semantic analysis to build the new expression.
2529   /// Subclasses may override this routine to provide different behavior.
2530   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2531                                    Stmt *SubStmt,
2532                                    SourceLocation RParenLoc) {
2533     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2534   }
2535 
2536   /// Build a new __builtin_choose_expr expression.
2537   ///
2538   /// By default, performs semantic analysis to build the new expression.
2539   /// Subclasses may override this routine to provide different behavior.
2540   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2541                                      Expr *Cond, Expr *LHS, Expr *RHS,
2542                                      SourceLocation RParenLoc) {
2543     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2544                                    Cond, LHS, RHS,
2545                                    RParenLoc);
2546   }
2547 
2548   /// Build a new generic selection expression.
2549   ///
2550   /// By default, performs semantic analysis to build the new expression.
2551   /// Subclasses may override this routine to provide different behavior.
2552   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2553                                          SourceLocation DefaultLoc,
2554                                          SourceLocation RParenLoc,
2555                                          Expr *ControllingExpr,
2556                                          ArrayRef<TypeSourceInfo *> Types,
2557                                          ArrayRef<Expr *> Exprs) {
2558     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2559                                                 ControllingExpr, Types, Exprs);
2560   }
2561 
2562   /// Build a new overloaded operator call expression.
2563   ///
2564   /// By default, performs semantic analysis to build the new expression.
2565   /// The semantic analysis provides the behavior of template instantiation,
2566   /// copying with transformations that turn what looks like an overloaded
2567   /// operator call into a use of a builtin operator, performing
2568   /// argument-dependent lookup, etc. Subclasses may override this routine to
2569   /// provide different behavior.
2570   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2571                                               SourceLocation OpLoc,
2572                                               Expr *Callee,
2573                                               Expr *First,
2574                                               Expr *Second);
2575 
2576   /// Build a new C++ "named" cast expression, such as static_cast or
2577   /// reinterpret_cast.
2578   ///
2579   /// By default, this routine dispatches to one of the more-specific routines
2580   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2581   /// Subclasses may override this routine to provide different behavior.
2582   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2583                                            Stmt::StmtClass Class,
2584                                            SourceLocation LAngleLoc,
2585                                            TypeSourceInfo *TInfo,
2586                                            SourceLocation RAngleLoc,
2587                                            SourceLocation LParenLoc,
2588                                            Expr *SubExpr,
2589                                            SourceLocation RParenLoc) {
2590     switch (Class) {
2591     case Stmt::CXXStaticCastExprClass:
2592       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2593                                                    RAngleLoc, LParenLoc,
2594                                                    SubExpr, RParenLoc);
2595 
2596     case Stmt::CXXDynamicCastExprClass:
2597       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2598                                                     RAngleLoc, LParenLoc,
2599                                                     SubExpr, RParenLoc);
2600 
2601     case Stmt::CXXReinterpretCastExprClass:
2602       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2603                                                         RAngleLoc, LParenLoc,
2604                                                         SubExpr,
2605                                                         RParenLoc);
2606 
2607     case Stmt::CXXConstCastExprClass:
2608       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2609                                                    RAngleLoc, LParenLoc,
2610                                                    SubExpr, RParenLoc);
2611 
2612     default:
2613       llvm_unreachable("Invalid C++ named cast");
2614     }
2615   }
2616 
2617   /// Build a new C++ static_cast expression.
2618   ///
2619   /// By default, performs semantic analysis to build the new expression.
2620   /// Subclasses may override this routine to provide different behavior.
2621   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2622                                             SourceLocation LAngleLoc,
2623                                             TypeSourceInfo *TInfo,
2624                                             SourceLocation RAngleLoc,
2625                                             SourceLocation LParenLoc,
2626                                             Expr *SubExpr,
2627                                             SourceLocation RParenLoc) {
2628     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2629                                        TInfo, SubExpr,
2630                                        SourceRange(LAngleLoc, RAngleLoc),
2631                                        SourceRange(LParenLoc, RParenLoc));
2632   }
2633 
2634   /// Build a new C++ dynamic_cast expression.
2635   ///
2636   /// By default, performs semantic analysis to build the new expression.
2637   /// Subclasses may override this routine to provide different behavior.
2638   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2639                                              SourceLocation LAngleLoc,
2640                                              TypeSourceInfo *TInfo,
2641                                              SourceLocation RAngleLoc,
2642                                              SourceLocation LParenLoc,
2643                                              Expr *SubExpr,
2644                                              SourceLocation RParenLoc) {
2645     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2646                                        TInfo, SubExpr,
2647                                        SourceRange(LAngleLoc, RAngleLoc),
2648                                        SourceRange(LParenLoc, RParenLoc));
2649   }
2650 
2651   /// Build a new C++ reinterpret_cast expression.
2652   ///
2653   /// By default, performs semantic analysis to build the new expression.
2654   /// Subclasses may override this routine to provide different behavior.
2655   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2656                                                  SourceLocation LAngleLoc,
2657                                                  TypeSourceInfo *TInfo,
2658                                                  SourceLocation RAngleLoc,
2659                                                  SourceLocation LParenLoc,
2660                                                  Expr *SubExpr,
2661                                                  SourceLocation RParenLoc) {
2662     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2663                                        TInfo, SubExpr,
2664                                        SourceRange(LAngleLoc, RAngleLoc),
2665                                        SourceRange(LParenLoc, RParenLoc));
2666   }
2667 
2668   /// Build a new C++ const_cast expression.
2669   ///
2670   /// By default, performs semantic analysis to build the new expression.
2671   /// Subclasses may override this routine to provide different behavior.
2672   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2673                                            SourceLocation LAngleLoc,
2674                                            TypeSourceInfo *TInfo,
2675                                            SourceLocation RAngleLoc,
2676                                            SourceLocation LParenLoc,
2677                                            Expr *SubExpr,
2678                                            SourceLocation RParenLoc) {
2679     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2680                                        TInfo, SubExpr,
2681                                        SourceRange(LAngleLoc, RAngleLoc),
2682                                        SourceRange(LParenLoc, RParenLoc));
2683   }
2684 
2685   /// Build a new C++ functional-style cast expression.
2686   ///
2687   /// By default, performs semantic analysis to build the new expression.
2688   /// Subclasses may override this routine to provide different behavior.
2689   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2690                                           SourceLocation LParenLoc,
2691                                           Expr *Sub,
2692                                           SourceLocation RParenLoc,
2693                                           bool ListInitialization) {
2694     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2695                                                MultiExprArg(&Sub, 1), RParenLoc,
2696                                                ListInitialization);
2697   }
2698 
2699   /// Build a new C++ __builtin_bit_cast expression.
2700   ///
2701   /// By default, performs semantic analysis to build the new expression.
2702   /// Subclasses may override this routine to provide different behavior.
2703   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2704                                        TypeSourceInfo *TSI, Expr *Sub,
2705                                        SourceLocation RParenLoc) {
2706     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
2707   }
2708 
2709   /// Build a new C++ typeid(type) expression.
2710   ///
2711   /// By default, performs semantic analysis to build the new expression.
2712   /// Subclasses may override this routine to provide different behavior.
2713   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2714                                         SourceLocation TypeidLoc,
2715                                         TypeSourceInfo *Operand,
2716                                         SourceLocation RParenLoc) {
2717     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2718                                     RParenLoc);
2719   }
2720 
2721 
2722   /// Build a new C++ typeid(expr) expression.
2723   ///
2724   /// By default, performs semantic analysis to build the new expression.
2725   /// Subclasses may override this routine to provide different behavior.
2726   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2727                                         SourceLocation TypeidLoc,
2728                                         Expr *Operand,
2729                                         SourceLocation RParenLoc) {
2730     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2731                                     RParenLoc);
2732   }
2733 
2734   /// Build a new C++ __uuidof(type) expression.
2735   ///
2736   /// By default, performs semantic analysis to build the new expression.
2737   /// Subclasses may override this routine to provide different behavior.
2738   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2739                                         SourceLocation TypeidLoc,
2740                                         TypeSourceInfo *Operand,
2741                                         SourceLocation RParenLoc) {
2742     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2743                                     RParenLoc);
2744   }
2745 
2746   /// Build a new C++ __uuidof(expr) expression.
2747   ///
2748   /// By default, performs semantic analysis to build the new expression.
2749   /// Subclasses may override this routine to provide different behavior.
2750   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2751                                         SourceLocation TypeidLoc,
2752                                         Expr *Operand,
2753                                         SourceLocation RParenLoc) {
2754     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2755                                     RParenLoc);
2756   }
2757 
2758   /// Build a new C++ "this" expression.
2759   ///
2760   /// By default, builds a new "this" expression without performing any
2761   /// semantic analysis. Subclasses may override this routine to provide
2762   /// different behavior.
2763   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2764                                 QualType ThisType,
2765                                 bool isImplicit) {
2766     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
2767   }
2768 
2769   /// Build a new C++ throw expression.
2770   ///
2771   /// By default, performs semantic analysis to build the new expression.
2772   /// Subclasses may override this routine to provide different behavior.
2773   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2774                                  bool IsThrownVariableInScope) {
2775     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2776   }
2777 
2778   /// Build a new C++ default-argument expression.
2779   ///
2780   /// By default, builds a new default-argument expression, which does not
2781   /// require any semantic analysis. Subclasses may override this routine to
2782   /// provide different behavior.
2783   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
2784     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
2785                                      getSema().CurContext);
2786   }
2787 
2788   /// Build a new C++11 default-initialization expression.
2789   ///
2790   /// By default, builds a new default field initialization expression, which
2791   /// does not require any semantic analysis. Subclasses may override this
2792   /// routine to provide different behavior.
2793   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2794                                        FieldDecl *Field) {
2795     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
2796                                       getSema().CurContext);
2797   }
2798 
2799   /// Build a new C++ zero-initialization expression.
2800   ///
2801   /// By default, performs semantic analysis to build the new expression.
2802   /// Subclasses may override this routine to provide different behavior.
2803   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2804                                            SourceLocation LParenLoc,
2805                                            SourceLocation RParenLoc) {
2806     return getSema().BuildCXXTypeConstructExpr(
2807         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2808   }
2809 
2810   /// Build a new C++ "new" expression.
2811   ///
2812   /// By default, performs semantic analysis to build the new expression.
2813   /// Subclasses may override this routine to provide different behavior.
2814   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2815                                bool UseGlobal,
2816                                SourceLocation PlacementLParen,
2817                                MultiExprArg PlacementArgs,
2818                                SourceLocation PlacementRParen,
2819                                SourceRange TypeIdParens,
2820                                QualType AllocatedType,
2821                                TypeSourceInfo *AllocatedTypeInfo,
2822                                Optional<Expr *> ArraySize,
2823                                SourceRange DirectInitRange,
2824                                Expr *Initializer) {
2825     return getSema().BuildCXXNew(StartLoc, UseGlobal,
2826                                  PlacementLParen,
2827                                  PlacementArgs,
2828                                  PlacementRParen,
2829                                  TypeIdParens,
2830                                  AllocatedType,
2831                                  AllocatedTypeInfo,
2832                                  ArraySize,
2833                                  DirectInitRange,
2834                                  Initializer);
2835   }
2836 
2837   /// Build a new C++ "delete" expression.
2838   ///
2839   /// By default, performs semantic analysis to build the new expression.
2840   /// Subclasses may override this routine to provide different behavior.
2841   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2842                                         bool IsGlobalDelete,
2843                                         bool IsArrayForm,
2844                                         Expr *Operand) {
2845     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2846                                     Operand);
2847   }
2848 
2849   /// Build a new type trait expression.
2850   ///
2851   /// By default, performs semantic analysis to build the new expression.
2852   /// Subclasses may override this routine to provide different behavior.
2853   ExprResult RebuildTypeTrait(TypeTrait Trait,
2854                               SourceLocation StartLoc,
2855                               ArrayRef<TypeSourceInfo *> Args,
2856                               SourceLocation RParenLoc) {
2857     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2858   }
2859 
2860   /// Build a new array type trait expression.
2861   ///
2862   /// By default, performs semantic analysis to build the new expression.
2863   /// Subclasses may override this routine to provide different behavior.
2864   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2865                                    SourceLocation StartLoc,
2866                                    TypeSourceInfo *TSInfo,
2867                                    Expr *DimExpr,
2868                                    SourceLocation RParenLoc) {
2869     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2870   }
2871 
2872   /// Build a new expression trait expression.
2873   ///
2874   /// By default, performs semantic analysis to build the new expression.
2875   /// Subclasses may override this routine to provide different behavior.
2876   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2877                                    SourceLocation StartLoc,
2878                                    Expr *Queried,
2879                                    SourceLocation RParenLoc) {
2880     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2881   }
2882 
2883   /// Build a new (previously unresolved) declaration reference
2884   /// expression.
2885   ///
2886   /// By default, performs semantic analysis to build the new expression.
2887   /// Subclasses may override this routine to provide different behavior.
2888   ExprResult RebuildDependentScopeDeclRefExpr(
2889                                           NestedNameSpecifierLoc QualifierLoc,
2890                                           SourceLocation TemplateKWLoc,
2891                                        const DeclarationNameInfo &NameInfo,
2892                               const TemplateArgumentListInfo *TemplateArgs,
2893                                           bool IsAddressOfOperand,
2894                                           TypeSourceInfo **RecoveryTSI) {
2895     CXXScopeSpec SS;
2896     SS.Adopt(QualifierLoc);
2897 
2898     if (TemplateArgs || TemplateKWLoc.isValid())
2899       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2900                                                     TemplateArgs);
2901 
2902     return getSema().BuildQualifiedDeclarationNameExpr(
2903         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2904   }
2905 
2906   /// Build a new template-id expression.
2907   ///
2908   /// By default, performs semantic analysis to build the new expression.
2909   /// Subclasses may override this routine to provide different behavior.
2910   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2911                                    SourceLocation TemplateKWLoc,
2912                                    LookupResult &R,
2913                                    bool RequiresADL,
2914                               const TemplateArgumentListInfo *TemplateArgs) {
2915     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2916                                          TemplateArgs);
2917   }
2918 
2919   /// Build a new object-construction expression.
2920   ///
2921   /// By default, performs semantic analysis to build the new expression.
2922   /// Subclasses may override this routine to provide different behavior.
2923   ExprResult RebuildCXXConstructExpr(QualType T,
2924                                      SourceLocation Loc,
2925                                      CXXConstructorDecl *Constructor,
2926                                      bool IsElidable,
2927                                      MultiExprArg Args,
2928                                      bool HadMultipleCandidates,
2929                                      bool ListInitialization,
2930                                      bool StdInitListInitialization,
2931                                      bool RequiresZeroInit,
2932                              CXXConstructExpr::ConstructionKind ConstructKind,
2933                                      SourceRange ParenRange) {
2934     SmallVector<Expr*, 8> ConvertedArgs;
2935     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2936                                           ConvertedArgs))
2937       return ExprError();
2938 
2939     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2940                                            IsElidable,
2941                                            ConvertedArgs,
2942                                            HadMultipleCandidates,
2943                                            ListInitialization,
2944                                            StdInitListInitialization,
2945                                            RequiresZeroInit, ConstructKind,
2946                                            ParenRange);
2947   }
2948 
2949   /// Build a new implicit construction via inherited constructor
2950   /// expression.
2951   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2952                                              CXXConstructorDecl *Constructor,
2953                                              bool ConstructsVBase,
2954                                              bool InheritedFromVBase) {
2955     return new (getSema().Context) CXXInheritedCtorInitExpr(
2956         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2957   }
2958 
2959   /// Build a new object-construction expression.
2960   ///
2961   /// By default, performs semantic analysis to build the new expression.
2962   /// Subclasses may override this routine to provide different behavior.
2963   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2964                                            SourceLocation LParenOrBraceLoc,
2965                                            MultiExprArg Args,
2966                                            SourceLocation RParenOrBraceLoc,
2967                                            bool ListInitialization) {
2968     return getSema().BuildCXXTypeConstructExpr(
2969         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
2970   }
2971 
2972   /// Build a new object-construction expression.
2973   ///
2974   /// By default, performs semantic analysis to build the new expression.
2975   /// Subclasses may override this routine to provide different behavior.
2976   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2977                                                SourceLocation LParenLoc,
2978                                                MultiExprArg Args,
2979                                                SourceLocation RParenLoc,
2980                                                bool ListInitialization) {
2981     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
2982                                                RParenLoc, ListInitialization);
2983   }
2984 
2985   /// Build a new member reference expression.
2986   ///
2987   /// By default, performs semantic analysis to build the new expression.
2988   /// Subclasses may override this routine to provide different behavior.
2989   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2990                                                 QualType BaseType,
2991                                                 bool IsArrow,
2992                                                 SourceLocation OperatorLoc,
2993                                           NestedNameSpecifierLoc QualifierLoc,
2994                                                 SourceLocation TemplateKWLoc,
2995                                             NamedDecl *FirstQualifierInScope,
2996                                    const DeclarationNameInfo &MemberNameInfo,
2997                               const TemplateArgumentListInfo *TemplateArgs) {
2998     CXXScopeSpec SS;
2999     SS.Adopt(QualifierLoc);
3000 
3001     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3002                                             OperatorLoc, IsArrow,
3003                                             SS, TemplateKWLoc,
3004                                             FirstQualifierInScope,
3005                                             MemberNameInfo,
3006                                             TemplateArgs, /*S*/nullptr);
3007   }
3008 
3009   /// Build a new member reference expression.
3010   ///
3011   /// By default, performs semantic analysis to build the new expression.
3012   /// Subclasses may override this routine to provide different behavior.
3013   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3014                                          SourceLocation OperatorLoc,
3015                                          bool IsArrow,
3016                                          NestedNameSpecifierLoc QualifierLoc,
3017                                          SourceLocation TemplateKWLoc,
3018                                          NamedDecl *FirstQualifierInScope,
3019                                          LookupResult &R,
3020                                 const TemplateArgumentListInfo *TemplateArgs) {
3021     CXXScopeSpec SS;
3022     SS.Adopt(QualifierLoc);
3023 
3024     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3025                                             OperatorLoc, IsArrow,
3026                                             SS, TemplateKWLoc,
3027                                             FirstQualifierInScope,
3028                                             R, TemplateArgs, /*S*/nullptr);
3029   }
3030 
3031   /// Build a new noexcept expression.
3032   ///
3033   /// By default, performs semantic analysis to build the new expression.
3034   /// Subclasses may override this routine to provide different behavior.
3035   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3036     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3037   }
3038 
3039   /// Build a new expression to compute the length of a parameter pack.
3040   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3041                                    NamedDecl *Pack,
3042                                    SourceLocation PackLoc,
3043                                    SourceLocation RParenLoc,
3044                                    Optional<unsigned> Length,
3045                                    ArrayRef<TemplateArgument> PartialArgs) {
3046     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3047                                   RParenLoc, Length, PartialArgs);
3048   }
3049 
3050   /// Build a new expression representing a call to a source location
3051   ///  builtin.
3052   ///
3053   /// By default, performs semantic analysis to build the new expression.
3054   /// Subclasses may override this routine to provide different behavior.
3055   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3056                                   SourceLocation BuiltinLoc,
3057                                   SourceLocation RPLoc,
3058                                   DeclContext *ParentContext) {
3059     return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3060   }
3061 
3062   /// Build a new Objective-C boxed expression.
3063   ///
3064   /// By default, performs semantic analysis to build the new expression.
3065   /// Subclasses may override this routine to provide different behavior.
3066   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3067       SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3068       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3069       TemplateArgumentListInfo *TALI) {
3070     CXXScopeSpec SS;
3071     SS.Adopt(NNS);
3072     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3073                                                          ConceptNameInfo,
3074                                                          FoundDecl,
3075                                                          NamedConcept, TALI);
3076     if (Result.isInvalid())
3077       return ExprError();
3078     return Result;
3079   }
3080 
3081     /// \brief Build a new Objective-C boxed expression.
3082   ///
3083   /// By default, performs semantic analysis to build the new expression.
3084   /// Subclasses may override this routine to provide different behavior.
3085   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3086     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3087   }
3088 
3089   /// Build a new Objective-C array literal.
3090   ///
3091   /// By default, performs semantic analysis to build the new expression.
3092   /// Subclasses may override this routine to provide different behavior.
3093   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3094                                      Expr **Elements, unsigned NumElements) {
3095     return getSema().BuildObjCArrayLiteral(Range,
3096                                            MultiExprArg(Elements, NumElements));
3097   }
3098 
3099   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3100                                          Expr *Base, Expr *Key,
3101                                          ObjCMethodDecl *getterMethod,
3102                                          ObjCMethodDecl *setterMethod) {
3103     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3104                                                    getterMethod, setterMethod);
3105   }
3106 
3107   /// Build a new Objective-C dictionary literal.
3108   ///
3109   /// By default, performs semantic analysis to build the new expression.
3110   /// Subclasses may override this routine to provide different behavior.
3111   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3112                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3113     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3114   }
3115 
3116   /// Build a new Objective-C \@encode expression.
3117   ///
3118   /// By default, performs semantic analysis to build the new expression.
3119   /// Subclasses may override this routine to provide different behavior.
3120   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3121                                          TypeSourceInfo *EncodeTypeInfo,
3122                                          SourceLocation RParenLoc) {
3123     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3124   }
3125 
3126   /// Build a new Objective-C class message.
3127   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3128                                           Selector Sel,
3129                                           ArrayRef<SourceLocation> SelectorLocs,
3130                                           ObjCMethodDecl *Method,
3131                                           SourceLocation LBracLoc,
3132                                           MultiExprArg Args,
3133                                           SourceLocation RBracLoc) {
3134     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3135                                      ReceiverTypeInfo->getType(),
3136                                      /*SuperLoc=*/SourceLocation(),
3137                                      Sel, Method, LBracLoc, SelectorLocs,
3138                                      RBracLoc, Args);
3139   }
3140 
3141   /// Build a new Objective-C instance message.
3142   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3143                                           Selector Sel,
3144                                           ArrayRef<SourceLocation> SelectorLocs,
3145                                           ObjCMethodDecl *Method,
3146                                           SourceLocation LBracLoc,
3147                                           MultiExprArg Args,
3148                                           SourceLocation RBracLoc) {
3149     return SemaRef.BuildInstanceMessage(Receiver,
3150                                         Receiver->getType(),
3151                                         /*SuperLoc=*/SourceLocation(),
3152                                         Sel, Method, LBracLoc, SelectorLocs,
3153                                         RBracLoc, Args);
3154   }
3155 
3156   /// Build a new Objective-C instance/class message to 'super'.
3157   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3158                                     Selector Sel,
3159                                     ArrayRef<SourceLocation> SelectorLocs,
3160                                     QualType SuperType,
3161                                     ObjCMethodDecl *Method,
3162                                     SourceLocation LBracLoc,
3163                                     MultiExprArg Args,
3164                                     SourceLocation RBracLoc) {
3165     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3166                                           SuperType,
3167                                           SuperLoc,
3168                                           Sel, Method, LBracLoc, SelectorLocs,
3169                                           RBracLoc, Args)
3170                                       : SemaRef.BuildClassMessage(nullptr,
3171                                           SuperType,
3172                                           SuperLoc,
3173                                           Sel, Method, LBracLoc, SelectorLocs,
3174                                           RBracLoc, Args);
3175 
3176 
3177   }
3178 
3179   /// Build a new Objective-C ivar reference expression.
3180   ///
3181   /// By default, performs semantic analysis to build the new expression.
3182   /// Subclasses may override this routine to provide different behavior.
3183   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3184                                           SourceLocation IvarLoc,
3185                                           bool IsArrow, bool IsFreeIvar) {
3186     CXXScopeSpec SS;
3187     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3188     ExprResult Result = getSema().BuildMemberReferenceExpr(
3189         BaseArg, BaseArg->getType(),
3190         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3191         /*FirstQualifierInScope=*/nullptr, NameInfo,
3192         /*TemplateArgs=*/nullptr,
3193         /*S=*/nullptr);
3194     if (IsFreeIvar && Result.isUsable())
3195       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3196     return Result;
3197   }
3198 
3199   /// Build a new Objective-C property reference expression.
3200   ///
3201   /// By default, performs semantic analysis to build the new expression.
3202   /// Subclasses may override this routine to provide different behavior.
3203   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3204                                         ObjCPropertyDecl *Property,
3205                                         SourceLocation PropertyLoc) {
3206     CXXScopeSpec SS;
3207     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3208     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3209                                               /*FIXME:*/PropertyLoc,
3210                                               /*IsArrow=*/false,
3211                                               SS, SourceLocation(),
3212                                               /*FirstQualifierInScope=*/nullptr,
3213                                               NameInfo,
3214                                               /*TemplateArgs=*/nullptr,
3215                                               /*S=*/nullptr);
3216   }
3217 
3218   /// Build a new Objective-C property reference expression.
3219   ///
3220   /// By default, performs semantic analysis to build the new expression.
3221   /// Subclasses may override this routine to provide different behavior.
3222   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3223                                         ObjCMethodDecl *Getter,
3224                                         ObjCMethodDecl *Setter,
3225                                         SourceLocation PropertyLoc) {
3226     // Since these expressions can only be value-dependent, we do not
3227     // need to perform semantic analysis again.
3228     return Owned(
3229       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3230                                                   VK_LValue, OK_ObjCProperty,
3231                                                   PropertyLoc, Base));
3232   }
3233 
3234   /// Build a new Objective-C "isa" expression.
3235   ///
3236   /// By default, performs semantic analysis to build the new expression.
3237   /// Subclasses may override this routine to provide different behavior.
3238   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3239                                 SourceLocation OpLoc, bool IsArrow) {
3240     CXXScopeSpec SS;
3241     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3242     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3243                                               OpLoc, IsArrow,
3244                                               SS, SourceLocation(),
3245                                               /*FirstQualifierInScope=*/nullptr,
3246                                               NameInfo,
3247                                               /*TemplateArgs=*/nullptr,
3248                                               /*S=*/nullptr);
3249   }
3250 
3251   /// Build a new shuffle vector expression.
3252   ///
3253   /// By default, performs semantic analysis to build the new expression.
3254   /// Subclasses may override this routine to provide different behavior.
3255   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3256                                       MultiExprArg SubExprs,
3257                                       SourceLocation RParenLoc) {
3258     // Find the declaration for __builtin_shufflevector
3259     const IdentifierInfo &Name
3260       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3261     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3262     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3263     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3264 
3265     // Build a reference to the __builtin_shufflevector builtin
3266     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3267     Expr *Callee = new (SemaRef.Context)
3268         DeclRefExpr(SemaRef.Context, Builtin, false,
3269                     SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3270     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3271     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3272                                        CK_BuiltinFnToFnPtr).get();
3273 
3274     // Build the CallExpr
3275     ExprResult TheCall = CallExpr::Create(
3276         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3277         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3278 
3279     // Type-check the __builtin_shufflevector expression.
3280     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3281   }
3282 
3283   /// Build a new convert vector expression.
3284   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3285                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3286                                       SourceLocation RParenLoc) {
3287     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3288                                          BuiltinLoc, RParenLoc);
3289   }
3290 
3291   /// Build a new template argument pack expansion.
3292   ///
3293   /// By default, performs semantic analysis to build a new pack expansion
3294   /// for a template argument. Subclasses may override this routine to provide
3295   /// different behavior.
3296   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3297                                            SourceLocation EllipsisLoc,
3298                                            Optional<unsigned> NumExpansions) {
3299     switch (Pattern.getArgument().getKind()) {
3300     case TemplateArgument::Expression: {
3301       ExprResult Result
3302         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3303                                        EllipsisLoc, NumExpansions);
3304       if (Result.isInvalid())
3305         return TemplateArgumentLoc();
3306 
3307       return TemplateArgumentLoc(Result.get(), Result.get());
3308     }
3309 
3310     case TemplateArgument::Template:
3311       return TemplateArgumentLoc(TemplateArgument(
3312                                           Pattern.getArgument().getAsTemplate(),
3313                                                   NumExpansions),
3314                                  Pattern.getTemplateQualifierLoc(),
3315                                  Pattern.getTemplateNameLoc(),
3316                                  EllipsisLoc);
3317 
3318     case TemplateArgument::Null:
3319     case TemplateArgument::Integral:
3320     case TemplateArgument::Declaration:
3321     case TemplateArgument::Pack:
3322     case TemplateArgument::TemplateExpansion:
3323     case TemplateArgument::NullPtr:
3324       llvm_unreachable("Pack expansion pattern has no parameter packs");
3325 
3326     case TemplateArgument::Type:
3327       if (TypeSourceInfo *Expansion
3328             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3329                                            EllipsisLoc,
3330                                            NumExpansions))
3331         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3332                                    Expansion);
3333       break;
3334     }
3335 
3336     return TemplateArgumentLoc();
3337   }
3338 
3339   /// Build a new expression pack expansion.
3340   ///
3341   /// By default, performs semantic analysis to build a new pack expansion
3342   /// for an expression. Subclasses may override this routine to provide
3343   /// different behavior.
3344   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3345                                   Optional<unsigned> NumExpansions) {
3346     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3347   }
3348 
3349   /// Build a new C++1z fold-expression.
3350   ///
3351   /// By default, performs semantic analysis in order to build a new fold
3352   /// expression.
3353   ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3354                                 BinaryOperatorKind Operator,
3355                                 SourceLocation EllipsisLoc, Expr *RHS,
3356                                 SourceLocation RParenLoc,
3357                                 Optional<unsigned> NumExpansions) {
3358     return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3359                                       RHS, RParenLoc, NumExpansions);
3360   }
3361 
3362   /// Build an empty C++1z fold-expression with the given operator.
3363   ///
3364   /// By default, produces the fallback value for the fold-expression, or
3365   /// produce an error if there is no fallback value.
3366   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3367                                      BinaryOperatorKind Operator) {
3368     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3369   }
3370 
3371   /// Build a new atomic operation expression.
3372   ///
3373   /// By default, performs semantic analysis to build the new expression.
3374   /// Subclasses may override this routine to provide different behavior.
3375   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3376                                AtomicExpr::AtomicOp Op,
3377                                SourceLocation RParenLoc) {
3378     // Use this for all of the locations, since we don't know the difference
3379     // between the call and the expr at this point.
3380     SourceRange Range{BuiltinLoc, RParenLoc};
3381     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3382                                      Sema::AtomicArgumentOrder::AST);
3383   }
3384 
3385 private:
3386   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3387                                      QualType ObjectType,
3388                                      NamedDecl *FirstQualifierInScope,
3389                                      CXXScopeSpec &SS);
3390 
3391   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3392                                              QualType ObjectType,
3393                                              NamedDecl *FirstQualifierInScope,
3394                                              CXXScopeSpec &SS);
3395 
3396   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3397                                             NamedDecl *FirstQualifierInScope,
3398                                             CXXScopeSpec &SS);
3399 
3400   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3401                                       DependentNameTypeLoc TL,
3402                                       bool DeducibleTSTContext);
3403 };
3404 
3405 template <typename Derived>
3406 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3407   if (!S)
3408     return S;
3409 
3410   switch (S->getStmtClass()) {
3411   case Stmt::NoStmtClass: break;
3412 
3413   // Transform individual statement nodes
3414   // Pass SDK into statements that can produce a value
3415 #define STMT(Node, Parent)                                              \
3416   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3417 #define VALUESTMT(Node, Parent)                                         \
3418   case Stmt::Node##Class:                                               \
3419     return getDerived().Transform##Node(cast<Node>(S), SDK);
3420 #define ABSTRACT_STMT(Node)
3421 #define EXPR(Node, Parent)
3422 #include "clang/AST/StmtNodes.inc"
3423 
3424   // Transform expressions by calling TransformExpr.
3425 #define STMT(Node, Parent)
3426 #define ABSTRACT_STMT(Stmt)
3427 #define EXPR(Node, Parent) case Stmt::Node##Class:
3428 #include "clang/AST/StmtNodes.inc"
3429     {
3430       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3431 
3432       if (SDK == SDK_StmtExprResult)
3433         E = getSema().ActOnStmtExprResult(E);
3434       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3435     }
3436   }
3437 
3438   return S;
3439 }
3440 
3441 template<typename Derived>
3442 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3443   if (!S)
3444     return S;
3445 
3446   switch (S->getClauseKind()) {
3447   default: break;
3448   // Transform individual clause nodes
3449 #define OPENMP_CLAUSE(Name, Class)                                             \
3450   case OMPC_ ## Name :                                                         \
3451     return getDerived().Transform ## Class(cast<Class>(S));
3452 #include "clang/Basic/OpenMPKinds.def"
3453   }
3454 
3455   return S;
3456 }
3457 
3458 
3459 template<typename Derived>
3460 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3461   if (!E)
3462     return E;
3463 
3464   switch (E->getStmtClass()) {
3465     case Stmt::NoStmtClass: break;
3466 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3467 #define ABSTRACT_STMT(Stmt)
3468 #define EXPR(Node, Parent)                                              \
3469     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3470 #include "clang/AST/StmtNodes.inc"
3471   }
3472 
3473   return E;
3474 }
3475 
3476 template<typename Derived>
3477 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3478                                                         bool NotCopyInit) {
3479   // Initializers are instantiated like expressions, except that various outer
3480   // layers are stripped.
3481   if (!Init)
3482     return Init;
3483 
3484   if (auto *FE = dyn_cast<FullExpr>(Init))
3485     Init = FE->getSubExpr();
3486 
3487   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3488     Init = AIL->getCommonExpr();
3489 
3490   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3491     Init = MTE->getSubExpr();
3492 
3493   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3494     Init = Binder->getSubExpr();
3495 
3496   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3497     Init = ICE->getSubExprAsWritten();
3498 
3499   if (CXXStdInitializerListExpr *ILE =
3500           dyn_cast<CXXStdInitializerListExpr>(Init))
3501     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3502 
3503   // If this is copy-initialization, we only need to reconstruct
3504   // InitListExprs. Other forms of copy-initialization will be a no-op if
3505   // the initializer is already the right type.
3506   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3507   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3508     return getDerived().TransformExpr(Init);
3509 
3510   // Revert value-initialization back to empty parens.
3511   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3512     SourceRange Parens = VIE->getSourceRange();
3513     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3514                                              Parens.getEnd());
3515   }
3516 
3517   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3518   if (isa<ImplicitValueInitExpr>(Init))
3519     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3520                                              SourceLocation());
3521 
3522   // Revert initialization by constructor back to a parenthesized or braced list
3523   // of expressions. Any other form of initializer can just be reused directly.
3524   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3525     return getDerived().TransformExpr(Init);
3526 
3527   // If the initialization implicitly converted an initializer list to a
3528   // std::initializer_list object, unwrap the std::initializer_list too.
3529   if (Construct && Construct->isStdInitListInitialization())
3530     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3531 
3532   // Enter a list-init context if this was list initialization.
3533   EnterExpressionEvaluationContext Context(
3534       getSema(), EnterExpressionEvaluationContext::InitList,
3535       Construct->isListInitialization());
3536 
3537   SmallVector<Expr*, 8> NewArgs;
3538   bool ArgChanged = false;
3539   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3540                                   /*IsCall*/true, NewArgs, &ArgChanged))
3541     return ExprError();
3542 
3543   // If this was list initialization, revert to syntactic list form.
3544   if (Construct->isListInitialization())
3545     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3546                                         Construct->getEndLoc());
3547 
3548   // Build a ParenListExpr to represent anything else.
3549   SourceRange Parens = Construct->getParenOrBraceRange();
3550   if (Parens.isInvalid()) {
3551     // This was a variable declaration's initialization for which no initializer
3552     // was specified.
3553     assert(NewArgs.empty() &&
3554            "no parens or braces but have direct init with arguments?");
3555     return ExprEmpty();
3556   }
3557   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3558                                            Parens.getEnd());
3559 }
3560 
3561 template<typename Derived>
3562 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3563                                             unsigned NumInputs,
3564                                             bool IsCall,
3565                                       SmallVectorImpl<Expr *> &Outputs,
3566                                             bool *ArgChanged) {
3567   for (unsigned I = 0; I != NumInputs; ++I) {
3568     // If requested, drop call arguments that need to be dropped.
3569     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3570       if (ArgChanged)
3571         *ArgChanged = true;
3572 
3573       break;
3574     }
3575 
3576     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3577       Expr *Pattern = Expansion->getPattern();
3578 
3579       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3580       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3581       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3582 
3583       // Determine whether the set of unexpanded parameter packs can and should
3584       // be expanded.
3585       bool Expand = true;
3586       bool RetainExpansion = false;
3587       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3588       Optional<unsigned> NumExpansions = OrigNumExpansions;
3589       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3590                                                Pattern->getSourceRange(),
3591                                                Unexpanded,
3592                                                Expand, RetainExpansion,
3593                                                NumExpansions))
3594         return true;
3595 
3596       if (!Expand) {
3597         // The transform has determined that we should perform a simple
3598         // transformation on the pack expansion, producing another pack
3599         // expansion.
3600         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3601         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3602         if (OutPattern.isInvalid())
3603           return true;
3604 
3605         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3606                                                 Expansion->getEllipsisLoc(),
3607                                                            NumExpansions);
3608         if (Out.isInvalid())
3609           return true;
3610 
3611         if (ArgChanged)
3612           *ArgChanged = true;
3613         Outputs.push_back(Out.get());
3614         continue;
3615       }
3616 
3617       // Record right away that the argument was changed.  This needs
3618       // to happen even if the array expands to nothing.
3619       if (ArgChanged) *ArgChanged = true;
3620 
3621       // The transform has determined that we should perform an elementwise
3622       // expansion of the pattern. Do so.
3623       for (unsigned I = 0; I != *NumExpansions; ++I) {
3624         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3625         ExprResult Out = getDerived().TransformExpr(Pattern);
3626         if (Out.isInvalid())
3627           return true;
3628 
3629         if (Out.get()->containsUnexpandedParameterPack()) {
3630           Out = getDerived().RebuildPackExpansion(
3631               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3632           if (Out.isInvalid())
3633             return true;
3634         }
3635 
3636         Outputs.push_back(Out.get());
3637       }
3638 
3639       // If we're supposed to retain a pack expansion, do so by temporarily
3640       // forgetting the partially-substituted parameter pack.
3641       if (RetainExpansion) {
3642         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3643 
3644         ExprResult Out = getDerived().TransformExpr(Pattern);
3645         if (Out.isInvalid())
3646           return true;
3647 
3648         Out = getDerived().RebuildPackExpansion(
3649             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3650         if (Out.isInvalid())
3651           return true;
3652 
3653         Outputs.push_back(Out.get());
3654       }
3655 
3656       continue;
3657     }
3658 
3659     ExprResult Result =
3660       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3661              : getDerived().TransformExpr(Inputs[I]);
3662     if (Result.isInvalid())
3663       return true;
3664 
3665     if (Result.get() != Inputs[I] && ArgChanged)
3666       *ArgChanged = true;
3667 
3668     Outputs.push_back(Result.get());
3669   }
3670 
3671   return false;
3672 }
3673 
3674 template <typename Derived>
3675 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3676     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3677   if (Var) {
3678     VarDecl *ConditionVar = cast_or_null<VarDecl>(
3679         getDerived().TransformDefinition(Var->getLocation(), Var));
3680 
3681     if (!ConditionVar)
3682       return Sema::ConditionError();
3683 
3684     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3685   }
3686 
3687   if (Expr) {
3688     ExprResult CondExpr = getDerived().TransformExpr(Expr);
3689 
3690     if (CondExpr.isInvalid())
3691       return Sema::ConditionError();
3692 
3693     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3694   }
3695 
3696   return Sema::ConditionResult();
3697 }
3698 
3699 template<typename Derived>
3700 NestedNameSpecifierLoc
3701 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3702                                                     NestedNameSpecifierLoc NNS,
3703                                                      QualType ObjectType,
3704                                              NamedDecl *FirstQualifierInScope) {
3705   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3706   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3707        Qualifier = Qualifier.getPrefix())
3708     Qualifiers.push_back(Qualifier);
3709 
3710   CXXScopeSpec SS;
3711   while (!Qualifiers.empty()) {
3712     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3713     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3714 
3715     switch (QNNS->getKind()) {
3716     case NestedNameSpecifier::Identifier: {
3717       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3718                           Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3719       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3720                                               SS, FirstQualifierInScope, false))
3721         return NestedNameSpecifierLoc();
3722     }
3723       break;
3724 
3725     case NestedNameSpecifier::Namespace: {
3726       NamespaceDecl *NS
3727         = cast_or_null<NamespaceDecl>(
3728                                     getDerived().TransformDecl(
3729                                                           Q.getLocalBeginLoc(),
3730                                                        QNNS->getAsNamespace()));
3731       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3732       break;
3733     }
3734 
3735     case NestedNameSpecifier::NamespaceAlias: {
3736       NamespaceAliasDecl *Alias
3737         = cast_or_null<NamespaceAliasDecl>(
3738                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
3739                                                  QNNS->getAsNamespaceAlias()));
3740       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3741                 Q.getLocalEndLoc());
3742       break;
3743     }
3744 
3745     case NestedNameSpecifier::Global:
3746       // There is no meaningful transformation that one could perform on the
3747       // global scope.
3748       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3749       break;
3750 
3751     case NestedNameSpecifier::Super: {
3752       CXXRecordDecl *RD =
3753           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3754               SourceLocation(), QNNS->getAsRecordDecl()));
3755       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3756       break;
3757     }
3758 
3759     case NestedNameSpecifier::TypeSpecWithTemplate:
3760     case NestedNameSpecifier::TypeSpec: {
3761       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3762                                               FirstQualifierInScope, SS);
3763 
3764       if (!TL)
3765         return NestedNameSpecifierLoc();
3766 
3767       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3768           (SemaRef.getLangOpts().CPlusPlus11 &&
3769            TL.getType()->isEnumeralType())) {
3770         assert(!TL.getType().hasLocalQualifiers() &&
3771                "Can't get cv-qualifiers here");
3772         if (TL.getType()->isEnumeralType())
3773           SemaRef.Diag(TL.getBeginLoc(),
3774                        diag::warn_cxx98_compat_enum_nested_name_spec);
3775         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3776                   Q.getLocalEndLoc());
3777         break;
3778       }
3779       // If the nested-name-specifier is an invalid type def, don't emit an
3780       // error because a previous error should have already been emitted.
3781       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3782       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3783         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3784           << TL.getType() << SS.getRange();
3785       }
3786       return NestedNameSpecifierLoc();
3787     }
3788     }
3789 
3790     // The qualifier-in-scope and object type only apply to the leftmost entity.
3791     FirstQualifierInScope = nullptr;
3792     ObjectType = QualType();
3793   }
3794 
3795   // Don't rebuild the nested-name-specifier if we don't have to.
3796   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3797       !getDerived().AlwaysRebuild())
3798     return NNS;
3799 
3800   // If we can re-use the source-location data from the original
3801   // nested-name-specifier, do so.
3802   if (SS.location_size() == NNS.getDataLength() &&
3803       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3804     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3805 
3806   // Allocate new nested-name-specifier location information.
3807   return SS.getWithLocInContext(SemaRef.Context);
3808 }
3809 
3810 template<typename Derived>
3811 DeclarationNameInfo
3812 TreeTransform<Derived>
3813 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3814   DeclarationName Name = NameInfo.getName();
3815   if (!Name)
3816     return DeclarationNameInfo();
3817 
3818   switch (Name.getNameKind()) {
3819   case DeclarationName::Identifier:
3820   case DeclarationName::ObjCZeroArgSelector:
3821   case DeclarationName::ObjCOneArgSelector:
3822   case DeclarationName::ObjCMultiArgSelector:
3823   case DeclarationName::CXXOperatorName:
3824   case DeclarationName::CXXLiteralOperatorName:
3825   case DeclarationName::CXXUsingDirective:
3826     return NameInfo;
3827 
3828   case DeclarationName::CXXDeductionGuideName: {
3829     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3830     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3831         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3832     if (!NewTemplate)
3833       return DeclarationNameInfo();
3834 
3835     DeclarationNameInfo NewNameInfo(NameInfo);
3836     NewNameInfo.setName(
3837         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3838     return NewNameInfo;
3839   }
3840 
3841   case DeclarationName::CXXConstructorName:
3842   case DeclarationName::CXXDestructorName:
3843   case DeclarationName::CXXConversionFunctionName: {
3844     TypeSourceInfo *NewTInfo;
3845     CanQualType NewCanTy;
3846     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3847       NewTInfo = getDerived().TransformType(OldTInfo);
3848       if (!NewTInfo)
3849         return DeclarationNameInfo();
3850       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3851     }
3852     else {
3853       NewTInfo = nullptr;
3854       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3855       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3856       if (NewT.isNull())
3857         return DeclarationNameInfo();
3858       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3859     }
3860 
3861     DeclarationName NewName
3862       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3863                                                            NewCanTy);
3864     DeclarationNameInfo NewNameInfo(NameInfo);
3865     NewNameInfo.setName(NewName);
3866     NewNameInfo.setNamedTypeInfo(NewTInfo);
3867     return NewNameInfo;
3868   }
3869   }
3870 
3871   llvm_unreachable("Unknown name kind.");
3872 }
3873 
3874 template<typename Derived>
3875 TemplateName
3876 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3877                                               TemplateName Name,
3878                                               SourceLocation NameLoc,
3879                                               QualType ObjectType,
3880                                               NamedDecl *FirstQualifierInScope,
3881                                               bool AllowInjectedClassName) {
3882   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3883     TemplateDecl *Template = QTN->getTemplateDecl();
3884     assert(Template && "qualified template name must refer to a template");
3885 
3886     TemplateDecl *TransTemplate
3887       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3888                                                               Template));
3889     if (!TransTemplate)
3890       return TemplateName();
3891 
3892     if (!getDerived().AlwaysRebuild() &&
3893         SS.getScopeRep() == QTN->getQualifier() &&
3894         TransTemplate == Template)
3895       return Name;
3896 
3897     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3898                                             TransTemplate);
3899   }
3900 
3901   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3902     if (SS.getScopeRep()) {
3903       // These apply to the scope specifier, not the template.
3904       ObjectType = QualType();
3905       FirstQualifierInScope = nullptr;
3906     }
3907 
3908     if (!getDerived().AlwaysRebuild() &&
3909         SS.getScopeRep() == DTN->getQualifier() &&
3910         ObjectType.isNull())
3911       return Name;
3912 
3913     // FIXME: Preserve the location of the "template" keyword.
3914     SourceLocation TemplateKWLoc = NameLoc;
3915 
3916     if (DTN->isIdentifier()) {
3917       return getDerived().RebuildTemplateName(SS,
3918                                               TemplateKWLoc,
3919                                               *DTN->getIdentifier(),
3920                                               NameLoc,
3921                                               ObjectType,
3922                                               FirstQualifierInScope,
3923                                               AllowInjectedClassName);
3924     }
3925 
3926     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
3927                                             DTN->getOperator(), NameLoc,
3928                                             ObjectType, AllowInjectedClassName);
3929   }
3930 
3931   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3932     TemplateDecl *TransTemplate
3933       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3934                                                               Template));
3935     if (!TransTemplate)
3936       return TemplateName();
3937 
3938     if (!getDerived().AlwaysRebuild() &&
3939         TransTemplate == Template)
3940       return Name;
3941 
3942     return TemplateName(TransTemplate);
3943   }
3944 
3945   if (SubstTemplateTemplateParmPackStorage *SubstPack
3946       = Name.getAsSubstTemplateTemplateParmPack()) {
3947     TemplateTemplateParmDecl *TransParam
3948     = cast_or_null<TemplateTemplateParmDecl>(
3949             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3950     if (!TransParam)
3951       return TemplateName();
3952 
3953     if (!getDerived().AlwaysRebuild() &&
3954         TransParam == SubstPack->getParameterPack())
3955       return Name;
3956 
3957     return getDerived().RebuildTemplateName(TransParam,
3958                                             SubstPack->getArgumentPack());
3959   }
3960 
3961   // These should be getting filtered out before they reach the AST.
3962   llvm_unreachable("overloaded function decl survived to here");
3963 }
3964 
3965 template<typename Derived>
3966 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3967                                          const TemplateArgument &Arg,
3968                                          TemplateArgumentLoc &Output) {
3969   SourceLocation Loc = getDerived().getBaseLocation();
3970   switch (Arg.getKind()) {
3971   case TemplateArgument::Null:
3972     llvm_unreachable("null template argument in TreeTransform");
3973     break;
3974 
3975   case TemplateArgument::Type:
3976     Output = TemplateArgumentLoc(Arg,
3977                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3978 
3979     break;
3980 
3981   case TemplateArgument::Template:
3982   case TemplateArgument::TemplateExpansion: {
3983     NestedNameSpecifierLocBuilder Builder;
3984     TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3985     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3986       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3987     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3988       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3989 
3990     if (Arg.getKind() == TemplateArgument::Template)
3991       Output = TemplateArgumentLoc(Arg,
3992                                    Builder.getWithLocInContext(SemaRef.Context),
3993                                    Loc);
3994     else
3995       Output = TemplateArgumentLoc(Arg,
3996                                    Builder.getWithLocInContext(SemaRef.Context),
3997                                    Loc, Loc);
3998 
3999     break;
4000   }
4001 
4002   case TemplateArgument::Expression:
4003     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
4004     break;
4005 
4006   case TemplateArgument::Declaration:
4007   case TemplateArgument::Integral:
4008   case TemplateArgument::Pack:
4009   case TemplateArgument::NullPtr:
4010     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
4011     break;
4012   }
4013 }
4014 
4015 template<typename Derived>
4016 bool TreeTransform<Derived>::TransformTemplateArgument(
4017                                          const TemplateArgumentLoc &Input,
4018                                          TemplateArgumentLoc &Output, bool Uneval) {
4019   const TemplateArgument &Arg = Input.getArgument();
4020   switch (Arg.getKind()) {
4021   case TemplateArgument::Null:
4022   case TemplateArgument::Integral:
4023   case TemplateArgument::Pack:
4024   case TemplateArgument::Declaration:
4025   case TemplateArgument::NullPtr:
4026     llvm_unreachable("Unexpected TemplateArgument");
4027 
4028   case TemplateArgument::Type: {
4029     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4030     if (!DI)
4031       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4032 
4033     DI = getDerived().TransformType(DI);
4034     if (!DI) return true;
4035 
4036     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4037     return false;
4038   }
4039 
4040   case TemplateArgument::Template: {
4041     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4042     if (QualifierLoc) {
4043       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4044       if (!QualifierLoc)
4045         return true;
4046     }
4047 
4048     CXXScopeSpec SS;
4049     SS.Adopt(QualifierLoc);
4050     TemplateName Template
4051       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
4052                                            Input.getTemplateNameLoc());
4053     if (Template.isNull())
4054       return true;
4055 
4056     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
4057                                  Input.getTemplateNameLoc());
4058     return false;
4059   }
4060 
4061   case TemplateArgument::TemplateExpansion:
4062     llvm_unreachable("Caller should expand pack expansions");
4063 
4064   case TemplateArgument::Expression: {
4065     // Template argument expressions are constant expressions.
4066     EnterExpressionEvaluationContext Unevaluated(
4067         getSema(),
4068         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4069                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4070         /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4071         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4072 
4073     Expr *InputExpr = Input.getSourceExpression();
4074     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
4075 
4076     ExprResult E = getDerived().TransformExpr(InputExpr);
4077     E = SemaRef.ActOnConstantExpression(E);
4078     if (E.isInvalid()) return true;
4079     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4080     return false;
4081   }
4082   }
4083 
4084   // Work around bogus GCC warning
4085   return true;
4086 }
4087 
4088 /// Iterator adaptor that invents template argument location information
4089 /// for each of the template arguments in its underlying iterator.
4090 template<typename Derived, typename InputIterator>
4091 class TemplateArgumentLocInventIterator {
4092   TreeTransform<Derived> &Self;
4093   InputIterator Iter;
4094 
4095 public:
4096   typedef TemplateArgumentLoc value_type;
4097   typedef TemplateArgumentLoc reference;
4098   typedef typename std::iterator_traits<InputIterator>::difference_type
4099     difference_type;
4100   typedef std::input_iterator_tag iterator_category;
4101 
4102   class pointer {
4103     TemplateArgumentLoc Arg;
4104 
4105   public:
4106     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4107 
4108     const TemplateArgumentLoc *operator->() const { return &Arg; }
4109   };
4110 
4111   TemplateArgumentLocInventIterator() { }
4112 
4113   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4114                                              InputIterator Iter)
4115     : Self(Self), Iter(Iter) { }
4116 
4117   TemplateArgumentLocInventIterator &operator++() {
4118     ++Iter;
4119     return *this;
4120   }
4121 
4122   TemplateArgumentLocInventIterator operator++(int) {
4123     TemplateArgumentLocInventIterator Old(*this);
4124     ++(*this);
4125     return Old;
4126   }
4127 
4128   reference operator*() const {
4129     TemplateArgumentLoc Result;
4130     Self.InventTemplateArgumentLoc(*Iter, Result);
4131     return Result;
4132   }
4133 
4134   pointer operator->() const { return pointer(**this); }
4135 
4136   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4137                          const TemplateArgumentLocInventIterator &Y) {
4138     return X.Iter == Y.Iter;
4139   }
4140 
4141   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4142                          const TemplateArgumentLocInventIterator &Y) {
4143     return X.Iter != Y.Iter;
4144   }
4145 };
4146 
4147 template<typename Derived>
4148 template<typename InputIterator>
4149 bool TreeTransform<Derived>::TransformTemplateArguments(
4150     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4151     bool Uneval) {
4152   for (; First != Last; ++First) {
4153     TemplateArgumentLoc Out;
4154     TemplateArgumentLoc In = *First;
4155 
4156     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4157       // Unpack argument packs, which we translate them into separate
4158       // arguments.
4159       // FIXME: We could do much better if we could guarantee that the
4160       // TemplateArgumentLocInfo for the pack expansion would be usable for
4161       // all of the template arguments in the argument pack.
4162       typedef TemplateArgumentLocInventIterator<Derived,
4163                                                 TemplateArgument::pack_iterator>
4164         PackLocIterator;
4165       if (TransformTemplateArguments(PackLocIterator(*this,
4166                                                  In.getArgument().pack_begin()),
4167                                      PackLocIterator(*this,
4168                                                    In.getArgument().pack_end()),
4169                                      Outputs, Uneval))
4170         return true;
4171 
4172       continue;
4173     }
4174 
4175     if (In.getArgument().isPackExpansion()) {
4176       // We have a pack expansion, for which we will be substituting into
4177       // the pattern.
4178       SourceLocation Ellipsis;
4179       Optional<unsigned> OrigNumExpansions;
4180       TemplateArgumentLoc Pattern
4181         = getSema().getTemplateArgumentPackExpansionPattern(
4182               In, Ellipsis, OrigNumExpansions);
4183 
4184       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4185       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4186       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4187 
4188       // Determine whether the set of unexpanded parameter packs can and should
4189       // be expanded.
4190       bool Expand = true;
4191       bool RetainExpansion = false;
4192       Optional<unsigned> NumExpansions = OrigNumExpansions;
4193       if (getDerived().TryExpandParameterPacks(Ellipsis,
4194                                                Pattern.getSourceRange(),
4195                                                Unexpanded,
4196                                                Expand,
4197                                                RetainExpansion,
4198                                                NumExpansions))
4199         return true;
4200 
4201       if (!Expand) {
4202         // The transform has determined that we should perform a simple
4203         // transformation on the pack expansion, producing another pack
4204         // expansion.
4205         TemplateArgumentLoc OutPattern;
4206         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4207         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4208           return true;
4209 
4210         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4211                                                 NumExpansions);
4212         if (Out.getArgument().isNull())
4213           return true;
4214 
4215         Outputs.addArgument(Out);
4216         continue;
4217       }
4218 
4219       // The transform has determined that we should perform an elementwise
4220       // expansion of the pattern. Do so.
4221       for (unsigned I = 0; I != *NumExpansions; ++I) {
4222         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4223 
4224         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4225           return true;
4226 
4227         if (Out.getArgument().containsUnexpandedParameterPack()) {
4228           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4229                                                   OrigNumExpansions);
4230           if (Out.getArgument().isNull())
4231             return true;
4232         }
4233 
4234         Outputs.addArgument(Out);
4235       }
4236 
4237       // If we're supposed to retain a pack expansion, do so by temporarily
4238       // forgetting the partially-substituted parameter pack.
4239       if (RetainExpansion) {
4240         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4241 
4242         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4243           return true;
4244 
4245         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4246                                                 OrigNumExpansions);
4247         if (Out.getArgument().isNull())
4248           return true;
4249 
4250         Outputs.addArgument(Out);
4251       }
4252 
4253       continue;
4254     }
4255 
4256     // The simple case:
4257     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4258       return true;
4259 
4260     Outputs.addArgument(Out);
4261   }
4262 
4263   return false;
4264 
4265 }
4266 
4267 //===----------------------------------------------------------------------===//
4268 // Type transformation
4269 //===----------------------------------------------------------------------===//
4270 
4271 template<typename Derived>
4272 QualType TreeTransform<Derived>::TransformType(QualType T) {
4273   if (getDerived().AlreadyTransformed(T))
4274     return T;
4275 
4276   // Temporary workaround.  All of these transformations should
4277   // eventually turn into transformations on TypeLocs.
4278   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4279                                                 getDerived().getBaseLocation());
4280 
4281   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4282 
4283   if (!NewDI)
4284     return QualType();
4285 
4286   return NewDI->getType();
4287 }
4288 
4289 template<typename Derived>
4290 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4291   // Refine the base location to the type's location.
4292   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4293                        getDerived().getBaseEntity());
4294   if (getDerived().AlreadyTransformed(DI->getType()))
4295     return DI;
4296 
4297   TypeLocBuilder TLB;
4298 
4299   TypeLoc TL = DI->getTypeLoc();
4300   TLB.reserve(TL.getFullDataSize());
4301 
4302   QualType Result = getDerived().TransformType(TLB, TL);
4303   if (Result.isNull())
4304     return nullptr;
4305 
4306   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4307 }
4308 
4309 template<typename Derived>
4310 QualType
4311 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4312   switch (T.getTypeLocClass()) {
4313 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4314 #define TYPELOC(CLASS, PARENT)                                                 \
4315   case TypeLoc::CLASS:                                                         \
4316     return getDerived().Transform##CLASS##Type(TLB,                            \
4317                                                T.castAs<CLASS##TypeLoc>());
4318 #include "clang/AST/TypeLocNodes.def"
4319   }
4320 
4321   llvm_unreachable("unhandled type loc!");
4322 }
4323 
4324 template<typename Derived>
4325 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4326   if (!isa<DependentNameType>(T))
4327     return TransformType(T);
4328 
4329   if (getDerived().AlreadyTransformed(T))
4330     return T;
4331   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4332                                                 getDerived().getBaseLocation());
4333   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4334   return NewDI ? NewDI->getType() : QualType();
4335 }
4336 
4337 template<typename Derived>
4338 TypeSourceInfo *
4339 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4340   if (!isa<DependentNameType>(DI->getType()))
4341     return TransformType(DI);
4342 
4343   // Refine the base location to the type's location.
4344   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4345                        getDerived().getBaseEntity());
4346   if (getDerived().AlreadyTransformed(DI->getType()))
4347     return DI;
4348 
4349   TypeLocBuilder TLB;
4350 
4351   TypeLoc TL = DI->getTypeLoc();
4352   TLB.reserve(TL.getFullDataSize());
4353 
4354   auto QTL = TL.getAs<QualifiedTypeLoc>();
4355   if (QTL)
4356     TL = QTL.getUnqualifiedLoc();
4357 
4358   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4359 
4360   QualType Result = getDerived().TransformDependentNameType(
4361       TLB, DNTL, /*DeducedTSTContext*/true);
4362   if (Result.isNull())
4363     return nullptr;
4364 
4365   if (QTL) {
4366     Result = getDerived().RebuildQualifiedType(Result, QTL);
4367     if (Result.isNull())
4368       return nullptr;
4369     TLB.TypeWasModifiedSafely(Result);
4370   }
4371 
4372   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4373 }
4374 
4375 template<typename Derived>
4376 QualType
4377 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4378                                                QualifiedTypeLoc T) {
4379   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4380   if (Result.isNull())
4381     return QualType();
4382 
4383   Result = getDerived().RebuildQualifiedType(Result, T);
4384 
4385   if (Result.isNull())
4386     return QualType();
4387 
4388   // RebuildQualifiedType might have updated the type, but not in a way
4389   // that invalidates the TypeLoc. (There's no location information for
4390   // qualifiers.)
4391   TLB.TypeWasModifiedSafely(Result);
4392 
4393   return Result;
4394 }
4395 
4396 template <typename Derived>
4397 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4398                                                       QualifiedTypeLoc TL) {
4399 
4400   SourceLocation Loc = TL.getBeginLoc();
4401   Qualifiers Quals = TL.getType().getLocalQualifiers();
4402 
4403   if (((T.getAddressSpace() != LangAS::Default &&
4404         Quals.getAddressSpace() != LangAS::Default)) &&
4405       T.getAddressSpace() != Quals.getAddressSpace()) {
4406     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4407         << TL.getType() << T;
4408     return QualType();
4409   }
4410 
4411   // C++ [dcl.fct]p7:
4412   //   [When] adding cv-qualifications on top of the function type [...] the
4413   //   cv-qualifiers are ignored.
4414   if (T->isFunctionType()) {
4415     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4416                                                      Quals.getAddressSpace());
4417     return T;
4418   }
4419 
4420   // C++ [dcl.ref]p1:
4421   //   when the cv-qualifiers are introduced through the use of a typedef-name
4422   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4423   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4424   // applied to a reference type.
4425   if (T->isReferenceType()) {
4426     // The only qualifier that applies to a reference type is restrict.
4427     if (!Quals.hasRestrict())
4428       return T;
4429     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4430   }
4431 
4432   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4433   // resulting type.
4434   if (Quals.hasObjCLifetime()) {
4435     if (!T->isObjCLifetimeType() && !T->isDependentType())
4436       Quals.removeObjCLifetime();
4437     else if (T.getObjCLifetime()) {
4438       // Objective-C ARC:
4439       //   A lifetime qualifier applied to a substituted template parameter
4440       //   overrides the lifetime qualifier from the template argument.
4441       const AutoType *AutoTy;
4442       if (const SubstTemplateTypeParmType *SubstTypeParam
4443                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4444         QualType Replacement = SubstTypeParam->getReplacementType();
4445         Qualifiers Qs = Replacement.getQualifiers();
4446         Qs.removeObjCLifetime();
4447         Replacement = SemaRef.Context.getQualifiedType(
4448             Replacement.getUnqualifiedType(), Qs);
4449         T = SemaRef.Context.getSubstTemplateTypeParmType(
4450             SubstTypeParam->getReplacedParameter(), Replacement);
4451       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4452         // 'auto' types behave the same way as template parameters.
4453         QualType Deduced = AutoTy->getDeducedType();
4454         Qualifiers Qs = Deduced.getQualifiers();
4455         Qs.removeObjCLifetime();
4456         Deduced =
4457             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4458         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4459                                         AutoTy->isDependentType());
4460       } else {
4461         // Otherwise, complain about the addition of a qualifier to an
4462         // already-qualified type.
4463         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4464         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4465         Quals.removeObjCLifetime();
4466       }
4467     }
4468   }
4469 
4470   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4471 }
4472 
4473 template<typename Derived>
4474 TypeLoc
4475 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4476                                                    QualType ObjectType,
4477                                                    NamedDecl *UnqualLookup,
4478                                                    CXXScopeSpec &SS) {
4479   if (getDerived().AlreadyTransformed(TL.getType()))
4480     return TL;
4481 
4482   TypeSourceInfo *TSI =
4483       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4484   if (TSI)
4485     return TSI->getTypeLoc();
4486   return TypeLoc();
4487 }
4488 
4489 template<typename Derived>
4490 TypeSourceInfo *
4491 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4492                                                    QualType ObjectType,
4493                                                    NamedDecl *UnqualLookup,
4494                                                    CXXScopeSpec &SS) {
4495   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4496     return TSInfo;
4497 
4498   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4499                                    UnqualLookup, SS);
4500 }
4501 
4502 template <typename Derived>
4503 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4504     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4505     CXXScopeSpec &SS) {
4506   QualType T = TL.getType();
4507   assert(!getDerived().AlreadyTransformed(T));
4508 
4509   TypeLocBuilder TLB;
4510   QualType Result;
4511 
4512   if (isa<TemplateSpecializationType>(T)) {
4513     TemplateSpecializationTypeLoc SpecTL =
4514         TL.castAs<TemplateSpecializationTypeLoc>();
4515 
4516     TemplateName Template = getDerived().TransformTemplateName(
4517         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4518         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4519     if (Template.isNull())
4520       return nullptr;
4521 
4522     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4523                                                               Template);
4524   } else if (isa<DependentTemplateSpecializationType>(T)) {
4525     DependentTemplateSpecializationTypeLoc SpecTL =
4526         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4527 
4528     TemplateName Template
4529       = getDerived().RebuildTemplateName(SS,
4530                                          SpecTL.getTemplateKeywordLoc(),
4531                                          *SpecTL.getTypePtr()->getIdentifier(),
4532                                          SpecTL.getTemplateNameLoc(),
4533                                          ObjectType, UnqualLookup,
4534                                          /*AllowInjectedClassName*/true);
4535     if (Template.isNull())
4536       return nullptr;
4537 
4538     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4539                                                                        SpecTL,
4540                                                                        Template,
4541                                                                        SS);
4542   } else {
4543     // Nothing special needs to be done for these.
4544     Result = getDerived().TransformType(TLB, TL);
4545   }
4546 
4547   if (Result.isNull())
4548     return nullptr;
4549 
4550   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4551 }
4552 
4553 template <class TyLoc> static inline
4554 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4555   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4556   NewT.setNameLoc(T.getNameLoc());
4557   return T.getType();
4558 }
4559 
4560 template<typename Derived>
4561 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4562                                                       BuiltinTypeLoc T) {
4563   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4564   NewT.setBuiltinLoc(T.getBuiltinLoc());
4565   if (T.needsExtraLocalData())
4566     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4567   return T.getType();
4568 }
4569 
4570 template<typename Derived>
4571 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4572                                                       ComplexTypeLoc T) {
4573   // FIXME: recurse?
4574   return TransformTypeSpecType(TLB, T);
4575 }
4576 
4577 template <typename Derived>
4578 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4579                                                        AdjustedTypeLoc TL) {
4580   // Adjustments applied during transformation are handled elsewhere.
4581   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4582 }
4583 
4584 template<typename Derived>
4585 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4586                                                       DecayedTypeLoc TL) {
4587   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4588   if (OriginalType.isNull())
4589     return QualType();
4590 
4591   QualType Result = TL.getType();
4592   if (getDerived().AlwaysRebuild() ||
4593       OriginalType != TL.getOriginalLoc().getType())
4594     Result = SemaRef.Context.getDecayedType(OriginalType);
4595   TLB.push<DecayedTypeLoc>(Result);
4596   // Nothing to set for DecayedTypeLoc.
4597   return Result;
4598 }
4599 
4600 template<typename Derived>
4601 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4602                                                       PointerTypeLoc TL) {
4603   QualType PointeeType
4604     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4605   if (PointeeType.isNull())
4606     return QualType();
4607 
4608   QualType Result = TL.getType();
4609   if (PointeeType->getAs<ObjCObjectType>()) {
4610     // A dependent pointer type 'T *' has is being transformed such
4611     // that an Objective-C class type is being replaced for 'T'. The
4612     // resulting pointer type is an ObjCObjectPointerType, not a
4613     // PointerType.
4614     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4615 
4616     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4617     NewT.setStarLoc(TL.getStarLoc());
4618     return Result;
4619   }
4620 
4621   if (getDerived().AlwaysRebuild() ||
4622       PointeeType != TL.getPointeeLoc().getType()) {
4623     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4624     if (Result.isNull())
4625       return QualType();
4626   }
4627 
4628   // Objective-C ARC can add lifetime qualifiers to the type that we're
4629   // pointing to.
4630   TLB.TypeWasModifiedSafely(Result->getPointeeType());
4631 
4632   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4633   NewT.setSigilLoc(TL.getSigilLoc());
4634   return Result;
4635 }
4636 
4637 template<typename Derived>
4638 QualType
4639 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4640                                                   BlockPointerTypeLoc TL) {
4641   QualType PointeeType
4642     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4643   if (PointeeType.isNull())
4644     return QualType();
4645 
4646   QualType Result = TL.getType();
4647   if (getDerived().AlwaysRebuild() ||
4648       PointeeType != TL.getPointeeLoc().getType()) {
4649     Result = getDerived().RebuildBlockPointerType(PointeeType,
4650                                                   TL.getSigilLoc());
4651     if (Result.isNull())
4652       return QualType();
4653   }
4654 
4655   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4656   NewT.setSigilLoc(TL.getSigilLoc());
4657   return Result;
4658 }
4659 
4660 /// Transforms a reference type.  Note that somewhat paradoxically we
4661 /// don't care whether the type itself is an l-value type or an r-value
4662 /// type;  we only care if the type was *written* as an l-value type
4663 /// or an r-value type.
4664 template<typename Derived>
4665 QualType
4666 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4667                                                ReferenceTypeLoc TL) {
4668   const ReferenceType *T = TL.getTypePtr();
4669 
4670   // Note that this works with the pointee-as-written.
4671   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4672   if (PointeeType.isNull())
4673     return QualType();
4674 
4675   QualType Result = TL.getType();
4676   if (getDerived().AlwaysRebuild() ||
4677       PointeeType != T->getPointeeTypeAsWritten()) {
4678     Result = getDerived().RebuildReferenceType(PointeeType,
4679                                                T->isSpelledAsLValue(),
4680                                                TL.getSigilLoc());
4681     if (Result.isNull())
4682       return QualType();
4683   }
4684 
4685   // Objective-C ARC can add lifetime qualifiers to the type that we're
4686   // referring to.
4687   TLB.TypeWasModifiedSafely(
4688       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
4689 
4690   // r-value references can be rebuilt as l-value references.
4691   ReferenceTypeLoc NewTL;
4692   if (isa<LValueReferenceType>(Result))
4693     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4694   else
4695     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4696   NewTL.setSigilLoc(TL.getSigilLoc());
4697 
4698   return Result;
4699 }
4700 
4701 template<typename Derived>
4702 QualType
4703 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4704                                                  LValueReferenceTypeLoc TL) {
4705   return TransformReferenceType(TLB, TL);
4706 }
4707 
4708 template<typename Derived>
4709 QualType
4710 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4711                                                  RValueReferenceTypeLoc TL) {
4712   return TransformReferenceType(TLB, TL);
4713 }
4714 
4715 template<typename Derived>
4716 QualType
4717 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4718                                                    MemberPointerTypeLoc TL) {
4719   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4720   if (PointeeType.isNull())
4721     return QualType();
4722 
4723   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4724   TypeSourceInfo *NewClsTInfo = nullptr;
4725   if (OldClsTInfo) {
4726     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4727     if (!NewClsTInfo)
4728       return QualType();
4729   }
4730 
4731   const MemberPointerType *T = TL.getTypePtr();
4732   QualType OldClsType = QualType(T->getClass(), 0);
4733   QualType NewClsType;
4734   if (NewClsTInfo)
4735     NewClsType = NewClsTInfo->getType();
4736   else {
4737     NewClsType = getDerived().TransformType(OldClsType);
4738     if (NewClsType.isNull())
4739       return QualType();
4740   }
4741 
4742   QualType Result = TL.getType();
4743   if (getDerived().AlwaysRebuild() ||
4744       PointeeType != T->getPointeeType() ||
4745       NewClsType != OldClsType) {
4746     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4747                                                    TL.getStarLoc());
4748     if (Result.isNull())
4749       return QualType();
4750   }
4751 
4752   // If we had to adjust the pointee type when building a member pointer, make
4753   // sure to push TypeLoc info for it.
4754   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4755   if (MPT && PointeeType != MPT->getPointeeType()) {
4756     assert(isa<AdjustedType>(MPT->getPointeeType()));
4757     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4758   }
4759 
4760   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4761   NewTL.setSigilLoc(TL.getSigilLoc());
4762   NewTL.setClassTInfo(NewClsTInfo);
4763 
4764   return Result;
4765 }
4766 
4767 template<typename Derived>
4768 QualType
4769 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4770                                                    ConstantArrayTypeLoc TL) {
4771   const ConstantArrayType *T = TL.getTypePtr();
4772   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4773   if (ElementType.isNull())
4774     return QualType();
4775 
4776   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
4777   Expr *OldSize = TL.getSizeExpr();
4778   if (!OldSize)
4779     OldSize = const_cast<Expr*>(T->getSizeExpr());
4780   Expr *NewSize = nullptr;
4781   if (OldSize) {
4782     EnterExpressionEvaluationContext Unevaluated(
4783         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4784     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
4785     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
4786   }
4787 
4788   QualType Result = TL.getType();
4789   if (getDerived().AlwaysRebuild() ||
4790       ElementType != T->getElementType() ||
4791       (T->getSizeExpr() && NewSize != OldSize)) {
4792     Result = getDerived().RebuildConstantArrayType(ElementType,
4793                                                    T->getSizeModifier(),
4794                                                    T->getSize(), NewSize,
4795                                              T->getIndexTypeCVRQualifiers(),
4796                                                    TL.getBracketsRange());
4797     if (Result.isNull())
4798       return QualType();
4799   }
4800 
4801   // We might have either a ConstantArrayType or a VariableArrayType now:
4802   // a ConstantArrayType is allowed to have an element type which is a
4803   // VariableArrayType if the type is dependent.  Fortunately, all array
4804   // types have the same location layout.
4805   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4806   NewTL.setLBracketLoc(TL.getLBracketLoc());
4807   NewTL.setRBracketLoc(TL.getRBracketLoc());
4808   NewTL.setSizeExpr(NewSize);
4809 
4810   return Result;
4811 }
4812 
4813 template<typename Derived>
4814 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4815                                               TypeLocBuilder &TLB,
4816                                               IncompleteArrayTypeLoc TL) {
4817   const IncompleteArrayType *T = TL.getTypePtr();
4818   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4819   if (ElementType.isNull())
4820     return QualType();
4821 
4822   QualType Result = TL.getType();
4823   if (getDerived().AlwaysRebuild() ||
4824       ElementType != T->getElementType()) {
4825     Result = getDerived().RebuildIncompleteArrayType(ElementType,
4826                                                      T->getSizeModifier(),
4827                                            T->getIndexTypeCVRQualifiers(),
4828                                                      TL.getBracketsRange());
4829     if (Result.isNull())
4830       return QualType();
4831   }
4832 
4833   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4834   NewTL.setLBracketLoc(TL.getLBracketLoc());
4835   NewTL.setRBracketLoc(TL.getRBracketLoc());
4836   NewTL.setSizeExpr(nullptr);
4837 
4838   return Result;
4839 }
4840 
4841 template<typename Derived>
4842 QualType
4843 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4844                                                    VariableArrayTypeLoc TL) {
4845   const VariableArrayType *T = TL.getTypePtr();
4846   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4847   if (ElementType.isNull())
4848     return QualType();
4849 
4850   ExprResult SizeResult;
4851   {
4852     EnterExpressionEvaluationContext Context(
4853         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4854     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4855   }
4856   if (SizeResult.isInvalid())
4857     return QualType();
4858   SizeResult =
4859       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
4860   if (SizeResult.isInvalid())
4861     return QualType();
4862 
4863   Expr *Size = SizeResult.get();
4864 
4865   QualType Result = TL.getType();
4866   if (getDerived().AlwaysRebuild() ||
4867       ElementType != T->getElementType() ||
4868       Size != T->getSizeExpr()) {
4869     Result = getDerived().RebuildVariableArrayType(ElementType,
4870                                                    T->getSizeModifier(),
4871                                                    Size,
4872                                              T->getIndexTypeCVRQualifiers(),
4873                                                    TL.getBracketsRange());
4874     if (Result.isNull())
4875       return QualType();
4876   }
4877 
4878   // We might have constant size array now, but fortunately it has the same
4879   // location layout.
4880   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4881   NewTL.setLBracketLoc(TL.getLBracketLoc());
4882   NewTL.setRBracketLoc(TL.getRBracketLoc());
4883   NewTL.setSizeExpr(Size);
4884 
4885   return Result;
4886 }
4887 
4888 template<typename Derived>
4889 QualType
4890 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4891                                              DependentSizedArrayTypeLoc TL) {
4892   const DependentSizedArrayType *T = TL.getTypePtr();
4893   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4894   if (ElementType.isNull())
4895     return QualType();
4896 
4897   // Array bounds are constant expressions.
4898   EnterExpressionEvaluationContext Unevaluated(
4899       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4900 
4901   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
4902   Expr *origSize = TL.getSizeExpr();
4903   if (!origSize) origSize = T->getSizeExpr();
4904 
4905   ExprResult sizeResult
4906     = getDerived().TransformExpr(origSize);
4907   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4908   if (sizeResult.isInvalid())
4909     return QualType();
4910 
4911   Expr *size = sizeResult.get();
4912 
4913   QualType Result = TL.getType();
4914   if (getDerived().AlwaysRebuild() ||
4915       ElementType != T->getElementType() ||
4916       size != origSize) {
4917     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4918                                                          T->getSizeModifier(),
4919                                                          size,
4920                                                 T->getIndexTypeCVRQualifiers(),
4921                                                         TL.getBracketsRange());
4922     if (Result.isNull())
4923       return QualType();
4924   }
4925 
4926   // We might have any sort of array type now, but fortunately they
4927   // all have the same location layout.
4928   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4929   NewTL.setLBracketLoc(TL.getLBracketLoc());
4930   NewTL.setRBracketLoc(TL.getRBracketLoc());
4931   NewTL.setSizeExpr(size);
4932 
4933   return Result;
4934 }
4935 
4936 template <typename Derived>
4937 QualType TreeTransform<Derived>::TransformDependentVectorType(
4938     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
4939   const DependentVectorType *T = TL.getTypePtr();
4940   QualType ElementType = getDerived().TransformType(T->getElementType());
4941   if (ElementType.isNull())
4942     return QualType();
4943 
4944   EnterExpressionEvaluationContext Unevaluated(
4945       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4946 
4947   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4948   Size = SemaRef.ActOnConstantExpression(Size);
4949   if (Size.isInvalid())
4950     return QualType();
4951 
4952   QualType Result = TL.getType();
4953   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
4954       Size.get() != T->getSizeExpr()) {
4955     Result = getDerived().RebuildDependentVectorType(
4956         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
4957     if (Result.isNull())
4958       return QualType();
4959   }
4960 
4961   // Result might be dependent or not.
4962   if (isa<DependentVectorType>(Result)) {
4963     DependentVectorTypeLoc NewTL =
4964         TLB.push<DependentVectorTypeLoc>(Result);
4965     NewTL.setNameLoc(TL.getNameLoc());
4966   } else {
4967     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4968     NewTL.setNameLoc(TL.getNameLoc());
4969   }
4970 
4971   return Result;
4972 }
4973 
4974 template<typename Derived>
4975 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4976                                       TypeLocBuilder &TLB,
4977                                       DependentSizedExtVectorTypeLoc TL) {
4978   const DependentSizedExtVectorType *T = TL.getTypePtr();
4979 
4980   // FIXME: ext vector locs should be nested
4981   QualType ElementType = getDerived().TransformType(T->getElementType());
4982   if (ElementType.isNull())
4983     return QualType();
4984 
4985   // Vector sizes are constant expressions.
4986   EnterExpressionEvaluationContext Unevaluated(
4987       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4988 
4989   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4990   Size = SemaRef.ActOnConstantExpression(Size);
4991   if (Size.isInvalid())
4992     return QualType();
4993 
4994   QualType Result = TL.getType();
4995   if (getDerived().AlwaysRebuild() ||
4996       ElementType != T->getElementType() ||
4997       Size.get() != T->getSizeExpr()) {
4998     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4999                                                              Size.get(),
5000                                                          T->getAttributeLoc());
5001     if (Result.isNull())
5002       return QualType();
5003   }
5004 
5005   // Result might be dependent or not.
5006   if (isa<DependentSizedExtVectorType>(Result)) {
5007     DependentSizedExtVectorTypeLoc NewTL
5008       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5009     NewTL.setNameLoc(TL.getNameLoc());
5010   } else {
5011     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5012     NewTL.setNameLoc(TL.getNameLoc());
5013   }
5014 
5015   return Result;
5016 }
5017 
5018 template <typename Derived>
5019 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5020     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5021   const DependentAddressSpaceType *T = TL.getTypePtr();
5022 
5023   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5024 
5025   if (pointeeType.isNull())
5026     return QualType();
5027 
5028   // Address spaces are constant expressions.
5029   EnterExpressionEvaluationContext Unevaluated(
5030       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5031 
5032   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5033   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5034   if (AddrSpace.isInvalid())
5035     return QualType();
5036 
5037   QualType Result = TL.getType();
5038   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5039       AddrSpace.get() != T->getAddrSpaceExpr()) {
5040     Result = getDerived().RebuildDependentAddressSpaceType(
5041         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5042     if (Result.isNull())
5043       return QualType();
5044   }
5045 
5046   // Result might be dependent or not.
5047   if (isa<DependentAddressSpaceType>(Result)) {
5048     DependentAddressSpaceTypeLoc NewTL =
5049         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5050 
5051     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5052     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5053     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5054 
5055   } else {
5056     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5057         Result, getDerived().getBaseLocation());
5058     TransformType(TLB, DI->getTypeLoc());
5059   }
5060 
5061   return Result;
5062 }
5063 
5064 template <typename Derived>
5065 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5066                                                      VectorTypeLoc TL) {
5067   const VectorType *T = TL.getTypePtr();
5068   QualType ElementType = getDerived().TransformType(T->getElementType());
5069   if (ElementType.isNull())
5070     return QualType();
5071 
5072   QualType Result = TL.getType();
5073   if (getDerived().AlwaysRebuild() ||
5074       ElementType != T->getElementType()) {
5075     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5076                                             T->getVectorKind());
5077     if (Result.isNull())
5078       return QualType();
5079   }
5080 
5081   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5082   NewTL.setNameLoc(TL.getNameLoc());
5083 
5084   return Result;
5085 }
5086 
5087 template<typename Derived>
5088 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5089                                                         ExtVectorTypeLoc TL) {
5090   const VectorType *T = TL.getTypePtr();
5091   QualType ElementType = getDerived().TransformType(T->getElementType());
5092   if (ElementType.isNull())
5093     return QualType();
5094 
5095   QualType Result = TL.getType();
5096   if (getDerived().AlwaysRebuild() ||
5097       ElementType != T->getElementType()) {
5098     Result = getDerived().RebuildExtVectorType(ElementType,
5099                                                T->getNumElements(),
5100                                                /*FIXME*/ SourceLocation());
5101     if (Result.isNull())
5102       return QualType();
5103   }
5104 
5105   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5106   NewTL.setNameLoc(TL.getNameLoc());
5107 
5108   return Result;
5109 }
5110 
5111 template <typename Derived>
5112 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5113     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5114     bool ExpectParameterPack) {
5115   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5116   TypeSourceInfo *NewDI = nullptr;
5117 
5118   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5119     // If we're substituting into a pack expansion type and we know the
5120     // length we want to expand to, just substitute for the pattern.
5121     TypeLoc OldTL = OldDI->getTypeLoc();
5122     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5123 
5124     TypeLocBuilder TLB;
5125     TypeLoc NewTL = OldDI->getTypeLoc();
5126     TLB.reserve(NewTL.getFullDataSize());
5127 
5128     QualType Result = getDerived().TransformType(TLB,
5129                                                OldExpansionTL.getPatternLoc());
5130     if (Result.isNull())
5131       return nullptr;
5132 
5133     Result = RebuildPackExpansionType(Result,
5134                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5135                                       OldExpansionTL.getEllipsisLoc(),
5136                                       NumExpansions);
5137     if (Result.isNull())
5138       return nullptr;
5139 
5140     PackExpansionTypeLoc NewExpansionTL
5141       = TLB.push<PackExpansionTypeLoc>(Result);
5142     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5143     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5144   } else
5145     NewDI = getDerived().TransformType(OldDI);
5146   if (!NewDI)
5147     return nullptr;
5148 
5149   if (NewDI == OldDI && indexAdjustment == 0)
5150     return OldParm;
5151 
5152   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5153                                              OldParm->getDeclContext(),
5154                                              OldParm->getInnerLocStart(),
5155                                              OldParm->getLocation(),
5156                                              OldParm->getIdentifier(),
5157                                              NewDI->getType(),
5158                                              NewDI,
5159                                              OldParm->getStorageClass(),
5160                                              /* DefArg */ nullptr);
5161   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5162                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5163   return newParm;
5164 }
5165 
5166 template <typename Derived>
5167 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5168     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5169     const QualType *ParamTypes,
5170     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5171     SmallVectorImpl<QualType> &OutParamTypes,
5172     SmallVectorImpl<ParmVarDecl *> *PVars,
5173     Sema::ExtParameterInfoBuilder &PInfos) {
5174   int indexAdjustment = 0;
5175 
5176   unsigned NumParams = Params.size();
5177   for (unsigned i = 0; i != NumParams; ++i) {
5178     if (ParmVarDecl *OldParm = Params[i]) {
5179       assert(OldParm->getFunctionScopeIndex() == i);
5180 
5181       Optional<unsigned> NumExpansions;
5182       ParmVarDecl *NewParm = nullptr;
5183       if (OldParm->isParameterPack()) {
5184         // We have a function parameter pack that may need to be expanded.
5185         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5186 
5187         // Find the parameter packs that could be expanded.
5188         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5189         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5190         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5191         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5192         assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
5193 
5194         // Determine whether we should expand the parameter packs.
5195         bool ShouldExpand = false;
5196         bool RetainExpansion = false;
5197         Optional<unsigned> OrigNumExpansions =
5198             ExpansionTL.getTypePtr()->getNumExpansions();
5199         NumExpansions = OrigNumExpansions;
5200         if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5201                                                  Pattern.getSourceRange(),
5202                                                  Unexpanded,
5203                                                  ShouldExpand,
5204                                                  RetainExpansion,
5205                                                  NumExpansions)) {
5206           return true;
5207         }
5208 
5209         if (ShouldExpand) {
5210           // Expand the function parameter pack into multiple, separate
5211           // parameters.
5212           getDerived().ExpandingFunctionParameterPack(OldParm);
5213           for (unsigned I = 0; I != *NumExpansions; ++I) {
5214             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5215             ParmVarDecl *NewParm
5216               = getDerived().TransformFunctionTypeParam(OldParm,
5217                                                         indexAdjustment++,
5218                                                         OrigNumExpansions,
5219                                                 /*ExpectParameterPack=*/false);
5220             if (!NewParm)
5221               return true;
5222 
5223             if (ParamInfos)
5224               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5225             OutParamTypes.push_back(NewParm->getType());
5226             if (PVars)
5227               PVars->push_back(NewParm);
5228           }
5229 
5230           // If we're supposed to retain a pack expansion, do so by temporarily
5231           // forgetting the partially-substituted parameter pack.
5232           if (RetainExpansion) {
5233             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5234             ParmVarDecl *NewParm
5235               = getDerived().TransformFunctionTypeParam(OldParm,
5236                                                         indexAdjustment++,
5237                                                         OrigNumExpansions,
5238                                                 /*ExpectParameterPack=*/false);
5239             if (!NewParm)
5240               return true;
5241 
5242             if (ParamInfos)
5243               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5244             OutParamTypes.push_back(NewParm->getType());
5245             if (PVars)
5246               PVars->push_back(NewParm);
5247           }
5248 
5249           // The next parameter should have the same adjustment as the
5250           // last thing we pushed, but we post-incremented indexAdjustment
5251           // on every push.  Also, if we push nothing, the adjustment should
5252           // go down by one.
5253           indexAdjustment--;
5254 
5255           // We're done with the pack expansion.
5256           continue;
5257         }
5258 
5259         // We'll substitute the parameter now without expanding the pack
5260         // expansion.
5261         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5262         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5263                                                           indexAdjustment,
5264                                                           NumExpansions,
5265                                                   /*ExpectParameterPack=*/true);
5266       } else {
5267         NewParm = getDerived().TransformFunctionTypeParam(
5268             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5269       }
5270 
5271       if (!NewParm)
5272         return true;
5273 
5274       if (ParamInfos)
5275         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5276       OutParamTypes.push_back(NewParm->getType());
5277       if (PVars)
5278         PVars->push_back(NewParm);
5279       continue;
5280     }
5281 
5282     // Deal with the possibility that we don't have a parameter
5283     // declaration for this parameter.
5284     QualType OldType = ParamTypes[i];
5285     bool IsPackExpansion = false;
5286     Optional<unsigned> NumExpansions;
5287     QualType NewType;
5288     if (const PackExpansionType *Expansion
5289                                        = dyn_cast<PackExpansionType>(OldType)) {
5290       // We have a function parameter pack that may need to be expanded.
5291       QualType Pattern = Expansion->getPattern();
5292       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5293       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5294 
5295       // Determine whether we should expand the parameter packs.
5296       bool ShouldExpand = false;
5297       bool RetainExpansion = false;
5298       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5299                                                Unexpanded,
5300                                                ShouldExpand,
5301                                                RetainExpansion,
5302                                                NumExpansions)) {
5303         return true;
5304       }
5305 
5306       if (ShouldExpand) {
5307         // Expand the function parameter pack into multiple, separate
5308         // parameters.
5309         for (unsigned I = 0; I != *NumExpansions; ++I) {
5310           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5311           QualType NewType = getDerived().TransformType(Pattern);
5312           if (NewType.isNull())
5313             return true;
5314 
5315           if (NewType->containsUnexpandedParameterPack()) {
5316             NewType =
5317                 getSema().getASTContext().getPackExpansionType(NewType, None);
5318 
5319             if (NewType.isNull())
5320               return true;
5321           }
5322 
5323           if (ParamInfos)
5324             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5325           OutParamTypes.push_back(NewType);
5326           if (PVars)
5327             PVars->push_back(nullptr);
5328         }
5329 
5330         // We're done with the pack expansion.
5331         continue;
5332       }
5333 
5334       // If we're supposed to retain a pack expansion, do so by temporarily
5335       // forgetting the partially-substituted parameter pack.
5336       if (RetainExpansion) {
5337         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5338         QualType NewType = getDerived().TransformType(Pattern);
5339         if (NewType.isNull())
5340           return true;
5341 
5342         if (ParamInfos)
5343           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5344         OutParamTypes.push_back(NewType);
5345         if (PVars)
5346           PVars->push_back(nullptr);
5347       }
5348 
5349       // We'll substitute the parameter now without expanding the pack
5350       // expansion.
5351       OldType = Expansion->getPattern();
5352       IsPackExpansion = true;
5353       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5354       NewType = getDerived().TransformType(OldType);
5355     } else {
5356       NewType = getDerived().TransformType(OldType);
5357     }
5358 
5359     if (NewType.isNull())
5360       return true;
5361 
5362     if (IsPackExpansion)
5363       NewType = getSema().Context.getPackExpansionType(NewType,
5364                                                        NumExpansions);
5365 
5366     if (ParamInfos)
5367       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5368     OutParamTypes.push_back(NewType);
5369     if (PVars)
5370       PVars->push_back(nullptr);
5371   }
5372 
5373 #ifndef NDEBUG
5374   if (PVars) {
5375     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5376       if (ParmVarDecl *parm = (*PVars)[i])
5377         assert(parm->getFunctionScopeIndex() == i);
5378   }
5379 #endif
5380 
5381   return false;
5382 }
5383 
5384 template<typename Derived>
5385 QualType
5386 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5387                                                    FunctionProtoTypeLoc TL) {
5388   SmallVector<QualType, 4> ExceptionStorage;
5389   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5390   return getDerived().TransformFunctionProtoType(
5391       TLB, TL, nullptr, Qualifiers(),
5392       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5393         return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5394                                             ExceptionStorage, Changed);
5395       });
5396 }
5397 
5398 template<typename Derived> template<typename Fn>
5399 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5400     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5401     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5402 
5403   // Transform the parameters and return type.
5404   //
5405   // We are required to instantiate the params and return type in source order.
5406   // When the function has a trailing return type, we instantiate the
5407   // parameters before the return type,  since the return type can then refer
5408   // to the parameters themselves (via decltype, sizeof, etc.).
5409   //
5410   SmallVector<QualType, 4> ParamTypes;
5411   SmallVector<ParmVarDecl*, 4> ParamDecls;
5412   Sema::ExtParameterInfoBuilder ExtParamInfos;
5413   const FunctionProtoType *T = TL.getTypePtr();
5414 
5415   QualType ResultType;
5416 
5417   if (T->hasTrailingReturn()) {
5418     if (getDerived().TransformFunctionTypeParams(
5419             TL.getBeginLoc(), TL.getParams(),
5420             TL.getTypePtr()->param_type_begin(),
5421             T->getExtParameterInfosOrNull(),
5422             ParamTypes, &ParamDecls, ExtParamInfos))
5423       return QualType();
5424 
5425     {
5426       // C++11 [expr.prim.general]p3:
5427       //   If a declaration declares a member function or member function
5428       //   template of a class X, the expression this is a prvalue of type
5429       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5430       //   and the end of the function-definition, member-declarator, or
5431       //   declarator.
5432       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5433 
5434       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5435       if (ResultType.isNull())
5436         return QualType();
5437     }
5438   }
5439   else {
5440     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5441     if (ResultType.isNull())
5442       return QualType();
5443 
5444     if (getDerived().TransformFunctionTypeParams(
5445             TL.getBeginLoc(), TL.getParams(),
5446             TL.getTypePtr()->param_type_begin(),
5447             T->getExtParameterInfosOrNull(),
5448             ParamTypes, &ParamDecls, ExtParamInfos))
5449       return QualType();
5450   }
5451 
5452   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5453 
5454   bool EPIChanged = false;
5455   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5456     return QualType();
5457 
5458   // Handle extended parameter information.
5459   if (auto NewExtParamInfos =
5460         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5461     if (!EPI.ExtParameterInfos ||
5462         llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5463           != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5464       EPIChanged = true;
5465     }
5466     EPI.ExtParameterInfos = NewExtParamInfos;
5467   } else if (EPI.ExtParameterInfos) {
5468     EPIChanged = true;
5469     EPI.ExtParameterInfos = nullptr;
5470   }
5471 
5472   QualType Result = TL.getType();
5473   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5474       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5475     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5476     if (Result.isNull())
5477       return QualType();
5478   }
5479 
5480   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5481   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5482   NewTL.setLParenLoc(TL.getLParenLoc());
5483   NewTL.setRParenLoc(TL.getRParenLoc());
5484   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5485   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5486   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5487     NewTL.setParam(i, ParamDecls[i]);
5488 
5489   return Result;
5490 }
5491 
5492 template<typename Derived>
5493 bool TreeTransform<Derived>::TransformExceptionSpec(
5494     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5495     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5496   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5497 
5498   // Instantiate a dynamic noexcept expression, if any.
5499   if (isComputedNoexcept(ESI.Type)) {
5500     EnterExpressionEvaluationContext Unevaluated(
5501         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5502     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5503     if (NoexceptExpr.isInvalid())
5504       return true;
5505 
5506     ExceptionSpecificationType EST = ESI.Type;
5507     NoexceptExpr =
5508         getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5509     if (NoexceptExpr.isInvalid())
5510       return true;
5511 
5512     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5513       Changed = true;
5514     ESI.NoexceptExpr = NoexceptExpr.get();
5515     ESI.Type = EST;
5516   }
5517 
5518   if (ESI.Type != EST_Dynamic)
5519     return false;
5520 
5521   // Instantiate a dynamic exception specification's type.
5522   for (QualType T : ESI.Exceptions) {
5523     if (const PackExpansionType *PackExpansion =
5524             T->getAs<PackExpansionType>()) {
5525       Changed = true;
5526 
5527       // We have a pack expansion. Instantiate it.
5528       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5529       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5530                                               Unexpanded);
5531       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5532 
5533       // Determine whether the set of unexpanded parameter packs can and
5534       // should
5535       // be expanded.
5536       bool Expand = false;
5537       bool RetainExpansion = false;
5538       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5539       // FIXME: Track the location of the ellipsis (and track source location
5540       // information for the types in the exception specification in general).
5541       if (getDerived().TryExpandParameterPacks(
5542               Loc, SourceRange(), Unexpanded, Expand,
5543               RetainExpansion, NumExpansions))
5544         return true;
5545 
5546       if (!Expand) {
5547         // We can't expand this pack expansion into separate arguments yet;
5548         // just substitute into the pattern and create a new pack expansion
5549         // type.
5550         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5551         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5552         if (U.isNull())
5553           return true;
5554 
5555         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5556         Exceptions.push_back(U);
5557         continue;
5558       }
5559 
5560       // Substitute into the pack expansion pattern for each slice of the
5561       // pack.
5562       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5563         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5564 
5565         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5566         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5567           return true;
5568 
5569         Exceptions.push_back(U);
5570       }
5571     } else {
5572       QualType U = getDerived().TransformType(T);
5573       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5574         return true;
5575       if (T != U)
5576         Changed = true;
5577 
5578       Exceptions.push_back(U);
5579     }
5580   }
5581 
5582   ESI.Exceptions = Exceptions;
5583   if (ESI.Exceptions.empty())
5584     ESI.Type = EST_DynamicNone;
5585   return false;
5586 }
5587 
5588 template<typename Derived>
5589 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5590                                                  TypeLocBuilder &TLB,
5591                                                  FunctionNoProtoTypeLoc TL) {
5592   const FunctionNoProtoType *T = TL.getTypePtr();
5593   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5594   if (ResultType.isNull())
5595     return QualType();
5596 
5597   QualType Result = TL.getType();
5598   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5599     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5600 
5601   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5602   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5603   NewTL.setLParenLoc(TL.getLParenLoc());
5604   NewTL.setRParenLoc(TL.getRParenLoc());
5605   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5606 
5607   return Result;
5608 }
5609 
5610 template<typename Derived> QualType
5611 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5612                                                  UnresolvedUsingTypeLoc TL) {
5613   const UnresolvedUsingType *T = TL.getTypePtr();
5614   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5615   if (!D)
5616     return QualType();
5617 
5618   QualType Result = TL.getType();
5619   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5620     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5621     if (Result.isNull())
5622       return QualType();
5623   }
5624 
5625   // We might get an arbitrary type spec type back.  We should at
5626   // least always get a type spec type, though.
5627   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5628   NewTL.setNameLoc(TL.getNameLoc());
5629 
5630   return Result;
5631 }
5632 
5633 template<typename Derived>
5634 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5635                                                       TypedefTypeLoc TL) {
5636   const TypedefType *T = TL.getTypePtr();
5637   TypedefNameDecl *Typedef
5638     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5639                                                                T->getDecl()));
5640   if (!Typedef)
5641     return QualType();
5642 
5643   QualType Result = TL.getType();
5644   if (getDerived().AlwaysRebuild() ||
5645       Typedef != T->getDecl()) {
5646     Result = getDerived().RebuildTypedefType(Typedef);
5647     if (Result.isNull())
5648       return QualType();
5649   }
5650 
5651   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5652   NewTL.setNameLoc(TL.getNameLoc());
5653 
5654   return Result;
5655 }
5656 
5657 template<typename Derived>
5658 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5659                                                       TypeOfExprTypeLoc TL) {
5660   // typeof expressions are not potentially evaluated contexts
5661   EnterExpressionEvaluationContext Unevaluated(
5662       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5663       Sema::ReuseLambdaContextDecl);
5664 
5665   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5666   if (E.isInvalid())
5667     return QualType();
5668 
5669   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5670   if (E.isInvalid())
5671     return QualType();
5672 
5673   QualType Result = TL.getType();
5674   if (getDerived().AlwaysRebuild() ||
5675       E.get() != TL.getUnderlyingExpr()) {
5676     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5677     if (Result.isNull())
5678       return QualType();
5679   }
5680   else E.get();
5681 
5682   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5683   NewTL.setTypeofLoc(TL.getTypeofLoc());
5684   NewTL.setLParenLoc(TL.getLParenLoc());
5685   NewTL.setRParenLoc(TL.getRParenLoc());
5686 
5687   return Result;
5688 }
5689 
5690 template<typename Derived>
5691 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
5692                                                      TypeOfTypeLoc TL) {
5693   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
5694   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
5695   if (!New_Under_TI)
5696     return QualType();
5697 
5698   QualType Result = TL.getType();
5699   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
5700     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
5701     if (Result.isNull())
5702       return QualType();
5703   }
5704 
5705   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
5706   NewTL.setTypeofLoc(TL.getTypeofLoc());
5707   NewTL.setLParenLoc(TL.getLParenLoc());
5708   NewTL.setRParenLoc(TL.getRParenLoc());
5709   NewTL.setUnderlyingTInfo(New_Under_TI);
5710 
5711   return Result;
5712 }
5713 
5714 template<typename Derived>
5715 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
5716                                                        DecltypeTypeLoc TL) {
5717   const DecltypeType *T = TL.getTypePtr();
5718 
5719   // decltype expressions are not potentially evaluated contexts
5720   EnterExpressionEvaluationContext Unevaluated(
5721       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
5722       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
5723 
5724   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
5725   if (E.isInvalid())
5726     return QualType();
5727 
5728   E = getSema().ActOnDecltypeExpression(E.get());
5729   if (E.isInvalid())
5730     return QualType();
5731 
5732   QualType Result = TL.getType();
5733   if (getDerived().AlwaysRebuild() ||
5734       E.get() != T->getUnderlyingExpr()) {
5735     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
5736     if (Result.isNull())
5737       return QualType();
5738   }
5739   else E.get();
5740 
5741   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
5742   NewTL.setNameLoc(TL.getNameLoc());
5743 
5744   return Result;
5745 }
5746 
5747 template<typename Derived>
5748 QualType TreeTransform<Derived>::TransformUnaryTransformType(
5749                                                             TypeLocBuilder &TLB,
5750                                                      UnaryTransformTypeLoc TL) {
5751   QualType Result = TL.getType();
5752   if (Result->isDependentType()) {
5753     const UnaryTransformType *T = TL.getTypePtr();
5754     QualType NewBase =
5755       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
5756     Result = getDerived().RebuildUnaryTransformType(NewBase,
5757                                                     T->getUTTKind(),
5758                                                     TL.getKWLoc());
5759     if (Result.isNull())
5760       return QualType();
5761   }
5762 
5763   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
5764   NewTL.setKWLoc(TL.getKWLoc());
5765   NewTL.setParensRange(TL.getParensRange());
5766   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5767   return Result;
5768 }
5769 
5770 template<typename Derived>
5771 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
5772                                                    AutoTypeLoc TL) {
5773   const AutoType *T = TL.getTypePtr();
5774   QualType OldDeduced = T->getDeducedType();
5775   QualType NewDeduced;
5776   if (!OldDeduced.isNull()) {
5777     NewDeduced = getDerived().TransformType(OldDeduced);
5778     if (NewDeduced.isNull())
5779       return QualType();
5780   }
5781 
5782   QualType Result = TL.getType();
5783   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
5784       T->isDependentType()) {
5785     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword());
5786     if (Result.isNull())
5787       return QualType();
5788   }
5789 
5790   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5791   NewTL.setNameLoc(TL.getNameLoc());
5792 
5793   return Result;
5794 }
5795 
5796 template<typename Derived>
5797 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
5798     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5799   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
5800 
5801   CXXScopeSpec SS;
5802   TemplateName TemplateName = getDerived().TransformTemplateName(
5803       SS, T->getTemplateName(), TL.getTemplateNameLoc());
5804   if (TemplateName.isNull())
5805     return QualType();
5806 
5807   QualType OldDeduced = T->getDeducedType();
5808   QualType NewDeduced;
5809   if (!OldDeduced.isNull()) {
5810     NewDeduced = getDerived().TransformType(OldDeduced);
5811     if (NewDeduced.isNull())
5812       return QualType();
5813   }
5814 
5815   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
5816       TemplateName, NewDeduced);
5817   if (Result.isNull())
5818     return QualType();
5819 
5820   DeducedTemplateSpecializationTypeLoc NewTL =
5821       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5822   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5823 
5824   return Result;
5825 }
5826 
5827 template<typename Derived>
5828 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5829                                                      RecordTypeLoc TL) {
5830   const RecordType *T = TL.getTypePtr();
5831   RecordDecl *Record
5832     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5833                                                           T->getDecl()));
5834   if (!Record)
5835     return QualType();
5836 
5837   QualType Result = TL.getType();
5838   if (getDerived().AlwaysRebuild() ||
5839       Record != T->getDecl()) {
5840     Result = getDerived().RebuildRecordType(Record);
5841     if (Result.isNull())
5842       return QualType();
5843   }
5844 
5845   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5846   NewTL.setNameLoc(TL.getNameLoc());
5847 
5848   return Result;
5849 }
5850 
5851 template<typename Derived>
5852 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5853                                                    EnumTypeLoc TL) {
5854   const EnumType *T = TL.getTypePtr();
5855   EnumDecl *Enum
5856     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5857                                                         T->getDecl()));
5858   if (!Enum)
5859     return QualType();
5860 
5861   QualType Result = TL.getType();
5862   if (getDerived().AlwaysRebuild() ||
5863       Enum != T->getDecl()) {
5864     Result = getDerived().RebuildEnumType(Enum);
5865     if (Result.isNull())
5866       return QualType();
5867   }
5868 
5869   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5870   NewTL.setNameLoc(TL.getNameLoc());
5871 
5872   return Result;
5873 }
5874 
5875 template<typename Derived>
5876 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5877                                          TypeLocBuilder &TLB,
5878                                          InjectedClassNameTypeLoc TL) {
5879   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5880                                        TL.getTypePtr()->getDecl());
5881   if (!D) return QualType();
5882 
5883   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5884   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5885   return T;
5886 }
5887 
5888 template<typename Derived>
5889 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5890                                                 TypeLocBuilder &TLB,
5891                                                 TemplateTypeParmTypeLoc TL) {
5892   return TransformTypeSpecType(TLB, TL);
5893 }
5894 
5895 template<typename Derived>
5896 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5897                                          TypeLocBuilder &TLB,
5898                                          SubstTemplateTypeParmTypeLoc TL) {
5899   const SubstTemplateTypeParmType *T = TL.getTypePtr();
5900 
5901   // Substitute into the replacement type, which itself might involve something
5902   // that needs to be transformed. This only tends to occur with default
5903   // template arguments of template template parameters.
5904   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5905   QualType Replacement = getDerived().TransformType(T->getReplacementType());
5906   if (Replacement.isNull())
5907     return QualType();
5908 
5909   // Always canonicalize the replacement type.
5910   Replacement = SemaRef.Context.getCanonicalType(Replacement);
5911   QualType Result
5912     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5913                                                    Replacement);
5914 
5915   // Propagate type-source information.
5916   SubstTemplateTypeParmTypeLoc NewTL
5917     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5918   NewTL.setNameLoc(TL.getNameLoc());
5919   return Result;
5920 
5921 }
5922 
5923 template<typename Derived>
5924 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5925                                           TypeLocBuilder &TLB,
5926                                           SubstTemplateTypeParmPackTypeLoc TL) {
5927   return TransformTypeSpecType(TLB, TL);
5928 }
5929 
5930 template<typename Derived>
5931 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5932                                                         TypeLocBuilder &TLB,
5933                                            TemplateSpecializationTypeLoc TL) {
5934   const TemplateSpecializationType *T = TL.getTypePtr();
5935 
5936   // The nested-name-specifier never matters in a TemplateSpecializationType,
5937   // because we can't have a dependent nested-name-specifier anyway.
5938   CXXScopeSpec SS;
5939   TemplateName Template
5940     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5941                                          TL.getTemplateNameLoc());
5942   if (Template.isNull())
5943     return QualType();
5944 
5945   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5946 }
5947 
5948 template<typename Derived>
5949 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5950                                                      AtomicTypeLoc TL) {
5951   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5952   if (ValueType.isNull())
5953     return QualType();
5954 
5955   QualType Result = TL.getType();
5956   if (getDerived().AlwaysRebuild() ||
5957       ValueType != TL.getValueLoc().getType()) {
5958     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5959     if (Result.isNull())
5960       return QualType();
5961   }
5962 
5963   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5964   NewTL.setKWLoc(TL.getKWLoc());
5965   NewTL.setLParenLoc(TL.getLParenLoc());
5966   NewTL.setRParenLoc(TL.getRParenLoc());
5967 
5968   return Result;
5969 }
5970 
5971 template <typename Derived>
5972 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
5973                                                    PipeTypeLoc TL) {
5974   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5975   if (ValueType.isNull())
5976     return QualType();
5977 
5978   QualType Result = TL.getType();
5979   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
5980     const PipeType *PT = Result->castAs<PipeType>();
5981     bool isReadPipe = PT->isReadOnly();
5982     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
5983     if (Result.isNull())
5984       return QualType();
5985   }
5986 
5987   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
5988   NewTL.setKWLoc(TL.getKWLoc());
5989 
5990   return Result;
5991 }
5992 
5993   /// Simple iterator that traverses the template arguments in a
5994   /// container that provides a \c getArgLoc() member function.
5995   ///
5996   /// This iterator is intended to be used with the iterator form of
5997   /// \c TreeTransform<Derived>::TransformTemplateArguments().
5998   template<typename ArgLocContainer>
5999   class TemplateArgumentLocContainerIterator {
6000     ArgLocContainer *Container;
6001     unsigned Index;
6002 
6003   public:
6004     typedef TemplateArgumentLoc value_type;
6005     typedef TemplateArgumentLoc reference;
6006     typedef int difference_type;
6007     typedef std::input_iterator_tag iterator_category;
6008 
6009     class pointer {
6010       TemplateArgumentLoc Arg;
6011 
6012     public:
6013       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6014 
6015       const TemplateArgumentLoc *operator->() const {
6016         return &Arg;
6017       }
6018     };
6019 
6020 
6021     TemplateArgumentLocContainerIterator() {}
6022 
6023     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6024                                  unsigned Index)
6025       : Container(&Container), Index(Index) { }
6026 
6027     TemplateArgumentLocContainerIterator &operator++() {
6028       ++Index;
6029       return *this;
6030     }
6031 
6032     TemplateArgumentLocContainerIterator operator++(int) {
6033       TemplateArgumentLocContainerIterator Old(*this);
6034       ++(*this);
6035       return Old;
6036     }
6037 
6038     TemplateArgumentLoc operator*() const {
6039       return Container->getArgLoc(Index);
6040     }
6041 
6042     pointer operator->() const {
6043       return pointer(Container->getArgLoc(Index));
6044     }
6045 
6046     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6047                            const TemplateArgumentLocContainerIterator &Y) {
6048       return X.Container == Y.Container && X.Index == Y.Index;
6049     }
6050 
6051     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6052                            const TemplateArgumentLocContainerIterator &Y) {
6053       return !(X == Y);
6054     }
6055   };
6056 
6057 
6058 template <typename Derived>
6059 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6060                                                         TypeLocBuilder &TLB,
6061                                            TemplateSpecializationTypeLoc TL,
6062                                                       TemplateName Template) {
6063   TemplateArgumentListInfo NewTemplateArgs;
6064   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6065   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6066   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6067     ArgIterator;
6068   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6069                                               ArgIterator(TL, TL.getNumArgs()),
6070                                               NewTemplateArgs))
6071     return QualType();
6072 
6073   // FIXME: maybe don't rebuild if all the template arguments are the same.
6074 
6075   QualType Result =
6076     getDerived().RebuildTemplateSpecializationType(Template,
6077                                                    TL.getTemplateNameLoc(),
6078                                                    NewTemplateArgs);
6079 
6080   if (!Result.isNull()) {
6081     // Specializations of template template parameters are represented as
6082     // TemplateSpecializationTypes, and substitution of type alias templates
6083     // within a dependent context can transform them into
6084     // DependentTemplateSpecializationTypes.
6085     if (isa<DependentTemplateSpecializationType>(Result)) {
6086       DependentTemplateSpecializationTypeLoc NewTL
6087         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6088       NewTL.setElaboratedKeywordLoc(SourceLocation());
6089       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6090       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6091       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6092       NewTL.setLAngleLoc(TL.getLAngleLoc());
6093       NewTL.setRAngleLoc(TL.getRAngleLoc());
6094       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6095         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6096       return Result;
6097     }
6098 
6099     TemplateSpecializationTypeLoc NewTL
6100       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6101     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6102     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6103     NewTL.setLAngleLoc(TL.getLAngleLoc());
6104     NewTL.setRAngleLoc(TL.getRAngleLoc());
6105     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6106       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6107   }
6108 
6109   return Result;
6110 }
6111 
6112 template <typename Derived>
6113 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6114                                      TypeLocBuilder &TLB,
6115                                      DependentTemplateSpecializationTypeLoc TL,
6116                                      TemplateName Template,
6117                                      CXXScopeSpec &SS) {
6118   TemplateArgumentListInfo NewTemplateArgs;
6119   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6120   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6121   typedef TemplateArgumentLocContainerIterator<
6122             DependentTemplateSpecializationTypeLoc> ArgIterator;
6123   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6124                                               ArgIterator(TL, TL.getNumArgs()),
6125                                               NewTemplateArgs))
6126     return QualType();
6127 
6128   // FIXME: maybe don't rebuild if all the template arguments are the same.
6129 
6130   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6131     QualType Result
6132       = getSema().Context.getDependentTemplateSpecializationType(
6133                                                 TL.getTypePtr()->getKeyword(),
6134                                                          DTN->getQualifier(),
6135                                                          DTN->getIdentifier(),
6136                                                                NewTemplateArgs);
6137 
6138     DependentTemplateSpecializationTypeLoc NewTL
6139       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6140     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6141     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6142     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6143     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6144     NewTL.setLAngleLoc(TL.getLAngleLoc());
6145     NewTL.setRAngleLoc(TL.getRAngleLoc());
6146     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6147       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6148     return Result;
6149   }
6150 
6151   QualType Result
6152     = getDerived().RebuildTemplateSpecializationType(Template,
6153                                                      TL.getTemplateNameLoc(),
6154                                                      NewTemplateArgs);
6155 
6156   if (!Result.isNull()) {
6157     /// FIXME: Wrap this in an elaborated-type-specifier?
6158     TemplateSpecializationTypeLoc NewTL
6159       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6160     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6161     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6162     NewTL.setLAngleLoc(TL.getLAngleLoc());
6163     NewTL.setRAngleLoc(TL.getRAngleLoc());
6164     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6165       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6166   }
6167 
6168   return Result;
6169 }
6170 
6171 template<typename Derived>
6172 QualType
6173 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6174                                                 ElaboratedTypeLoc TL) {
6175   const ElaboratedType *T = TL.getTypePtr();
6176 
6177   NestedNameSpecifierLoc QualifierLoc;
6178   // NOTE: the qualifier in an ElaboratedType is optional.
6179   if (TL.getQualifierLoc()) {
6180     QualifierLoc
6181       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6182     if (!QualifierLoc)
6183       return QualType();
6184   }
6185 
6186   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6187   if (NamedT.isNull())
6188     return QualType();
6189 
6190   // C++0x [dcl.type.elab]p2:
6191   //   If the identifier resolves to a typedef-name or the simple-template-id
6192   //   resolves to an alias template specialization, the
6193   //   elaborated-type-specifier is ill-formed.
6194   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6195     if (const TemplateSpecializationType *TST =
6196           NamedT->getAs<TemplateSpecializationType>()) {
6197       TemplateName Template = TST->getTemplateName();
6198       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6199               Template.getAsTemplateDecl())) {
6200         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6201                      diag::err_tag_reference_non_tag)
6202             << TAT << Sema::NTK_TypeAliasTemplate
6203             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6204         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6205       }
6206     }
6207   }
6208 
6209   QualType Result = TL.getType();
6210   if (getDerived().AlwaysRebuild() ||
6211       QualifierLoc != TL.getQualifierLoc() ||
6212       NamedT != T->getNamedType()) {
6213     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6214                                                 T->getKeyword(),
6215                                                 QualifierLoc, NamedT);
6216     if (Result.isNull())
6217       return QualType();
6218   }
6219 
6220   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6221   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6222   NewTL.setQualifierLoc(QualifierLoc);
6223   return Result;
6224 }
6225 
6226 template<typename Derived>
6227 QualType TreeTransform<Derived>::TransformAttributedType(
6228                                                 TypeLocBuilder &TLB,
6229                                                 AttributedTypeLoc TL) {
6230   const AttributedType *oldType = TL.getTypePtr();
6231   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6232   if (modifiedType.isNull())
6233     return QualType();
6234 
6235   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6236   const Attr *oldAttr = TL.getAttr();
6237   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6238   if (oldAttr && !newAttr)
6239     return QualType();
6240 
6241   QualType result = TL.getType();
6242 
6243   // FIXME: dependent operand expressions?
6244   if (getDerived().AlwaysRebuild() ||
6245       modifiedType != oldType->getModifiedType()) {
6246     // TODO: this is really lame; we should really be rebuilding the
6247     // equivalent type from first principles.
6248     QualType equivalentType
6249       = getDerived().TransformType(oldType->getEquivalentType());
6250     if (equivalentType.isNull())
6251       return QualType();
6252 
6253     // Check whether we can add nullability; it is only represented as
6254     // type sugar, and therefore cannot be diagnosed in any other way.
6255     if (auto nullability = oldType->getImmediateNullability()) {
6256       if (!modifiedType->canHaveNullability()) {
6257         SemaRef.Diag(TL.getAttr()->getLocation(),
6258                      diag::err_nullability_nonpointer)
6259             << DiagNullabilityKind(*nullability, false) << modifiedType;
6260         return QualType();
6261       }
6262     }
6263 
6264     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6265                                                modifiedType,
6266                                                equivalentType);
6267   }
6268 
6269   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6270   newTL.setAttr(newAttr);
6271   return result;
6272 }
6273 
6274 template<typename Derived>
6275 QualType
6276 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6277                                            ParenTypeLoc TL) {
6278   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6279   if (Inner.isNull())
6280     return QualType();
6281 
6282   QualType Result = TL.getType();
6283   if (getDerived().AlwaysRebuild() ||
6284       Inner != TL.getInnerLoc().getType()) {
6285     Result = getDerived().RebuildParenType(Inner);
6286     if (Result.isNull())
6287       return QualType();
6288   }
6289 
6290   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6291   NewTL.setLParenLoc(TL.getLParenLoc());
6292   NewTL.setRParenLoc(TL.getRParenLoc());
6293   return Result;
6294 }
6295 
6296 template <typename Derived>
6297 QualType
6298 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6299                                                     MacroQualifiedTypeLoc TL) {
6300   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6301   if (Inner.isNull())
6302     return QualType();
6303 
6304   QualType Result = TL.getType();
6305   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6306     Result =
6307         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6308     if (Result.isNull())
6309       return QualType();
6310   }
6311 
6312   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6313   NewTL.setExpansionLoc(TL.getExpansionLoc());
6314   return Result;
6315 }
6316 
6317 template<typename Derived>
6318 QualType TreeTransform<Derived>::TransformDependentNameType(
6319     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6320   return TransformDependentNameType(TLB, TL, false);
6321 }
6322 
6323 template<typename Derived>
6324 QualType TreeTransform<Derived>::TransformDependentNameType(
6325     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6326   const DependentNameType *T = TL.getTypePtr();
6327 
6328   NestedNameSpecifierLoc QualifierLoc
6329     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6330   if (!QualifierLoc)
6331     return QualType();
6332 
6333   QualType Result
6334     = getDerived().RebuildDependentNameType(T->getKeyword(),
6335                                             TL.getElaboratedKeywordLoc(),
6336                                             QualifierLoc,
6337                                             T->getIdentifier(),
6338                                             TL.getNameLoc(),
6339                                             DeducedTSTContext);
6340   if (Result.isNull())
6341     return QualType();
6342 
6343   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6344     QualType NamedT = ElabT->getNamedType();
6345     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6346 
6347     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6348     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6349     NewTL.setQualifierLoc(QualifierLoc);
6350   } else {
6351     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6352     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6353     NewTL.setQualifierLoc(QualifierLoc);
6354     NewTL.setNameLoc(TL.getNameLoc());
6355   }
6356   return Result;
6357 }
6358 
6359 template<typename Derived>
6360 QualType TreeTransform<Derived>::
6361           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6362                                  DependentTemplateSpecializationTypeLoc TL) {
6363   NestedNameSpecifierLoc QualifierLoc;
6364   if (TL.getQualifierLoc()) {
6365     QualifierLoc
6366       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6367     if (!QualifierLoc)
6368       return QualType();
6369   }
6370 
6371   return getDerived()
6372            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6373 }
6374 
6375 template<typename Derived>
6376 QualType TreeTransform<Derived>::
6377 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6378                                    DependentTemplateSpecializationTypeLoc TL,
6379                                        NestedNameSpecifierLoc QualifierLoc) {
6380   const DependentTemplateSpecializationType *T = TL.getTypePtr();
6381 
6382   TemplateArgumentListInfo NewTemplateArgs;
6383   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6384   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6385 
6386   typedef TemplateArgumentLocContainerIterator<
6387   DependentTemplateSpecializationTypeLoc> ArgIterator;
6388   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6389                                               ArgIterator(TL, TL.getNumArgs()),
6390                                               NewTemplateArgs))
6391     return QualType();
6392 
6393   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6394       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6395       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6396       /*AllowInjectedClassName*/ false);
6397   if (Result.isNull())
6398     return QualType();
6399 
6400   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6401     QualType NamedT = ElabT->getNamedType();
6402 
6403     // Copy information relevant to the template specialization.
6404     TemplateSpecializationTypeLoc NamedTL
6405       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6406     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6407     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6408     NamedTL.setLAngleLoc(TL.getLAngleLoc());
6409     NamedTL.setRAngleLoc(TL.getRAngleLoc());
6410     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6411       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6412 
6413     // Copy information relevant to the elaborated type.
6414     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6415     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6416     NewTL.setQualifierLoc(QualifierLoc);
6417   } else if (isa<DependentTemplateSpecializationType>(Result)) {
6418     DependentTemplateSpecializationTypeLoc SpecTL
6419       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6420     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6421     SpecTL.setQualifierLoc(QualifierLoc);
6422     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6423     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6424     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6425     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6426     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6427       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6428   } else {
6429     TemplateSpecializationTypeLoc SpecTL
6430       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6431     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6432     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6433     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6434     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6435     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6436       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6437   }
6438   return Result;
6439 }
6440 
6441 template<typename Derived>
6442 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6443                                                       PackExpansionTypeLoc TL) {
6444   QualType Pattern
6445     = getDerived().TransformType(TLB, TL.getPatternLoc());
6446   if (Pattern.isNull())
6447     return QualType();
6448 
6449   QualType Result = TL.getType();
6450   if (getDerived().AlwaysRebuild() ||
6451       Pattern != TL.getPatternLoc().getType()) {
6452     Result = getDerived().RebuildPackExpansionType(Pattern,
6453                                            TL.getPatternLoc().getSourceRange(),
6454                                                    TL.getEllipsisLoc(),
6455                                            TL.getTypePtr()->getNumExpansions());
6456     if (Result.isNull())
6457       return QualType();
6458   }
6459 
6460   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6461   NewT.setEllipsisLoc(TL.getEllipsisLoc());
6462   return Result;
6463 }
6464 
6465 template<typename Derived>
6466 QualType
6467 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6468                                                    ObjCInterfaceTypeLoc TL) {
6469   // ObjCInterfaceType is never dependent.
6470   TLB.pushFullCopy(TL);
6471   return TL.getType();
6472 }
6473 
6474 template<typename Derived>
6475 QualType
6476 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6477                                                    ObjCTypeParamTypeLoc TL) {
6478   const ObjCTypeParamType *T = TL.getTypePtr();
6479   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6480       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6481   if (!OTP)
6482     return QualType();
6483 
6484   QualType Result = TL.getType();
6485   if (getDerived().AlwaysRebuild() ||
6486       OTP != T->getDecl()) {
6487     Result = getDerived().RebuildObjCTypeParamType(OTP,
6488                  TL.getProtocolLAngleLoc(),
6489                  llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6490                                     TL.getNumProtocols()),
6491                  TL.getProtocolLocs(),
6492                  TL.getProtocolRAngleLoc());
6493     if (Result.isNull())
6494       return QualType();
6495   }
6496 
6497   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6498   if (TL.getNumProtocols()) {
6499     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6500     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6501       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6502     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6503   }
6504   return Result;
6505 }
6506 
6507 template<typename Derived>
6508 QualType
6509 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6510                                                 ObjCObjectTypeLoc TL) {
6511   // Transform base type.
6512   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6513   if (BaseType.isNull())
6514     return QualType();
6515 
6516   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6517 
6518   // Transform type arguments.
6519   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6520   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6521     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6522     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6523     QualType TypeArg = TypeArgInfo->getType();
6524     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6525       AnyChanged = true;
6526 
6527       // We have a pack expansion. Instantiate it.
6528       const auto *PackExpansion = PackExpansionLoc.getType()
6529                                     ->castAs<PackExpansionType>();
6530       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6531       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6532                                               Unexpanded);
6533       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6534 
6535       // Determine whether the set of unexpanded parameter packs can
6536       // and should be expanded.
6537       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6538       bool Expand = false;
6539       bool RetainExpansion = false;
6540       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6541       if (getDerived().TryExpandParameterPacks(
6542             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6543             Unexpanded, Expand, RetainExpansion, NumExpansions))
6544         return QualType();
6545 
6546       if (!Expand) {
6547         // We can't expand this pack expansion into separate arguments yet;
6548         // just substitute into the pattern and create a new pack expansion
6549         // type.
6550         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6551 
6552         TypeLocBuilder TypeArgBuilder;
6553         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6554         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6555                                                              PatternLoc);
6556         if (NewPatternType.isNull())
6557           return QualType();
6558 
6559         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6560                                       NewPatternType, NumExpansions);
6561         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6562         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6563         NewTypeArgInfos.push_back(
6564           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6565         continue;
6566       }
6567 
6568       // Substitute into the pack expansion pattern for each slice of the
6569       // pack.
6570       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6571         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6572 
6573         TypeLocBuilder TypeArgBuilder;
6574         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6575 
6576         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6577                                                          PatternLoc);
6578         if (NewTypeArg.isNull())
6579           return QualType();
6580 
6581         NewTypeArgInfos.push_back(
6582           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6583       }
6584 
6585       continue;
6586     }
6587 
6588     TypeLocBuilder TypeArgBuilder;
6589     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6590     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6591     if (NewTypeArg.isNull())
6592       return QualType();
6593 
6594     // If nothing changed, just keep the old TypeSourceInfo.
6595     if (NewTypeArg == TypeArg) {
6596       NewTypeArgInfos.push_back(TypeArgInfo);
6597       continue;
6598     }
6599 
6600     NewTypeArgInfos.push_back(
6601       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6602     AnyChanged = true;
6603   }
6604 
6605   QualType Result = TL.getType();
6606   if (getDerived().AlwaysRebuild() || AnyChanged) {
6607     // Rebuild the type.
6608     Result = getDerived().RebuildObjCObjectType(
6609         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
6610         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
6611         llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
6612         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
6613 
6614     if (Result.isNull())
6615       return QualType();
6616   }
6617 
6618   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
6619   NewT.setHasBaseTypeAsWritten(true);
6620   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
6621   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
6622     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
6623   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
6624   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6625   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6626     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
6627   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6628   return Result;
6629 }
6630 
6631 template<typename Derived>
6632 QualType
6633 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
6634                                                ObjCObjectPointerTypeLoc TL) {
6635   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
6636   if (PointeeType.isNull())
6637     return QualType();
6638 
6639   QualType Result = TL.getType();
6640   if (getDerived().AlwaysRebuild() ||
6641       PointeeType != TL.getPointeeLoc().getType()) {
6642     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
6643                                                        TL.getStarLoc());
6644     if (Result.isNull())
6645       return QualType();
6646   }
6647 
6648   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
6649   NewT.setStarLoc(TL.getStarLoc());
6650   return Result;
6651 }
6652 
6653 //===----------------------------------------------------------------------===//
6654 // Statement transformation
6655 //===----------------------------------------------------------------------===//
6656 template<typename Derived>
6657 StmtResult
6658 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
6659   return S;
6660 }
6661 
6662 template<typename Derived>
6663 StmtResult
6664 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
6665   return getDerived().TransformCompoundStmt(S, false);
6666 }
6667 
6668 template<typename Derived>
6669 StmtResult
6670 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
6671                                               bool IsStmtExpr) {
6672   Sema::CompoundScopeRAII CompoundScope(getSema());
6673 
6674   const Stmt *ExprResult = S->getStmtExprResult();
6675   bool SubStmtInvalid = false;
6676   bool SubStmtChanged = false;
6677   SmallVector<Stmt*, 8> Statements;
6678   for (auto *B : S->body()) {
6679     StmtResult Result = getDerived().TransformStmt(
6680         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
6681 
6682     if (Result.isInvalid()) {
6683       // Immediately fail if this was a DeclStmt, since it's very
6684       // likely that this will cause problems for future statements.
6685       if (isa<DeclStmt>(B))
6686         return StmtError();
6687 
6688       // Otherwise, just keep processing substatements and fail later.
6689       SubStmtInvalid = true;
6690       continue;
6691     }
6692 
6693     SubStmtChanged = SubStmtChanged || Result.get() != B;
6694     Statements.push_back(Result.getAs<Stmt>());
6695   }
6696 
6697   if (SubStmtInvalid)
6698     return StmtError();
6699 
6700   if (!getDerived().AlwaysRebuild() &&
6701       !SubStmtChanged)
6702     return S;
6703 
6704   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
6705                                           Statements,
6706                                           S->getRBracLoc(),
6707                                           IsStmtExpr);
6708 }
6709 
6710 template<typename Derived>
6711 StmtResult
6712 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
6713   ExprResult LHS, RHS;
6714   {
6715     EnterExpressionEvaluationContext Unevaluated(
6716         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6717 
6718     // Transform the left-hand case value.
6719     LHS = getDerived().TransformExpr(S->getLHS());
6720     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
6721     if (LHS.isInvalid())
6722       return StmtError();
6723 
6724     // Transform the right-hand case value (for the GNU case-range extension).
6725     RHS = getDerived().TransformExpr(S->getRHS());
6726     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
6727     if (RHS.isInvalid())
6728       return StmtError();
6729   }
6730 
6731   // Build the case statement.
6732   // Case statements are always rebuilt so that they will attached to their
6733   // transformed switch statement.
6734   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
6735                                                        LHS.get(),
6736                                                        S->getEllipsisLoc(),
6737                                                        RHS.get(),
6738                                                        S->getColonLoc());
6739   if (Case.isInvalid())
6740     return StmtError();
6741 
6742   // Transform the statement following the case
6743   StmtResult SubStmt =
6744       getDerived().TransformStmt(S->getSubStmt());
6745   if (SubStmt.isInvalid())
6746     return StmtError();
6747 
6748   // Attach the body to the case statement
6749   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
6750 }
6751 
6752 template <typename Derived>
6753 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
6754   // Transform the statement following the default case
6755   StmtResult SubStmt =
6756       getDerived().TransformStmt(S->getSubStmt());
6757   if (SubStmt.isInvalid())
6758     return StmtError();
6759 
6760   // Default statements are always rebuilt
6761   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
6762                                          SubStmt.get());
6763 }
6764 
6765 template<typename Derived>
6766 StmtResult
6767 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
6768   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6769   if (SubStmt.isInvalid())
6770     return StmtError();
6771 
6772   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
6773                                         S->getDecl());
6774   if (!LD)
6775     return StmtError();
6776 
6777   // If we're transforming "in-place" (we're not creating new local
6778   // declarations), assume we're replacing the old label statement
6779   // and clear out the reference to it.
6780   if (LD == S->getDecl())
6781     S->getDecl()->setStmt(nullptr);
6782 
6783   // FIXME: Pass the real colon location in.
6784   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
6785                                        cast<LabelDecl>(LD), SourceLocation(),
6786                                        SubStmt.get());
6787 }
6788 
6789 template <typename Derived>
6790 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
6791   if (!R)
6792     return R;
6793 
6794   switch (R->getKind()) {
6795 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
6796 #define ATTR(X)
6797 #define PRAGMA_SPELLING_ATTR(X)                                                \
6798   case attr::X:                                                                \
6799     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
6800 #include "clang/Basic/AttrList.inc"
6801   default:
6802     return R;
6803   }
6804 }
6805 
6806 template <typename Derived>
6807 StmtResult
6808 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
6809                                                 StmtDiscardKind SDK) {
6810   bool AttrsChanged = false;
6811   SmallVector<const Attr *, 1> Attrs;
6812 
6813   // Visit attributes and keep track if any are transformed.
6814   for (const auto *I : S->getAttrs()) {
6815     const Attr *R = getDerived().TransformAttr(I);
6816     AttrsChanged |= (I != R);
6817     Attrs.push_back(R);
6818   }
6819 
6820   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6821   if (SubStmt.isInvalid())
6822     return StmtError();
6823 
6824   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
6825     return S;
6826 
6827   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
6828                                             SubStmt.get());
6829 }
6830 
6831 template<typename Derived>
6832 StmtResult
6833 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
6834   // Transform the initialization statement
6835   StmtResult Init = getDerived().TransformStmt(S->getInit());
6836   if (Init.isInvalid())
6837     return StmtError();
6838 
6839   // Transform the condition
6840   Sema::ConditionResult Cond = getDerived().TransformCondition(
6841       S->getIfLoc(), S->getConditionVariable(), S->getCond(),
6842       S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
6843                        : Sema::ConditionKind::Boolean);
6844   if (Cond.isInvalid())
6845     return StmtError();
6846 
6847   // If this is a constexpr if, determine which arm we should instantiate.
6848   llvm::Optional<bool> ConstexprConditionValue;
6849   if (S->isConstexpr())
6850     ConstexprConditionValue = Cond.getKnownValue();
6851 
6852   // Transform the "then" branch.
6853   StmtResult Then;
6854   if (!ConstexprConditionValue || *ConstexprConditionValue) {
6855     Then = getDerived().TransformStmt(S->getThen());
6856     if (Then.isInvalid())
6857       return StmtError();
6858   } else {
6859     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
6860   }
6861 
6862   // Transform the "else" branch.
6863   StmtResult Else;
6864   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
6865     Else = getDerived().TransformStmt(S->getElse());
6866     if (Else.isInvalid())
6867       return StmtError();
6868   }
6869 
6870   if (!getDerived().AlwaysRebuild() &&
6871       Init.get() == S->getInit() &&
6872       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6873       Then.get() == S->getThen() &&
6874       Else.get() == S->getElse())
6875     return S;
6876 
6877   return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
6878                                     Init.get(), Then.get(), S->getElseLoc(),
6879                                     Else.get());
6880 }
6881 
6882 template<typename Derived>
6883 StmtResult
6884 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6885   // Transform the initialization statement
6886   StmtResult Init = getDerived().TransformStmt(S->getInit());
6887   if (Init.isInvalid())
6888     return StmtError();
6889 
6890   // Transform the condition.
6891   Sema::ConditionResult Cond = getDerived().TransformCondition(
6892       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
6893       Sema::ConditionKind::Switch);
6894   if (Cond.isInvalid())
6895     return StmtError();
6896 
6897   // Rebuild the switch statement.
6898   StmtResult Switch
6899     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
6900   if (Switch.isInvalid())
6901     return StmtError();
6902 
6903   // Transform the body of the switch statement.
6904   StmtResult Body = getDerived().TransformStmt(S->getBody());
6905   if (Body.isInvalid())
6906     return StmtError();
6907 
6908   // Complete the switch statement.
6909   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
6910                                             Body.get());
6911 }
6912 
6913 template<typename Derived>
6914 StmtResult
6915 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
6916   // Transform the condition
6917   Sema::ConditionResult Cond = getDerived().TransformCondition(
6918       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
6919       Sema::ConditionKind::Boolean);
6920   if (Cond.isInvalid())
6921     return StmtError();
6922 
6923   // Transform the body
6924   StmtResult Body = getDerived().TransformStmt(S->getBody());
6925   if (Body.isInvalid())
6926     return StmtError();
6927 
6928   if (!getDerived().AlwaysRebuild() &&
6929       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6930       Body.get() == S->getBody())
6931     return Owned(S);
6932 
6933   return getDerived().RebuildWhileStmt(S->getWhileLoc(), Cond, Body.get());
6934 }
6935 
6936 template<typename Derived>
6937 StmtResult
6938 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
6939   // Transform the body
6940   StmtResult Body = getDerived().TransformStmt(S->getBody());
6941   if (Body.isInvalid())
6942     return StmtError();
6943 
6944   // Transform the condition
6945   ExprResult Cond = getDerived().TransformExpr(S->getCond());
6946   if (Cond.isInvalid())
6947     return StmtError();
6948 
6949   if (!getDerived().AlwaysRebuild() &&
6950       Cond.get() == S->getCond() &&
6951       Body.get() == S->getBody())
6952     return S;
6953 
6954   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
6955                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
6956                                     S->getRParenLoc());
6957 }
6958 
6959 template<typename Derived>
6960 StmtResult
6961 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
6962   if (getSema().getLangOpts().OpenMP)
6963     getSema().startOpenMPLoop();
6964 
6965   // Transform the initialization statement
6966   StmtResult Init = getDerived().TransformStmt(S->getInit());
6967   if (Init.isInvalid())
6968     return StmtError();
6969 
6970   // In OpenMP loop region loop control variable must be captured and be
6971   // private. Perform analysis of first part (if any).
6972   if (getSema().getLangOpts().OpenMP && Init.isUsable())
6973     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
6974 
6975   // Transform the condition
6976   Sema::ConditionResult Cond = getDerived().TransformCondition(
6977       S->getForLoc(), S->getConditionVariable(), S->getCond(),
6978       Sema::ConditionKind::Boolean);
6979   if (Cond.isInvalid())
6980     return StmtError();
6981 
6982   // Transform the increment
6983   ExprResult Inc = getDerived().TransformExpr(S->getInc());
6984   if (Inc.isInvalid())
6985     return StmtError();
6986 
6987   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6988   if (S->getInc() && !FullInc.get())
6989     return StmtError();
6990 
6991   // Transform the body
6992   StmtResult Body = getDerived().TransformStmt(S->getBody());
6993   if (Body.isInvalid())
6994     return StmtError();
6995 
6996   if (!getDerived().AlwaysRebuild() &&
6997       Init.get() == S->getInit() &&
6998       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6999       Inc.get() == S->getInc() &&
7000       Body.get() == S->getBody())
7001     return S;
7002 
7003   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7004                                      Init.get(), Cond, FullInc,
7005                                      S->getRParenLoc(), Body.get());
7006 }
7007 
7008 template<typename Derived>
7009 StmtResult
7010 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7011   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7012                                         S->getLabel());
7013   if (!LD)
7014     return StmtError();
7015 
7016   // Goto statements must always be rebuilt, to resolve the label.
7017   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7018                                       cast<LabelDecl>(LD));
7019 }
7020 
7021 template<typename Derived>
7022 StmtResult
7023 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7024   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7025   if (Target.isInvalid())
7026     return StmtError();
7027   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7028 
7029   if (!getDerived().AlwaysRebuild() &&
7030       Target.get() == S->getTarget())
7031     return S;
7032 
7033   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7034                                               Target.get());
7035 }
7036 
7037 template<typename Derived>
7038 StmtResult
7039 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7040   return S;
7041 }
7042 
7043 template<typename Derived>
7044 StmtResult
7045 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7046   return S;
7047 }
7048 
7049 template<typename Derived>
7050 StmtResult
7051 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7052   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7053                                                         /*NotCopyInit*/false);
7054   if (Result.isInvalid())
7055     return StmtError();
7056 
7057   // FIXME: We always rebuild the return statement because there is no way
7058   // to tell whether the return type of the function has changed.
7059   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7060 }
7061 
7062 template<typename Derived>
7063 StmtResult
7064 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7065   bool DeclChanged = false;
7066   SmallVector<Decl *, 4> Decls;
7067   for (auto *D : S->decls()) {
7068     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7069     if (!Transformed)
7070       return StmtError();
7071 
7072     if (Transformed != D)
7073       DeclChanged = true;
7074 
7075     Decls.push_back(Transformed);
7076   }
7077 
7078   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7079     return S;
7080 
7081   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7082 }
7083 
7084 template<typename Derived>
7085 StmtResult
7086 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7087 
7088   SmallVector<Expr*, 8> Constraints;
7089   SmallVector<Expr*, 8> Exprs;
7090   SmallVector<IdentifierInfo *, 4> Names;
7091 
7092   ExprResult AsmString;
7093   SmallVector<Expr*, 8> Clobbers;
7094 
7095   bool ExprsChanged = false;
7096 
7097   // Go through the outputs.
7098   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7099     Names.push_back(S->getOutputIdentifier(I));
7100 
7101     // No need to transform the constraint literal.
7102     Constraints.push_back(S->getOutputConstraintLiteral(I));
7103 
7104     // Transform the output expr.
7105     Expr *OutputExpr = S->getOutputExpr(I);
7106     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7107     if (Result.isInvalid())
7108       return StmtError();
7109 
7110     ExprsChanged |= Result.get() != OutputExpr;
7111 
7112     Exprs.push_back(Result.get());
7113   }
7114 
7115   // Go through the inputs.
7116   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7117     Names.push_back(S->getInputIdentifier(I));
7118 
7119     // No need to transform the constraint literal.
7120     Constraints.push_back(S->getInputConstraintLiteral(I));
7121 
7122     // Transform the input expr.
7123     Expr *InputExpr = S->getInputExpr(I);
7124     ExprResult Result = getDerived().TransformExpr(InputExpr);
7125     if (Result.isInvalid())
7126       return StmtError();
7127 
7128     ExprsChanged |= Result.get() != InputExpr;
7129 
7130     Exprs.push_back(Result.get());
7131   }
7132 
7133   // Go through the Labels.
7134   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7135     Names.push_back(S->getLabelIdentifier(I));
7136 
7137     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7138     if (Result.isInvalid())
7139       return StmtError();
7140     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7141     Exprs.push_back(Result.get());
7142   }
7143   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7144     return S;
7145 
7146   // Go through the clobbers.
7147   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7148     Clobbers.push_back(S->getClobberStringLiteral(I));
7149 
7150   // No need to transform the asm string literal.
7151   AsmString = S->getAsmString();
7152   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7153                                         S->isVolatile(), S->getNumOutputs(),
7154                                         S->getNumInputs(), Names.data(),
7155                                         Constraints, Exprs, AsmString.get(),
7156                                         Clobbers, S->getNumLabels(),
7157                                         S->getRParenLoc());
7158 }
7159 
7160 template<typename Derived>
7161 StmtResult
7162 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7163   ArrayRef<Token> AsmToks =
7164     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7165 
7166   bool HadError = false, HadChange = false;
7167 
7168   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7169   SmallVector<Expr*, 8> TransformedExprs;
7170   TransformedExprs.reserve(SrcExprs.size());
7171   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7172     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7173     if (!Result.isUsable()) {
7174       HadError = true;
7175     } else {
7176       HadChange |= (Result.get() != SrcExprs[i]);
7177       TransformedExprs.push_back(Result.get());
7178     }
7179   }
7180 
7181   if (HadError) return StmtError();
7182   if (!HadChange && !getDerived().AlwaysRebuild())
7183     return Owned(S);
7184 
7185   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7186                                        AsmToks, S->getAsmString(),
7187                                        S->getNumOutputs(), S->getNumInputs(),
7188                                        S->getAllConstraints(), S->getClobbers(),
7189                                        TransformedExprs, S->getEndLoc());
7190 }
7191 
7192 // C++ Coroutines TS
7193 
7194 template<typename Derived>
7195 StmtResult
7196 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7197   auto *ScopeInfo = SemaRef.getCurFunction();
7198   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7199   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7200          ScopeInfo->NeedsCoroutineSuspends &&
7201          ScopeInfo->CoroutineSuspends.first == nullptr &&
7202          ScopeInfo->CoroutineSuspends.second == nullptr &&
7203          "expected clean scope info");
7204 
7205   // Set that we have (possibly-invalid) suspend points before we do anything
7206   // that may fail.
7207   ScopeInfo->setNeedsCoroutineSuspends(false);
7208 
7209   // We re-build the coroutine promise object (and the coroutine parameters its
7210   // type and constructor depend on) based on the types used in our current
7211   // function. We must do so, and set it on the current FunctionScopeInfo,
7212   // before attempting to transform the other parts of the coroutine body
7213   // statement, such as the implicit suspend statements (because those
7214   // statements reference the FunctionScopeInfo::CoroutinePromise).
7215   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7216     return StmtError();
7217   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7218   if (!Promise)
7219     return StmtError();
7220   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7221   ScopeInfo->CoroutinePromise = Promise;
7222 
7223   // Transform the implicit coroutine statements constructed using dependent
7224   // types during the previous parse: initial and final suspensions, the return
7225   // object, and others. We also transform the coroutine function's body.
7226   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7227   if (InitSuspend.isInvalid())
7228     return StmtError();
7229   StmtResult FinalSuspend =
7230       getDerived().TransformStmt(S->getFinalSuspendStmt());
7231   if (FinalSuspend.isInvalid())
7232     return StmtError();
7233   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7234   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7235 
7236   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7237   if (BodyRes.isInvalid())
7238     return StmtError();
7239 
7240   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7241   if (Builder.isInvalid())
7242     return StmtError();
7243 
7244   Expr *ReturnObject = S->getReturnValueInit();
7245   assert(ReturnObject && "the return object is expected to be valid");
7246   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7247                                                      /*NoCopyInit*/ false);
7248   if (Res.isInvalid())
7249     return StmtError();
7250   Builder.ReturnValue = Res.get();
7251 
7252   // If during the previous parse the coroutine still had a dependent promise
7253   // statement, we may need to build some implicit coroutine statements
7254   // (such as exception and fallthrough handlers) for the first time.
7255   if (S->hasDependentPromiseType()) {
7256     // We can only build these statements, however, if the current promise type
7257     // is not dependent.
7258     if (!Promise->getType()->isDependentType()) {
7259       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7260              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7261              "these nodes should not have been built yet");
7262       if (!Builder.buildDependentStatements())
7263         return StmtError();
7264     }
7265   } else {
7266     if (auto *OnFallthrough = S->getFallthroughHandler()) {
7267       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7268       if (Res.isInvalid())
7269         return StmtError();
7270       Builder.OnFallthrough = Res.get();
7271     }
7272 
7273     if (auto *OnException = S->getExceptionHandler()) {
7274       StmtResult Res = getDerived().TransformStmt(OnException);
7275       if (Res.isInvalid())
7276         return StmtError();
7277       Builder.OnException = Res.get();
7278     }
7279 
7280     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7281       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7282       if (Res.isInvalid())
7283         return StmtError();
7284       Builder.ReturnStmtOnAllocFailure = Res.get();
7285     }
7286 
7287     // Transform any additional statements we may have already built
7288     assert(S->getAllocate() && S->getDeallocate() &&
7289            "allocation and deallocation calls must already be built");
7290     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7291     if (AllocRes.isInvalid())
7292       return StmtError();
7293     Builder.Allocate = AllocRes.get();
7294 
7295     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7296     if (DeallocRes.isInvalid())
7297       return StmtError();
7298     Builder.Deallocate = DeallocRes.get();
7299 
7300     assert(S->getResultDecl() && "ResultDecl must already be built");
7301     StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7302     if (ResultDecl.isInvalid())
7303       return StmtError();
7304     Builder.ResultDecl = ResultDecl.get();
7305 
7306     if (auto *ReturnStmt = S->getReturnStmt()) {
7307       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7308       if (Res.isInvalid())
7309         return StmtError();
7310       Builder.ReturnStmt = Res.get();
7311     }
7312   }
7313 
7314   return getDerived().RebuildCoroutineBodyStmt(Builder);
7315 }
7316 
7317 template<typename Derived>
7318 StmtResult
7319 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7320   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7321                                                         /*NotCopyInit*/false);
7322   if (Result.isInvalid())
7323     return StmtError();
7324 
7325   // Always rebuild; we don't know if this needs to be injected into a new
7326   // context or if the promise type has changed.
7327   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7328                                           S->isImplicit());
7329 }
7330 
7331 template<typename Derived>
7332 ExprResult
7333 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7334   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7335                                                         /*NotCopyInit*/false);
7336   if (Result.isInvalid())
7337     return ExprError();
7338 
7339   // Always rebuild; we don't know if this needs to be injected into a new
7340   // context or if the promise type has changed.
7341   return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7342                                          E->isImplicit());
7343 }
7344 
7345 template <typename Derived>
7346 ExprResult
7347 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7348   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7349                                                         /*NotCopyInit*/ false);
7350   if (OperandResult.isInvalid())
7351     return ExprError();
7352 
7353   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7354           E->getOperatorCoawaitLookup());
7355 
7356   if (LookupResult.isInvalid())
7357     return ExprError();
7358 
7359   // Always rebuild; we don't know if this needs to be injected into a new
7360   // context or if the promise type has changed.
7361   return getDerived().RebuildDependentCoawaitExpr(
7362       E->getKeywordLoc(), OperandResult.get(),
7363       cast<UnresolvedLookupExpr>(LookupResult.get()));
7364 }
7365 
7366 template<typename Derived>
7367 ExprResult
7368 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7369   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7370                                                         /*NotCopyInit*/false);
7371   if (Result.isInvalid())
7372     return ExprError();
7373 
7374   // Always rebuild; we don't know if this needs to be injected into a new
7375   // context or if the promise type has changed.
7376   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7377 }
7378 
7379 // Objective-C Statements.
7380 
7381 template<typename Derived>
7382 StmtResult
7383 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7384   // Transform the body of the @try.
7385   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7386   if (TryBody.isInvalid())
7387     return StmtError();
7388 
7389   // Transform the @catch statements (if present).
7390   bool AnyCatchChanged = false;
7391   SmallVector<Stmt*, 8> CatchStmts;
7392   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7393     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7394     if (Catch.isInvalid())
7395       return StmtError();
7396     if (Catch.get() != S->getCatchStmt(I))
7397       AnyCatchChanged = true;
7398     CatchStmts.push_back(Catch.get());
7399   }
7400 
7401   // Transform the @finally statement (if present).
7402   StmtResult Finally;
7403   if (S->getFinallyStmt()) {
7404     Finally = getDerived().TransformStmt(S->getFinallyStmt());
7405     if (Finally.isInvalid())
7406       return StmtError();
7407   }
7408 
7409   // If nothing changed, just retain this statement.
7410   if (!getDerived().AlwaysRebuild() &&
7411       TryBody.get() == S->getTryBody() &&
7412       !AnyCatchChanged &&
7413       Finally.get() == S->getFinallyStmt())
7414     return S;
7415 
7416   // Build a new statement.
7417   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7418                                            CatchStmts, Finally.get());
7419 }
7420 
7421 template<typename Derived>
7422 StmtResult
7423 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7424   // Transform the @catch parameter, if there is one.
7425   VarDecl *Var = nullptr;
7426   if (VarDecl *FromVar = S->getCatchParamDecl()) {
7427     TypeSourceInfo *TSInfo = nullptr;
7428     if (FromVar->getTypeSourceInfo()) {
7429       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7430       if (!TSInfo)
7431         return StmtError();
7432     }
7433 
7434     QualType T;
7435     if (TSInfo)
7436       T = TSInfo->getType();
7437     else {
7438       T = getDerived().TransformType(FromVar->getType());
7439       if (T.isNull())
7440         return StmtError();
7441     }
7442 
7443     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7444     if (!Var)
7445       return StmtError();
7446   }
7447 
7448   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7449   if (Body.isInvalid())
7450     return StmtError();
7451 
7452   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7453                                              S->getRParenLoc(),
7454                                              Var, Body.get());
7455 }
7456 
7457 template<typename Derived>
7458 StmtResult
7459 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7460   // Transform the body.
7461   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7462   if (Body.isInvalid())
7463     return StmtError();
7464 
7465   // If nothing changed, just retain this statement.
7466   if (!getDerived().AlwaysRebuild() &&
7467       Body.get() == S->getFinallyBody())
7468     return S;
7469 
7470   // Build a new statement.
7471   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7472                                                Body.get());
7473 }
7474 
7475 template<typename Derived>
7476 StmtResult
7477 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7478   ExprResult Operand;
7479   if (S->getThrowExpr()) {
7480     Operand = getDerived().TransformExpr(S->getThrowExpr());
7481     if (Operand.isInvalid())
7482       return StmtError();
7483   }
7484 
7485   if (!getDerived().AlwaysRebuild() &&
7486       Operand.get() == S->getThrowExpr())
7487     return S;
7488 
7489   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7490 }
7491 
7492 template<typename Derived>
7493 StmtResult
7494 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7495                                                   ObjCAtSynchronizedStmt *S) {
7496   // Transform the object we are locking.
7497   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7498   if (Object.isInvalid())
7499     return StmtError();
7500   Object =
7501     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7502                                                   Object.get());
7503   if (Object.isInvalid())
7504     return StmtError();
7505 
7506   // Transform the body.
7507   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7508   if (Body.isInvalid())
7509     return StmtError();
7510 
7511   // If nothing change, just retain the current statement.
7512   if (!getDerived().AlwaysRebuild() &&
7513       Object.get() == S->getSynchExpr() &&
7514       Body.get() == S->getSynchBody())
7515     return S;
7516 
7517   // Build a new statement.
7518   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7519                                                     Object.get(), Body.get());
7520 }
7521 
7522 template<typename Derived>
7523 StmtResult
7524 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7525                                               ObjCAutoreleasePoolStmt *S) {
7526   // Transform the body.
7527   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7528   if (Body.isInvalid())
7529     return StmtError();
7530 
7531   // If nothing changed, just retain this statement.
7532   if (!getDerived().AlwaysRebuild() &&
7533       Body.get() == S->getSubStmt())
7534     return S;
7535 
7536   // Build a new statement.
7537   return getDerived().RebuildObjCAutoreleasePoolStmt(
7538                         S->getAtLoc(), Body.get());
7539 }
7540 
7541 template<typename Derived>
7542 StmtResult
7543 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7544                                                   ObjCForCollectionStmt *S) {
7545   // Transform the element statement.
7546   StmtResult Element =
7547       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
7548   if (Element.isInvalid())
7549     return StmtError();
7550 
7551   // Transform the collection expression.
7552   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7553   if (Collection.isInvalid())
7554     return StmtError();
7555 
7556   // Transform the body.
7557   StmtResult Body = getDerived().TransformStmt(S->getBody());
7558   if (Body.isInvalid())
7559     return StmtError();
7560 
7561   // If nothing changed, just retain this statement.
7562   if (!getDerived().AlwaysRebuild() &&
7563       Element.get() == S->getElement() &&
7564       Collection.get() == S->getCollection() &&
7565       Body.get() == S->getBody())
7566     return S;
7567 
7568   // Build a new statement.
7569   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7570                                                    Element.get(),
7571                                                    Collection.get(),
7572                                                    S->getRParenLoc(),
7573                                                    Body.get());
7574 }
7575 
7576 template <typename Derived>
7577 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7578   // Transform the exception declaration, if any.
7579   VarDecl *Var = nullptr;
7580   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7581     TypeSourceInfo *T =
7582         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7583     if (!T)
7584       return StmtError();
7585 
7586     Var = getDerived().RebuildExceptionDecl(
7587         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7588         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7589     if (!Var || Var->isInvalidDecl())
7590       return StmtError();
7591   }
7592 
7593   // Transform the actual exception handler.
7594   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7595   if (Handler.isInvalid())
7596     return StmtError();
7597 
7598   if (!getDerived().AlwaysRebuild() && !Var &&
7599       Handler.get() == S->getHandlerBlock())
7600     return S;
7601 
7602   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7603 }
7604 
7605 template <typename Derived>
7606 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7607   // Transform the try block itself.
7608   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7609   if (TryBlock.isInvalid())
7610     return StmtError();
7611 
7612   // Transform the handlers.
7613   bool HandlerChanged = false;
7614   SmallVector<Stmt *, 8> Handlers;
7615   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7616     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7617     if (Handler.isInvalid())
7618       return StmtError();
7619 
7620     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7621     Handlers.push_back(Handler.getAs<Stmt>());
7622   }
7623 
7624   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7625       !HandlerChanged)
7626     return S;
7627 
7628   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7629                                         Handlers);
7630 }
7631 
7632 template<typename Derived>
7633 StmtResult
7634 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7635   StmtResult Init =
7636       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
7637   if (Init.isInvalid())
7638     return StmtError();
7639 
7640   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7641   if (Range.isInvalid())
7642     return StmtError();
7643 
7644   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7645   if (Begin.isInvalid())
7646     return StmtError();
7647   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7648   if (End.isInvalid())
7649     return StmtError();
7650 
7651   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7652   if (Cond.isInvalid())
7653     return StmtError();
7654   if (Cond.get())
7655     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7656   if (Cond.isInvalid())
7657     return StmtError();
7658   if (Cond.get())
7659     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7660 
7661   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7662   if (Inc.isInvalid())
7663     return StmtError();
7664   if (Inc.get())
7665     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7666 
7667   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7668   if (LoopVar.isInvalid())
7669     return StmtError();
7670 
7671   StmtResult NewStmt = S;
7672   if (getDerived().AlwaysRebuild() ||
7673       Init.get() != S->getInit() ||
7674       Range.get() != S->getRangeStmt() ||
7675       Begin.get() != S->getBeginStmt() ||
7676       End.get() != S->getEndStmt() ||
7677       Cond.get() != S->getCond() ||
7678       Inc.get() != S->getInc() ||
7679       LoopVar.get() != S->getLoopVarStmt()) {
7680     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7681                                                   S->getCoawaitLoc(), Init.get(),
7682                                                   S->getColonLoc(), Range.get(),
7683                                                   Begin.get(), End.get(),
7684                                                   Cond.get(),
7685                                                   Inc.get(), LoopVar.get(),
7686                                                   S->getRParenLoc());
7687     if (NewStmt.isInvalid())
7688       return StmtError();
7689   }
7690 
7691   StmtResult Body = getDerived().TransformStmt(S->getBody());
7692   if (Body.isInvalid())
7693     return StmtError();
7694 
7695   // Body has changed but we didn't rebuild the for-range statement. Rebuild
7696   // it now so we have a new statement to attach the body to.
7697   if (Body.get() != S->getBody() && NewStmt.get() == S) {
7698     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7699                                                   S->getCoawaitLoc(), Init.get(),
7700                                                   S->getColonLoc(), Range.get(),
7701                                                   Begin.get(), End.get(),
7702                                                   Cond.get(),
7703                                                   Inc.get(), LoopVar.get(),
7704                                                   S->getRParenLoc());
7705     if (NewStmt.isInvalid())
7706       return StmtError();
7707   }
7708 
7709   if (NewStmt.get() == S)
7710     return S;
7711 
7712   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7713 }
7714 
7715 template<typename Derived>
7716 StmtResult
7717 TreeTransform<Derived>::TransformMSDependentExistsStmt(
7718                                                     MSDependentExistsStmt *S) {
7719   // Transform the nested-name-specifier, if any.
7720   NestedNameSpecifierLoc QualifierLoc;
7721   if (S->getQualifierLoc()) {
7722     QualifierLoc
7723       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7724     if (!QualifierLoc)
7725       return StmtError();
7726   }
7727 
7728   // Transform the declaration name.
7729   DeclarationNameInfo NameInfo = S->getNameInfo();
7730   if (NameInfo.getName()) {
7731     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7732     if (!NameInfo.getName())
7733       return StmtError();
7734   }
7735 
7736   // Check whether anything changed.
7737   if (!getDerived().AlwaysRebuild() &&
7738       QualifierLoc == S->getQualifierLoc() &&
7739       NameInfo.getName() == S->getNameInfo().getName())
7740     return S;
7741 
7742   // Determine whether this name exists, if we can.
7743   CXXScopeSpec SS;
7744   SS.Adopt(QualifierLoc);
7745   bool Dependent = false;
7746   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7747   case Sema::IER_Exists:
7748     if (S->isIfExists())
7749       break;
7750 
7751     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7752 
7753   case Sema::IER_DoesNotExist:
7754     if (S->isIfNotExists())
7755       break;
7756 
7757     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7758 
7759   case Sema::IER_Dependent:
7760     Dependent = true;
7761     break;
7762 
7763   case Sema::IER_Error:
7764     return StmtError();
7765   }
7766 
7767   // We need to continue with the instantiation, so do so now.
7768   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7769   if (SubStmt.isInvalid())
7770     return StmtError();
7771 
7772   // If we have resolved the name, just transform to the substatement.
7773   if (!Dependent)
7774     return SubStmt;
7775 
7776   // The name is still dependent, so build a dependent expression again.
7777   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7778                                                    S->isIfExists(),
7779                                                    QualifierLoc,
7780                                                    NameInfo,
7781                                                    SubStmt.get());
7782 }
7783 
7784 template<typename Derived>
7785 ExprResult
7786 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7787   NestedNameSpecifierLoc QualifierLoc;
7788   if (E->getQualifierLoc()) {
7789     QualifierLoc
7790     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7791     if (!QualifierLoc)
7792       return ExprError();
7793   }
7794 
7795   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7796     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7797   if (!PD)
7798     return ExprError();
7799 
7800   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7801   if (Base.isInvalid())
7802     return ExprError();
7803 
7804   return new (SemaRef.getASTContext())
7805       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7806                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7807                         QualifierLoc, E->getMemberLoc());
7808 }
7809 
7810 template <typename Derived>
7811 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7812     MSPropertySubscriptExpr *E) {
7813   auto BaseRes = getDerived().TransformExpr(E->getBase());
7814   if (BaseRes.isInvalid())
7815     return ExprError();
7816   auto IdxRes = getDerived().TransformExpr(E->getIdx());
7817   if (IdxRes.isInvalid())
7818     return ExprError();
7819 
7820   if (!getDerived().AlwaysRebuild() &&
7821       BaseRes.get() == E->getBase() &&
7822       IdxRes.get() == E->getIdx())
7823     return E;
7824 
7825   return getDerived().RebuildArraySubscriptExpr(
7826       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7827 }
7828 
7829 template <typename Derived>
7830 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7831   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7832   if (TryBlock.isInvalid())
7833     return StmtError();
7834 
7835   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7836   if (Handler.isInvalid())
7837     return StmtError();
7838 
7839   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7840       Handler.get() == S->getHandler())
7841     return S;
7842 
7843   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7844                                         TryBlock.get(), Handler.get());
7845 }
7846 
7847 template <typename Derived>
7848 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7849   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7850   if (Block.isInvalid())
7851     return StmtError();
7852 
7853   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7854 }
7855 
7856 template <typename Derived>
7857 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7858   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7859   if (FilterExpr.isInvalid())
7860     return StmtError();
7861 
7862   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7863   if (Block.isInvalid())
7864     return StmtError();
7865 
7866   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7867                                            Block.get());
7868 }
7869 
7870 template <typename Derived>
7871 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7872   if (isa<SEHFinallyStmt>(Handler))
7873     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7874   else
7875     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7876 }
7877 
7878 template<typename Derived>
7879 StmtResult
7880 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7881   return S;
7882 }
7883 
7884 //===----------------------------------------------------------------------===//
7885 // OpenMP directive transformation
7886 //===----------------------------------------------------------------------===//
7887 template <typename Derived>
7888 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7889     OMPExecutableDirective *D) {
7890 
7891   // Transform the clauses
7892   llvm::SmallVector<OMPClause *, 16> TClauses;
7893   ArrayRef<OMPClause *> Clauses = D->clauses();
7894   TClauses.reserve(Clauses.size());
7895   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
7896        I != E; ++I) {
7897     if (*I) {
7898       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
7899       OMPClause *Clause = getDerived().TransformOMPClause(*I);
7900       getDerived().getSema().EndOpenMPClause();
7901       if (Clause)
7902         TClauses.push_back(Clause);
7903     } else {
7904       TClauses.push_back(nullptr);
7905     }
7906   }
7907   StmtResult AssociatedStmt;
7908   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
7909     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
7910                                                   /*CurScope=*/nullptr);
7911     StmtResult Body;
7912     {
7913       Sema::CompoundScopeRAII CompoundScope(getSema());
7914       Stmt *CS = D->getInnermostCapturedStmt()->getCapturedStmt();
7915       Body = getDerived().TransformStmt(CS);
7916     }
7917     AssociatedStmt =
7918         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
7919     if (AssociatedStmt.isInvalid()) {
7920       return StmtError();
7921     }
7922   }
7923   if (TClauses.size() != Clauses.size()) {
7924     return StmtError();
7925   }
7926 
7927   // Transform directive name for 'omp critical' directive.
7928   DeclarationNameInfo DirName;
7929   if (D->getDirectiveKind() == OMPD_critical) {
7930     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
7931     DirName = getDerived().TransformDeclarationNameInfo(DirName);
7932   }
7933   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
7934   if (D->getDirectiveKind() == OMPD_cancellation_point) {
7935     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
7936   } else if (D->getDirectiveKind() == OMPD_cancel) {
7937     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
7938   }
7939 
7940   return getDerived().RebuildOMPExecutableDirective(
7941       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
7942       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
7943 }
7944 
7945 template <typename Derived>
7946 StmtResult
7947 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
7948   DeclarationNameInfo DirName;
7949   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
7950                                              D->getBeginLoc());
7951   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7952   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7953   return Res;
7954 }
7955 
7956 template <typename Derived>
7957 StmtResult
7958 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
7959   DeclarationNameInfo DirName;
7960   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
7961                                              D->getBeginLoc());
7962   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7963   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7964   return Res;
7965 }
7966 
7967 template <typename Derived>
7968 StmtResult
7969 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
7970   DeclarationNameInfo DirName;
7971   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
7972                                              D->getBeginLoc());
7973   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7974   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7975   return Res;
7976 }
7977 
7978 template <typename Derived>
7979 StmtResult
7980 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
7981   DeclarationNameInfo DirName;
7982   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
7983                                              D->getBeginLoc());
7984   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7985   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7986   return Res;
7987 }
7988 
7989 template <typename Derived>
7990 StmtResult
7991 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
7992   DeclarationNameInfo DirName;
7993   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
7994                                              D->getBeginLoc());
7995   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7996   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7997   return Res;
7998 }
7999 
8000 template <typename Derived>
8001 StmtResult
8002 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8003   DeclarationNameInfo DirName;
8004   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8005                                              D->getBeginLoc());
8006   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8007   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8008   return Res;
8009 }
8010 
8011 template <typename Derived>
8012 StmtResult
8013 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8014   DeclarationNameInfo DirName;
8015   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8016                                              D->getBeginLoc());
8017   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8018   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8019   return Res;
8020 }
8021 
8022 template <typename Derived>
8023 StmtResult
8024 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8025   DeclarationNameInfo DirName;
8026   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8027                                              D->getBeginLoc());
8028   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8029   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8030   return Res;
8031 }
8032 
8033 template <typename Derived>
8034 StmtResult
8035 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8036   getDerived().getSema().StartOpenMPDSABlock(
8037       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8038   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8039   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8040   return Res;
8041 }
8042 
8043 template <typename Derived>
8044 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8045     OMPParallelForDirective *D) {
8046   DeclarationNameInfo DirName;
8047   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8048                                              nullptr, D->getBeginLoc());
8049   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8050   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8051   return Res;
8052 }
8053 
8054 template <typename Derived>
8055 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8056     OMPParallelForSimdDirective *D) {
8057   DeclarationNameInfo DirName;
8058   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8059                                              nullptr, D->getBeginLoc());
8060   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8061   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8062   return Res;
8063 }
8064 
8065 template <typename Derived>
8066 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8067     OMPParallelMasterDirective *D) {
8068   DeclarationNameInfo DirName;
8069   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8070                                              nullptr, D->getBeginLoc());
8071   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8072   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8073   return Res;
8074 }
8075 
8076 template <typename Derived>
8077 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8078     OMPParallelSectionsDirective *D) {
8079   DeclarationNameInfo DirName;
8080   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8081                                              nullptr, D->getBeginLoc());
8082   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8083   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8084   return Res;
8085 }
8086 
8087 template <typename Derived>
8088 StmtResult
8089 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8090   DeclarationNameInfo DirName;
8091   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8092                                              D->getBeginLoc());
8093   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8094   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8095   return Res;
8096 }
8097 
8098 template <typename Derived>
8099 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8100     OMPTaskyieldDirective *D) {
8101   DeclarationNameInfo DirName;
8102   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8103                                              D->getBeginLoc());
8104   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8105   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8106   return Res;
8107 }
8108 
8109 template <typename Derived>
8110 StmtResult
8111 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8112   DeclarationNameInfo DirName;
8113   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8114                                              D->getBeginLoc());
8115   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8116   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8117   return Res;
8118 }
8119 
8120 template <typename Derived>
8121 StmtResult
8122 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8123   DeclarationNameInfo DirName;
8124   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8125                                              D->getBeginLoc());
8126   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8127   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8128   return Res;
8129 }
8130 
8131 template <typename Derived>
8132 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8133     OMPTaskgroupDirective *D) {
8134   DeclarationNameInfo DirName;
8135   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8136                                              D->getBeginLoc());
8137   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8138   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8139   return Res;
8140 }
8141 
8142 template <typename Derived>
8143 StmtResult
8144 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8145   DeclarationNameInfo DirName;
8146   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8147                                              D->getBeginLoc());
8148   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8149   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8150   return Res;
8151 }
8152 
8153 template <typename Derived>
8154 StmtResult
8155 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8156   DeclarationNameInfo DirName;
8157   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8158                                              D->getBeginLoc());
8159   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8160   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8161   return Res;
8162 }
8163 
8164 template <typename Derived>
8165 StmtResult
8166 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8167   DeclarationNameInfo DirName;
8168   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8169                                              D->getBeginLoc());
8170   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8171   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8172   return Res;
8173 }
8174 
8175 template <typename Derived>
8176 StmtResult
8177 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8178   DeclarationNameInfo DirName;
8179   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8180                                              D->getBeginLoc());
8181   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8182   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8183   return Res;
8184 }
8185 
8186 template <typename Derived>
8187 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8188     OMPTargetDataDirective *D) {
8189   DeclarationNameInfo DirName;
8190   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8191                                              D->getBeginLoc());
8192   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8193   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8194   return Res;
8195 }
8196 
8197 template <typename Derived>
8198 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8199     OMPTargetEnterDataDirective *D) {
8200   DeclarationNameInfo DirName;
8201   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8202                                              nullptr, D->getBeginLoc());
8203   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8204   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8205   return Res;
8206 }
8207 
8208 template <typename Derived>
8209 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8210     OMPTargetExitDataDirective *D) {
8211   DeclarationNameInfo DirName;
8212   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8213                                              nullptr, D->getBeginLoc());
8214   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8215   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8216   return Res;
8217 }
8218 
8219 template <typename Derived>
8220 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8221     OMPTargetParallelDirective *D) {
8222   DeclarationNameInfo DirName;
8223   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8224                                              nullptr, D->getBeginLoc());
8225   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8226   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8227   return Res;
8228 }
8229 
8230 template <typename Derived>
8231 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8232     OMPTargetParallelForDirective *D) {
8233   DeclarationNameInfo DirName;
8234   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8235                                              nullptr, D->getBeginLoc());
8236   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8237   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8238   return Res;
8239 }
8240 
8241 template <typename Derived>
8242 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8243     OMPTargetUpdateDirective *D) {
8244   DeclarationNameInfo DirName;
8245   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8246                                              nullptr, D->getBeginLoc());
8247   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8248   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8249   return Res;
8250 }
8251 
8252 template <typename Derived>
8253 StmtResult
8254 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8255   DeclarationNameInfo DirName;
8256   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8257                                              D->getBeginLoc());
8258   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8259   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8260   return Res;
8261 }
8262 
8263 template <typename Derived>
8264 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8265     OMPCancellationPointDirective *D) {
8266   DeclarationNameInfo DirName;
8267   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8268                                              nullptr, D->getBeginLoc());
8269   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8270   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8271   return Res;
8272 }
8273 
8274 template <typename Derived>
8275 StmtResult
8276 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8277   DeclarationNameInfo DirName;
8278   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8279                                              D->getBeginLoc());
8280   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8281   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8282   return Res;
8283 }
8284 
8285 template <typename Derived>
8286 StmtResult
8287 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8288   DeclarationNameInfo DirName;
8289   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8290                                              D->getBeginLoc());
8291   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8292   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8293   return Res;
8294 }
8295 
8296 template <typename Derived>
8297 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8298     OMPTaskLoopSimdDirective *D) {
8299   DeclarationNameInfo DirName;
8300   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8301                                              nullptr, D->getBeginLoc());
8302   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8303   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8304   return Res;
8305 }
8306 
8307 template <typename Derived>
8308 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
8309     OMPMasterTaskLoopDirective *D) {
8310   DeclarationNameInfo DirName;
8311   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
8312                                              nullptr, D->getBeginLoc());
8313   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8314   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8315   return Res;
8316 }
8317 
8318 template <typename Derived>
8319 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
8320     OMPMasterTaskLoopSimdDirective *D) {
8321   DeclarationNameInfo DirName;
8322   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
8323                                              nullptr, D->getBeginLoc());
8324   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8325   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8326   return Res;
8327 }
8328 
8329 template <typename Derived>
8330 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
8331     OMPParallelMasterTaskLoopDirective *D) {
8332   DeclarationNameInfo DirName;
8333   getDerived().getSema().StartOpenMPDSABlock(
8334       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
8335   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8336   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8337   return Res;
8338 }
8339 
8340 template <typename Derived>
8341 StmtResult
8342 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
8343     OMPParallelMasterTaskLoopSimdDirective *D) {
8344   DeclarationNameInfo DirName;
8345   getDerived().getSema().StartOpenMPDSABlock(
8346       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
8347   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8348   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8349   return Res;
8350 }
8351 
8352 template <typename Derived>
8353 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8354     OMPDistributeDirective *D) {
8355   DeclarationNameInfo DirName;
8356   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8357                                              D->getBeginLoc());
8358   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8359   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8360   return Res;
8361 }
8362 
8363 template <typename Derived>
8364 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8365     OMPDistributeParallelForDirective *D) {
8366   DeclarationNameInfo DirName;
8367   getDerived().getSema().StartOpenMPDSABlock(
8368       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8369   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8370   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8371   return Res;
8372 }
8373 
8374 template <typename Derived>
8375 StmtResult
8376 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8377     OMPDistributeParallelForSimdDirective *D) {
8378   DeclarationNameInfo DirName;
8379   getDerived().getSema().StartOpenMPDSABlock(
8380       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8381   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8382   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8383   return Res;
8384 }
8385 
8386 template <typename Derived>
8387 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8388     OMPDistributeSimdDirective *D) {
8389   DeclarationNameInfo DirName;
8390   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8391                                              nullptr, D->getBeginLoc());
8392   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8393   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8394   return Res;
8395 }
8396 
8397 template <typename Derived>
8398 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
8399     OMPTargetParallelForSimdDirective *D) {
8400   DeclarationNameInfo DirName;
8401   getDerived().getSema().StartOpenMPDSABlock(
8402       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8403   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8404   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8405   return Res;
8406 }
8407 
8408 template <typename Derived>
8409 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8410     OMPTargetSimdDirective *D) {
8411   DeclarationNameInfo DirName;
8412   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8413                                              D->getBeginLoc());
8414   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8415   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8416   return Res;
8417 }
8418 
8419 template <typename Derived>
8420 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8421     OMPTeamsDistributeDirective *D) {
8422   DeclarationNameInfo DirName;
8423   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8424                                              nullptr, D->getBeginLoc());
8425   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8426   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8427   return Res;
8428 }
8429 
8430 template <typename Derived>
8431 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8432     OMPTeamsDistributeSimdDirective *D) {
8433   DeclarationNameInfo DirName;
8434   getDerived().getSema().StartOpenMPDSABlock(
8435       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8436   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8437   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8438   return Res;
8439 }
8440 
8441 template <typename Derived>
8442 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8443     OMPTeamsDistributeParallelForSimdDirective *D) {
8444   DeclarationNameInfo DirName;
8445   getDerived().getSema().StartOpenMPDSABlock(
8446       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
8447       D->getBeginLoc());
8448   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8449   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8450   return Res;
8451 }
8452 
8453 template <typename Derived>
8454 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8455     OMPTeamsDistributeParallelForDirective *D) {
8456   DeclarationNameInfo DirName;
8457   getDerived().getSema().StartOpenMPDSABlock(
8458       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8459   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8460   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8461   return Res;
8462 }
8463 
8464 template <typename Derived>
8465 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8466     OMPTargetTeamsDirective *D) {
8467   DeclarationNameInfo DirName;
8468   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8469                                              nullptr, D->getBeginLoc());
8470   auto Res = getDerived().TransformOMPExecutableDirective(D);
8471   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8472   return Res;
8473 }
8474 
8475 template <typename Derived>
8476 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8477     OMPTargetTeamsDistributeDirective *D) {
8478   DeclarationNameInfo DirName;
8479   getDerived().getSema().StartOpenMPDSABlock(
8480       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
8481   auto Res = getDerived().TransformOMPExecutableDirective(D);
8482   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8483   return Res;
8484 }
8485 
8486 template <typename Derived>
8487 StmtResult
8488 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8489     OMPTargetTeamsDistributeParallelForDirective *D) {
8490   DeclarationNameInfo DirName;
8491   getDerived().getSema().StartOpenMPDSABlock(
8492       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8493       D->getBeginLoc());
8494   auto Res = getDerived().TransformOMPExecutableDirective(D);
8495   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8496   return Res;
8497 }
8498 
8499 template <typename Derived>
8500 StmtResult TreeTransform<Derived>::
8501     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8502         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8503   DeclarationNameInfo DirName;
8504   getDerived().getSema().StartOpenMPDSABlock(
8505       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8506       D->getBeginLoc());
8507   auto Res = getDerived().TransformOMPExecutableDirective(D);
8508   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8509   return Res;
8510 }
8511 
8512 template <typename Derived>
8513 StmtResult
8514 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8515     OMPTargetTeamsDistributeSimdDirective *D) {
8516   DeclarationNameInfo DirName;
8517   getDerived().getSema().StartOpenMPDSABlock(
8518       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8519   auto Res = getDerived().TransformOMPExecutableDirective(D);
8520   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8521   return Res;
8522 }
8523 
8524 
8525 //===----------------------------------------------------------------------===//
8526 // OpenMP clause transformation
8527 //===----------------------------------------------------------------------===//
8528 template <typename Derived>
8529 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8530   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8531   if (Cond.isInvalid())
8532     return nullptr;
8533   return getDerived().RebuildOMPIfClause(
8534       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
8535       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
8536 }
8537 
8538 template <typename Derived>
8539 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8540   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8541   if (Cond.isInvalid())
8542     return nullptr;
8543   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
8544                                             C->getLParenLoc(), C->getEndLoc());
8545 }
8546 
8547 template <typename Derived>
8548 OMPClause *
8549 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8550   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8551   if (NumThreads.isInvalid())
8552     return nullptr;
8553   return getDerived().RebuildOMPNumThreadsClause(
8554       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8555 }
8556 
8557 template <typename Derived>
8558 OMPClause *
8559 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8560   ExprResult E = getDerived().TransformExpr(C->getSafelen());
8561   if (E.isInvalid())
8562     return nullptr;
8563   return getDerived().RebuildOMPSafelenClause(
8564       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8565 }
8566 
8567 template <typename Derived>
8568 OMPClause *
8569 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
8570   ExprResult E = getDerived().TransformExpr(C->getAllocator());
8571   if (E.isInvalid())
8572     return nullptr;
8573   return getDerived().RebuildOMPAllocatorClause(
8574       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8575 }
8576 
8577 template <typename Derived>
8578 OMPClause *
8579 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8580   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8581   if (E.isInvalid())
8582     return nullptr;
8583   return getDerived().RebuildOMPSimdlenClause(
8584       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8585 }
8586 
8587 template <typename Derived>
8588 OMPClause *
8589 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8590   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8591   if (E.isInvalid())
8592     return nullptr;
8593   return getDerived().RebuildOMPCollapseClause(
8594       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8595 }
8596 
8597 template <typename Derived>
8598 OMPClause *
8599 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8600   return getDerived().RebuildOMPDefaultClause(
8601       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
8602       C->getLParenLoc(), C->getEndLoc());
8603 }
8604 
8605 template <typename Derived>
8606 OMPClause *
8607 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8608   return getDerived().RebuildOMPProcBindClause(
8609       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
8610       C->getLParenLoc(), C->getEndLoc());
8611 }
8612 
8613 template <typename Derived>
8614 OMPClause *
8615 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8616   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8617   if (E.isInvalid())
8618     return nullptr;
8619   return getDerived().RebuildOMPScheduleClause(
8620       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8621       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
8622       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8623       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
8624 }
8625 
8626 template <typename Derived>
8627 OMPClause *
8628 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8629   ExprResult E;
8630   if (auto *Num = C->getNumForLoops()) {
8631     E = getDerived().TransformExpr(Num);
8632     if (E.isInvalid())
8633       return nullptr;
8634   }
8635   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
8636                                               C->getLParenLoc(), E.get());
8637 }
8638 
8639 template <typename Derived>
8640 OMPClause *
8641 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8642   // No need to rebuild this clause, no template-dependent parameters.
8643   return C;
8644 }
8645 
8646 template <typename Derived>
8647 OMPClause *
8648 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8649   // No need to rebuild this clause, no template-dependent parameters.
8650   return C;
8651 }
8652 
8653 template <typename Derived>
8654 OMPClause *
8655 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8656   // No need to rebuild this clause, no template-dependent parameters.
8657   return C;
8658 }
8659 
8660 template <typename Derived>
8661 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8662   // No need to rebuild this clause, no template-dependent parameters.
8663   return C;
8664 }
8665 
8666 template <typename Derived>
8667 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8668   // No need to rebuild this clause, no template-dependent parameters.
8669   return C;
8670 }
8671 
8672 template <typename Derived>
8673 OMPClause *
8674 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8675   // No need to rebuild this clause, no template-dependent parameters.
8676   return C;
8677 }
8678 
8679 template <typename Derived>
8680 OMPClause *
8681 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8682   // No need to rebuild this clause, no template-dependent parameters.
8683   return C;
8684 }
8685 
8686 template <typename Derived>
8687 OMPClause *
8688 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8689   // No need to rebuild this clause, no template-dependent parameters.
8690   return C;
8691 }
8692 
8693 template <typename Derived>
8694 OMPClause *
8695 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8696   // No need to rebuild this clause, no template-dependent parameters.
8697   return C;
8698 }
8699 
8700 template <typename Derived>
8701 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8702   // No need to rebuild this clause, no template-dependent parameters.
8703   return C;
8704 }
8705 
8706 template <typename Derived>
8707 OMPClause *
8708 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8709   // No need to rebuild this clause, no template-dependent parameters.
8710   return C;
8711 }
8712 
8713 template <typename Derived>
8714 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
8715     OMPUnifiedAddressClause *C) {
8716   llvm_unreachable("unified_address clause cannot appear in dependent context");
8717 }
8718 
8719 template <typename Derived>
8720 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
8721     OMPUnifiedSharedMemoryClause *C) {
8722   llvm_unreachable(
8723       "unified_shared_memory clause cannot appear in dependent context");
8724 }
8725 
8726 template <typename Derived>
8727 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
8728     OMPReverseOffloadClause *C) {
8729   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
8730 }
8731 
8732 template <typename Derived>
8733 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
8734     OMPDynamicAllocatorsClause *C) {
8735   llvm_unreachable(
8736       "dynamic_allocators clause cannot appear in dependent context");
8737 }
8738 
8739 template <typename Derived>
8740 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
8741     OMPAtomicDefaultMemOrderClause *C) {
8742   llvm_unreachable(
8743       "atomic_default_mem_order clause cannot appear in dependent context");
8744 }
8745 
8746 template <typename Derived>
8747 OMPClause *
8748 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8749   llvm::SmallVector<Expr *, 16> Vars;
8750   Vars.reserve(C->varlist_size());
8751   for (auto *VE : C->varlists()) {
8752     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8753     if (EVar.isInvalid())
8754       return nullptr;
8755     Vars.push_back(EVar.get());
8756   }
8757   return getDerived().RebuildOMPPrivateClause(
8758       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8759 }
8760 
8761 template <typename Derived>
8762 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8763     OMPFirstprivateClause *C) {
8764   llvm::SmallVector<Expr *, 16> Vars;
8765   Vars.reserve(C->varlist_size());
8766   for (auto *VE : C->varlists()) {
8767     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8768     if (EVar.isInvalid())
8769       return nullptr;
8770     Vars.push_back(EVar.get());
8771   }
8772   return getDerived().RebuildOMPFirstprivateClause(
8773       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8774 }
8775 
8776 template <typename Derived>
8777 OMPClause *
8778 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8779   llvm::SmallVector<Expr *, 16> Vars;
8780   Vars.reserve(C->varlist_size());
8781   for (auto *VE : C->varlists()) {
8782     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8783     if (EVar.isInvalid())
8784       return nullptr;
8785     Vars.push_back(EVar.get());
8786   }
8787   return getDerived().RebuildOMPLastprivateClause(
8788       Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
8789       C->getLParenLoc(), C->getEndLoc());
8790 }
8791 
8792 template <typename Derived>
8793 OMPClause *
8794 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8795   llvm::SmallVector<Expr *, 16> Vars;
8796   Vars.reserve(C->varlist_size());
8797   for (auto *VE : C->varlists()) {
8798     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8799     if (EVar.isInvalid())
8800       return nullptr;
8801     Vars.push_back(EVar.get());
8802   }
8803   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
8804                                              C->getLParenLoc(), C->getEndLoc());
8805 }
8806 
8807 template <typename Derived>
8808 OMPClause *
8809 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8810   llvm::SmallVector<Expr *, 16> Vars;
8811   Vars.reserve(C->varlist_size());
8812   for (auto *VE : C->varlists()) {
8813     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8814     if (EVar.isInvalid())
8815       return nullptr;
8816     Vars.push_back(EVar.get());
8817   }
8818   CXXScopeSpec ReductionIdScopeSpec;
8819   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8820 
8821   DeclarationNameInfo NameInfo = C->getNameInfo();
8822   if (NameInfo.getName()) {
8823     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8824     if (!NameInfo.getName())
8825       return nullptr;
8826   }
8827   // Build a list of all UDR decls with the same names ranged by the Scopes.
8828   // The Scope boundary is a duplication of the previous decl.
8829   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8830   for (auto *E : C->reduction_ops()) {
8831     // Transform all the decls.
8832     if (E) {
8833       auto *ULE = cast<UnresolvedLookupExpr>(E);
8834       UnresolvedSet<8> Decls;
8835       for (auto *D : ULE->decls()) {
8836         NamedDecl *InstD =
8837             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8838         Decls.addDecl(InstD, InstD->getAccess());
8839       }
8840       UnresolvedReductions.push_back(
8841        UnresolvedLookupExpr::Create(
8842           SemaRef.Context, /*NamingClass=*/nullptr,
8843           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8844           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8845           Decls.begin(), Decls.end()));
8846     } else
8847       UnresolvedReductions.push_back(nullptr);
8848   }
8849   return getDerived().RebuildOMPReductionClause(
8850       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8851       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8852 }
8853 
8854 template <typename Derived>
8855 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
8856     OMPTaskReductionClause *C) {
8857   llvm::SmallVector<Expr *, 16> Vars;
8858   Vars.reserve(C->varlist_size());
8859   for (auto *VE : C->varlists()) {
8860     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8861     if (EVar.isInvalid())
8862       return nullptr;
8863     Vars.push_back(EVar.get());
8864   }
8865   CXXScopeSpec ReductionIdScopeSpec;
8866   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8867 
8868   DeclarationNameInfo NameInfo = C->getNameInfo();
8869   if (NameInfo.getName()) {
8870     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8871     if (!NameInfo.getName())
8872       return nullptr;
8873   }
8874   // Build a list of all UDR decls with the same names ranged by the Scopes.
8875   // The Scope boundary is a duplication of the previous decl.
8876   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8877   for (auto *E : C->reduction_ops()) {
8878     // Transform all the decls.
8879     if (E) {
8880       auto *ULE = cast<UnresolvedLookupExpr>(E);
8881       UnresolvedSet<8> Decls;
8882       for (auto *D : ULE->decls()) {
8883         NamedDecl *InstD =
8884             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8885         Decls.addDecl(InstD, InstD->getAccess());
8886       }
8887       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8888           SemaRef.Context, /*NamingClass=*/nullptr,
8889           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8890           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8891     } else
8892       UnresolvedReductions.push_back(nullptr);
8893   }
8894   return getDerived().RebuildOMPTaskReductionClause(
8895       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8896       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8897 }
8898 
8899 template <typename Derived>
8900 OMPClause *
8901 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
8902   llvm::SmallVector<Expr *, 16> Vars;
8903   Vars.reserve(C->varlist_size());
8904   for (auto *VE : C->varlists()) {
8905     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8906     if (EVar.isInvalid())
8907       return nullptr;
8908     Vars.push_back(EVar.get());
8909   }
8910   CXXScopeSpec ReductionIdScopeSpec;
8911   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8912 
8913   DeclarationNameInfo NameInfo = C->getNameInfo();
8914   if (NameInfo.getName()) {
8915     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8916     if (!NameInfo.getName())
8917       return nullptr;
8918   }
8919   // Build a list of all UDR decls with the same names ranged by the Scopes.
8920   // The Scope boundary is a duplication of the previous decl.
8921   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8922   for (auto *E : C->reduction_ops()) {
8923     // Transform all the decls.
8924     if (E) {
8925       auto *ULE = cast<UnresolvedLookupExpr>(E);
8926       UnresolvedSet<8> Decls;
8927       for (auto *D : ULE->decls()) {
8928         NamedDecl *InstD =
8929             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8930         Decls.addDecl(InstD, InstD->getAccess());
8931       }
8932       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8933           SemaRef.Context, /*NamingClass=*/nullptr,
8934           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8935           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8936     } else
8937       UnresolvedReductions.push_back(nullptr);
8938   }
8939   return getDerived().RebuildOMPInReductionClause(
8940       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8941       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8942 }
8943 
8944 template <typename Derived>
8945 OMPClause *
8946 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8947   llvm::SmallVector<Expr *, 16> Vars;
8948   Vars.reserve(C->varlist_size());
8949   for (auto *VE : C->varlists()) {
8950     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8951     if (EVar.isInvalid())
8952       return nullptr;
8953     Vars.push_back(EVar.get());
8954   }
8955   ExprResult Step = getDerived().TransformExpr(C->getStep());
8956   if (Step.isInvalid())
8957     return nullptr;
8958   return getDerived().RebuildOMPLinearClause(
8959       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
8960       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
8961 }
8962 
8963 template <typename Derived>
8964 OMPClause *
8965 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8966   llvm::SmallVector<Expr *, 16> Vars;
8967   Vars.reserve(C->varlist_size());
8968   for (auto *VE : C->varlists()) {
8969     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8970     if (EVar.isInvalid())
8971       return nullptr;
8972     Vars.push_back(EVar.get());
8973   }
8974   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8975   if (Alignment.isInvalid())
8976     return nullptr;
8977   return getDerived().RebuildOMPAlignedClause(
8978       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
8979       C->getColonLoc(), C->getEndLoc());
8980 }
8981 
8982 template <typename Derived>
8983 OMPClause *
8984 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8985   llvm::SmallVector<Expr *, 16> Vars;
8986   Vars.reserve(C->varlist_size());
8987   for (auto *VE : C->varlists()) {
8988     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8989     if (EVar.isInvalid())
8990       return nullptr;
8991     Vars.push_back(EVar.get());
8992   }
8993   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
8994                                              C->getLParenLoc(), C->getEndLoc());
8995 }
8996 
8997 template <typename Derived>
8998 OMPClause *
8999 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
9000   llvm::SmallVector<Expr *, 16> Vars;
9001   Vars.reserve(C->varlist_size());
9002   for (auto *VE : C->varlists()) {
9003     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9004     if (EVar.isInvalid())
9005       return nullptr;
9006     Vars.push_back(EVar.get());
9007   }
9008   return getDerived().RebuildOMPCopyprivateClause(
9009       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9010 }
9011 
9012 template <typename Derived>
9013 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
9014   llvm::SmallVector<Expr *, 16> Vars;
9015   Vars.reserve(C->varlist_size());
9016   for (auto *VE : C->varlists()) {
9017     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9018     if (EVar.isInvalid())
9019       return nullptr;
9020     Vars.push_back(EVar.get());
9021   }
9022   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
9023                                             C->getLParenLoc(), C->getEndLoc());
9024 }
9025 
9026 template <typename Derived>
9027 OMPClause *
9028 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
9029   llvm::SmallVector<Expr *, 16> Vars;
9030   Vars.reserve(C->varlist_size());
9031   for (auto *VE : C->varlists()) {
9032     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9033     if (EVar.isInvalid())
9034       return nullptr;
9035     Vars.push_back(EVar.get());
9036   }
9037   return getDerived().RebuildOMPDependClause(
9038       C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
9039       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9040 }
9041 
9042 template <typename Derived>
9043 OMPClause *
9044 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
9045   ExprResult E = getDerived().TransformExpr(C->getDevice());
9046   if (E.isInvalid())
9047     return nullptr;
9048   return getDerived().RebuildOMPDeviceClause(E.get(), C->getBeginLoc(),
9049                                              C->getLParenLoc(), C->getEndLoc());
9050 }
9051 
9052 template <typename Derived, class T>
9053 bool transformOMPMappableExprListClause(
9054     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
9055     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
9056     DeclarationNameInfo &MapperIdInfo,
9057     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
9058   // Transform expressions in the list.
9059   Vars.reserve(C->varlist_size());
9060   for (auto *VE : C->varlists()) {
9061     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
9062     if (EVar.isInvalid())
9063       return true;
9064     Vars.push_back(EVar.get());
9065   }
9066   // Transform mapper scope specifier and identifier.
9067   NestedNameSpecifierLoc QualifierLoc;
9068   if (C->getMapperQualifierLoc()) {
9069     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
9070         C->getMapperQualifierLoc());
9071     if (!QualifierLoc)
9072       return true;
9073   }
9074   MapperIdScopeSpec.Adopt(QualifierLoc);
9075   MapperIdInfo = C->getMapperIdInfo();
9076   if (MapperIdInfo.getName()) {
9077     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
9078     if (!MapperIdInfo.getName())
9079       return true;
9080   }
9081   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
9082   // the previous user-defined mapper lookup in dependent environment.
9083   for (auto *E : C->mapperlists()) {
9084     // Transform all the decls.
9085     if (E) {
9086       auto *ULE = cast<UnresolvedLookupExpr>(E);
9087       UnresolvedSet<8> Decls;
9088       for (auto *D : ULE->decls()) {
9089         NamedDecl *InstD =
9090             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
9091         Decls.addDecl(InstD, InstD->getAccess());
9092       }
9093       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
9094           TT.getSema().Context, /*NamingClass=*/nullptr,
9095           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
9096           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
9097           Decls.end()));
9098     } else {
9099       UnresolvedMappers.push_back(nullptr);
9100     }
9101   }
9102   return false;
9103 }
9104 
9105 template <typename Derived>
9106 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
9107   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9108   llvm::SmallVector<Expr *, 16> Vars;
9109   CXXScopeSpec MapperIdScopeSpec;
9110   DeclarationNameInfo MapperIdInfo;
9111   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9112   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9113           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9114     return nullptr;
9115   return getDerived().RebuildOMPMapClause(
9116       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9117       MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9118       C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9119 }
9120 
9121 template <typename Derived>
9122 OMPClause *
9123 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9124   Expr *Allocator = C->getAllocator();
9125   if (Allocator) {
9126     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9127     if (AllocatorRes.isInvalid())
9128       return nullptr;
9129     Allocator = AllocatorRes.get();
9130   }
9131   llvm::SmallVector<Expr *, 16> Vars;
9132   Vars.reserve(C->varlist_size());
9133   for (auto *VE : C->varlists()) {
9134     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9135     if (EVar.isInvalid())
9136       return nullptr;
9137     Vars.push_back(EVar.get());
9138   }
9139   return getDerived().RebuildOMPAllocateClause(
9140       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9141       C->getEndLoc());
9142 }
9143 
9144 template <typename Derived>
9145 OMPClause *
9146 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9147   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9148   if (E.isInvalid())
9149     return nullptr;
9150   return getDerived().RebuildOMPNumTeamsClause(
9151       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9152 }
9153 
9154 template <typename Derived>
9155 OMPClause *
9156 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9157   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9158   if (E.isInvalid())
9159     return nullptr;
9160   return getDerived().RebuildOMPThreadLimitClause(
9161       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9162 }
9163 
9164 template <typename Derived>
9165 OMPClause *
9166 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9167   ExprResult E = getDerived().TransformExpr(C->getPriority());
9168   if (E.isInvalid())
9169     return nullptr;
9170   return getDerived().RebuildOMPPriorityClause(
9171       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9172 }
9173 
9174 template <typename Derived>
9175 OMPClause *
9176 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9177   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9178   if (E.isInvalid())
9179     return nullptr;
9180   return getDerived().RebuildOMPGrainsizeClause(
9181       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9182 }
9183 
9184 template <typename Derived>
9185 OMPClause *
9186 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
9187   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
9188   if (E.isInvalid())
9189     return nullptr;
9190   return getDerived().RebuildOMPNumTasksClause(
9191       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9192 }
9193 
9194 template <typename Derived>
9195 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
9196   ExprResult E = getDerived().TransformExpr(C->getHint());
9197   if (E.isInvalid())
9198     return nullptr;
9199   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
9200                                            C->getLParenLoc(), C->getEndLoc());
9201 }
9202 
9203 template <typename Derived>
9204 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
9205     OMPDistScheduleClause *C) {
9206   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9207   if (E.isInvalid())
9208     return nullptr;
9209   return getDerived().RebuildOMPDistScheduleClause(
9210       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9211       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9212 }
9213 
9214 template <typename Derived>
9215 OMPClause *
9216 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
9217   // Rebuild Defaultmap Clause since we need to invoke the checking of
9218   // defaultmap(none:variable-category) after template initialization.
9219   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
9220                                                  C->getDefaultmapKind(),
9221                                                  C->getBeginLoc(),
9222                                                  C->getLParenLoc(),
9223                                                  C->getDefaultmapModifierLoc(),
9224                                                  C->getDefaultmapKindLoc(),
9225                                                  C->getEndLoc());
9226 }
9227 
9228 template <typename Derived>
9229 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
9230   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9231   llvm::SmallVector<Expr *, 16> Vars;
9232   CXXScopeSpec MapperIdScopeSpec;
9233   DeclarationNameInfo MapperIdInfo;
9234   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9235   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
9236           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9237     return nullptr;
9238   return getDerived().RebuildOMPToClause(Vars, MapperIdScopeSpec, MapperIdInfo,
9239                                          Locs, UnresolvedMappers);
9240 }
9241 
9242 template <typename Derived>
9243 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
9244   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9245   llvm::SmallVector<Expr *, 16> Vars;
9246   CXXScopeSpec MapperIdScopeSpec;
9247   DeclarationNameInfo MapperIdInfo;
9248   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9249   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
9250           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9251     return nullptr;
9252   return getDerived().RebuildOMPFromClause(
9253       Vars, MapperIdScopeSpec, MapperIdInfo, Locs, UnresolvedMappers);
9254 }
9255 
9256 template <typename Derived>
9257 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
9258     OMPUseDevicePtrClause *C) {
9259   llvm::SmallVector<Expr *, 16> Vars;
9260   Vars.reserve(C->varlist_size());
9261   for (auto *VE : C->varlists()) {
9262     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9263     if (EVar.isInvalid())
9264       return nullptr;
9265     Vars.push_back(EVar.get());
9266   }
9267   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9268   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
9269 }
9270 
9271 template <typename Derived>
9272 OMPClause *
9273 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
9274   llvm::SmallVector<Expr *, 16> Vars;
9275   Vars.reserve(C->varlist_size());
9276   for (auto *VE : C->varlists()) {
9277     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9278     if (EVar.isInvalid())
9279       return nullptr;
9280     Vars.push_back(EVar.get());
9281   }
9282   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9283   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
9284 }
9285 
9286 template <typename Derived>
9287 OMPClause *
9288 TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
9289   llvm::SmallVector<Expr *, 16> Vars;
9290   Vars.reserve(C->varlist_size());
9291   for (auto *VE : C->varlists()) {
9292     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9293     if (EVar.isInvalid())
9294       return nullptr;
9295     Vars.push_back(EVar.get());
9296   }
9297   return getDerived().RebuildOMPNontemporalClause(
9298       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9299 }
9300 
9301 //===----------------------------------------------------------------------===//
9302 // Expression transformation
9303 //===----------------------------------------------------------------------===//
9304 template<typename Derived>
9305 ExprResult
9306 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
9307   return TransformExpr(E->getSubExpr());
9308 }
9309 
9310 template<typename Derived>
9311 ExprResult
9312 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
9313   if (!E->isTypeDependent())
9314     return E;
9315 
9316   return getDerived().RebuildPredefinedExpr(E->getLocation(),
9317                                             E->getIdentKind());
9318 }
9319 
9320 template<typename Derived>
9321 ExprResult
9322 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
9323   NestedNameSpecifierLoc QualifierLoc;
9324   if (E->getQualifierLoc()) {
9325     QualifierLoc
9326       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9327     if (!QualifierLoc)
9328       return ExprError();
9329   }
9330 
9331   ValueDecl *ND
9332     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
9333                                                          E->getDecl()));
9334   if (!ND)
9335     return ExprError();
9336 
9337   NamedDecl *Found = ND;
9338   if (E->getFoundDecl() != E->getDecl()) {
9339     Found = cast_or_null<NamedDecl>(
9340         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
9341     if (!Found)
9342       return ExprError();
9343   }
9344 
9345   DeclarationNameInfo NameInfo = E->getNameInfo();
9346   if (NameInfo.getName()) {
9347     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9348     if (!NameInfo.getName())
9349       return ExprError();
9350   }
9351 
9352   if (!getDerived().AlwaysRebuild() &&
9353       QualifierLoc == E->getQualifierLoc() &&
9354       ND == E->getDecl() &&
9355       Found == E->getFoundDecl() &&
9356       NameInfo.getName() == E->getDecl()->getDeclName() &&
9357       !E->hasExplicitTemplateArgs()) {
9358 
9359     // Mark it referenced in the new context regardless.
9360     // FIXME: this is a bit instantiation-specific.
9361     SemaRef.MarkDeclRefReferenced(E);
9362 
9363     return E;
9364   }
9365 
9366   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
9367   if (E->hasExplicitTemplateArgs()) {
9368     TemplateArgs = &TransArgs;
9369     TransArgs.setLAngleLoc(E->getLAngleLoc());
9370     TransArgs.setRAngleLoc(E->getRAngleLoc());
9371     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9372                                                 E->getNumTemplateArgs(),
9373                                                 TransArgs))
9374       return ExprError();
9375   }
9376 
9377   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
9378                                          Found, TemplateArgs);
9379 }
9380 
9381 template<typename Derived>
9382 ExprResult
9383 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
9384   return E;
9385 }
9386 
9387 template <typename Derived>
9388 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
9389     FixedPointLiteral *E) {
9390   return E;
9391 }
9392 
9393 template<typename Derived>
9394 ExprResult
9395 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
9396   return E;
9397 }
9398 
9399 template<typename Derived>
9400 ExprResult
9401 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
9402   return E;
9403 }
9404 
9405 template<typename Derived>
9406 ExprResult
9407 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
9408   return E;
9409 }
9410 
9411 template<typename Derived>
9412 ExprResult
9413 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
9414   return E;
9415 }
9416 
9417 template<typename Derived>
9418 ExprResult
9419 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
9420   if (FunctionDecl *FD = E->getDirectCallee())
9421     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
9422   return SemaRef.MaybeBindToTemporary(E);
9423 }
9424 
9425 template<typename Derived>
9426 ExprResult
9427 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
9428   ExprResult ControllingExpr =
9429     getDerived().TransformExpr(E->getControllingExpr());
9430   if (ControllingExpr.isInvalid())
9431     return ExprError();
9432 
9433   SmallVector<Expr *, 4> AssocExprs;
9434   SmallVector<TypeSourceInfo *, 4> AssocTypes;
9435   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
9436     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
9437     if (TSI) {
9438       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
9439       if (!AssocType)
9440         return ExprError();
9441       AssocTypes.push_back(AssocType);
9442     } else {
9443       AssocTypes.push_back(nullptr);
9444     }
9445 
9446     ExprResult AssocExpr =
9447         getDerived().TransformExpr(Assoc.getAssociationExpr());
9448     if (AssocExpr.isInvalid())
9449       return ExprError();
9450     AssocExprs.push_back(AssocExpr.get());
9451   }
9452 
9453   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
9454                                                   E->getDefaultLoc(),
9455                                                   E->getRParenLoc(),
9456                                                   ControllingExpr.get(),
9457                                                   AssocTypes,
9458                                                   AssocExprs);
9459 }
9460 
9461 template<typename Derived>
9462 ExprResult
9463 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
9464   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9465   if (SubExpr.isInvalid())
9466     return ExprError();
9467 
9468   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9469     return E;
9470 
9471   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
9472                                        E->getRParen());
9473 }
9474 
9475 /// The operand of a unary address-of operator has special rules: it's
9476 /// allowed to refer to a non-static member of a class even if there's no 'this'
9477 /// object available.
9478 template<typename Derived>
9479 ExprResult
9480 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
9481   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
9482     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
9483   else
9484     return getDerived().TransformExpr(E);
9485 }
9486 
9487 template<typename Derived>
9488 ExprResult
9489 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
9490   ExprResult SubExpr;
9491   if (E->getOpcode() == UO_AddrOf)
9492     SubExpr = TransformAddressOfOperand(E->getSubExpr());
9493   else
9494     SubExpr = TransformExpr(E->getSubExpr());
9495   if (SubExpr.isInvalid())
9496     return ExprError();
9497 
9498   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9499     return E;
9500 
9501   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
9502                                            E->getOpcode(),
9503                                            SubExpr.get());
9504 }
9505 
9506 template<typename Derived>
9507 ExprResult
9508 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
9509   // Transform the type.
9510   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
9511   if (!Type)
9512     return ExprError();
9513 
9514   // Transform all of the components into components similar to what the
9515   // parser uses.
9516   // FIXME: It would be slightly more efficient in the non-dependent case to
9517   // just map FieldDecls, rather than requiring the rebuilder to look for
9518   // the fields again. However, __builtin_offsetof is rare enough in
9519   // template code that we don't care.
9520   bool ExprChanged = false;
9521   typedef Sema::OffsetOfComponent Component;
9522   SmallVector<Component, 4> Components;
9523   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
9524     const OffsetOfNode &ON = E->getComponent(I);
9525     Component Comp;
9526     Comp.isBrackets = true;
9527     Comp.LocStart = ON.getSourceRange().getBegin();
9528     Comp.LocEnd = ON.getSourceRange().getEnd();
9529     switch (ON.getKind()) {
9530     case OffsetOfNode::Array: {
9531       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
9532       ExprResult Index = getDerived().TransformExpr(FromIndex);
9533       if (Index.isInvalid())
9534         return ExprError();
9535 
9536       ExprChanged = ExprChanged || Index.get() != FromIndex;
9537       Comp.isBrackets = true;
9538       Comp.U.E = Index.get();
9539       break;
9540     }
9541 
9542     case OffsetOfNode::Field:
9543     case OffsetOfNode::Identifier:
9544       Comp.isBrackets = false;
9545       Comp.U.IdentInfo = ON.getFieldName();
9546       if (!Comp.U.IdentInfo)
9547         continue;
9548 
9549       break;
9550 
9551     case OffsetOfNode::Base:
9552       // Will be recomputed during the rebuild.
9553       continue;
9554     }
9555 
9556     Components.push_back(Comp);
9557   }
9558 
9559   // If nothing changed, retain the existing expression.
9560   if (!getDerived().AlwaysRebuild() &&
9561       Type == E->getTypeSourceInfo() &&
9562       !ExprChanged)
9563     return E;
9564 
9565   // Build a new offsetof expression.
9566   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
9567                                           Components, E->getRParenLoc());
9568 }
9569 
9570 template<typename Derived>
9571 ExprResult
9572 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
9573   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
9574          "opaque value expression requires transformation");
9575   return E;
9576 }
9577 
9578 template<typename Derived>
9579 ExprResult
9580 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
9581   return E;
9582 }
9583 
9584 template<typename Derived>
9585 ExprResult
9586 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
9587   // Rebuild the syntactic form.  The original syntactic form has
9588   // opaque-value expressions in it, so strip those away and rebuild
9589   // the result.  This is a really awful way of doing this, but the
9590   // better solution (rebuilding the semantic expressions and
9591   // rebinding OVEs as necessary) doesn't work; we'd need
9592   // TreeTransform to not strip away implicit conversions.
9593   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
9594   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
9595   if (result.isInvalid()) return ExprError();
9596 
9597   // If that gives us a pseudo-object result back, the pseudo-object
9598   // expression must have been an lvalue-to-rvalue conversion which we
9599   // should reapply.
9600   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
9601     result = SemaRef.checkPseudoObjectRValue(result.get());
9602 
9603   return result;
9604 }
9605 
9606 template<typename Derived>
9607 ExprResult
9608 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
9609                                                 UnaryExprOrTypeTraitExpr *E) {
9610   if (E->isArgumentType()) {
9611     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
9612 
9613     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9614     if (!NewT)
9615       return ExprError();
9616 
9617     if (!getDerived().AlwaysRebuild() && OldT == NewT)
9618       return E;
9619 
9620     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
9621                                                     E->getKind(),
9622                                                     E->getSourceRange());
9623   }
9624 
9625   // C++0x [expr.sizeof]p1:
9626   //   The operand is either an expression, which is an unevaluated operand
9627   //   [...]
9628   EnterExpressionEvaluationContext Unevaluated(
9629       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9630       Sema::ReuseLambdaContextDecl);
9631 
9632   // Try to recover if we have something like sizeof(T::X) where X is a type.
9633   // Notably, there must be *exactly* one set of parens if X is a type.
9634   TypeSourceInfo *RecoveryTSI = nullptr;
9635   ExprResult SubExpr;
9636   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
9637   if (auto *DRE =
9638           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
9639     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
9640         PE, DRE, false, &RecoveryTSI);
9641   else
9642     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
9643 
9644   if (RecoveryTSI) {
9645     return getDerived().RebuildUnaryExprOrTypeTrait(
9646         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
9647   } else if (SubExpr.isInvalid())
9648     return ExprError();
9649 
9650   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
9651     return E;
9652 
9653   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
9654                                                   E->getOperatorLoc(),
9655                                                   E->getKind(),
9656                                                   E->getSourceRange());
9657 }
9658 
9659 template<typename Derived>
9660 ExprResult
9661 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
9662   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9663   if (LHS.isInvalid())
9664     return ExprError();
9665 
9666   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9667   if (RHS.isInvalid())
9668     return ExprError();
9669 
9670 
9671   if (!getDerived().AlwaysRebuild() &&
9672       LHS.get() == E->getLHS() &&
9673       RHS.get() == E->getRHS())
9674     return E;
9675 
9676   return getDerived().RebuildArraySubscriptExpr(
9677       LHS.get(),
9678       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
9679 }
9680 
9681 template <typename Derived>
9682 ExprResult
9683 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9684   ExprResult Base = getDerived().TransformExpr(E->getBase());
9685   if (Base.isInvalid())
9686     return ExprError();
9687 
9688   ExprResult LowerBound;
9689   if (E->getLowerBound()) {
9690     LowerBound = getDerived().TransformExpr(E->getLowerBound());
9691     if (LowerBound.isInvalid())
9692       return ExprError();
9693   }
9694 
9695   ExprResult Length;
9696   if (E->getLength()) {
9697     Length = getDerived().TransformExpr(E->getLength());
9698     if (Length.isInvalid())
9699       return ExprError();
9700   }
9701 
9702   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9703       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9704     return E;
9705 
9706   return getDerived().RebuildOMPArraySectionExpr(
9707       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(), E->getColonLoc(),
9708       Length.get(), E->getRBracketLoc());
9709 }
9710 
9711 template<typename Derived>
9712 ExprResult
9713 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9714   // Transform the callee.
9715   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9716   if (Callee.isInvalid())
9717     return ExprError();
9718 
9719   // Transform arguments.
9720   bool ArgChanged = false;
9721   SmallVector<Expr*, 8> Args;
9722   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9723                                   &ArgChanged))
9724     return ExprError();
9725 
9726   if (!getDerived().AlwaysRebuild() &&
9727       Callee.get() == E->getCallee() &&
9728       !ArgChanged)
9729     return SemaRef.MaybeBindToTemporary(E);
9730 
9731   // FIXME: Wrong source location information for the '('.
9732   SourceLocation FakeLParenLoc
9733     = ((Expr *)Callee.get())->getSourceRange().getBegin();
9734   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9735                                       Args,
9736                                       E->getRParenLoc());
9737 }
9738 
9739 template<typename Derived>
9740 ExprResult
9741 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9742   ExprResult Base = getDerived().TransformExpr(E->getBase());
9743   if (Base.isInvalid())
9744     return ExprError();
9745 
9746   NestedNameSpecifierLoc QualifierLoc;
9747   if (E->hasQualifier()) {
9748     QualifierLoc
9749       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9750 
9751     if (!QualifierLoc)
9752       return ExprError();
9753   }
9754   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9755 
9756   ValueDecl *Member
9757     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9758                                                          E->getMemberDecl()));
9759   if (!Member)
9760     return ExprError();
9761 
9762   NamedDecl *FoundDecl = E->getFoundDecl();
9763   if (FoundDecl == E->getMemberDecl()) {
9764     FoundDecl = Member;
9765   } else {
9766     FoundDecl = cast_or_null<NamedDecl>(
9767                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9768     if (!FoundDecl)
9769       return ExprError();
9770   }
9771 
9772   if (!getDerived().AlwaysRebuild() &&
9773       Base.get() == E->getBase() &&
9774       QualifierLoc == E->getQualifierLoc() &&
9775       Member == E->getMemberDecl() &&
9776       FoundDecl == E->getFoundDecl() &&
9777       !E->hasExplicitTemplateArgs()) {
9778 
9779     // Mark it referenced in the new context regardless.
9780     // FIXME: this is a bit instantiation-specific.
9781     SemaRef.MarkMemberReferenced(E);
9782 
9783     return E;
9784   }
9785 
9786   TemplateArgumentListInfo TransArgs;
9787   if (E->hasExplicitTemplateArgs()) {
9788     TransArgs.setLAngleLoc(E->getLAngleLoc());
9789     TransArgs.setRAngleLoc(E->getRAngleLoc());
9790     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9791                                                 E->getNumTemplateArgs(),
9792                                                 TransArgs))
9793       return ExprError();
9794   }
9795 
9796   // FIXME: Bogus source location for the operator
9797   SourceLocation FakeOperatorLoc =
9798       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9799 
9800   // FIXME: to do this check properly, we will need to preserve the
9801   // first-qualifier-in-scope here, just in case we had a dependent
9802   // base (and therefore couldn't do the check) and a
9803   // nested-name-qualifier (and therefore could do the lookup).
9804   NamedDecl *FirstQualifierInScope = nullptr;
9805   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9806   if (MemberNameInfo.getName()) {
9807     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9808     if (!MemberNameInfo.getName())
9809       return ExprError();
9810   }
9811 
9812   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9813                                         E->isArrow(),
9814                                         QualifierLoc,
9815                                         TemplateKWLoc,
9816                                         MemberNameInfo,
9817                                         Member,
9818                                         FoundDecl,
9819                                         (E->hasExplicitTemplateArgs()
9820                                            ? &TransArgs : nullptr),
9821                                         FirstQualifierInScope);
9822 }
9823 
9824 template<typename Derived>
9825 ExprResult
9826 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9827   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9828   if (LHS.isInvalid())
9829     return ExprError();
9830 
9831   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9832   if (RHS.isInvalid())
9833     return ExprError();
9834 
9835   if (!getDerived().AlwaysRebuild() &&
9836       LHS.get() == E->getLHS() &&
9837       RHS.get() == E->getRHS())
9838     return E;
9839 
9840   Sema::FPContractStateRAII FPContractState(getSema());
9841   getSema().FPFeatures = E->getFPFeatures();
9842 
9843   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9844                                             LHS.get(), RHS.get());
9845 }
9846 
9847 template <typename Derived>
9848 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
9849     CXXRewrittenBinaryOperator *E) {
9850   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
9851 
9852   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
9853   if (LHS.isInvalid())
9854     return ExprError();
9855 
9856   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
9857   if (RHS.isInvalid())
9858     return ExprError();
9859 
9860   if (!getDerived().AlwaysRebuild() &&
9861       LHS.get() == Decomp.LHS &&
9862       RHS.get() == Decomp.RHS)
9863     return E;
9864 
9865   // Extract the already-resolved callee declarations so that we can restrict
9866   // ourselves to using them as the unqualified lookup results when rebuilding.
9867   UnresolvedSet<2> UnqualLookups;
9868   Expr *PossibleBinOps[] = {E->getSemanticForm(),
9869                             const_cast<Expr *>(Decomp.InnerBinOp)};
9870   for (Expr *PossibleBinOp : PossibleBinOps) {
9871     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
9872     if (!Op)
9873       continue;
9874     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
9875     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
9876       continue;
9877 
9878     // Transform the callee in case we built a call to a local extern
9879     // declaration.
9880     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
9881         E->getOperatorLoc(), Callee->getFoundDecl()));
9882     if (!Found)
9883       return ExprError();
9884     UnqualLookups.addDecl(Found);
9885   }
9886 
9887   return getDerived().RebuildCXXRewrittenBinaryOperator(
9888       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
9889 }
9890 
9891 template<typename Derived>
9892 ExprResult
9893 TreeTransform<Derived>::TransformCompoundAssignOperator(
9894                                                       CompoundAssignOperator *E) {
9895   return getDerived().TransformBinaryOperator(E);
9896 }
9897 
9898 template<typename Derived>
9899 ExprResult TreeTransform<Derived>::
9900 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9901   // Just rebuild the common and RHS expressions and see whether we
9902   // get any changes.
9903 
9904   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9905   if (commonExpr.isInvalid())
9906     return ExprError();
9907 
9908   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9909   if (rhs.isInvalid())
9910     return ExprError();
9911 
9912   if (!getDerived().AlwaysRebuild() &&
9913       commonExpr.get() == e->getCommon() &&
9914       rhs.get() == e->getFalseExpr())
9915     return e;
9916 
9917   return getDerived().RebuildConditionalOperator(commonExpr.get(),
9918                                                  e->getQuestionLoc(),
9919                                                  nullptr,
9920                                                  e->getColonLoc(),
9921                                                  rhs.get());
9922 }
9923 
9924 template<typename Derived>
9925 ExprResult
9926 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9927   ExprResult Cond = getDerived().TransformExpr(E->getCond());
9928   if (Cond.isInvalid())
9929     return ExprError();
9930 
9931   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9932   if (LHS.isInvalid())
9933     return ExprError();
9934 
9935   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9936   if (RHS.isInvalid())
9937     return ExprError();
9938 
9939   if (!getDerived().AlwaysRebuild() &&
9940       Cond.get() == E->getCond() &&
9941       LHS.get() == E->getLHS() &&
9942       RHS.get() == E->getRHS())
9943     return E;
9944 
9945   return getDerived().RebuildConditionalOperator(Cond.get(),
9946                                                  E->getQuestionLoc(),
9947                                                  LHS.get(),
9948                                                  E->getColonLoc(),
9949                                                  RHS.get());
9950 }
9951 
9952 template<typename Derived>
9953 ExprResult
9954 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9955   // Implicit casts are eliminated during transformation, since they
9956   // will be recomputed by semantic analysis after transformation.
9957   return getDerived().TransformExpr(E->getSubExprAsWritten());
9958 }
9959 
9960 template<typename Derived>
9961 ExprResult
9962 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9963   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9964   if (!Type)
9965     return ExprError();
9966 
9967   ExprResult SubExpr
9968     = getDerived().TransformExpr(E->getSubExprAsWritten());
9969   if (SubExpr.isInvalid())
9970     return ExprError();
9971 
9972   if (!getDerived().AlwaysRebuild() &&
9973       Type == E->getTypeInfoAsWritten() &&
9974       SubExpr.get() == E->getSubExpr())
9975     return E;
9976 
9977   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9978                                             Type,
9979                                             E->getRParenLoc(),
9980                                             SubExpr.get());
9981 }
9982 
9983 template<typename Derived>
9984 ExprResult
9985 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9986   TypeSourceInfo *OldT = E->getTypeSourceInfo();
9987   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9988   if (!NewT)
9989     return ExprError();
9990 
9991   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9992   if (Init.isInvalid())
9993     return ExprError();
9994 
9995   if (!getDerived().AlwaysRebuild() &&
9996       OldT == NewT &&
9997       Init.get() == E->getInitializer())
9998     return SemaRef.MaybeBindToTemporary(E);
9999 
10000   // Note: the expression type doesn't necessarily match the
10001   // type-as-written, but that's okay, because it should always be
10002   // derivable from the initializer.
10003 
10004   return getDerived().RebuildCompoundLiteralExpr(
10005       E->getLParenLoc(), NewT,
10006       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
10007 }
10008 
10009 template<typename Derived>
10010 ExprResult
10011 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
10012   ExprResult Base = getDerived().TransformExpr(E->getBase());
10013   if (Base.isInvalid())
10014     return ExprError();
10015 
10016   if (!getDerived().AlwaysRebuild() &&
10017       Base.get() == E->getBase())
10018     return E;
10019 
10020   // FIXME: Bad source location
10021   SourceLocation FakeOperatorLoc =
10022       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
10023   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
10024                                                   E->getAccessorLoc(),
10025                                                   E->getAccessor());
10026 }
10027 
10028 template<typename Derived>
10029 ExprResult
10030 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
10031   if (InitListExpr *Syntactic = E->getSyntacticForm())
10032     E = Syntactic;
10033 
10034   bool InitChanged = false;
10035 
10036   EnterExpressionEvaluationContext Context(
10037       getSema(), EnterExpressionEvaluationContext::InitList);
10038 
10039   SmallVector<Expr*, 4> Inits;
10040   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
10041                                   Inits, &InitChanged))
10042     return ExprError();
10043 
10044   if (!getDerived().AlwaysRebuild() && !InitChanged) {
10045     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
10046     // in some cases. We can't reuse it in general, because the syntactic and
10047     // semantic forms are linked, and we can't know that semantic form will
10048     // match even if the syntactic form does.
10049   }
10050 
10051   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
10052                                       E->getRBraceLoc());
10053 }
10054 
10055 template<typename Derived>
10056 ExprResult
10057 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
10058   Designation Desig;
10059 
10060   // transform the initializer value
10061   ExprResult Init = getDerived().TransformExpr(E->getInit());
10062   if (Init.isInvalid())
10063     return ExprError();
10064 
10065   // transform the designators.
10066   SmallVector<Expr*, 4> ArrayExprs;
10067   bool ExprChanged = false;
10068   for (const DesignatedInitExpr::Designator &D : E->designators()) {
10069     if (D.isFieldDesignator()) {
10070       Desig.AddDesignator(Designator::getField(D.getFieldName(),
10071                                                D.getDotLoc(),
10072                                                D.getFieldLoc()));
10073       if (D.getField()) {
10074         FieldDecl *Field = cast_or_null<FieldDecl>(
10075             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
10076         if (Field != D.getField())
10077           // Rebuild the expression when the transformed FieldDecl is
10078           // different to the already assigned FieldDecl.
10079           ExprChanged = true;
10080       } else {
10081         // Ensure that the designator expression is rebuilt when there isn't
10082         // a resolved FieldDecl in the designator as we don't want to assign
10083         // a FieldDecl to a pattern designator that will be instantiated again.
10084         ExprChanged = true;
10085       }
10086       continue;
10087     }
10088 
10089     if (D.isArrayDesignator()) {
10090       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
10091       if (Index.isInvalid())
10092         return ExprError();
10093 
10094       Desig.AddDesignator(
10095           Designator::getArray(Index.get(), D.getLBracketLoc()));
10096 
10097       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
10098       ArrayExprs.push_back(Index.get());
10099       continue;
10100     }
10101 
10102     assert(D.isArrayRangeDesignator() && "New kind of designator?");
10103     ExprResult Start
10104       = getDerived().TransformExpr(E->getArrayRangeStart(D));
10105     if (Start.isInvalid())
10106       return ExprError();
10107 
10108     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
10109     if (End.isInvalid())
10110       return ExprError();
10111 
10112     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
10113                                                   End.get(),
10114                                                   D.getLBracketLoc(),
10115                                                   D.getEllipsisLoc()));
10116 
10117     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
10118                   End.get() != E->getArrayRangeEnd(D);
10119 
10120     ArrayExprs.push_back(Start.get());
10121     ArrayExprs.push_back(End.get());
10122   }
10123 
10124   if (!getDerived().AlwaysRebuild() &&
10125       Init.get() == E->getInit() &&
10126       !ExprChanged)
10127     return E;
10128 
10129   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
10130                                                 E->getEqualOrColonLoc(),
10131                                                 E->usesGNUSyntax(), Init.get());
10132 }
10133 
10134 // Seems that if TransformInitListExpr() only works on the syntactic form of an
10135 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
10136 template<typename Derived>
10137 ExprResult
10138 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
10139     DesignatedInitUpdateExpr *E) {
10140   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
10141                    "initializer");
10142   return ExprError();
10143 }
10144 
10145 template<typename Derived>
10146 ExprResult
10147 TreeTransform<Derived>::TransformNoInitExpr(
10148     NoInitExpr *E) {
10149   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
10150   return ExprError();
10151 }
10152 
10153 template<typename Derived>
10154 ExprResult
10155 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
10156   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
10157   return ExprError();
10158 }
10159 
10160 template<typename Derived>
10161 ExprResult
10162 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
10163   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
10164   return ExprError();
10165 }
10166 
10167 template<typename Derived>
10168 ExprResult
10169 TreeTransform<Derived>::TransformImplicitValueInitExpr(
10170                                                      ImplicitValueInitExpr *E) {
10171   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
10172 
10173   // FIXME: Will we ever have proper type location here? Will we actually
10174   // need to transform the type?
10175   QualType T = getDerived().TransformType(E->getType());
10176   if (T.isNull())
10177     return ExprError();
10178 
10179   if (!getDerived().AlwaysRebuild() &&
10180       T == E->getType())
10181     return E;
10182 
10183   return getDerived().RebuildImplicitValueInitExpr(T);
10184 }
10185 
10186 template<typename Derived>
10187 ExprResult
10188 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
10189   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
10190   if (!TInfo)
10191     return ExprError();
10192 
10193   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10194   if (SubExpr.isInvalid())
10195     return ExprError();
10196 
10197   if (!getDerived().AlwaysRebuild() &&
10198       TInfo == E->getWrittenTypeInfo() &&
10199       SubExpr.get() == E->getSubExpr())
10200     return E;
10201 
10202   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
10203                                        TInfo, E->getRParenLoc());
10204 }
10205 
10206 template<typename Derived>
10207 ExprResult
10208 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
10209   bool ArgumentChanged = false;
10210   SmallVector<Expr*, 4> Inits;
10211   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
10212                      &ArgumentChanged))
10213     return ExprError();
10214 
10215   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
10216                                            Inits,
10217                                            E->getRParenLoc());
10218 }
10219 
10220 /// Transform an address-of-label expression.
10221 ///
10222 /// By default, the transformation of an address-of-label expression always
10223 /// rebuilds the expression, so that the label identifier can be resolved to
10224 /// the corresponding label statement by semantic analysis.
10225 template<typename Derived>
10226 ExprResult
10227 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
10228   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
10229                                         E->getLabel());
10230   if (!LD)
10231     return ExprError();
10232 
10233   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
10234                                            cast<LabelDecl>(LD));
10235 }
10236 
10237 template<typename Derived>
10238 ExprResult
10239 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
10240   SemaRef.ActOnStartStmtExpr();
10241   StmtResult SubStmt
10242     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
10243   if (SubStmt.isInvalid()) {
10244     SemaRef.ActOnStmtExprError();
10245     return ExprError();
10246   }
10247 
10248   if (!getDerived().AlwaysRebuild() &&
10249       SubStmt.get() == E->getSubStmt()) {
10250     // Calling this an 'error' is unintuitive, but it does the right thing.
10251     SemaRef.ActOnStmtExprError();
10252     return SemaRef.MaybeBindToTemporary(E);
10253   }
10254 
10255   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
10256                                       SubStmt.get(),
10257                                       E->getRParenLoc());
10258 }
10259 
10260 template<typename Derived>
10261 ExprResult
10262 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
10263   ExprResult Cond = getDerived().TransformExpr(E->getCond());
10264   if (Cond.isInvalid())
10265     return ExprError();
10266 
10267   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10268   if (LHS.isInvalid())
10269     return ExprError();
10270 
10271   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10272   if (RHS.isInvalid())
10273     return ExprError();
10274 
10275   if (!getDerived().AlwaysRebuild() &&
10276       Cond.get() == E->getCond() &&
10277       LHS.get() == E->getLHS() &&
10278       RHS.get() == E->getRHS())
10279     return E;
10280 
10281   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
10282                                         Cond.get(), LHS.get(), RHS.get(),
10283                                         E->getRParenLoc());
10284 }
10285 
10286 template<typename Derived>
10287 ExprResult
10288 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
10289   return E;
10290 }
10291 
10292 template<typename Derived>
10293 ExprResult
10294 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10295   switch (E->getOperator()) {
10296   case OO_New:
10297   case OO_Delete:
10298   case OO_Array_New:
10299   case OO_Array_Delete:
10300     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
10301 
10302   case OO_Call: {
10303     // This is a call to an object's operator().
10304     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
10305 
10306     // Transform the object itself.
10307     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
10308     if (Object.isInvalid())
10309       return ExprError();
10310 
10311     // FIXME: Poor location information
10312     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
10313         static_cast<Expr *>(Object.get())->getEndLoc());
10314 
10315     // Transform the call arguments.
10316     SmallVector<Expr*, 8> Args;
10317     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
10318                                     Args))
10319       return ExprError();
10320 
10321     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
10322                                         E->getEndLoc());
10323   }
10324 
10325 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10326   case OO_##Name:
10327 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
10328 #include "clang/Basic/OperatorKinds.def"
10329   case OO_Subscript:
10330     // Handled below.
10331     break;
10332 
10333   case OO_Conditional:
10334     llvm_unreachable("conditional operator is not actually overloadable");
10335 
10336   case OO_None:
10337   case NUM_OVERLOADED_OPERATORS:
10338     llvm_unreachable("not an overloaded operator?");
10339   }
10340 
10341   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10342   if (Callee.isInvalid())
10343     return ExprError();
10344 
10345   ExprResult First;
10346   if (E->getOperator() == OO_Amp)
10347     First = getDerived().TransformAddressOfOperand(E->getArg(0));
10348   else
10349     First = getDerived().TransformExpr(E->getArg(0));
10350   if (First.isInvalid())
10351     return ExprError();
10352 
10353   ExprResult Second;
10354   if (E->getNumArgs() == 2) {
10355     Second = getDerived().TransformExpr(E->getArg(1));
10356     if (Second.isInvalid())
10357       return ExprError();
10358   }
10359 
10360   if (!getDerived().AlwaysRebuild() &&
10361       Callee.get() == E->getCallee() &&
10362       First.get() == E->getArg(0) &&
10363       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
10364     return SemaRef.MaybeBindToTemporary(E);
10365 
10366   Sema::FPContractStateRAII FPContractState(getSema());
10367   getSema().FPFeatures = E->getFPFeatures();
10368 
10369   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
10370                                                  E->getOperatorLoc(),
10371                                                  Callee.get(),
10372                                                  First.get(),
10373                                                  Second.get());
10374 }
10375 
10376 template<typename Derived>
10377 ExprResult
10378 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
10379   return getDerived().TransformCallExpr(E);
10380 }
10381 
10382 template <typename Derived>
10383 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
10384   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
10385                          getSema().CurContext != E->getParentContext();
10386 
10387   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
10388     return E;
10389 
10390   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
10391                                            E->getEndLoc(),
10392                                            getSema().CurContext);
10393 }
10394 
10395 template<typename Derived>
10396 ExprResult
10397 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
10398   // Transform the callee.
10399   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10400   if (Callee.isInvalid())
10401     return ExprError();
10402 
10403   // Transform exec config.
10404   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
10405   if (EC.isInvalid())
10406     return ExprError();
10407 
10408   // Transform arguments.
10409   bool ArgChanged = false;
10410   SmallVector<Expr*, 8> Args;
10411   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10412                                   &ArgChanged))
10413     return ExprError();
10414 
10415   if (!getDerived().AlwaysRebuild() &&
10416       Callee.get() == E->getCallee() &&
10417       !ArgChanged)
10418     return SemaRef.MaybeBindToTemporary(E);
10419 
10420   // FIXME: Wrong source location information for the '('.
10421   SourceLocation FakeLParenLoc
10422     = ((Expr *)Callee.get())->getSourceRange().getBegin();
10423   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10424                                       Args,
10425                                       E->getRParenLoc(), EC.get());
10426 }
10427 
10428 template<typename Derived>
10429 ExprResult
10430 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
10431   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10432   if (!Type)
10433     return ExprError();
10434 
10435   ExprResult SubExpr
10436     = getDerived().TransformExpr(E->getSubExprAsWritten());
10437   if (SubExpr.isInvalid())
10438     return ExprError();
10439 
10440   if (!getDerived().AlwaysRebuild() &&
10441       Type == E->getTypeInfoAsWritten() &&
10442       SubExpr.get() == E->getSubExpr())
10443     return E;
10444   return getDerived().RebuildCXXNamedCastExpr(
10445       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
10446       Type, E->getAngleBrackets().getEnd(),
10447       // FIXME. this should be '(' location
10448       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
10449 }
10450 
10451 template<typename Derived>
10452 ExprResult
10453 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
10454   TypeSourceInfo *TSI =
10455       getDerived().TransformType(BCE->getTypeInfoAsWritten());
10456   if (!TSI)
10457     return ExprError();
10458 
10459   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
10460   if (Sub.isInvalid())
10461     return ExprError();
10462 
10463   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
10464                                                 Sub.get(), BCE->getEndLoc());
10465 }
10466 
10467 template<typename Derived>
10468 ExprResult
10469 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
10470   return getDerived().TransformCXXNamedCastExpr(E);
10471 }
10472 
10473 template<typename Derived>
10474 ExprResult
10475 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
10476   return getDerived().TransformCXXNamedCastExpr(E);
10477 }
10478 
10479 template<typename Derived>
10480 ExprResult
10481 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
10482                                                       CXXReinterpretCastExpr *E) {
10483   return getDerived().TransformCXXNamedCastExpr(E);
10484 }
10485 
10486 template<typename Derived>
10487 ExprResult
10488 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
10489   return getDerived().TransformCXXNamedCastExpr(E);
10490 }
10491 
10492 template<typename Derived>
10493 ExprResult
10494 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
10495                                                      CXXFunctionalCastExpr *E) {
10496   TypeSourceInfo *Type =
10497       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
10498   if (!Type)
10499     return ExprError();
10500 
10501   ExprResult SubExpr
10502     = getDerived().TransformExpr(E->getSubExprAsWritten());
10503   if (SubExpr.isInvalid())
10504     return ExprError();
10505 
10506   if (!getDerived().AlwaysRebuild() &&
10507       Type == E->getTypeInfoAsWritten() &&
10508       SubExpr.get() == E->getSubExpr())
10509     return E;
10510 
10511   return getDerived().RebuildCXXFunctionalCastExpr(Type,
10512                                                    E->getLParenLoc(),
10513                                                    SubExpr.get(),
10514                                                    E->getRParenLoc(),
10515                                                    E->isListInitialization());
10516 }
10517 
10518 template<typename Derived>
10519 ExprResult
10520 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
10521   if (E->isTypeOperand()) {
10522     TypeSourceInfo *TInfo
10523       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10524     if (!TInfo)
10525       return ExprError();
10526 
10527     if (!getDerived().AlwaysRebuild() &&
10528         TInfo == E->getTypeOperandSourceInfo())
10529       return E;
10530 
10531     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10532                                              TInfo, E->getEndLoc());
10533   }
10534 
10535   // We don't know whether the subexpression is potentially evaluated until
10536   // after we perform semantic analysis.  We speculatively assume it is
10537   // unevaluated; it will get fixed later if the subexpression is in fact
10538   // potentially evaluated.
10539   EnterExpressionEvaluationContext Unevaluated(
10540       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10541       Sema::ReuseLambdaContextDecl);
10542 
10543   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10544   if (SubExpr.isInvalid())
10545     return ExprError();
10546 
10547   if (!getDerived().AlwaysRebuild() &&
10548       SubExpr.get() == E->getExprOperand())
10549     return E;
10550 
10551   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10552                                            SubExpr.get(), E->getEndLoc());
10553 }
10554 
10555 template<typename Derived>
10556 ExprResult
10557 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
10558   if (E->isTypeOperand()) {
10559     TypeSourceInfo *TInfo
10560       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10561     if (!TInfo)
10562       return ExprError();
10563 
10564     if (!getDerived().AlwaysRebuild() &&
10565         TInfo == E->getTypeOperandSourceInfo())
10566       return E;
10567 
10568     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10569                                              TInfo, E->getEndLoc());
10570   }
10571 
10572   EnterExpressionEvaluationContext Unevaluated(
10573       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10574 
10575   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10576   if (SubExpr.isInvalid())
10577     return ExprError();
10578 
10579   if (!getDerived().AlwaysRebuild() &&
10580       SubExpr.get() == E->getExprOperand())
10581     return E;
10582 
10583   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10584                                            SubExpr.get(), E->getEndLoc());
10585 }
10586 
10587 template<typename Derived>
10588 ExprResult
10589 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
10590   return E;
10591 }
10592 
10593 template<typename Derived>
10594 ExprResult
10595 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
10596                                                      CXXNullPtrLiteralExpr *E) {
10597   return E;
10598 }
10599 
10600 template<typename Derived>
10601 ExprResult
10602 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
10603   QualType T = getSema().getCurrentThisType();
10604 
10605   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
10606     // Mark it referenced in the new context regardless.
10607     // FIXME: this is a bit instantiation-specific.
10608     getSema().MarkThisReferenced(E);
10609     return E;
10610   }
10611 
10612   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
10613 }
10614 
10615 template<typename Derived>
10616 ExprResult
10617 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
10618   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10619   if (SubExpr.isInvalid())
10620     return ExprError();
10621 
10622   if (!getDerived().AlwaysRebuild() &&
10623       SubExpr.get() == E->getSubExpr())
10624     return E;
10625 
10626   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
10627                                           E->isThrownVariableInScope());
10628 }
10629 
10630 template<typename Derived>
10631 ExprResult
10632 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10633   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
10634       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
10635   if (!Param)
10636     return ExprError();
10637 
10638   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
10639       E->getUsedContext() == SemaRef.CurContext)
10640     return E;
10641 
10642   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
10643 }
10644 
10645 template<typename Derived>
10646 ExprResult
10647 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
10648   FieldDecl *Field = cast_or_null<FieldDecl>(
10649       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
10650   if (!Field)
10651     return ExprError();
10652 
10653   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
10654       E->getUsedContext() == SemaRef.CurContext)
10655     return E;
10656 
10657   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
10658 }
10659 
10660 template<typename Derived>
10661 ExprResult
10662 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
10663                                                     CXXScalarValueInitExpr *E) {
10664   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
10665   if (!T)
10666     return ExprError();
10667 
10668   if (!getDerived().AlwaysRebuild() &&
10669       T == E->getTypeSourceInfo())
10670     return E;
10671 
10672   return getDerived().RebuildCXXScalarValueInitExpr(T,
10673                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
10674                                                     E->getRParenLoc());
10675 }
10676 
10677 template<typename Derived>
10678 ExprResult
10679 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
10680   // Transform the type that we're allocating
10681   TypeSourceInfo *AllocTypeInfo =
10682       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
10683   if (!AllocTypeInfo)
10684     return ExprError();
10685 
10686   // Transform the size of the array we're allocating (if any).
10687   Optional<Expr *> ArraySize;
10688   if (Optional<Expr *> OldArraySize = E->getArraySize()) {
10689     ExprResult NewArraySize;
10690     if (*OldArraySize) {
10691       NewArraySize = getDerived().TransformExpr(*OldArraySize);
10692       if (NewArraySize.isInvalid())
10693         return ExprError();
10694     }
10695     ArraySize = NewArraySize.get();
10696   }
10697 
10698   // Transform the placement arguments (if any).
10699   bool ArgumentChanged = false;
10700   SmallVector<Expr*, 8> PlacementArgs;
10701   if (getDerived().TransformExprs(E->getPlacementArgs(),
10702                                   E->getNumPlacementArgs(), true,
10703                                   PlacementArgs, &ArgumentChanged))
10704     return ExprError();
10705 
10706   // Transform the initializer (if any).
10707   Expr *OldInit = E->getInitializer();
10708   ExprResult NewInit;
10709   if (OldInit)
10710     NewInit = getDerived().TransformInitializer(OldInit, true);
10711   if (NewInit.isInvalid())
10712     return ExprError();
10713 
10714   // Transform new operator and delete operator.
10715   FunctionDecl *OperatorNew = nullptr;
10716   if (E->getOperatorNew()) {
10717     OperatorNew = cast_or_null<FunctionDecl>(
10718         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
10719     if (!OperatorNew)
10720       return ExprError();
10721   }
10722 
10723   FunctionDecl *OperatorDelete = nullptr;
10724   if (E->getOperatorDelete()) {
10725     OperatorDelete = cast_or_null<FunctionDecl>(
10726         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10727     if (!OperatorDelete)
10728       return ExprError();
10729   }
10730 
10731   if (!getDerived().AlwaysRebuild() &&
10732       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
10733       ArraySize == E->getArraySize() &&
10734       NewInit.get() == OldInit &&
10735       OperatorNew == E->getOperatorNew() &&
10736       OperatorDelete == E->getOperatorDelete() &&
10737       !ArgumentChanged) {
10738     // Mark any declarations we need as referenced.
10739     // FIXME: instantiation-specific.
10740     if (OperatorNew)
10741       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
10742     if (OperatorDelete)
10743       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10744 
10745     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
10746       QualType ElementType
10747         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
10748       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
10749         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10750         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10751           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
10752         }
10753       }
10754     }
10755 
10756     return E;
10757   }
10758 
10759   QualType AllocType = AllocTypeInfo->getType();
10760   if (!ArraySize) {
10761     // If no array size was specified, but the new expression was
10762     // instantiated with an array type (e.g., "new T" where T is
10763     // instantiated with "int[4]"), extract the outer bound from the
10764     // array type as our array size. We do this with constant and
10765     // dependently-sized array types.
10766     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10767     if (!ArrayT) {
10768       // Do nothing
10769     } else if (const ConstantArrayType *ConsArrayT
10770                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
10771       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10772                                          SemaRef.Context.getSizeType(),
10773                                          /*FIXME:*/ E->getBeginLoc());
10774       AllocType = ConsArrayT->getElementType();
10775     } else if (const DependentSizedArrayType *DepArrayT
10776                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10777       if (DepArrayT->getSizeExpr()) {
10778         ArraySize = DepArrayT->getSizeExpr();
10779         AllocType = DepArrayT->getElementType();
10780       }
10781     }
10782   }
10783 
10784   return getDerived().RebuildCXXNewExpr(
10785       E->getBeginLoc(), E->isGlobalNew(),
10786       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
10787       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
10788       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
10789 }
10790 
10791 template<typename Derived>
10792 ExprResult
10793 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10794   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10795   if (Operand.isInvalid())
10796     return ExprError();
10797 
10798   // Transform the delete operator, if known.
10799   FunctionDecl *OperatorDelete = nullptr;
10800   if (E->getOperatorDelete()) {
10801     OperatorDelete = cast_or_null<FunctionDecl>(
10802         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10803     if (!OperatorDelete)
10804       return ExprError();
10805   }
10806 
10807   if (!getDerived().AlwaysRebuild() &&
10808       Operand.get() == E->getArgument() &&
10809       OperatorDelete == E->getOperatorDelete()) {
10810     // Mark any declarations we need as referenced.
10811     // FIXME: instantiation-specific.
10812     if (OperatorDelete)
10813       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10814 
10815     if (!E->getArgument()->isTypeDependent()) {
10816       QualType Destroyed = SemaRef.Context.getBaseElementType(
10817                                                          E->getDestroyedType());
10818       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10819         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10820         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
10821                                        SemaRef.LookupDestructor(Record));
10822       }
10823     }
10824 
10825     return E;
10826   }
10827 
10828   return getDerived().RebuildCXXDeleteExpr(
10829       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
10830 }
10831 
10832 template<typename Derived>
10833 ExprResult
10834 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10835                                                      CXXPseudoDestructorExpr *E) {
10836   ExprResult Base = getDerived().TransformExpr(E->getBase());
10837   if (Base.isInvalid())
10838     return ExprError();
10839 
10840   ParsedType ObjectTypePtr;
10841   bool MayBePseudoDestructor = false;
10842   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10843                                               E->getOperatorLoc(),
10844                                         E->isArrow()? tok::arrow : tok::period,
10845                                               ObjectTypePtr,
10846                                               MayBePseudoDestructor);
10847   if (Base.isInvalid())
10848     return ExprError();
10849 
10850   QualType ObjectType = ObjectTypePtr.get();
10851   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10852   if (QualifierLoc) {
10853     QualifierLoc
10854       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10855     if (!QualifierLoc)
10856       return ExprError();
10857   }
10858   CXXScopeSpec SS;
10859   SS.Adopt(QualifierLoc);
10860 
10861   PseudoDestructorTypeStorage Destroyed;
10862   if (E->getDestroyedTypeInfo()) {
10863     TypeSourceInfo *DestroyedTypeInfo
10864       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10865                                                 ObjectType, nullptr, SS);
10866     if (!DestroyedTypeInfo)
10867       return ExprError();
10868     Destroyed = DestroyedTypeInfo;
10869   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10870     // We aren't likely to be able to resolve the identifier down to a type
10871     // now anyway, so just retain the identifier.
10872     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10873                                             E->getDestroyedTypeLoc());
10874   } else {
10875     // Look for a destructor known with the given name.
10876     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10877                                               *E->getDestroyedTypeIdentifier(),
10878                                                 E->getDestroyedTypeLoc(),
10879                                                 /*Scope=*/nullptr,
10880                                                 SS, ObjectTypePtr,
10881                                                 false);
10882     if (!T)
10883       return ExprError();
10884 
10885     Destroyed
10886       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10887                                                  E->getDestroyedTypeLoc());
10888   }
10889 
10890   TypeSourceInfo *ScopeTypeInfo = nullptr;
10891   if (E->getScopeTypeInfo()) {
10892     CXXScopeSpec EmptySS;
10893     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10894                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10895     if (!ScopeTypeInfo)
10896       return ExprError();
10897   }
10898 
10899   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10900                                                      E->getOperatorLoc(),
10901                                                      E->isArrow(),
10902                                                      SS,
10903                                                      ScopeTypeInfo,
10904                                                      E->getColonColonLoc(),
10905                                                      E->getTildeLoc(),
10906                                                      Destroyed);
10907 }
10908 
10909 template <typename Derived>
10910 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10911                                                         bool RequiresADL,
10912                                                         LookupResult &R) {
10913   // Transform all the decls.
10914   bool AllEmptyPacks = true;
10915   for (auto *OldD : Old->decls()) {
10916     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10917     if (!InstD) {
10918       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10919       // This can happen because of dependent hiding.
10920       if (isa<UsingShadowDecl>(OldD))
10921         continue;
10922       else {
10923         R.clear();
10924         return true;
10925       }
10926     }
10927 
10928     // Expand using pack declarations.
10929     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10930     ArrayRef<NamedDecl*> Decls = SingleDecl;
10931     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10932       Decls = UPD->expansions();
10933 
10934     // Expand using declarations.
10935     for (auto *D : Decls) {
10936       if (auto *UD = dyn_cast<UsingDecl>(D)) {
10937         for (auto *SD : UD->shadows())
10938           R.addDecl(SD);
10939       } else {
10940         R.addDecl(D);
10941       }
10942     }
10943 
10944     AllEmptyPacks &= Decls.empty();
10945   };
10946 
10947   // C++ [temp.res]/8.4.2:
10948   //   The program is ill-formed, no diagnostic required, if [...] lookup for
10949   //   a name in the template definition found a using-declaration, but the
10950   //   lookup in the corresponding scope in the instantiation odoes not find
10951   //   any declarations because the using-declaration was a pack expansion and
10952   //   the corresponding pack is empty
10953   if (AllEmptyPacks && !RequiresADL) {
10954     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10955         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
10956     return true;
10957   }
10958 
10959   // Resolve a kind, but don't do any further analysis.  If it's
10960   // ambiguous, the callee needs to deal with it.
10961   R.resolveKind();
10962   return false;
10963 }
10964 
10965 template<typename Derived>
10966 ExprResult
10967 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10968                                                   UnresolvedLookupExpr *Old) {
10969   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10970                  Sema::LookupOrdinaryName);
10971 
10972   // Transform the declaration set.
10973   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10974     return ExprError();
10975 
10976   // Rebuild the nested-name qualifier, if present.
10977   CXXScopeSpec SS;
10978   if (Old->getQualifierLoc()) {
10979     NestedNameSpecifierLoc QualifierLoc
10980       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10981     if (!QualifierLoc)
10982       return ExprError();
10983 
10984     SS.Adopt(QualifierLoc);
10985   }
10986 
10987   if (Old->getNamingClass()) {
10988     CXXRecordDecl *NamingClass
10989       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10990                                                             Old->getNameLoc(),
10991                                                         Old->getNamingClass()));
10992     if (!NamingClass) {
10993       R.clear();
10994       return ExprError();
10995     }
10996 
10997     R.setNamingClass(NamingClass);
10998   }
10999 
11000   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11001 
11002   // If we have neither explicit template arguments, nor the template keyword,
11003   // it's a normal declaration name or member reference.
11004   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
11005     NamedDecl *D = R.getAsSingle<NamedDecl>();
11006     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
11007     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
11008     // give a good diagnostic.
11009     if (D && D->isCXXInstanceMember()) {
11010       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
11011                                                      /*TemplateArgs=*/nullptr,
11012                                                      /*Scope=*/nullptr);
11013     }
11014 
11015     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
11016   }
11017 
11018   // If we have template arguments, rebuild them, then rebuild the
11019   // templateid expression.
11020   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
11021   if (Old->hasExplicitTemplateArgs() &&
11022       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11023                                               Old->getNumTemplateArgs(),
11024                                               TransArgs)) {
11025     R.clear();
11026     return ExprError();
11027   }
11028 
11029   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
11030                                             Old->requiresADL(), &TransArgs);
11031 }
11032 
11033 template<typename Derived>
11034 ExprResult
11035 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
11036   bool ArgChanged = false;
11037   SmallVector<TypeSourceInfo *, 4> Args;
11038   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
11039     TypeSourceInfo *From = E->getArg(I);
11040     TypeLoc FromTL = From->getTypeLoc();
11041     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
11042       TypeLocBuilder TLB;
11043       TLB.reserve(FromTL.getFullDataSize());
11044       QualType To = getDerived().TransformType(TLB, FromTL);
11045       if (To.isNull())
11046         return ExprError();
11047 
11048       if (To == From->getType())
11049         Args.push_back(From);
11050       else {
11051         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11052         ArgChanged = true;
11053       }
11054       continue;
11055     }
11056 
11057     ArgChanged = true;
11058 
11059     // We have a pack expansion. Instantiate it.
11060     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
11061     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
11062     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11063     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
11064 
11065     // Determine whether the set of unexpanded parameter packs can and should
11066     // be expanded.
11067     bool Expand = true;
11068     bool RetainExpansion = false;
11069     Optional<unsigned> OrigNumExpansions =
11070         ExpansionTL.getTypePtr()->getNumExpansions();
11071     Optional<unsigned> NumExpansions = OrigNumExpansions;
11072     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
11073                                              PatternTL.getSourceRange(),
11074                                              Unexpanded,
11075                                              Expand, RetainExpansion,
11076                                              NumExpansions))
11077       return ExprError();
11078 
11079     if (!Expand) {
11080       // The transform has determined that we should perform a simple
11081       // transformation on the pack expansion, producing another pack
11082       // expansion.
11083       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11084 
11085       TypeLocBuilder TLB;
11086       TLB.reserve(From->getTypeLoc().getFullDataSize());
11087 
11088       QualType To = getDerived().TransformType(TLB, PatternTL);
11089       if (To.isNull())
11090         return ExprError();
11091 
11092       To = getDerived().RebuildPackExpansionType(To,
11093                                                  PatternTL.getSourceRange(),
11094                                                  ExpansionTL.getEllipsisLoc(),
11095                                                  NumExpansions);
11096       if (To.isNull())
11097         return ExprError();
11098 
11099       PackExpansionTypeLoc ToExpansionTL
11100         = TLB.push<PackExpansionTypeLoc>(To);
11101       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11102       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11103       continue;
11104     }
11105 
11106     // Expand the pack expansion by substituting for each argument in the
11107     // pack(s).
11108     for (unsigned I = 0; I != *NumExpansions; ++I) {
11109       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
11110       TypeLocBuilder TLB;
11111       TLB.reserve(PatternTL.getFullDataSize());
11112       QualType To = getDerived().TransformType(TLB, PatternTL);
11113       if (To.isNull())
11114         return ExprError();
11115 
11116       if (To->containsUnexpandedParameterPack()) {
11117         To = getDerived().RebuildPackExpansionType(To,
11118                                                    PatternTL.getSourceRange(),
11119                                                    ExpansionTL.getEllipsisLoc(),
11120                                                    NumExpansions);
11121         if (To.isNull())
11122           return ExprError();
11123 
11124         PackExpansionTypeLoc ToExpansionTL
11125           = TLB.push<PackExpansionTypeLoc>(To);
11126         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11127       }
11128 
11129       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11130     }
11131 
11132     if (!RetainExpansion)
11133       continue;
11134 
11135     // If we're supposed to retain a pack expansion, do so by temporarily
11136     // forgetting the partially-substituted parameter pack.
11137     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11138 
11139     TypeLocBuilder TLB;
11140     TLB.reserve(From->getTypeLoc().getFullDataSize());
11141 
11142     QualType To = getDerived().TransformType(TLB, PatternTL);
11143     if (To.isNull())
11144       return ExprError();
11145 
11146     To = getDerived().RebuildPackExpansionType(To,
11147                                                PatternTL.getSourceRange(),
11148                                                ExpansionTL.getEllipsisLoc(),
11149                                                NumExpansions);
11150     if (To.isNull())
11151       return ExprError();
11152 
11153     PackExpansionTypeLoc ToExpansionTL
11154       = TLB.push<PackExpansionTypeLoc>(To);
11155     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11156     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11157   }
11158 
11159   if (!getDerived().AlwaysRebuild() && !ArgChanged)
11160     return E;
11161 
11162   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
11163                                        E->getEndLoc());
11164 }
11165 
11166 template<typename Derived>
11167 ExprResult
11168 TreeTransform<Derived>::TransformConceptSpecializationExpr(
11169                                                  ConceptSpecializationExpr *E) {
11170   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
11171   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
11172   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11173                                               Old->NumTemplateArgs, TransArgs))
11174     return ExprError();
11175 
11176   return getDerived().RebuildConceptSpecializationExpr(
11177       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
11178       E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
11179       &TransArgs);
11180 }
11181 
11182 
11183 template<typename Derived>
11184 ExprResult
11185 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
11186   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
11187   if (!T)
11188     return ExprError();
11189 
11190   if (!getDerived().AlwaysRebuild() &&
11191       T == E->getQueriedTypeSourceInfo())
11192     return E;
11193 
11194   ExprResult SubExpr;
11195   {
11196     EnterExpressionEvaluationContext Unevaluated(
11197         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11198     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
11199     if (SubExpr.isInvalid())
11200       return ExprError();
11201 
11202     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
11203       return E;
11204   }
11205 
11206   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
11207                                             SubExpr.get(), E->getEndLoc());
11208 }
11209 
11210 template<typename Derived>
11211 ExprResult
11212 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
11213   ExprResult SubExpr;
11214   {
11215     EnterExpressionEvaluationContext Unevaluated(
11216         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11217     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
11218     if (SubExpr.isInvalid())
11219       return ExprError();
11220 
11221     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
11222       return E;
11223   }
11224 
11225   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
11226                                              SubExpr.get(), E->getEndLoc());
11227 }
11228 
11229 template <typename Derived>
11230 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
11231     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
11232     TypeSourceInfo **RecoveryTSI) {
11233   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
11234       DRE, AddrTaken, RecoveryTSI);
11235 
11236   // Propagate both errors and recovered types, which return ExprEmpty.
11237   if (!NewDRE.isUsable())
11238     return NewDRE;
11239 
11240   // We got an expr, wrap it up in parens.
11241   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
11242     return PE;
11243   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
11244                                        PE->getRParen());
11245 }
11246 
11247 template <typename Derived>
11248 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11249     DependentScopeDeclRefExpr *E) {
11250   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
11251                                             nullptr);
11252 }
11253 
11254 template<typename Derived>
11255 ExprResult
11256 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11257                                                DependentScopeDeclRefExpr *E,
11258                                                bool IsAddressOfOperand,
11259                                                TypeSourceInfo **RecoveryTSI) {
11260   assert(E->getQualifierLoc());
11261   NestedNameSpecifierLoc QualifierLoc
11262   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11263   if (!QualifierLoc)
11264     return ExprError();
11265   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11266 
11267   // TODO: If this is a conversion-function-id, verify that the
11268   // destination type name (if present) resolves the same way after
11269   // instantiation as it did in the local scope.
11270 
11271   DeclarationNameInfo NameInfo
11272     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
11273   if (!NameInfo.getName())
11274     return ExprError();
11275 
11276   if (!E->hasExplicitTemplateArgs()) {
11277     if (!getDerived().AlwaysRebuild() &&
11278         QualifierLoc == E->getQualifierLoc() &&
11279         // Note: it is sufficient to compare the Name component of NameInfo:
11280         // if name has not changed, DNLoc has not changed either.
11281         NameInfo.getName() == E->getDeclName())
11282       return E;
11283 
11284     return getDerived().RebuildDependentScopeDeclRefExpr(
11285         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
11286         IsAddressOfOperand, RecoveryTSI);
11287   }
11288 
11289   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11290   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11291                                               E->getNumTemplateArgs(),
11292                                               TransArgs))
11293     return ExprError();
11294 
11295   return getDerived().RebuildDependentScopeDeclRefExpr(
11296       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
11297       RecoveryTSI);
11298 }
11299 
11300 template<typename Derived>
11301 ExprResult
11302 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
11303   // CXXConstructExprs other than for list-initialization and
11304   // CXXTemporaryObjectExpr are always implicit, so when we have
11305   // a 1-argument construction we just transform that argument.
11306   if ((E->getNumArgs() == 1 ||
11307        (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
11308       (!getDerived().DropCallArgument(E->getArg(0))) &&
11309       !E->isListInitialization())
11310     return getDerived().TransformExpr(E->getArg(0));
11311 
11312   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
11313 
11314   QualType T = getDerived().TransformType(E->getType());
11315   if (T.isNull())
11316     return ExprError();
11317 
11318   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11319       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11320   if (!Constructor)
11321     return ExprError();
11322 
11323   bool ArgumentChanged = false;
11324   SmallVector<Expr*, 8> Args;
11325   {
11326     EnterExpressionEvaluationContext Context(
11327         getSema(), EnterExpressionEvaluationContext::InitList,
11328         E->isListInitialization());
11329     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11330                                     &ArgumentChanged))
11331       return ExprError();
11332   }
11333 
11334   if (!getDerived().AlwaysRebuild() &&
11335       T == E->getType() &&
11336       Constructor == E->getConstructor() &&
11337       !ArgumentChanged) {
11338     // Mark the constructor as referenced.
11339     // FIXME: Instantiation-specific
11340     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11341     return E;
11342   }
11343 
11344   return getDerived().RebuildCXXConstructExpr(
11345       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
11346       E->hadMultipleCandidates(), E->isListInitialization(),
11347       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
11348       E->getConstructionKind(), E->getParenOrBraceRange());
11349 }
11350 
11351 template<typename Derived>
11352 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
11353     CXXInheritedCtorInitExpr *E) {
11354   QualType T = getDerived().TransformType(E->getType());
11355   if (T.isNull())
11356     return ExprError();
11357 
11358   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11359       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11360   if (!Constructor)
11361     return ExprError();
11362 
11363   if (!getDerived().AlwaysRebuild() &&
11364       T == E->getType() &&
11365       Constructor == E->getConstructor()) {
11366     // Mark the constructor as referenced.
11367     // FIXME: Instantiation-specific
11368     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11369     return E;
11370   }
11371 
11372   return getDerived().RebuildCXXInheritedCtorInitExpr(
11373       T, E->getLocation(), Constructor,
11374       E->constructsVBase(), E->inheritedFromVBase());
11375 }
11376 
11377 /// Transform a C++ temporary-binding expression.
11378 ///
11379 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
11380 /// transform the subexpression and return that.
11381 template<typename Derived>
11382 ExprResult
11383 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11384   return getDerived().TransformExpr(E->getSubExpr());
11385 }
11386 
11387 /// Transform a C++ expression that contains cleanups that should
11388 /// be run after the expression is evaluated.
11389 ///
11390 /// Since ExprWithCleanups nodes are implicitly generated, we
11391 /// just transform the subexpression and return that.
11392 template<typename Derived>
11393 ExprResult
11394 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
11395   return getDerived().TransformExpr(E->getSubExpr());
11396 }
11397 
11398 template<typename Derived>
11399 ExprResult
11400 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
11401                                                     CXXTemporaryObjectExpr *E) {
11402   TypeSourceInfo *T =
11403       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11404   if (!T)
11405     return ExprError();
11406 
11407   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11408       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11409   if (!Constructor)
11410     return ExprError();
11411 
11412   bool ArgumentChanged = false;
11413   SmallVector<Expr*, 8> Args;
11414   Args.reserve(E->getNumArgs());
11415   {
11416     EnterExpressionEvaluationContext Context(
11417         getSema(), EnterExpressionEvaluationContext::InitList,
11418         E->isListInitialization());
11419     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11420                        &ArgumentChanged))
11421       return ExprError();
11422   }
11423 
11424   if (!getDerived().AlwaysRebuild() &&
11425       T == E->getTypeSourceInfo() &&
11426       Constructor == E->getConstructor() &&
11427       !ArgumentChanged) {
11428     // FIXME: Instantiation-specific
11429     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11430     return SemaRef.MaybeBindToTemporary(E);
11431   }
11432 
11433   // FIXME: We should just pass E->isListInitialization(), but we're not
11434   // prepared to handle list-initialization without a child InitListExpr.
11435   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
11436   return getDerived().RebuildCXXTemporaryObjectExpr(
11437       T, LParenLoc, Args, E->getEndLoc(),
11438       /*ListInitialization=*/LParenLoc.isInvalid());
11439 }
11440 
11441 template<typename Derived>
11442 ExprResult
11443 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
11444   // Transform any init-capture expressions before entering the scope of the
11445   // lambda body, because they are not semantically within that scope.
11446   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
11447   struct TransformedInitCapture {
11448     // The location of the ... if the result is retaining a pack expansion.
11449     SourceLocation EllipsisLoc;
11450     // Zero or more expansions of the init-capture.
11451     SmallVector<InitCaptureInfoTy, 4> Expansions;
11452   };
11453   SmallVector<TransformedInitCapture, 4> InitCaptures;
11454   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
11455   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11456                                     CEnd = E->capture_end();
11457        C != CEnd; ++C) {
11458     if (!E->isInitCapture(C))
11459       continue;
11460 
11461     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
11462     VarDecl *OldVD = C->getCapturedVar();
11463 
11464     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
11465                                 Optional<unsigned> NumExpansions) {
11466       ExprResult NewExprInitResult = getDerived().TransformInitializer(
11467           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
11468 
11469       if (NewExprInitResult.isInvalid()) {
11470         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
11471         return;
11472       }
11473       Expr *NewExprInit = NewExprInitResult.get();
11474 
11475       QualType NewInitCaptureType =
11476           getSema().buildLambdaInitCaptureInitialization(
11477               C->getLocation(), OldVD->getType()->isReferenceType(),
11478               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
11479               C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
11480               NewExprInit);
11481       Result.Expansions.push_back(
11482           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
11483     };
11484 
11485     // If this is an init-capture pack, consider expanding the pack now.
11486     if (OldVD->isParameterPack()) {
11487       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
11488                                              ->getTypeLoc()
11489                                              .castAs<PackExpansionTypeLoc>();
11490       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11491       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
11492 
11493       // Determine whether the set of unexpanded parameter packs can and should
11494       // be expanded.
11495       bool Expand = true;
11496       bool RetainExpansion = false;
11497       Optional<unsigned> OrigNumExpansions =
11498           ExpansionTL.getTypePtr()->getNumExpansions();
11499       Optional<unsigned> NumExpansions = OrigNumExpansions;
11500       if (getDerived().TryExpandParameterPacks(
11501               ExpansionTL.getEllipsisLoc(),
11502               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
11503               RetainExpansion, NumExpansions))
11504         return ExprError();
11505       if (Expand) {
11506         for (unsigned I = 0; I != *NumExpansions; ++I) {
11507           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11508           SubstInitCapture(SourceLocation(), None);
11509         }
11510       }
11511       if (!Expand || RetainExpansion) {
11512         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11513         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
11514         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
11515       }
11516     } else {
11517       SubstInitCapture(SourceLocation(), None);
11518     }
11519   }
11520 
11521   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
11522   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
11523 
11524   // Transform the template parameters, and add them to the current
11525   // instantiation scope. The null case is handled correctly.
11526   auto TPL = getDerived().TransformTemplateParameterList(
11527       E->getTemplateParameterList());
11528   LSI->GLTemplateParameterList = TPL;
11529 
11530   // Transform the type of the original lambda's call operator.
11531   // The transformation MUST be done in the CurrentInstantiationScope since
11532   // it introduces a mapping of the original to the newly created
11533   // transformed parameters.
11534   TypeSourceInfo *NewCallOpTSI = nullptr;
11535   {
11536     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
11537     FunctionProtoTypeLoc OldCallOpFPTL =
11538         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
11539 
11540     TypeLocBuilder NewCallOpTLBuilder;
11541     SmallVector<QualType, 4> ExceptionStorage;
11542     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
11543     QualType NewCallOpType = TransformFunctionProtoType(
11544         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
11545         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
11546           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
11547                                               ExceptionStorage, Changed);
11548         });
11549     if (NewCallOpType.isNull())
11550       return ExprError();
11551     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
11552                                                         NewCallOpType);
11553   }
11554 
11555   // Transform the trailing requires clause
11556   ExprResult NewTrailingRequiresClause;
11557   if (Expr *TRC = E->getCallOperator()->getTrailingRequiresClause())
11558     // FIXME: Concepts: Substitution into requires clause should only happen
11559     //                  when checking satisfaction.
11560     NewTrailingRequiresClause = getDerived().TransformExpr(TRC);
11561 
11562   // Create the local class that will describe the lambda.
11563   CXXRecordDecl *OldClass = E->getLambdaClass();
11564   CXXRecordDecl *Class
11565     = getSema().createLambdaClosureType(E->getIntroducerRange(),
11566                                         NewCallOpTSI,
11567                                         /*KnownDependent=*/false,
11568                                         E->getCaptureDefault());
11569   getDerived().transformedLocalDecl(OldClass, {Class});
11570 
11571   Optional<std::tuple<unsigned, bool, Decl *>> Mangling;
11572   if (getDerived().ReplacingOriginal())
11573     Mangling = std::make_tuple(OldClass->getLambdaManglingNumber(),
11574                                OldClass->hasKnownLambdaInternalLinkage(),
11575                                OldClass->getLambdaContextDecl());
11576 
11577   // Build the call operator.
11578   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
11579       Class, E->getIntroducerRange(), NewCallOpTSI,
11580       E->getCallOperator()->getEndLoc(),
11581       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
11582       E->getCallOperator()->getConstexprKind(),
11583       NewTrailingRequiresClause.get());
11584 
11585   LSI->CallOperator = NewCallOperator;
11586 
11587   for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
11588        I != NumParams; ++I) {
11589     auto *P = NewCallOperator->getParamDecl(I);
11590     if (P->hasUninstantiatedDefaultArg()) {
11591       EnterExpressionEvaluationContext Eval(
11592           getSema(),
11593           Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
11594       ExprResult R = getDerived().TransformExpr(
11595           E->getCallOperator()->getParamDecl(I)->getDefaultArg());
11596       P->setDefaultArg(R.get());
11597     }
11598   }
11599 
11600   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
11601   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
11602 
11603   // Number the lambda for linkage purposes if necessary.
11604   getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
11605 
11606   // Introduce the context of the call operator.
11607   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
11608                                  /*NewThisContext*/false);
11609 
11610   // Enter the scope of the lambda.
11611   getSema().buildLambdaScope(LSI, NewCallOperator,
11612                              E->getIntroducerRange(),
11613                              E->getCaptureDefault(),
11614                              E->getCaptureDefaultLoc(),
11615                              E->hasExplicitParameters(),
11616                              E->hasExplicitResultType(),
11617                              E->isMutable());
11618 
11619   bool Invalid = false;
11620 
11621   // Transform captures.
11622   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11623                                  CEnd = E->capture_end();
11624        C != CEnd; ++C) {
11625     // When we hit the first implicit capture, tell Sema that we've finished
11626     // the list of explicit captures.
11627     if (C->isImplicit())
11628       break;
11629 
11630     // Capturing 'this' is trivial.
11631     if (C->capturesThis()) {
11632       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11633                                     /*BuildAndDiagnose*/ true, nullptr,
11634                                     C->getCaptureKind() == LCK_StarThis);
11635       continue;
11636     }
11637     // Captured expression will be recaptured during captured variables
11638     // rebuilding.
11639     if (C->capturesVLAType())
11640       continue;
11641 
11642     // Rebuild init-captures, including the implied field declaration.
11643     if (E->isInitCapture(C)) {
11644       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
11645 
11646       VarDecl *OldVD = C->getCapturedVar();
11647       llvm::SmallVector<Decl*, 4> NewVDs;
11648 
11649       for (InitCaptureInfoTy &Info : NewC.Expansions) {
11650         ExprResult Init = Info.first;
11651         QualType InitQualType = Info.second;
11652         if (Init.isInvalid() || InitQualType.isNull()) {
11653           Invalid = true;
11654           break;
11655         }
11656         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
11657             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
11658             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
11659         if (!NewVD) {
11660           Invalid = true;
11661           break;
11662         }
11663         NewVDs.push_back(NewVD);
11664         getSema().addInitCapture(LSI, NewVD);
11665       }
11666 
11667       if (Invalid)
11668         break;
11669 
11670       getDerived().transformedLocalDecl(OldVD, NewVDs);
11671       continue;
11672     }
11673 
11674     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11675 
11676     // Determine the capture kind for Sema.
11677     Sema::TryCaptureKind Kind
11678       = C->isImplicit()? Sema::TryCapture_Implicit
11679                        : C->getCaptureKind() == LCK_ByCopy
11680                            ? Sema::TryCapture_ExplicitByVal
11681                            : Sema::TryCapture_ExplicitByRef;
11682     SourceLocation EllipsisLoc;
11683     if (C->isPackExpansion()) {
11684       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
11685       bool ShouldExpand = false;
11686       bool RetainExpansion = false;
11687       Optional<unsigned> NumExpansions;
11688       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
11689                                                C->getLocation(),
11690                                                Unexpanded,
11691                                                ShouldExpand, RetainExpansion,
11692                                                NumExpansions)) {
11693         Invalid = true;
11694         continue;
11695       }
11696 
11697       if (ShouldExpand) {
11698         // The transform has determined that we should perform an expansion;
11699         // transform and capture each of the arguments.
11700         // expansion of the pattern. Do so.
11701         VarDecl *Pack = C->getCapturedVar();
11702         for (unsigned I = 0; I != *NumExpansions; ++I) {
11703           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11704           VarDecl *CapturedVar
11705             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11706                                                                Pack));
11707           if (!CapturedVar) {
11708             Invalid = true;
11709             continue;
11710           }
11711 
11712           // Capture the transformed variable.
11713           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
11714         }
11715 
11716         // FIXME: Retain a pack expansion if RetainExpansion is true.
11717 
11718         continue;
11719       }
11720 
11721       EllipsisLoc = C->getEllipsisLoc();
11722     }
11723 
11724     // Transform the captured variable.
11725     VarDecl *CapturedVar
11726       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11727                                                          C->getCapturedVar()));
11728     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
11729       Invalid = true;
11730       continue;
11731     }
11732 
11733     // Capture the transformed variable.
11734     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
11735                                  EllipsisLoc);
11736   }
11737   getSema().finishLambdaExplicitCaptures(LSI);
11738 
11739   // FIXME: Sema's lambda-building mechanism expects us to push an expression
11740   // evaluation context even if we're not transforming the function body.
11741   getSema().PushExpressionEvaluationContext(
11742       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
11743 
11744   // Instantiate the body of the lambda expression.
11745   StmtResult Body =
11746       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
11747 
11748   // ActOnLambda* will pop the function scope for us.
11749   FuncScopeCleanup.disable();
11750 
11751   if (Body.isInvalid()) {
11752     SavedContext.pop();
11753     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
11754                                /*IsInstantiation=*/true);
11755     return ExprError();
11756   }
11757 
11758   // Copy the LSI before ActOnFinishFunctionBody removes it.
11759   // FIXME: This is dumb. Store the lambda information somewhere that outlives
11760   // the call operator.
11761   auto LSICopy = *LSI;
11762   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
11763                                     /*IsInstantiation*/ true);
11764   SavedContext.pop();
11765 
11766   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
11767                                    &LSICopy);
11768 }
11769 
11770 template<typename Derived>
11771 StmtResult
11772 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
11773   return TransformStmt(S);
11774 }
11775 
11776 template<typename Derived>
11777 StmtResult
11778 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
11779   // Transform captures.
11780   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11781                                  CEnd = E->capture_end();
11782        C != CEnd; ++C) {
11783     // When we hit the first implicit capture, tell Sema that we've finished
11784     // the list of explicit captures.
11785     if (!C->isImplicit())
11786       continue;
11787 
11788     // Capturing 'this' is trivial.
11789     if (C->capturesThis()) {
11790       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11791                                     /*BuildAndDiagnose*/ true, nullptr,
11792                                     C->getCaptureKind() == LCK_StarThis);
11793       continue;
11794     }
11795     // Captured expression will be recaptured during captured variables
11796     // rebuilding.
11797     if (C->capturesVLAType())
11798       continue;
11799 
11800     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11801     assert(!E->isInitCapture(C) && "implicit init-capture?");
11802 
11803     // Transform the captured variable.
11804     VarDecl *CapturedVar = cast_or_null<VarDecl>(
11805         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
11806     if (!CapturedVar || CapturedVar->isInvalidDecl())
11807       return StmtError();
11808 
11809     // Capture the transformed variable.
11810     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
11811   }
11812 
11813   return S;
11814 }
11815 
11816 template<typename Derived>
11817 ExprResult
11818 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
11819                                                   CXXUnresolvedConstructExpr *E) {
11820   TypeSourceInfo *T =
11821       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11822   if (!T)
11823     return ExprError();
11824 
11825   bool ArgumentChanged = false;
11826   SmallVector<Expr*, 8> Args;
11827   Args.reserve(E->arg_size());
11828   {
11829     EnterExpressionEvaluationContext Context(
11830         getSema(), EnterExpressionEvaluationContext::InitList,
11831         E->isListInitialization());
11832     if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
11833                                     &ArgumentChanged))
11834       return ExprError();
11835   }
11836 
11837   if (!getDerived().AlwaysRebuild() &&
11838       T == E->getTypeSourceInfo() &&
11839       !ArgumentChanged)
11840     return E;
11841 
11842   // FIXME: we're faking the locations of the commas
11843   return getDerived().RebuildCXXUnresolvedConstructExpr(
11844       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
11845 }
11846 
11847 template<typename Derived>
11848 ExprResult
11849 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
11850                                              CXXDependentScopeMemberExpr *E) {
11851   // Transform the base of the expression.
11852   ExprResult Base((Expr*) nullptr);
11853   Expr *OldBase;
11854   QualType BaseType;
11855   QualType ObjectType;
11856   if (!E->isImplicitAccess()) {
11857     OldBase = E->getBase();
11858     Base = getDerived().TransformExpr(OldBase);
11859     if (Base.isInvalid())
11860       return ExprError();
11861 
11862     // Start the member reference and compute the object's type.
11863     ParsedType ObjectTy;
11864     bool MayBePseudoDestructor = false;
11865     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11866                                                 E->getOperatorLoc(),
11867                                       E->isArrow()? tok::arrow : tok::period,
11868                                                 ObjectTy,
11869                                                 MayBePseudoDestructor);
11870     if (Base.isInvalid())
11871       return ExprError();
11872 
11873     ObjectType = ObjectTy.get();
11874     BaseType = ((Expr*) Base.get())->getType();
11875   } else {
11876     OldBase = nullptr;
11877     BaseType = getDerived().TransformType(E->getBaseType());
11878     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
11879   }
11880 
11881   // Transform the first part of the nested-name-specifier that qualifies
11882   // the member name.
11883   NamedDecl *FirstQualifierInScope
11884     = getDerived().TransformFirstQualifierInScope(
11885                                             E->getFirstQualifierFoundInScope(),
11886                                             E->getQualifierLoc().getBeginLoc());
11887 
11888   NestedNameSpecifierLoc QualifierLoc;
11889   if (E->getQualifier()) {
11890     QualifierLoc
11891       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11892                                                      ObjectType,
11893                                                      FirstQualifierInScope);
11894     if (!QualifierLoc)
11895       return ExprError();
11896   }
11897 
11898   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11899 
11900   // TODO: If this is a conversion-function-id, verify that the
11901   // destination type name (if present) resolves the same way after
11902   // instantiation as it did in the local scope.
11903 
11904   DeclarationNameInfo NameInfo
11905     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11906   if (!NameInfo.getName())
11907     return ExprError();
11908 
11909   if (!E->hasExplicitTemplateArgs()) {
11910     // This is a reference to a member without an explicitly-specified
11911     // template argument list. Optimize for this common case.
11912     if (!getDerived().AlwaysRebuild() &&
11913         Base.get() == OldBase &&
11914         BaseType == E->getBaseType() &&
11915         QualifierLoc == E->getQualifierLoc() &&
11916         NameInfo.getName() == E->getMember() &&
11917         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11918       return E;
11919 
11920     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11921                                                        BaseType,
11922                                                        E->isArrow(),
11923                                                        E->getOperatorLoc(),
11924                                                        QualifierLoc,
11925                                                        TemplateKWLoc,
11926                                                        FirstQualifierInScope,
11927                                                        NameInfo,
11928                                                        /*TemplateArgs*/nullptr);
11929   }
11930 
11931   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11932   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11933                                               E->getNumTemplateArgs(),
11934                                               TransArgs))
11935     return ExprError();
11936 
11937   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11938                                                      BaseType,
11939                                                      E->isArrow(),
11940                                                      E->getOperatorLoc(),
11941                                                      QualifierLoc,
11942                                                      TemplateKWLoc,
11943                                                      FirstQualifierInScope,
11944                                                      NameInfo,
11945                                                      &TransArgs);
11946 }
11947 
11948 template<typename Derived>
11949 ExprResult
11950 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11951   // Transform the base of the expression.
11952   ExprResult Base((Expr*) nullptr);
11953   QualType BaseType;
11954   if (!Old->isImplicitAccess()) {
11955     Base = getDerived().TransformExpr(Old->getBase());
11956     if (Base.isInvalid())
11957       return ExprError();
11958     Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11959                                                      Old->isArrow());
11960     if (Base.isInvalid())
11961       return ExprError();
11962     BaseType = Base.get()->getType();
11963   } else {
11964     BaseType = getDerived().TransformType(Old->getBaseType());
11965   }
11966 
11967   NestedNameSpecifierLoc QualifierLoc;
11968   if (Old->getQualifierLoc()) {
11969     QualifierLoc
11970     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11971     if (!QualifierLoc)
11972       return ExprError();
11973   }
11974 
11975   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11976 
11977   LookupResult R(SemaRef, Old->getMemberNameInfo(),
11978                  Sema::LookupOrdinaryName);
11979 
11980   // Transform the declaration set.
11981   if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11982     return ExprError();
11983 
11984   // Determine the naming class.
11985   if (Old->getNamingClass()) {
11986     CXXRecordDecl *NamingClass
11987       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11988                                                           Old->getMemberLoc(),
11989                                                         Old->getNamingClass()));
11990     if (!NamingClass)
11991       return ExprError();
11992 
11993     R.setNamingClass(NamingClass);
11994   }
11995 
11996   TemplateArgumentListInfo TransArgs;
11997   if (Old->hasExplicitTemplateArgs()) {
11998     TransArgs.setLAngleLoc(Old->getLAngleLoc());
11999     TransArgs.setRAngleLoc(Old->getRAngleLoc());
12000     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12001                                                 Old->getNumTemplateArgs(),
12002                                                 TransArgs))
12003       return ExprError();
12004   }
12005 
12006   // FIXME: to do this check properly, we will need to preserve the
12007   // first-qualifier-in-scope here, just in case we had a dependent
12008   // base (and therefore couldn't do the check) and a
12009   // nested-name-qualifier (and therefore could do the lookup).
12010   NamedDecl *FirstQualifierInScope = nullptr;
12011 
12012   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
12013                                                   BaseType,
12014                                                   Old->getOperatorLoc(),
12015                                                   Old->isArrow(),
12016                                                   QualifierLoc,
12017                                                   TemplateKWLoc,
12018                                                   FirstQualifierInScope,
12019                                                   R,
12020                                               (Old->hasExplicitTemplateArgs()
12021                                                   ? &TransArgs : nullptr));
12022 }
12023 
12024 template<typename Derived>
12025 ExprResult
12026 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
12027   EnterExpressionEvaluationContext Unevaluated(
12028       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12029   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
12030   if (SubExpr.isInvalid())
12031     return ExprError();
12032 
12033   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
12034     return E;
12035 
12036   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
12037 }
12038 
12039 template<typename Derived>
12040 ExprResult
12041 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
12042   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
12043   if (Pattern.isInvalid())
12044     return ExprError();
12045 
12046   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
12047     return E;
12048 
12049   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
12050                                            E->getNumExpansions());
12051 }
12052 
12053 template<typename Derived>
12054 ExprResult
12055 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
12056   // If E is not value-dependent, then nothing will change when we transform it.
12057   // Note: This is an instantiation-centric view.
12058   if (!E->isValueDependent())
12059     return E;
12060 
12061   EnterExpressionEvaluationContext Unevaluated(
12062       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
12063 
12064   ArrayRef<TemplateArgument> PackArgs;
12065   TemplateArgument ArgStorage;
12066 
12067   // Find the argument list to transform.
12068   if (E->isPartiallySubstituted()) {
12069     PackArgs = E->getPartialArguments();
12070   } else if (E->isValueDependent()) {
12071     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
12072     bool ShouldExpand = false;
12073     bool RetainExpansion = false;
12074     Optional<unsigned> NumExpansions;
12075     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
12076                                              Unexpanded,
12077                                              ShouldExpand, RetainExpansion,
12078                                              NumExpansions))
12079       return ExprError();
12080 
12081     // If we need to expand the pack, build a template argument from it and
12082     // expand that.
12083     if (ShouldExpand) {
12084       auto *Pack = E->getPack();
12085       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
12086         ArgStorage = getSema().Context.getPackExpansionType(
12087             getSema().Context.getTypeDeclType(TTPD), None);
12088       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
12089         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
12090       } else {
12091         auto *VD = cast<ValueDecl>(Pack);
12092         ExprResult DRE = getSema().BuildDeclRefExpr(
12093             VD, VD->getType().getNonLValueExprType(getSema().Context),
12094             VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
12095             E->getPackLoc());
12096         if (DRE.isInvalid())
12097           return ExprError();
12098         ArgStorage = new (getSema().Context) PackExpansionExpr(
12099             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
12100       }
12101       PackArgs = ArgStorage;
12102     }
12103   }
12104 
12105   // If we're not expanding the pack, just transform the decl.
12106   if (!PackArgs.size()) {
12107     auto *Pack = cast_or_null<NamedDecl>(
12108         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
12109     if (!Pack)
12110       return ExprError();
12111     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
12112                                               E->getPackLoc(),
12113                                               E->getRParenLoc(), None, None);
12114   }
12115 
12116   // Try to compute the result without performing a partial substitution.
12117   Optional<unsigned> Result = 0;
12118   for (const TemplateArgument &Arg : PackArgs) {
12119     if (!Arg.isPackExpansion()) {
12120       Result = *Result + 1;
12121       continue;
12122     }
12123 
12124     TemplateArgumentLoc ArgLoc;
12125     InventTemplateArgumentLoc(Arg, ArgLoc);
12126 
12127     // Find the pattern of the pack expansion.
12128     SourceLocation Ellipsis;
12129     Optional<unsigned> OrigNumExpansions;
12130     TemplateArgumentLoc Pattern =
12131         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
12132                                                           OrigNumExpansions);
12133 
12134     // Substitute under the pack expansion. Do not expand the pack (yet).
12135     TemplateArgumentLoc OutPattern;
12136     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12137     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
12138                                                /*Uneval*/ true))
12139       return true;
12140 
12141     // See if we can determine the number of arguments from the result.
12142     Optional<unsigned> NumExpansions =
12143         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
12144     if (!NumExpansions) {
12145       // No: we must be in an alias template expansion, and we're going to need
12146       // to actually expand the packs.
12147       Result = None;
12148       break;
12149     }
12150 
12151     Result = *Result + *NumExpansions;
12152   }
12153 
12154   // Common case: we could determine the number of expansions without
12155   // substituting.
12156   if (Result)
12157     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12158                                               E->getPackLoc(),
12159                                               E->getRParenLoc(), *Result, None);
12160 
12161   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
12162                                                E->getPackLoc());
12163   {
12164     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
12165     typedef TemplateArgumentLocInventIterator<
12166         Derived, const TemplateArgument*> PackLocIterator;
12167     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
12168                                    PackLocIterator(*this, PackArgs.end()),
12169                                    TransformedPackArgs, /*Uneval*/true))
12170       return ExprError();
12171   }
12172 
12173   // Check whether we managed to fully-expand the pack.
12174   // FIXME: Is it possible for us to do so and not hit the early exit path?
12175   SmallVector<TemplateArgument, 8> Args;
12176   bool PartialSubstitution = false;
12177   for (auto &Loc : TransformedPackArgs.arguments()) {
12178     Args.push_back(Loc.getArgument());
12179     if (Loc.getArgument().isPackExpansion())
12180       PartialSubstitution = true;
12181   }
12182 
12183   if (PartialSubstitution)
12184     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12185                                               E->getPackLoc(),
12186                                               E->getRParenLoc(), None, Args);
12187 
12188   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12189                                             E->getPackLoc(), E->getRParenLoc(),
12190                                             Args.size(), None);
12191 }
12192 
12193 template<typename Derived>
12194 ExprResult
12195 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
12196                                           SubstNonTypeTemplateParmPackExpr *E) {
12197   // Default behavior is to do nothing with this transformation.
12198   return E;
12199 }
12200 
12201 template<typename Derived>
12202 ExprResult
12203 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
12204                                           SubstNonTypeTemplateParmExpr *E) {
12205   // Default behavior is to do nothing with this transformation.
12206   return E;
12207 }
12208 
12209 template<typename Derived>
12210 ExprResult
12211 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
12212   // Default behavior is to do nothing with this transformation.
12213   return E;
12214 }
12215 
12216 template<typename Derived>
12217 ExprResult
12218 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
12219                                                   MaterializeTemporaryExpr *E) {
12220   return getDerived().TransformExpr(E->getSubExpr());
12221 }
12222 
12223 template<typename Derived>
12224 ExprResult
12225 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
12226   Expr *Pattern = E->getPattern();
12227 
12228   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12229   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
12230   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12231 
12232   // Determine whether the set of unexpanded parameter packs can and should
12233   // be expanded.
12234   bool Expand = true;
12235   bool RetainExpansion = false;
12236   Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
12237                      NumExpansions = OrigNumExpansions;
12238   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
12239                                            Pattern->getSourceRange(),
12240                                            Unexpanded,
12241                                            Expand, RetainExpansion,
12242                                            NumExpansions))
12243     return true;
12244 
12245   if (!Expand) {
12246     // Do not expand any packs here, just transform and rebuild a fold
12247     // expression.
12248     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12249 
12250     ExprResult LHS =
12251         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
12252     if (LHS.isInvalid())
12253       return true;
12254 
12255     ExprResult RHS =
12256         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
12257     if (RHS.isInvalid())
12258       return true;
12259 
12260     if (!getDerived().AlwaysRebuild() &&
12261         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
12262       return E;
12263 
12264     return getDerived().RebuildCXXFoldExpr(
12265         E->getBeginLoc(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
12266         RHS.get(), E->getEndLoc(), NumExpansions);
12267   }
12268 
12269   // The transform has determined that we should perform an elementwise
12270   // expansion of the pattern. Do so.
12271   ExprResult Result = getDerived().TransformExpr(E->getInit());
12272   if (Result.isInvalid())
12273     return true;
12274   bool LeftFold = E->isLeftFold();
12275 
12276   // If we're retaining an expansion for a right fold, it is the innermost
12277   // component and takes the init (if any).
12278   if (!LeftFold && RetainExpansion) {
12279     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12280 
12281     ExprResult Out = getDerived().TransformExpr(Pattern);
12282     if (Out.isInvalid())
12283       return true;
12284 
12285     Result = getDerived().RebuildCXXFoldExpr(
12286         E->getBeginLoc(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
12287         Result.get(), E->getEndLoc(), OrigNumExpansions);
12288     if (Result.isInvalid())
12289       return true;
12290   }
12291 
12292   for (unsigned I = 0; I != *NumExpansions; ++I) {
12293     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
12294         getSema(), LeftFold ? I : *NumExpansions - I - 1);
12295     ExprResult Out = getDerived().TransformExpr(Pattern);
12296     if (Out.isInvalid())
12297       return true;
12298 
12299     if (Out.get()->containsUnexpandedParameterPack()) {
12300       // We still have a pack; retain a pack expansion for this slice.
12301       Result = getDerived().RebuildCXXFoldExpr(
12302           E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
12303           E->getOperator(), E->getEllipsisLoc(),
12304           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
12305           OrigNumExpansions);
12306     } else if (Result.isUsable()) {
12307       // We've got down to a single element; build a binary operator.
12308       Result = getDerived().RebuildBinaryOperator(
12309           E->getEllipsisLoc(), E->getOperator(),
12310           LeftFold ? Result.get() : Out.get(),
12311           LeftFold ? Out.get() : Result.get());
12312     } else
12313       Result = Out;
12314 
12315     if (Result.isInvalid())
12316       return true;
12317   }
12318 
12319   // If we're retaining an expansion for a left fold, it is the outermost
12320   // component and takes the complete expansion so far as its init (if any).
12321   if (LeftFold && RetainExpansion) {
12322     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12323 
12324     ExprResult Out = getDerived().TransformExpr(Pattern);
12325     if (Out.isInvalid())
12326       return true;
12327 
12328     Result = getDerived().RebuildCXXFoldExpr(
12329         E->getBeginLoc(), Result.get(), E->getOperator(), E->getEllipsisLoc(),
12330         Out.get(), E->getEndLoc(), OrigNumExpansions);
12331     if (Result.isInvalid())
12332       return true;
12333   }
12334 
12335   // If we had no init and an empty pack, and we're not retaining an expansion,
12336   // then produce a fallback value or error.
12337   if (Result.isUnset())
12338     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
12339                                                 E->getOperator());
12340 
12341   return Result;
12342 }
12343 
12344 template<typename Derived>
12345 ExprResult
12346 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
12347     CXXStdInitializerListExpr *E) {
12348   return getDerived().TransformExpr(E->getSubExpr());
12349 }
12350 
12351 template<typename Derived>
12352 ExprResult
12353 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
12354   return SemaRef.MaybeBindToTemporary(E);
12355 }
12356 
12357 template<typename Derived>
12358 ExprResult
12359 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
12360   return E;
12361 }
12362 
12363 template<typename Derived>
12364 ExprResult
12365 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
12366   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12367   if (SubExpr.isInvalid())
12368     return ExprError();
12369 
12370   if (!getDerived().AlwaysRebuild() &&
12371       SubExpr.get() == E->getSubExpr())
12372     return E;
12373 
12374   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
12375 }
12376 
12377 template<typename Derived>
12378 ExprResult
12379 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
12380   // Transform each of the elements.
12381   SmallVector<Expr *, 8> Elements;
12382   bool ArgChanged = false;
12383   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
12384                                   /*IsCall=*/false, Elements, &ArgChanged))
12385     return ExprError();
12386 
12387   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12388     return SemaRef.MaybeBindToTemporary(E);
12389 
12390   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
12391                                               Elements.data(),
12392                                               Elements.size());
12393 }
12394 
12395 template<typename Derived>
12396 ExprResult
12397 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
12398                                                     ObjCDictionaryLiteral *E) {
12399   // Transform each of the elements.
12400   SmallVector<ObjCDictionaryElement, 8> Elements;
12401   bool ArgChanged = false;
12402   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
12403     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
12404 
12405     if (OrigElement.isPackExpansion()) {
12406       // This key/value element is a pack expansion.
12407       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12408       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
12409       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
12410       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12411 
12412       // Determine whether the set of unexpanded parameter packs can
12413       // and should be expanded.
12414       bool Expand = true;
12415       bool RetainExpansion = false;
12416       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
12417       Optional<unsigned> NumExpansions = OrigNumExpansions;
12418       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
12419                                OrigElement.Value->getEndLoc());
12420       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
12421                                                PatternRange, Unexpanded, Expand,
12422                                                RetainExpansion, NumExpansions))
12423         return ExprError();
12424 
12425       if (!Expand) {
12426         // The transform has determined that we should perform a simple
12427         // transformation on the pack expansion, producing another pack
12428         // expansion.
12429         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12430         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12431         if (Key.isInvalid())
12432           return ExprError();
12433 
12434         if (Key.get() != OrigElement.Key)
12435           ArgChanged = true;
12436 
12437         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12438         if (Value.isInvalid())
12439           return ExprError();
12440 
12441         if (Value.get() != OrigElement.Value)
12442           ArgChanged = true;
12443 
12444         ObjCDictionaryElement Expansion = {
12445           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
12446         };
12447         Elements.push_back(Expansion);
12448         continue;
12449       }
12450 
12451       // Record right away that the argument was changed.  This needs
12452       // to happen even if the array expands to nothing.
12453       ArgChanged = true;
12454 
12455       // The transform has determined that we should perform an elementwise
12456       // expansion of the pattern. Do so.
12457       for (unsigned I = 0; I != *NumExpansions; ++I) {
12458         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12459         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12460         if (Key.isInvalid())
12461           return ExprError();
12462 
12463         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12464         if (Value.isInvalid())
12465           return ExprError();
12466 
12467         ObjCDictionaryElement Element = {
12468           Key.get(), Value.get(), SourceLocation(), NumExpansions
12469         };
12470 
12471         // If any unexpanded parameter packs remain, we still have a
12472         // pack expansion.
12473         // FIXME: Can this really happen?
12474         if (Key.get()->containsUnexpandedParameterPack() ||
12475             Value.get()->containsUnexpandedParameterPack())
12476           Element.EllipsisLoc = OrigElement.EllipsisLoc;
12477 
12478         Elements.push_back(Element);
12479       }
12480 
12481       // FIXME: Retain a pack expansion if RetainExpansion is true.
12482 
12483       // We've finished with this pack expansion.
12484       continue;
12485     }
12486 
12487     // Transform and check key.
12488     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12489     if (Key.isInvalid())
12490       return ExprError();
12491 
12492     if (Key.get() != OrigElement.Key)
12493       ArgChanged = true;
12494 
12495     // Transform and check value.
12496     ExprResult Value
12497       = getDerived().TransformExpr(OrigElement.Value);
12498     if (Value.isInvalid())
12499       return ExprError();
12500 
12501     if (Value.get() != OrigElement.Value)
12502       ArgChanged = true;
12503 
12504     ObjCDictionaryElement Element = {
12505       Key.get(), Value.get(), SourceLocation(), None
12506     };
12507     Elements.push_back(Element);
12508   }
12509 
12510   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12511     return SemaRef.MaybeBindToTemporary(E);
12512 
12513   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
12514                                                    Elements);
12515 }
12516 
12517 template<typename Derived>
12518 ExprResult
12519 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
12520   TypeSourceInfo *EncodedTypeInfo
12521     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
12522   if (!EncodedTypeInfo)
12523     return ExprError();
12524 
12525   if (!getDerived().AlwaysRebuild() &&
12526       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
12527     return E;
12528 
12529   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
12530                                             EncodedTypeInfo,
12531                                             E->getRParenLoc());
12532 }
12533 
12534 template<typename Derived>
12535 ExprResult TreeTransform<Derived>::
12536 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
12537   // This is a kind of implicit conversion, and it needs to get dropped
12538   // and recomputed for the same general reasons that ImplicitCastExprs
12539   // do, as well a more specific one: this expression is only valid when
12540   // it appears *immediately* as an argument expression.
12541   return getDerived().TransformExpr(E->getSubExpr());
12542 }
12543 
12544 template<typename Derived>
12545 ExprResult TreeTransform<Derived>::
12546 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
12547   TypeSourceInfo *TSInfo
12548     = getDerived().TransformType(E->getTypeInfoAsWritten());
12549   if (!TSInfo)
12550     return ExprError();
12551 
12552   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
12553   if (Result.isInvalid())
12554     return ExprError();
12555 
12556   if (!getDerived().AlwaysRebuild() &&
12557       TSInfo == E->getTypeInfoAsWritten() &&
12558       Result.get() == E->getSubExpr())
12559     return E;
12560 
12561   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
12562                                       E->getBridgeKeywordLoc(), TSInfo,
12563                                       Result.get());
12564 }
12565 
12566 template <typename Derived>
12567 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
12568     ObjCAvailabilityCheckExpr *E) {
12569   return E;
12570 }
12571 
12572 template<typename Derived>
12573 ExprResult
12574 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
12575   // Transform arguments.
12576   bool ArgChanged = false;
12577   SmallVector<Expr*, 8> Args;
12578   Args.reserve(E->getNumArgs());
12579   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
12580                                   &ArgChanged))
12581     return ExprError();
12582 
12583   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
12584     // Class message: transform the receiver type.
12585     TypeSourceInfo *ReceiverTypeInfo
12586       = getDerived().TransformType(E->getClassReceiverTypeInfo());
12587     if (!ReceiverTypeInfo)
12588       return ExprError();
12589 
12590     // If nothing changed, just retain the existing message send.
12591     if (!getDerived().AlwaysRebuild() &&
12592         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
12593       return SemaRef.MaybeBindToTemporary(E);
12594 
12595     // Build a new class message send.
12596     SmallVector<SourceLocation, 16> SelLocs;
12597     E->getSelectorLocs(SelLocs);
12598     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
12599                                                E->getSelector(),
12600                                                SelLocs,
12601                                                E->getMethodDecl(),
12602                                                E->getLeftLoc(),
12603                                                Args,
12604                                                E->getRightLoc());
12605   }
12606   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
12607            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12608     if (!E->getMethodDecl())
12609       return ExprError();
12610 
12611     // Build a new class message send to 'super'.
12612     SmallVector<SourceLocation, 16> SelLocs;
12613     E->getSelectorLocs(SelLocs);
12614     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
12615                                                E->getSelector(),
12616                                                SelLocs,
12617                                                E->getReceiverType(),
12618                                                E->getMethodDecl(),
12619                                                E->getLeftLoc(),
12620                                                Args,
12621                                                E->getRightLoc());
12622   }
12623 
12624   // Instance message: transform the receiver
12625   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
12626          "Only class and instance messages may be instantiated");
12627   ExprResult Receiver
12628     = getDerived().TransformExpr(E->getInstanceReceiver());
12629   if (Receiver.isInvalid())
12630     return ExprError();
12631 
12632   // If nothing changed, just retain the existing message send.
12633   if (!getDerived().AlwaysRebuild() &&
12634       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
12635     return SemaRef.MaybeBindToTemporary(E);
12636 
12637   // Build a new instance message send.
12638   SmallVector<SourceLocation, 16> SelLocs;
12639   E->getSelectorLocs(SelLocs);
12640   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
12641                                              E->getSelector(),
12642                                              SelLocs,
12643                                              E->getMethodDecl(),
12644                                              E->getLeftLoc(),
12645                                              Args,
12646                                              E->getRightLoc());
12647 }
12648 
12649 template<typename Derived>
12650 ExprResult
12651 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
12652   return E;
12653 }
12654 
12655 template<typename Derived>
12656 ExprResult
12657 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
12658   return E;
12659 }
12660 
12661 template<typename Derived>
12662 ExprResult
12663 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
12664   // Transform the base expression.
12665   ExprResult Base = getDerived().TransformExpr(E->getBase());
12666   if (Base.isInvalid())
12667     return ExprError();
12668 
12669   // We don't need to transform the ivar; it will never change.
12670 
12671   // If nothing changed, just retain the existing expression.
12672   if (!getDerived().AlwaysRebuild() &&
12673       Base.get() == E->getBase())
12674     return E;
12675 
12676   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
12677                                              E->getLocation(),
12678                                              E->isArrow(), E->isFreeIvar());
12679 }
12680 
12681 template<typename Derived>
12682 ExprResult
12683 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
12684   // 'super' and types never change. Property never changes. Just
12685   // retain the existing expression.
12686   if (!E->isObjectReceiver())
12687     return E;
12688 
12689   // Transform the base expression.
12690   ExprResult Base = getDerived().TransformExpr(E->getBase());
12691   if (Base.isInvalid())
12692     return ExprError();
12693 
12694   // We don't need to transform the property; it will never change.
12695 
12696   // If nothing changed, just retain the existing expression.
12697   if (!getDerived().AlwaysRebuild() &&
12698       Base.get() == E->getBase())
12699     return E;
12700 
12701   if (E->isExplicitProperty())
12702     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12703                                                    E->getExplicitProperty(),
12704                                                    E->getLocation());
12705 
12706   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12707                                                  SemaRef.Context.PseudoObjectTy,
12708                                                  E->getImplicitPropertyGetter(),
12709                                                  E->getImplicitPropertySetter(),
12710                                                  E->getLocation());
12711 }
12712 
12713 template<typename Derived>
12714 ExprResult
12715 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
12716   // Transform the base expression.
12717   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
12718   if (Base.isInvalid())
12719     return ExprError();
12720 
12721   // Transform the key expression.
12722   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
12723   if (Key.isInvalid())
12724     return ExprError();
12725 
12726   // If nothing changed, just retain the existing expression.
12727   if (!getDerived().AlwaysRebuild() &&
12728       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
12729     return E;
12730 
12731   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
12732                                                   Base.get(), Key.get(),
12733                                                   E->getAtIndexMethodDecl(),
12734                                                   E->setAtIndexMethodDecl());
12735 }
12736 
12737 template<typename Derived>
12738 ExprResult
12739 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
12740   // Transform the base expression.
12741   ExprResult Base = getDerived().TransformExpr(E->getBase());
12742   if (Base.isInvalid())
12743     return ExprError();
12744 
12745   // If nothing changed, just retain the existing expression.
12746   if (!getDerived().AlwaysRebuild() &&
12747       Base.get() == E->getBase())
12748     return E;
12749 
12750   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
12751                                          E->getOpLoc(),
12752                                          E->isArrow());
12753 }
12754 
12755 template<typename Derived>
12756 ExprResult
12757 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
12758   bool ArgumentChanged = false;
12759   SmallVector<Expr*, 8> SubExprs;
12760   SubExprs.reserve(E->getNumSubExprs());
12761   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12762                                   SubExprs, &ArgumentChanged))
12763     return ExprError();
12764 
12765   if (!getDerived().AlwaysRebuild() &&
12766       !ArgumentChanged)
12767     return E;
12768 
12769   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
12770                                                SubExprs,
12771                                                E->getRParenLoc());
12772 }
12773 
12774 template<typename Derived>
12775 ExprResult
12776 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
12777   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
12778   if (SrcExpr.isInvalid())
12779     return ExprError();
12780 
12781   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
12782   if (!Type)
12783     return ExprError();
12784 
12785   if (!getDerived().AlwaysRebuild() &&
12786       Type == E->getTypeSourceInfo() &&
12787       SrcExpr.get() == E->getSrcExpr())
12788     return E;
12789 
12790   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
12791                                                SrcExpr.get(), Type,
12792                                                E->getRParenLoc());
12793 }
12794 
12795 template<typename Derived>
12796 ExprResult
12797 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
12798   BlockDecl *oldBlock = E->getBlockDecl();
12799 
12800   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
12801   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
12802 
12803   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
12804   blockScope->TheDecl->setBlockMissingReturnType(
12805                          oldBlock->blockMissingReturnType());
12806 
12807   SmallVector<ParmVarDecl*, 4> params;
12808   SmallVector<QualType, 4> paramTypes;
12809 
12810   const FunctionProtoType *exprFunctionType = E->getFunctionType();
12811 
12812   // Parameter substitution.
12813   Sema::ExtParameterInfoBuilder extParamInfos;
12814   if (getDerived().TransformFunctionTypeParams(
12815           E->getCaretLocation(), oldBlock->parameters(), nullptr,
12816           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
12817           extParamInfos)) {
12818     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12819     return ExprError();
12820   }
12821 
12822   QualType exprResultType =
12823       getDerived().TransformType(exprFunctionType->getReturnType());
12824 
12825   auto epi = exprFunctionType->getExtProtoInfo();
12826   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
12827 
12828   QualType functionType =
12829     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
12830   blockScope->FunctionType = functionType;
12831 
12832   // Set the parameters on the block decl.
12833   if (!params.empty())
12834     blockScope->TheDecl->setParams(params);
12835 
12836   if (!oldBlock->blockMissingReturnType()) {
12837     blockScope->HasImplicitReturnType = false;
12838     blockScope->ReturnType = exprResultType;
12839   }
12840 
12841   // Transform the body
12842   StmtResult body = getDerived().TransformStmt(E->getBody());
12843   if (body.isInvalid()) {
12844     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12845     return ExprError();
12846   }
12847 
12848 #ifndef NDEBUG
12849   // In builds with assertions, make sure that we captured everything we
12850   // captured before.
12851   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
12852     for (const auto &I : oldBlock->captures()) {
12853       VarDecl *oldCapture = I.getVariable();
12854 
12855       // Ignore parameter packs.
12856       if (oldCapture->isParameterPack())
12857         continue;
12858 
12859       VarDecl *newCapture =
12860         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
12861                                                  oldCapture));
12862       assert(blockScope->CaptureMap.count(newCapture));
12863     }
12864     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
12865   }
12866 #endif
12867 
12868   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
12869                                     /*Scope=*/nullptr);
12870 }
12871 
12872 template<typename Derived>
12873 ExprResult
12874 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12875   llvm_unreachable("Cannot transform asType expressions yet");
12876 }
12877 
12878 template<typename Derived>
12879 ExprResult
12880 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12881   bool ArgumentChanged = false;
12882   SmallVector<Expr*, 8> SubExprs;
12883   SubExprs.reserve(E->getNumSubExprs());
12884   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12885                                   SubExprs, &ArgumentChanged))
12886     return ExprError();
12887 
12888   if (!getDerived().AlwaysRebuild() &&
12889       !ArgumentChanged)
12890     return E;
12891 
12892   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12893                                         E->getOp(), E->getRParenLoc());
12894 }
12895 
12896 //===----------------------------------------------------------------------===//
12897 // Type reconstruction
12898 //===----------------------------------------------------------------------===//
12899 
12900 template<typename Derived>
12901 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12902                                                     SourceLocation Star) {
12903   return SemaRef.BuildPointerType(PointeeType, Star,
12904                                   getDerived().getBaseEntity());
12905 }
12906 
12907 template<typename Derived>
12908 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12909                                                          SourceLocation Star) {
12910   return SemaRef.BuildBlockPointerType(PointeeType, Star,
12911                                        getDerived().getBaseEntity());
12912 }
12913 
12914 template<typename Derived>
12915 QualType
12916 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12917                                              bool WrittenAsLValue,
12918                                              SourceLocation Sigil) {
12919   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12920                                     Sigil, getDerived().getBaseEntity());
12921 }
12922 
12923 template<typename Derived>
12924 QualType
12925 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12926                                                  QualType ClassType,
12927                                                  SourceLocation Sigil) {
12928   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12929                                         getDerived().getBaseEntity());
12930 }
12931 
12932 template<typename Derived>
12933 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12934            const ObjCTypeParamDecl *Decl,
12935            SourceLocation ProtocolLAngleLoc,
12936            ArrayRef<ObjCProtocolDecl *> Protocols,
12937            ArrayRef<SourceLocation> ProtocolLocs,
12938            SourceLocation ProtocolRAngleLoc) {
12939   return SemaRef.BuildObjCTypeParamType(Decl,
12940                                         ProtocolLAngleLoc, Protocols,
12941                                         ProtocolLocs, ProtocolRAngleLoc,
12942                                         /*FailOnError=*/true);
12943 }
12944 
12945 template<typename Derived>
12946 QualType TreeTransform<Derived>::RebuildObjCObjectType(
12947            QualType BaseType,
12948            SourceLocation Loc,
12949            SourceLocation TypeArgsLAngleLoc,
12950            ArrayRef<TypeSourceInfo *> TypeArgs,
12951            SourceLocation TypeArgsRAngleLoc,
12952            SourceLocation ProtocolLAngleLoc,
12953            ArrayRef<ObjCProtocolDecl *> Protocols,
12954            ArrayRef<SourceLocation> ProtocolLocs,
12955            SourceLocation ProtocolRAngleLoc) {
12956   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12957                                      TypeArgs, TypeArgsRAngleLoc,
12958                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
12959                                      ProtocolRAngleLoc,
12960                                      /*FailOnError=*/true);
12961 }
12962 
12963 template<typename Derived>
12964 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12965            QualType PointeeType,
12966            SourceLocation Star) {
12967   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12968 }
12969 
12970 template<typename Derived>
12971 QualType
12972 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12973                                          ArrayType::ArraySizeModifier SizeMod,
12974                                          const llvm::APInt *Size,
12975                                          Expr *SizeExpr,
12976                                          unsigned IndexTypeQuals,
12977                                          SourceRange BracketsRange) {
12978   if (SizeExpr || !Size)
12979     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12980                                   IndexTypeQuals, BracketsRange,
12981                                   getDerived().getBaseEntity());
12982 
12983   QualType Types[] = {
12984     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12985     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12986     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12987   };
12988   const unsigned NumTypes = llvm::array_lengthof(Types);
12989   QualType SizeType;
12990   for (unsigned I = 0; I != NumTypes; ++I)
12991     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12992       SizeType = Types[I];
12993       break;
12994     }
12995 
12996   // Note that we can return a VariableArrayType here in the case where
12997   // the element type was a dependent VariableArrayType.
12998   IntegerLiteral *ArraySize
12999       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
13000                                /*FIXME*/BracketsRange.getBegin());
13001   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
13002                                 IndexTypeQuals, BracketsRange,
13003                                 getDerived().getBaseEntity());
13004 }
13005 
13006 template<typename Derived>
13007 QualType
13008 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
13009                                                  ArrayType::ArraySizeModifier SizeMod,
13010                                                  const llvm::APInt &Size,
13011                                                  Expr *SizeExpr,
13012                                                  unsigned IndexTypeQuals,
13013                                                  SourceRange BracketsRange) {
13014   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
13015                                         IndexTypeQuals, BracketsRange);
13016 }
13017 
13018 template<typename Derived>
13019 QualType
13020 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
13021                                           ArrayType::ArraySizeModifier SizeMod,
13022                                                  unsigned IndexTypeQuals,
13023                                                    SourceRange BracketsRange) {
13024   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
13025                                        IndexTypeQuals, BracketsRange);
13026 }
13027 
13028 template<typename Derived>
13029 QualType
13030 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
13031                                           ArrayType::ArraySizeModifier SizeMod,
13032                                                  Expr *SizeExpr,
13033                                                  unsigned IndexTypeQuals,
13034                                                  SourceRange BracketsRange) {
13035   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
13036                                        SizeExpr,
13037                                        IndexTypeQuals, BracketsRange);
13038 }
13039 
13040 template<typename Derived>
13041 QualType
13042 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
13043                                           ArrayType::ArraySizeModifier SizeMod,
13044                                                        Expr *SizeExpr,
13045                                                        unsigned IndexTypeQuals,
13046                                                    SourceRange BracketsRange) {
13047   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
13048                                        SizeExpr,
13049                                        IndexTypeQuals, BracketsRange);
13050 }
13051 
13052 template <typename Derived>
13053 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
13054     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
13055   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
13056                                           AttributeLoc);
13057 }
13058 
13059 template <typename Derived>
13060 QualType
13061 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
13062                                           unsigned NumElements,
13063                                           VectorType::VectorKind VecKind) {
13064   // FIXME: semantic checking!
13065   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
13066 }
13067 
13068 template <typename Derived>
13069 QualType TreeTransform<Derived>::RebuildDependentVectorType(
13070     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
13071     VectorType::VectorKind VecKind) {
13072   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
13073 }
13074 
13075 template<typename Derived>
13076 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
13077                                                       unsigned NumElements,
13078                                                  SourceLocation AttributeLoc) {
13079   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
13080                           NumElements, true);
13081   IntegerLiteral *VectorSize
13082     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
13083                              AttributeLoc);
13084   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
13085 }
13086 
13087 template<typename Derived>
13088 QualType
13089 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
13090                                                            Expr *SizeExpr,
13091                                                   SourceLocation AttributeLoc) {
13092   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
13093 }
13094 
13095 template<typename Derived>
13096 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
13097     QualType T,
13098     MutableArrayRef<QualType> ParamTypes,
13099     const FunctionProtoType::ExtProtoInfo &EPI) {
13100   return SemaRef.BuildFunctionType(T, ParamTypes,
13101                                    getDerived().getBaseLocation(),
13102                                    getDerived().getBaseEntity(),
13103                                    EPI);
13104 }
13105 
13106 template<typename Derived>
13107 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
13108   return SemaRef.Context.getFunctionNoProtoType(T);
13109 }
13110 
13111 template<typename Derived>
13112 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
13113                                                             Decl *D) {
13114   assert(D && "no decl found");
13115   if (D->isInvalidDecl()) return QualType();
13116 
13117   // FIXME: Doesn't account for ObjCInterfaceDecl!
13118   TypeDecl *Ty;
13119   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
13120     // A valid resolved using typename pack expansion decl can have multiple
13121     // UsingDecls, but they must each have exactly one type, and it must be
13122     // the same type in every case. But we must have at least one expansion!
13123     if (UPD->expansions().empty()) {
13124       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
13125           << UPD->isCXXClassMember() << UPD;
13126       return QualType();
13127     }
13128 
13129     // We might still have some unresolved types. Try to pick a resolved type
13130     // if we can. The final instantiation will check that the remaining
13131     // unresolved types instantiate to the type we pick.
13132     QualType FallbackT;
13133     QualType T;
13134     for (auto *E : UPD->expansions()) {
13135       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
13136       if (ThisT.isNull())
13137         continue;
13138       else if (ThisT->getAs<UnresolvedUsingType>())
13139         FallbackT = ThisT;
13140       else if (T.isNull())
13141         T = ThisT;
13142       else
13143         assert(getSema().Context.hasSameType(ThisT, T) &&
13144                "mismatched resolved types in using pack expansion");
13145     }
13146     return T.isNull() ? FallbackT : T;
13147   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
13148     assert(Using->hasTypename() &&
13149            "UnresolvedUsingTypenameDecl transformed to non-typename using");
13150 
13151     // A valid resolved using typename decl points to exactly one type decl.
13152     assert(++Using->shadow_begin() == Using->shadow_end());
13153     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
13154   } else {
13155     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
13156            "UnresolvedUsingTypenameDecl transformed to non-using decl");
13157     Ty = cast<UnresolvedUsingTypenameDecl>(D);
13158   }
13159 
13160   return SemaRef.Context.getTypeDeclType(Ty);
13161 }
13162 
13163 template<typename Derived>
13164 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
13165                                                        SourceLocation Loc) {
13166   return SemaRef.BuildTypeofExprType(E, Loc);
13167 }
13168 
13169 template<typename Derived>
13170 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
13171   return SemaRef.Context.getTypeOfType(Underlying);
13172 }
13173 
13174 template<typename Derived>
13175 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
13176                                                      SourceLocation Loc) {
13177   return SemaRef.BuildDecltypeType(E, Loc);
13178 }
13179 
13180 template<typename Derived>
13181 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
13182                                             UnaryTransformType::UTTKind UKind,
13183                                             SourceLocation Loc) {
13184   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
13185 }
13186 
13187 template<typename Derived>
13188 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
13189                                                       TemplateName Template,
13190                                              SourceLocation TemplateNameLoc,
13191                                      TemplateArgumentListInfo &TemplateArgs) {
13192   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
13193 }
13194 
13195 template<typename Derived>
13196 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
13197                                                    SourceLocation KWLoc) {
13198   return SemaRef.BuildAtomicType(ValueType, KWLoc);
13199 }
13200 
13201 template<typename Derived>
13202 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
13203                                                  SourceLocation KWLoc,
13204                                                  bool isReadPipe) {
13205   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
13206                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
13207 }
13208 
13209 template<typename Derived>
13210 TemplateName
13211 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13212                                             bool TemplateKW,
13213                                             TemplateDecl *Template) {
13214   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
13215                                                   Template);
13216 }
13217 
13218 template<typename Derived>
13219 TemplateName
13220 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13221                                             SourceLocation TemplateKWLoc,
13222                                             const IdentifierInfo &Name,
13223                                             SourceLocation NameLoc,
13224                                             QualType ObjectType,
13225                                             NamedDecl *FirstQualifierInScope,
13226                                             bool AllowInjectedClassName) {
13227   UnqualifiedId TemplateName;
13228   TemplateName.setIdentifier(&Name, NameLoc);
13229   Sema::TemplateTy Template;
13230   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13231                                        SS, TemplateKWLoc, TemplateName,
13232                                        ParsedType::make(ObjectType),
13233                                        /*EnteringContext=*/false,
13234                                        Template, AllowInjectedClassName);
13235   return Template.get();
13236 }
13237 
13238 template<typename Derived>
13239 TemplateName
13240 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13241                                             SourceLocation TemplateKWLoc,
13242                                             OverloadedOperatorKind Operator,
13243                                             SourceLocation NameLoc,
13244                                             QualType ObjectType,
13245                                             bool AllowInjectedClassName) {
13246   UnqualifiedId Name;
13247   // FIXME: Bogus location information.
13248   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
13249   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
13250   Sema::TemplateTy Template;
13251   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13252                                        SS, TemplateKWLoc, Name,
13253                                        ParsedType::make(ObjectType),
13254                                        /*EnteringContext=*/false,
13255                                        Template, AllowInjectedClassName);
13256   return Template.get();
13257 }
13258 
13259 template<typename Derived>
13260 ExprResult
13261 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
13262                                                    SourceLocation OpLoc,
13263                                                    Expr *OrigCallee,
13264                                                    Expr *First,
13265                                                    Expr *Second) {
13266   Expr *Callee = OrigCallee->IgnoreParenCasts();
13267   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
13268 
13269   if (First->getObjectKind() == OK_ObjCProperty) {
13270     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13271     if (BinaryOperator::isAssignmentOp(Opc))
13272       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
13273                                                  First, Second);
13274     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
13275     if (Result.isInvalid())
13276       return ExprError();
13277     First = Result.get();
13278   }
13279 
13280   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
13281     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
13282     if (Result.isInvalid())
13283       return ExprError();
13284     Second = Result.get();
13285   }
13286 
13287   // Determine whether this should be a builtin operation.
13288   if (Op == OO_Subscript) {
13289     if (!First->getType()->isOverloadableType() &&
13290         !Second->getType()->isOverloadableType())
13291       return getSema().CreateBuiltinArraySubscriptExpr(
13292           First, Callee->getBeginLoc(), Second, OpLoc);
13293   } else if (Op == OO_Arrow) {
13294     // -> is never a builtin operation.
13295     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
13296   } else if (Second == nullptr || isPostIncDec) {
13297     if (!First->getType()->isOverloadableType() ||
13298         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
13299       // The argument is not of overloadable type, or this is an expression
13300       // of the form &Class::member, so try to create a built-in unary
13301       // operation.
13302       UnaryOperatorKind Opc
13303         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13304 
13305       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
13306     }
13307   } else {
13308     if (!First->getType()->isOverloadableType() &&
13309         !Second->getType()->isOverloadableType()) {
13310       // Neither of the arguments is an overloadable type, so try to
13311       // create a built-in binary operation.
13312       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13313       ExprResult Result
13314         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
13315       if (Result.isInvalid())
13316         return ExprError();
13317 
13318       return Result;
13319     }
13320   }
13321 
13322   // Compute the transformed set of functions (and function templates) to be
13323   // used during overload resolution.
13324   UnresolvedSet<16> Functions;
13325   bool RequiresADL;
13326 
13327   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
13328     Functions.append(ULE->decls_begin(), ULE->decls_end());
13329     // If the overload could not be resolved in the template definition
13330     // (because we had a dependent argument), ADL is performed as part of
13331     // template instantiation.
13332     RequiresADL = ULE->requiresADL();
13333   } else {
13334     // If we've resolved this to a particular non-member function, just call
13335     // that function. If we resolved it to a member function,
13336     // CreateOverloaded* will find that function for us.
13337     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
13338     if (!isa<CXXMethodDecl>(ND))
13339       Functions.addDecl(ND);
13340     RequiresADL = false;
13341   }
13342 
13343   // Add any functions found via argument-dependent lookup.
13344   Expr *Args[2] = { First, Second };
13345   unsigned NumArgs = 1 + (Second != nullptr);
13346 
13347   // Create the overloaded operator invocation for unary operators.
13348   if (NumArgs == 1 || isPostIncDec) {
13349     UnaryOperatorKind Opc
13350       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13351     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
13352                                            RequiresADL);
13353   }
13354 
13355   if (Op == OO_Subscript) {
13356     SourceLocation LBrace;
13357     SourceLocation RBrace;
13358 
13359     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
13360         DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
13361         LBrace = SourceLocation::getFromRawEncoding(
13362                     NameLoc.CXXOperatorName.BeginOpNameLoc);
13363         RBrace = SourceLocation::getFromRawEncoding(
13364                     NameLoc.CXXOperatorName.EndOpNameLoc);
13365     } else {
13366       LBrace = Callee->getBeginLoc();
13367       RBrace = OpLoc;
13368     }
13369 
13370     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
13371                                                       First, Second);
13372   }
13373 
13374   // Create the overloaded operator invocation for binary operators.
13375   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13376   ExprResult Result = SemaRef.CreateOverloadedBinOp(
13377       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
13378   if (Result.isInvalid())
13379     return ExprError();
13380 
13381   return Result;
13382 }
13383 
13384 template<typename Derived>
13385 ExprResult
13386 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
13387                                                      SourceLocation OperatorLoc,
13388                                                        bool isArrow,
13389                                                        CXXScopeSpec &SS,
13390                                                      TypeSourceInfo *ScopeType,
13391                                                        SourceLocation CCLoc,
13392                                                        SourceLocation TildeLoc,
13393                                         PseudoDestructorTypeStorage Destroyed) {
13394   QualType BaseType = Base->getType();
13395   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
13396       (!isArrow && !BaseType->getAs<RecordType>()) ||
13397       (isArrow && BaseType->getAs<PointerType>() &&
13398        !BaseType->castAs<PointerType>()->getPointeeType()
13399                                               ->template getAs<RecordType>())){
13400     // This pseudo-destructor expression is still a pseudo-destructor.
13401     return SemaRef.BuildPseudoDestructorExpr(
13402         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
13403         CCLoc, TildeLoc, Destroyed);
13404   }
13405 
13406   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
13407   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
13408                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
13409   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
13410   NameInfo.setNamedTypeInfo(DestroyedType);
13411 
13412   // The scope type is now known to be a valid nested name specifier
13413   // component. Tack it on to the end of the nested name specifier.
13414   if (ScopeType) {
13415     if (!ScopeType->getType()->getAs<TagType>()) {
13416       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
13417                      diag::err_expected_class_or_namespace)
13418           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
13419       return ExprError();
13420     }
13421     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
13422               CCLoc);
13423   }
13424 
13425   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
13426   return getSema().BuildMemberReferenceExpr(Base, BaseType,
13427                                             OperatorLoc, isArrow,
13428                                             SS, TemplateKWLoc,
13429                                             /*FIXME: FirstQualifier*/ nullptr,
13430                                             NameInfo,
13431                                             /*TemplateArgs*/ nullptr,
13432                                             /*S*/nullptr);
13433 }
13434 
13435 template<typename Derived>
13436 StmtResult
13437 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
13438   SourceLocation Loc = S->getBeginLoc();
13439   CapturedDecl *CD = S->getCapturedDecl();
13440   unsigned NumParams = CD->getNumParams();
13441   unsigned ContextParamPos = CD->getContextParamPosition();
13442   SmallVector<Sema::CapturedParamNameType, 4> Params;
13443   for (unsigned I = 0; I < NumParams; ++I) {
13444     if (I != ContextParamPos) {
13445       Params.push_back(
13446              std::make_pair(
13447                   CD->getParam(I)->getName(),
13448                   getDerived().TransformType(CD->getParam(I)->getType())));
13449     } else {
13450       Params.push_back(std::make_pair(StringRef(), QualType()));
13451     }
13452   }
13453   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
13454                                      S->getCapturedRegionKind(), Params);
13455   StmtResult Body;
13456   {
13457     Sema::CompoundScopeRAII CompoundScope(getSema());
13458     Body = getDerived().TransformStmt(S->getCapturedStmt());
13459   }
13460 
13461   if (Body.isInvalid()) {
13462     getSema().ActOnCapturedRegionError();
13463     return StmtError();
13464   }
13465 
13466   return getSema().ActOnCapturedRegionEnd(Body.get());
13467 }
13468 
13469 } // end namespace clang
13470 
13471 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
13472