]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/TreeTransform.h
Vendor import of stripped clang trunk r375505, the last commit before
[FreeBSD/FreeBSD.git] / lib / Sema / TreeTransform.h
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/Stmt.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/StmtObjC.h"
28 #include "clang/AST/StmtOpenMP.h"
29 #include "clang/Sema/Designator.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Ownership.h"
32 #include "clang/Sema/ParsedTemplate.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/SemaDiagnostic.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include <algorithm>
39
40 namespace clang {
41 using namespace sema;
42
43 /// A semantic tree transformation that allows one to transform one
44 /// abstract syntax tree into another.
45 ///
46 /// A new tree transformation is defined by creating a new subclass \c X of
47 /// \c TreeTransform<X> and then overriding certain operations to provide
48 /// behavior specific to that transformation. For example, template
49 /// instantiation is implemented as a tree transformation where the
50 /// transformation of TemplateTypeParmType nodes involves substituting the
51 /// template arguments for their corresponding template parameters; a similar
52 /// transformation is performed for non-type template parameters and
53 /// template template parameters.
54 ///
55 /// This tree-transformation template uses static polymorphism to allow
56 /// subclasses to customize any of its operations. Thus, a subclass can
57 /// override any of the transformation or rebuild operators by providing an
58 /// operation with the same signature as the default implementation. The
59 /// overriding function should not be virtual.
60 ///
61 /// Semantic tree transformations are split into two stages, either of which
62 /// can be replaced by a subclass. The "transform" step transforms an AST node
63 /// or the parts of an AST node using the various transformation functions,
64 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
65 /// node of the appropriate kind from the pieces. The default transformation
66 /// routines recursively transform the operands to composite AST nodes (e.g.,
67 /// the pointee type of a PointerType node) and, if any of those operand nodes
68 /// were changed by the transformation, invokes the rebuild operation to create
69 /// a new AST node.
70 ///
71 /// Subclasses can customize the transformation at various levels. The
72 /// most coarse-grained transformations involve replacing TransformType(),
73 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
74 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
75 /// new implementations.
76 ///
77 /// For more fine-grained transformations, subclasses can replace any of the
78 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
79 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
80 /// replacing TransformTemplateTypeParmType() allows template instantiation
81 /// to substitute template arguments for their corresponding template
82 /// parameters. Additionally, subclasses can override the \c RebuildXXX
83 /// functions to control how AST nodes are rebuilt when their operands change.
84 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
85 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
86 /// be able to use more efficient rebuild steps.
87 ///
88 /// There are a handful of other functions that can be overridden, allowing one
89 /// to avoid traversing nodes that don't need any transformation
90 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
91 /// operands have not changed (\c AlwaysRebuild()), and customize the
92 /// default locations and entity names used for type-checking
93 /// (\c getBaseLocation(), \c getBaseEntity()).
94 template<typename Derived>
95 class TreeTransform {
96   /// Private RAII object that helps us forget and then re-remember
97   /// the template argument corresponding to a partially-substituted parameter
98   /// pack.
99   class ForgetPartiallySubstitutedPackRAII {
100     Derived &Self;
101     TemplateArgument Old;
102
103   public:
104     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
105       Old = Self.ForgetPartiallySubstitutedPack();
106     }
107
108     ~ForgetPartiallySubstitutedPackRAII() {
109       Self.RememberPartiallySubstitutedPack(Old);
110     }
111   };
112
113 protected:
114   Sema &SemaRef;
115
116   /// The set of local declarations that have been transformed, for
117   /// cases where we are forced to build new declarations within the transformer
118   /// rather than in the subclass (e.g., lambda closure types).
119   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
120
121 public:
122   /// Initializes a new tree transformer.
123   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
124
125   /// Retrieves a reference to the derived class.
126   Derived &getDerived() { return static_cast<Derived&>(*this); }
127
128   /// Retrieves a reference to the derived class.
129   const Derived &getDerived() const {
130     return static_cast<const Derived&>(*this);
131   }
132
133   static inline ExprResult Owned(Expr *E) { return E; }
134   static inline StmtResult Owned(Stmt *S) { return S; }
135
136   /// Retrieves a reference to the semantic analysis object used for
137   /// this tree transform.
138   Sema &getSema() const { return SemaRef; }
139
140   /// Whether the transformation should always rebuild AST nodes, even
141   /// if none of the children have changed.
142   ///
143   /// Subclasses may override this function to specify when the transformation
144   /// should rebuild all AST nodes.
145   ///
146   /// We must always rebuild all AST nodes when performing variadic template
147   /// pack expansion, in order to avoid violating the AST invariant that each
148   /// statement node appears at most once in its containing declaration.
149   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
150
151   /// Whether the transformation is forming an expression or statement that
152   /// replaces the original. In this case, we'll reuse mangling numbers from
153   /// existing lambdas.
154   bool ReplacingOriginal() { return false; }
155
156   /// Returns the location of the entity being transformed, if that
157   /// information was not available elsewhere in the AST.
158   ///
159   /// By default, returns no source-location information. Subclasses can
160   /// provide an alternative implementation that provides better location
161   /// information.
162   SourceLocation getBaseLocation() { return SourceLocation(); }
163
164   /// Returns the name of the entity being transformed, if that
165   /// information was not available elsewhere in the AST.
166   ///
167   /// By default, returns an empty name. Subclasses can provide an alternative
168   /// implementation with a more precise name.
169   DeclarationName getBaseEntity() { return DeclarationName(); }
170
171   /// Sets the "base" location and entity when that
172   /// information is known based on another transformation.
173   ///
174   /// By default, the source location and entity are ignored. Subclasses can
175   /// override this function to provide a customized implementation.
176   void setBase(SourceLocation Loc, DeclarationName Entity) { }
177
178   /// RAII object that temporarily sets the base location and entity
179   /// used for reporting diagnostics in types.
180   class TemporaryBase {
181     TreeTransform &Self;
182     SourceLocation OldLocation;
183     DeclarationName OldEntity;
184
185   public:
186     TemporaryBase(TreeTransform &Self, SourceLocation Location,
187                   DeclarationName Entity) : Self(Self) {
188       OldLocation = Self.getDerived().getBaseLocation();
189       OldEntity = Self.getDerived().getBaseEntity();
190
191       if (Location.isValid())
192         Self.getDerived().setBase(Location, Entity);
193     }
194
195     ~TemporaryBase() {
196       Self.getDerived().setBase(OldLocation, OldEntity);
197     }
198   };
199
200   /// Determine whether the given type \p T has already been
201   /// transformed.
202   ///
203   /// Subclasses can provide an alternative implementation of this routine
204   /// to short-circuit evaluation when it is known that a given type will
205   /// not change. For example, template instantiation need not traverse
206   /// non-dependent types.
207   bool AlreadyTransformed(QualType T) {
208     return T.isNull();
209   }
210
211   /// Determine whether the given call argument should be dropped, e.g.,
212   /// because it is a default argument.
213   ///
214   /// Subclasses can provide an alternative implementation of this routine to
215   /// determine which kinds of call arguments get dropped. By default,
216   /// CXXDefaultArgument nodes are dropped (prior to transformation).
217   bool DropCallArgument(Expr *E) {
218     return E->isDefaultArgument();
219   }
220
221   /// Determine whether we should expand a pack expansion with the
222   /// given set of parameter packs into separate arguments by repeatedly
223   /// transforming the pattern.
224   ///
225   /// By default, the transformer never tries to expand pack expansions.
226   /// Subclasses can override this routine to provide different behavior.
227   ///
228   /// \param EllipsisLoc The location of the ellipsis that identifies the
229   /// pack expansion.
230   ///
231   /// \param PatternRange The source range that covers the entire pattern of
232   /// the pack expansion.
233   ///
234   /// \param Unexpanded The set of unexpanded parameter packs within the
235   /// pattern.
236   ///
237   /// \param ShouldExpand Will be set to \c true if the transformer should
238   /// expand the corresponding pack expansions into separate arguments. When
239   /// set, \c NumExpansions must also be set.
240   ///
241   /// \param RetainExpansion Whether the caller should add an unexpanded
242   /// pack expansion after all of the expanded arguments. This is used
243   /// when extending explicitly-specified template argument packs per
244   /// C++0x [temp.arg.explicit]p9.
245   ///
246   /// \param NumExpansions The number of separate arguments that will be in
247   /// the expanded form of the corresponding pack expansion. This is both an
248   /// input and an output parameter, which can be set by the caller if the
249   /// number of expansions is known a priori (e.g., due to a prior substitution)
250   /// and will be set by the callee when the number of expansions is known.
251   /// The callee must set this value when \c ShouldExpand is \c true; it may
252   /// set this value in other cases.
253   ///
254   /// \returns true if an error occurred (e.g., because the parameter packs
255   /// are to be instantiated with arguments of different lengths), false
256   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
257   /// must be set.
258   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
259                                SourceRange PatternRange,
260                                ArrayRef<UnexpandedParameterPack> Unexpanded,
261                                bool &ShouldExpand,
262                                bool &RetainExpansion,
263                                Optional<unsigned> &NumExpansions) {
264     ShouldExpand = false;
265     return false;
266   }
267
268   /// "Forget" about the partially-substituted pack template argument,
269   /// when performing an instantiation that must preserve the parameter pack
270   /// use.
271   ///
272   /// This routine is meant to be overridden by the template instantiator.
273   TemplateArgument ForgetPartiallySubstitutedPack() {
274     return TemplateArgument();
275   }
276
277   /// "Remember" the partially-substituted pack template argument
278   /// after performing an instantiation that must preserve the parameter pack
279   /// use.
280   ///
281   /// This routine is meant to be overridden by the template instantiator.
282   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
283
284   /// Note to the derived class when a function parameter pack is
285   /// being expanded.
286   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
287
288   /// Transforms the given type into another type.
289   ///
290   /// By default, this routine transforms a type by creating a
291   /// TypeSourceInfo for it and delegating to the appropriate
292   /// function.  This is expensive, but we don't mind, because
293   /// this method is deprecated anyway;  all users should be
294   /// switched to storing TypeSourceInfos.
295   ///
296   /// \returns the transformed type.
297   QualType TransformType(QualType T);
298
299   /// Transforms the given type-with-location into a new
300   /// type-with-location.
301   ///
302   /// By default, this routine transforms a type by delegating to the
303   /// appropriate TransformXXXType to build a new type.  Subclasses
304   /// may override this function (to take over all type
305   /// transformations) or some set of the TransformXXXType functions
306   /// to alter the transformation.
307   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
308
309   /// Transform the given type-with-location into a new
310   /// type, collecting location information in the given builder
311   /// as necessary.
312   ///
313   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
314
315   /// Transform a type that is permitted to produce a
316   /// DeducedTemplateSpecializationType.
317   ///
318   /// This is used in the (relatively rare) contexts where it is acceptable
319   /// for transformation to produce a class template type with deduced
320   /// template arguments.
321   /// @{
322   QualType TransformTypeWithDeducedTST(QualType T);
323   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
324   /// @}
325
326   /// The reason why the value of a statement is not discarded, if any.
327   enum StmtDiscardKind {
328     SDK_Discarded,
329     SDK_NotDiscarded,
330     SDK_StmtExprResult,
331   };
332
333   /// Transform the given statement.
334   ///
335   /// By default, this routine transforms a statement by delegating to the
336   /// appropriate TransformXXXStmt function to transform a specific kind of
337   /// statement or the TransformExpr() function to transform an expression.
338   /// Subclasses may override this function to transform statements using some
339   /// other mechanism.
340   ///
341   /// \returns the transformed statement.
342   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
343
344   /// Transform the given statement.
345   ///
346   /// By default, this routine transforms a statement by delegating to the
347   /// appropriate TransformOMPXXXClause function to transform a specific kind
348   /// of clause. Subclasses may override this function to transform statements
349   /// using some other mechanism.
350   ///
351   /// \returns the transformed OpenMP clause.
352   OMPClause *TransformOMPClause(OMPClause *S);
353
354   /// Transform the given attribute.
355   ///
356   /// By default, this routine transforms a statement by delegating to the
357   /// appropriate TransformXXXAttr function to transform a specific kind
358   /// of attribute. Subclasses may override this function to transform
359   /// attributed statements using some other mechanism.
360   ///
361   /// \returns the transformed attribute
362   const Attr *TransformAttr(const Attr *S);
363
364 /// Transform the specified attribute.
365 ///
366 /// Subclasses should override the transformation of attributes with a pragma
367 /// spelling to transform expressions stored within the attribute.
368 ///
369 /// \returns the transformed attribute.
370 #define ATTR(X)
371 #define PRAGMA_SPELLING_ATTR(X)                                                \
372   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
373 #include "clang/Basic/AttrList.inc"
374
375   /// Transform the given expression.
376   ///
377   /// By default, this routine transforms an expression by delegating to the
378   /// appropriate TransformXXXExpr function to build a new expression.
379   /// Subclasses may override this function to transform expressions using some
380   /// other mechanism.
381   ///
382   /// \returns the transformed expression.
383   ExprResult TransformExpr(Expr *E);
384
385   /// Transform the given initializer.
386   ///
387   /// By default, this routine transforms an initializer by stripping off the
388   /// semantic nodes added by initialization, then passing the result to
389   /// TransformExpr or TransformExprs.
390   ///
391   /// \returns the transformed initializer.
392   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
393
394   /// Transform the given list of expressions.
395   ///
396   /// This routine transforms a list of expressions by invoking
397   /// \c TransformExpr() for each subexpression. However, it also provides
398   /// support for variadic templates by expanding any pack expansions (if the
399   /// derived class permits such expansion) along the way. When pack expansions
400   /// are present, the number of outputs may not equal the number of inputs.
401   ///
402   /// \param Inputs The set of expressions to be transformed.
403   ///
404   /// \param NumInputs The number of expressions in \c Inputs.
405   ///
406   /// \param IsCall If \c true, then this transform is being performed on
407   /// function-call arguments, and any arguments that should be dropped, will
408   /// be.
409   ///
410   /// \param Outputs The transformed input expressions will be added to this
411   /// vector.
412   ///
413   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
414   /// due to transformation.
415   ///
416   /// \returns true if an error occurred, false otherwise.
417   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
418                       SmallVectorImpl<Expr *> &Outputs,
419                       bool *ArgChanged = nullptr);
420
421   /// Transform the given declaration, which is referenced from a type
422   /// or expression.
423   ///
424   /// By default, acts as the identity function on declarations, unless the
425   /// transformer has had to transform the declaration itself. Subclasses
426   /// may override this function to provide alternate behavior.
427   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
428     llvm::DenseMap<Decl *, Decl *>::iterator Known
429       = TransformedLocalDecls.find(D);
430     if (Known != TransformedLocalDecls.end())
431       return Known->second;
432
433     return D;
434   }
435
436   /// Transform the specified condition.
437   ///
438   /// By default, this transforms the variable and expression and rebuilds
439   /// the condition.
440   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
441                                            Expr *Expr,
442                                            Sema::ConditionKind Kind);
443
444   /// Transform the attributes associated with the given declaration and
445   /// place them on the new declaration.
446   ///
447   /// By default, this operation does nothing. Subclasses may override this
448   /// behavior to transform attributes.
449   void transformAttrs(Decl *Old, Decl *New) { }
450
451   /// Note that a local declaration has been transformed by this
452   /// transformer.
453   ///
454   /// Local declarations are typically transformed via a call to
455   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
456   /// the transformer itself has to transform the declarations. This routine
457   /// can be overridden by a subclass that keeps track of such mappings.
458   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
459     assert(New.size() == 1 &&
460            "must override transformedLocalDecl if performing pack expansion");
461     TransformedLocalDecls[Old] = New.front();
462   }
463
464   /// Transform the definition of the given declaration.
465   ///
466   /// By default, invokes TransformDecl() to transform the declaration.
467   /// Subclasses may override this function to provide alternate behavior.
468   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
469     return getDerived().TransformDecl(Loc, D);
470   }
471
472   /// Transform the given declaration, which was the first part of a
473   /// nested-name-specifier in a member access expression.
474   ///
475   /// This specific declaration transformation only applies to the first
476   /// identifier in a nested-name-specifier of a member access expression, e.g.,
477   /// the \c T in \c x->T::member
478   ///
479   /// By default, invokes TransformDecl() to transform the declaration.
480   /// Subclasses may override this function to provide alternate behavior.
481   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
482     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
483   }
484
485   /// Transform the set of declarations in an OverloadExpr.
486   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
487                                   LookupResult &R);
488
489   /// Transform the given nested-name-specifier with source-location
490   /// information.
491   ///
492   /// By default, transforms all of the types and declarations within the
493   /// nested-name-specifier. Subclasses may override this function to provide
494   /// alternate behavior.
495   NestedNameSpecifierLoc
496   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
497                                   QualType ObjectType = QualType(),
498                                   NamedDecl *FirstQualifierInScope = nullptr);
499
500   /// Transform the given declaration name.
501   ///
502   /// By default, transforms the types of conversion function, constructor,
503   /// and destructor names and then (if needed) rebuilds the declaration name.
504   /// Identifiers and selectors are returned unmodified. Sublcasses may
505   /// override this function to provide alternate behavior.
506   DeclarationNameInfo
507   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
508
509   /// Transform the given template name.
510   ///
511   /// \param SS The nested-name-specifier that qualifies the template
512   /// name. This nested-name-specifier must already have been transformed.
513   ///
514   /// \param Name The template name to transform.
515   ///
516   /// \param NameLoc The source location of the template name.
517   ///
518   /// \param ObjectType If we're translating a template name within a member
519   /// access expression, this is the type of the object whose member template
520   /// is being referenced.
521   ///
522   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
523   /// also refers to a name within the current (lexical) scope, this is the
524   /// declaration it refers to.
525   ///
526   /// By default, transforms the template name by transforming the declarations
527   /// and nested-name-specifiers that occur within the template name.
528   /// Subclasses may override this function to provide alternate behavior.
529   TemplateName
530   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
531                         SourceLocation NameLoc,
532                         QualType ObjectType = QualType(),
533                         NamedDecl *FirstQualifierInScope = nullptr,
534                         bool AllowInjectedClassName = false);
535
536   /// Transform the given template argument.
537   ///
538   /// By default, this operation transforms the type, expression, or
539   /// declaration stored within the template argument and constructs a
540   /// new template argument from the transformed result. Subclasses may
541   /// override this function to provide alternate behavior.
542   ///
543   /// Returns true if there was an error.
544   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
545                                  TemplateArgumentLoc &Output,
546                                  bool Uneval = false);
547
548   /// Transform the given set of template arguments.
549   ///
550   /// By default, this operation transforms all of the template arguments
551   /// in the input set using \c TransformTemplateArgument(), and appends
552   /// the transformed arguments to the output list.
553   ///
554   /// Note that this overload of \c TransformTemplateArguments() is merely
555   /// a convenience function. Subclasses that wish to override this behavior
556   /// should override the iterator-based member template version.
557   ///
558   /// \param Inputs The set of template arguments to be transformed.
559   ///
560   /// \param NumInputs The number of template arguments in \p Inputs.
561   ///
562   /// \param Outputs The set of transformed template arguments output by this
563   /// routine.
564   ///
565   /// Returns true if an error occurred.
566   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
567                                   unsigned NumInputs,
568                                   TemplateArgumentListInfo &Outputs,
569                                   bool Uneval = false) {
570     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
571                                       Uneval);
572   }
573
574   /// Transform the given set of template arguments.
575   ///
576   /// By default, this operation transforms all of the template arguments
577   /// in the input set using \c TransformTemplateArgument(), and appends
578   /// the transformed arguments to the output list.
579   ///
580   /// \param First An iterator to the first template argument.
581   ///
582   /// \param Last An iterator one step past the last template argument.
583   ///
584   /// \param Outputs The set of transformed template arguments output by this
585   /// routine.
586   ///
587   /// Returns true if an error occurred.
588   template<typename InputIterator>
589   bool TransformTemplateArguments(InputIterator First,
590                                   InputIterator Last,
591                                   TemplateArgumentListInfo &Outputs,
592                                   bool Uneval = false);
593
594   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
595   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
596                                  TemplateArgumentLoc &ArgLoc);
597
598   /// Fakes up a TypeSourceInfo for a type.
599   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
600     return SemaRef.Context.getTrivialTypeSourceInfo(T,
601                        getDerived().getBaseLocation());
602   }
603
604 #define ABSTRACT_TYPELOC(CLASS, PARENT)
605 #define TYPELOC(CLASS, PARENT)                                   \
606   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
607 #include "clang/AST/TypeLocNodes.def"
608
609   template<typename Fn>
610   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
611                                       FunctionProtoTypeLoc TL,
612                                       CXXRecordDecl *ThisContext,
613                                       Qualifiers ThisTypeQuals,
614                                       Fn TransformExceptionSpec);
615
616   bool TransformExceptionSpec(SourceLocation Loc,
617                               FunctionProtoType::ExceptionSpecInfo &ESI,
618                               SmallVectorImpl<QualType> &Exceptions,
619                               bool &Changed);
620
621   StmtResult TransformSEHHandler(Stmt *Handler);
622
623   QualType
624   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
625                                       TemplateSpecializationTypeLoc TL,
626                                       TemplateName Template);
627
628   QualType
629   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
630                                       DependentTemplateSpecializationTypeLoc TL,
631                                                TemplateName Template,
632                                                CXXScopeSpec &SS);
633
634   QualType TransformDependentTemplateSpecializationType(
635       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
636       NestedNameSpecifierLoc QualifierLoc);
637
638   /// Transforms the parameters of a function type into the
639   /// given vectors.
640   ///
641   /// The result vectors should be kept in sync; null entries in the
642   /// variables vector are acceptable.
643   ///
644   /// Return true on error.
645   bool TransformFunctionTypeParams(
646       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
647       const QualType *ParamTypes,
648       const FunctionProtoType::ExtParameterInfo *ParamInfos,
649       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
650       Sema::ExtParameterInfoBuilder &PInfos);
651
652   /// Transforms a single function-type parameter.  Return null
653   /// on error.
654   ///
655   /// \param indexAdjustment - A number to add to the parameter's
656   ///   scope index;  can be negative
657   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
658                                           int indexAdjustment,
659                                           Optional<unsigned> NumExpansions,
660                                           bool ExpectParameterPack);
661
662   /// Transform the body of a lambda-expression.
663   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
664   /// Alternative implementation of TransformLambdaBody that skips transforming
665   /// the body.
666   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
667
668   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
669
670   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
671   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
672
673   TemplateParameterList *TransformTemplateParameterList(
674         TemplateParameterList *TPL) {
675     return TPL;
676   }
677
678   ExprResult TransformAddressOfOperand(Expr *E);
679
680   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
681                                                 bool IsAddressOfOperand,
682                                                 TypeSourceInfo **RecoveryTSI);
683
684   ExprResult TransformParenDependentScopeDeclRefExpr(
685       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
686       TypeSourceInfo **RecoveryTSI);
687
688   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
689
690 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
691 // amount of stack usage with clang.
692 #define STMT(Node, Parent)                        \
693   LLVM_ATTRIBUTE_NOINLINE \
694   StmtResult Transform##Node(Node *S);
695 #define VALUESTMT(Node, Parent)                   \
696   LLVM_ATTRIBUTE_NOINLINE \
697   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
698 #define EXPR(Node, Parent)                        \
699   LLVM_ATTRIBUTE_NOINLINE \
700   ExprResult Transform##Node(Node *E);
701 #define ABSTRACT_STMT(Stmt)
702 #include "clang/AST/StmtNodes.inc"
703
704 #define OPENMP_CLAUSE(Name, Class)                        \
705   LLVM_ATTRIBUTE_NOINLINE \
706   OMPClause *Transform ## Class(Class *S);
707 #include "clang/Basic/OpenMPKinds.def"
708
709   /// Build a new qualified type given its unqualified type and type location.
710   ///
711   /// By default, this routine adds type qualifiers only to types that can
712   /// have qualifiers, and silently suppresses those qualifiers that are not
713   /// permitted. Subclasses may override this routine to provide different
714   /// behavior.
715   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
716
717   /// Build a new pointer type given its pointee type.
718   ///
719   /// By default, performs semantic analysis when building the pointer type.
720   /// Subclasses may override this routine to provide different behavior.
721   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
722
723   /// Build a new block pointer type given its pointee type.
724   ///
725   /// By default, performs semantic analysis when building the block pointer
726   /// type. Subclasses may override this routine to provide different behavior.
727   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
728
729   /// Build a new reference type given the type it references.
730   ///
731   /// By default, performs semantic analysis when building the
732   /// reference type. Subclasses may override this routine to provide
733   /// different behavior.
734   ///
735   /// \param LValue whether the type was written with an lvalue sigil
736   /// or an rvalue sigil.
737   QualType RebuildReferenceType(QualType ReferentType,
738                                 bool LValue,
739                                 SourceLocation Sigil);
740
741   /// Build a new member pointer type given the pointee type and the
742   /// class type it refers into.
743   ///
744   /// By default, performs semantic analysis when building the member pointer
745   /// type. Subclasses may override this routine to provide different behavior.
746   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
747                                     SourceLocation Sigil);
748
749   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
750                                     SourceLocation ProtocolLAngleLoc,
751                                     ArrayRef<ObjCProtocolDecl *> Protocols,
752                                     ArrayRef<SourceLocation> ProtocolLocs,
753                                     SourceLocation ProtocolRAngleLoc);
754
755   /// Build an Objective-C object type.
756   ///
757   /// By default, performs semantic analysis when building the object type.
758   /// Subclasses may override this routine to provide different behavior.
759   QualType RebuildObjCObjectType(QualType BaseType,
760                                  SourceLocation Loc,
761                                  SourceLocation TypeArgsLAngleLoc,
762                                  ArrayRef<TypeSourceInfo *> TypeArgs,
763                                  SourceLocation TypeArgsRAngleLoc,
764                                  SourceLocation ProtocolLAngleLoc,
765                                  ArrayRef<ObjCProtocolDecl *> Protocols,
766                                  ArrayRef<SourceLocation> ProtocolLocs,
767                                  SourceLocation ProtocolRAngleLoc);
768
769   /// Build a new Objective-C object pointer type given the pointee type.
770   ///
771   /// By default, directly builds the pointer type, with no additional semantic
772   /// analysis.
773   QualType RebuildObjCObjectPointerType(QualType PointeeType,
774                                         SourceLocation Star);
775
776   /// Build a new array type given the element type, size
777   /// modifier, size of the array (if known), size expression, and index type
778   /// qualifiers.
779   ///
780   /// By default, performs semantic analysis when building the array type.
781   /// Subclasses may override this routine to provide different behavior.
782   /// Also by default, all of the other Rebuild*Array
783   QualType RebuildArrayType(QualType ElementType,
784                             ArrayType::ArraySizeModifier SizeMod,
785                             const llvm::APInt *Size,
786                             Expr *SizeExpr,
787                             unsigned IndexTypeQuals,
788                             SourceRange BracketsRange);
789
790   /// Build a new constant array type given the element type, size
791   /// modifier, (known) size of the array, and index type qualifiers.
792   ///
793   /// By default, performs semantic analysis when building the array type.
794   /// Subclasses may override this routine to provide different behavior.
795   QualType RebuildConstantArrayType(QualType ElementType,
796                                     ArrayType::ArraySizeModifier SizeMod,
797                                     const llvm::APInt &Size,
798                                     Expr *SizeExpr,
799                                     unsigned IndexTypeQuals,
800                                     SourceRange BracketsRange);
801
802   /// Build a new incomplete array type given the element type, size
803   /// modifier, and index type qualifiers.
804   ///
805   /// By default, performs semantic analysis when building the array type.
806   /// Subclasses may override this routine to provide different behavior.
807   QualType RebuildIncompleteArrayType(QualType ElementType,
808                                       ArrayType::ArraySizeModifier SizeMod,
809                                       unsigned IndexTypeQuals,
810                                       SourceRange BracketsRange);
811
812   /// Build a new variable-length array type given the element type,
813   /// size modifier, size expression, and index type qualifiers.
814   ///
815   /// By default, performs semantic analysis when building the array type.
816   /// Subclasses may override this routine to provide different behavior.
817   QualType RebuildVariableArrayType(QualType ElementType,
818                                     ArrayType::ArraySizeModifier SizeMod,
819                                     Expr *SizeExpr,
820                                     unsigned IndexTypeQuals,
821                                     SourceRange BracketsRange);
822
823   /// Build a new dependent-sized array type given the element type,
824   /// size modifier, size expression, and index type qualifiers.
825   ///
826   /// By default, performs semantic analysis when building the array type.
827   /// Subclasses may override this routine to provide different behavior.
828   QualType RebuildDependentSizedArrayType(QualType ElementType,
829                                           ArrayType::ArraySizeModifier SizeMod,
830                                           Expr *SizeExpr,
831                                           unsigned IndexTypeQuals,
832                                           SourceRange BracketsRange);
833
834   /// Build a new vector type given the element type and
835   /// number of elements.
836   ///
837   /// By default, performs semantic analysis when building the vector type.
838   /// Subclasses may override this routine to provide different behavior.
839   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
840                              VectorType::VectorKind VecKind);
841
842   /// Build a new potentially dependently-sized extended vector type
843   /// given the element type and number of elements.
844   ///
845   /// By default, performs semantic analysis when building the vector type.
846   /// Subclasses may override this routine to provide different behavior.
847   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
848                                            SourceLocation AttributeLoc,
849                                            VectorType::VectorKind);
850
851   /// Build a new extended vector type given the element type and
852   /// number of elements.
853   ///
854   /// By default, performs semantic analysis when building the vector type.
855   /// Subclasses may override this routine to provide different behavior.
856   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
857                                 SourceLocation AttributeLoc);
858
859   /// Build a new potentially dependently-sized extended vector type
860   /// given the element type and number of elements.
861   ///
862   /// By default, performs semantic analysis when building the vector type.
863   /// Subclasses may override this routine to provide different behavior.
864   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
865                                               Expr *SizeExpr,
866                                               SourceLocation AttributeLoc);
867
868   /// Build a new DependentAddressSpaceType or return the pointee
869   /// type variable with the correct address space (retrieved from
870   /// AddrSpaceExpr) applied to it. The former will be returned in cases
871   /// where the address space remains dependent.
872   ///
873   /// By default, performs semantic analysis when building the type with address
874   /// space applied. Subclasses may override this routine to provide different
875   /// behavior.
876   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
877                                             Expr *AddrSpaceExpr,
878                                             SourceLocation AttributeLoc);
879
880   /// Build a new function type.
881   ///
882   /// By default, performs semantic analysis when building the function type.
883   /// Subclasses may override this routine to provide different behavior.
884   QualType RebuildFunctionProtoType(QualType T,
885                                     MutableArrayRef<QualType> ParamTypes,
886                                     const FunctionProtoType::ExtProtoInfo &EPI);
887
888   /// Build a new unprototyped function type.
889   QualType RebuildFunctionNoProtoType(QualType ResultType);
890
891   /// Rebuild an unresolved typename type, given the decl that
892   /// the UnresolvedUsingTypenameDecl was transformed to.
893   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
894
895   /// Build a new typedef type.
896   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
897     return SemaRef.Context.getTypeDeclType(Typedef);
898   }
899
900   /// Build a new MacroDefined type.
901   QualType RebuildMacroQualifiedType(QualType T,
902                                      const IdentifierInfo *MacroII) {
903     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
904   }
905
906   /// Build a new class/struct/union type.
907   QualType RebuildRecordType(RecordDecl *Record) {
908     return SemaRef.Context.getTypeDeclType(Record);
909   }
910
911   /// Build a new Enum type.
912   QualType RebuildEnumType(EnumDecl *Enum) {
913     return SemaRef.Context.getTypeDeclType(Enum);
914   }
915
916   /// Build a new typeof(expr) type.
917   ///
918   /// By default, performs semantic analysis when building the typeof type.
919   /// Subclasses may override this routine to provide different behavior.
920   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
921
922   /// Build a new typeof(type) type.
923   ///
924   /// By default, builds a new TypeOfType with the given underlying type.
925   QualType RebuildTypeOfType(QualType Underlying);
926
927   /// Build a new unary transform type.
928   QualType RebuildUnaryTransformType(QualType BaseType,
929                                      UnaryTransformType::UTTKind UKind,
930                                      SourceLocation Loc);
931
932   /// Build a new C++11 decltype type.
933   ///
934   /// By default, performs semantic analysis when building the decltype type.
935   /// Subclasses may override this routine to provide different behavior.
936   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
937
938   /// Build a new C++11 auto type.
939   ///
940   /// By default, builds a new AutoType with the given deduced type.
941   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
942     // Note, IsDependent is always false here: we implicitly convert an 'auto'
943     // which has been deduced to a dependent type into an undeduced 'auto', so
944     // that we'll retry deduction after the transformation.
945     return SemaRef.Context.getAutoType(Deduced, Keyword,
946                                        /*IsDependent*/ false);
947   }
948
949   /// By default, builds a new DeducedTemplateSpecializationType with the given
950   /// deduced type.
951   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
952       QualType Deduced) {
953     return SemaRef.Context.getDeducedTemplateSpecializationType(
954         Template, Deduced, /*IsDependent*/ false);
955   }
956
957   /// Build a new template specialization type.
958   ///
959   /// By default, performs semantic analysis when building the template
960   /// specialization type. Subclasses may override this routine to provide
961   /// different behavior.
962   QualType RebuildTemplateSpecializationType(TemplateName Template,
963                                              SourceLocation TemplateLoc,
964                                              TemplateArgumentListInfo &Args);
965
966   /// Build a new parenthesized type.
967   ///
968   /// By default, builds a new ParenType type from the inner type.
969   /// Subclasses may override this routine to provide different behavior.
970   QualType RebuildParenType(QualType InnerType) {
971     return SemaRef.BuildParenType(InnerType);
972   }
973
974   /// Build a new qualified name type.
975   ///
976   /// By default, builds a new ElaboratedType type from the keyword,
977   /// the nested-name-specifier and the named type.
978   /// Subclasses may override this routine to provide different behavior.
979   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
980                                  ElaboratedTypeKeyword Keyword,
981                                  NestedNameSpecifierLoc QualifierLoc,
982                                  QualType Named) {
983     return SemaRef.Context.getElaboratedType(Keyword,
984                                          QualifierLoc.getNestedNameSpecifier(),
985                                              Named);
986   }
987
988   /// Build a new typename type that refers to a template-id.
989   ///
990   /// By default, builds a new DependentNameType type from the
991   /// nested-name-specifier and the given type. Subclasses may override
992   /// this routine to provide different behavior.
993   QualType RebuildDependentTemplateSpecializationType(
994                                           ElaboratedTypeKeyword Keyword,
995                                           NestedNameSpecifierLoc QualifierLoc,
996                                           SourceLocation TemplateKWLoc,
997                                           const IdentifierInfo *Name,
998                                           SourceLocation NameLoc,
999                                           TemplateArgumentListInfo &Args,
1000                                           bool AllowInjectedClassName) {
1001     // Rebuild the template name.
1002     // TODO: avoid TemplateName abstraction
1003     CXXScopeSpec SS;
1004     SS.Adopt(QualifierLoc);
1005     TemplateName InstName = getDerived().RebuildTemplateName(
1006         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1007         AllowInjectedClassName);
1008
1009     if (InstName.isNull())
1010       return QualType();
1011
1012     // If it's still dependent, make a dependent specialization.
1013     if (InstName.getAsDependentTemplateName())
1014       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1015                                           QualifierLoc.getNestedNameSpecifier(),
1016                                                                     Name,
1017                                                                     Args);
1018
1019     // Otherwise, make an elaborated type wrapping a non-dependent
1020     // specialization.
1021     QualType T =
1022     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1023     if (T.isNull()) return QualType();
1024
1025     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1026       return T;
1027
1028     return SemaRef.Context.getElaboratedType(Keyword,
1029                                        QualifierLoc.getNestedNameSpecifier(),
1030                                              T);
1031   }
1032
1033   /// Build a new typename type that refers to an identifier.
1034   ///
1035   /// By default, performs semantic analysis when building the typename type
1036   /// (or elaborated type). Subclasses may override this routine to provide
1037   /// different behavior.
1038   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1039                                     SourceLocation KeywordLoc,
1040                                     NestedNameSpecifierLoc QualifierLoc,
1041                                     const IdentifierInfo *Id,
1042                                     SourceLocation IdLoc,
1043                                     bool DeducedTSTContext) {
1044     CXXScopeSpec SS;
1045     SS.Adopt(QualifierLoc);
1046
1047     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1048       // If the name is still dependent, just build a new dependent name type.
1049       if (!SemaRef.computeDeclContext(SS))
1050         return SemaRef.Context.getDependentNameType(Keyword,
1051                                           QualifierLoc.getNestedNameSpecifier(),
1052                                                     Id);
1053     }
1054
1055     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1056       QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1057                                              *Id, IdLoc);
1058       // If a dependent name resolves to a deduced template specialization type,
1059       // check that we're in one of the syntactic contexts permitting it.
1060       if (!DeducedTSTContext) {
1061         if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1062                 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1063           SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1064             << (int)SemaRef.getTemplateNameKindForDiagnostics(
1065                    Deduced->getTemplateName())
1066             << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1067           if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1068             SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1069           return QualType();
1070         }
1071       }
1072       return T;
1073     }
1074
1075     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1076
1077     // We had a dependent elaborated-type-specifier that has been transformed
1078     // into a non-dependent elaborated-type-specifier. Find the tag we're
1079     // referring to.
1080     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1081     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1082     if (!DC)
1083       return QualType();
1084
1085     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1086       return QualType();
1087
1088     TagDecl *Tag = nullptr;
1089     SemaRef.LookupQualifiedName(Result, DC);
1090     switch (Result.getResultKind()) {
1091       case LookupResult::NotFound:
1092       case LookupResult::NotFoundInCurrentInstantiation:
1093         break;
1094
1095       case LookupResult::Found:
1096         Tag = Result.getAsSingle<TagDecl>();
1097         break;
1098
1099       case LookupResult::FoundOverloaded:
1100       case LookupResult::FoundUnresolvedValue:
1101         llvm_unreachable("Tag lookup cannot find non-tags");
1102
1103       case LookupResult::Ambiguous:
1104         // Let the LookupResult structure handle ambiguities.
1105         return QualType();
1106     }
1107
1108     if (!Tag) {
1109       // Check where the name exists but isn't a tag type and use that to emit
1110       // better diagnostics.
1111       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1112       SemaRef.LookupQualifiedName(Result, DC);
1113       switch (Result.getResultKind()) {
1114         case LookupResult::Found:
1115         case LookupResult::FoundOverloaded:
1116         case LookupResult::FoundUnresolvedValue: {
1117           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1118           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1119           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1120                                                                << NTK << Kind;
1121           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1122           break;
1123         }
1124         default:
1125           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1126               << Kind << Id << DC << QualifierLoc.getSourceRange();
1127           break;
1128       }
1129       return QualType();
1130     }
1131
1132     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1133                                               IdLoc, Id)) {
1134       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1135       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1136       return QualType();
1137     }
1138
1139     // Build the elaborated-type-specifier type.
1140     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1141     return SemaRef.Context.getElaboratedType(Keyword,
1142                                          QualifierLoc.getNestedNameSpecifier(),
1143                                              T);
1144   }
1145
1146   /// Build a new pack expansion type.
1147   ///
1148   /// By default, builds a new PackExpansionType type from the given pattern.
1149   /// Subclasses may override this routine to provide different behavior.
1150   QualType RebuildPackExpansionType(QualType Pattern,
1151                                     SourceRange PatternRange,
1152                                     SourceLocation EllipsisLoc,
1153                                     Optional<unsigned> NumExpansions) {
1154     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1155                                         NumExpansions);
1156   }
1157
1158   /// Build a new atomic type given its value type.
1159   ///
1160   /// By default, performs semantic analysis when building the atomic type.
1161   /// Subclasses may override this routine to provide different behavior.
1162   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1163
1164   /// Build a new pipe type given its value type.
1165   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1166                            bool isReadPipe);
1167
1168   /// Build a new template name given a nested name specifier, a flag
1169   /// indicating whether the "template" keyword was provided, and the template
1170   /// that the template name refers to.
1171   ///
1172   /// By default, builds the new template name directly. Subclasses may override
1173   /// this routine to provide different behavior.
1174   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1175                                    bool TemplateKW,
1176                                    TemplateDecl *Template);
1177
1178   /// Build a new template name given a nested name specifier and the
1179   /// name that is referred to as a template.
1180   ///
1181   /// By default, performs semantic analysis to determine whether the name can
1182   /// be resolved to a specific template, then builds the appropriate kind of
1183   /// template name. Subclasses may override this routine to provide different
1184   /// behavior.
1185   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1186                                    SourceLocation TemplateKWLoc,
1187                                    const IdentifierInfo &Name,
1188                                    SourceLocation NameLoc, QualType ObjectType,
1189                                    NamedDecl *FirstQualifierInScope,
1190                                    bool AllowInjectedClassName);
1191
1192   /// Build a new template name given a nested name specifier and the
1193   /// overloaded operator name that is referred to as a template.
1194   ///
1195   /// By default, performs semantic analysis to determine whether the name can
1196   /// be resolved to a specific template, then builds the appropriate kind of
1197   /// template name. Subclasses may override this routine to provide different
1198   /// behavior.
1199   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1200                                    SourceLocation TemplateKWLoc,
1201                                    OverloadedOperatorKind Operator,
1202                                    SourceLocation NameLoc, QualType ObjectType,
1203                                    bool AllowInjectedClassName);
1204
1205   /// Build a new template name given a template template parameter pack
1206   /// and the
1207   ///
1208   /// By default, performs semantic analysis to determine whether the name can
1209   /// be resolved to a specific template, then builds the appropriate kind of
1210   /// template name. Subclasses may override this routine to provide different
1211   /// behavior.
1212   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1213                                    const TemplateArgument &ArgPack) {
1214     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1215   }
1216
1217   /// Build a new compound statement.
1218   ///
1219   /// By default, performs semantic analysis to build the new statement.
1220   /// Subclasses may override this routine to provide different behavior.
1221   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1222                                        MultiStmtArg Statements,
1223                                        SourceLocation RBraceLoc,
1224                                        bool IsStmtExpr) {
1225     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1226                                        IsStmtExpr);
1227   }
1228
1229   /// Build a new case statement.
1230   ///
1231   /// By default, performs semantic analysis to build the new statement.
1232   /// Subclasses may override this routine to provide different behavior.
1233   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1234                                    Expr *LHS,
1235                                    SourceLocation EllipsisLoc,
1236                                    Expr *RHS,
1237                                    SourceLocation ColonLoc) {
1238     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1239                                    ColonLoc);
1240   }
1241
1242   /// Attach the body to a new case statement.
1243   ///
1244   /// By default, performs semantic analysis to build the new statement.
1245   /// Subclasses may override this routine to provide different behavior.
1246   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1247     getSema().ActOnCaseStmtBody(S, Body);
1248     return S;
1249   }
1250
1251   /// Build a new default statement.
1252   ///
1253   /// By default, performs semantic analysis to build the new statement.
1254   /// Subclasses may override this routine to provide different behavior.
1255   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1256                                       SourceLocation ColonLoc,
1257                                       Stmt *SubStmt) {
1258     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1259                                       /*CurScope=*/nullptr);
1260   }
1261
1262   /// Build a new label statement.
1263   ///
1264   /// By default, performs semantic analysis to build the new statement.
1265   /// Subclasses may override this routine to provide different behavior.
1266   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1267                               SourceLocation ColonLoc, Stmt *SubStmt) {
1268     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1269   }
1270
1271   /// Build a new label statement.
1272   ///
1273   /// By default, performs semantic analysis to build the new statement.
1274   /// Subclasses may override this routine to provide different behavior.
1275   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1276                                    ArrayRef<const Attr*> Attrs,
1277                                    Stmt *SubStmt) {
1278     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1279   }
1280
1281   /// Build a new "if" statement.
1282   ///
1283   /// By default, performs semantic analysis to build the new statement.
1284   /// Subclasses may override this routine to provide different behavior.
1285   StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1286                            Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1287                            SourceLocation ElseLoc, Stmt *Else) {
1288     return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1289                                  ElseLoc, Else);
1290   }
1291
1292   /// Start building a new switch statement.
1293   ///
1294   /// By default, performs semantic analysis to build the new statement.
1295   /// Subclasses may override this routine to provide different behavior.
1296   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1297                                     Sema::ConditionResult Cond) {
1298     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1299   }
1300
1301   /// Attach the body to the switch statement.
1302   ///
1303   /// By default, performs semantic analysis to build the new statement.
1304   /// Subclasses may override this routine to provide different behavior.
1305   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1306                                    Stmt *Switch, Stmt *Body) {
1307     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1308   }
1309
1310   /// Build a new while statement.
1311   ///
1312   /// By default, performs semantic analysis to build the new statement.
1313   /// Subclasses may override this routine to provide different behavior.
1314   StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1315                               Sema::ConditionResult Cond, Stmt *Body) {
1316     return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1317   }
1318
1319   /// Build a new do-while statement.
1320   ///
1321   /// By default, performs semantic analysis to build the new statement.
1322   /// Subclasses may override this routine to provide different behavior.
1323   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1324                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1325                            Expr *Cond, SourceLocation RParenLoc) {
1326     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1327                                  Cond, RParenLoc);
1328   }
1329
1330   /// Build a new for statement.
1331   ///
1332   /// By default, performs semantic analysis to build the new statement.
1333   /// Subclasses may override this routine to provide different behavior.
1334   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1335                             Stmt *Init, Sema::ConditionResult Cond,
1336                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1337                             Stmt *Body) {
1338     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1339                                   Inc, RParenLoc, Body);
1340   }
1341
1342   /// Build a new goto statement.
1343   ///
1344   /// By default, performs semantic analysis to build the new statement.
1345   /// Subclasses may override this routine to provide different behavior.
1346   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1347                              LabelDecl *Label) {
1348     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1349   }
1350
1351   /// Build a new indirect goto statement.
1352   ///
1353   /// By default, performs semantic analysis to build the new statement.
1354   /// Subclasses may override this routine to provide different behavior.
1355   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1356                                      SourceLocation StarLoc,
1357                                      Expr *Target) {
1358     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1359   }
1360
1361   /// Build a new return statement.
1362   ///
1363   /// By default, performs semantic analysis to build the new statement.
1364   /// Subclasses may override this routine to provide different behavior.
1365   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1366     return getSema().BuildReturnStmt(ReturnLoc, Result);
1367   }
1368
1369   /// Build a new declaration statement.
1370   ///
1371   /// By default, performs semantic analysis to build the new statement.
1372   /// Subclasses may override this routine to provide different behavior.
1373   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1374                              SourceLocation StartLoc, SourceLocation EndLoc) {
1375     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1376     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1377   }
1378
1379   /// Build a new inline asm statement.
1380   ///
1381   /// By default, performs semantic analysis to build the new statement.
1382   /// Subclasses may override this routine to provide different behavior.
1383   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1384                                bool IsVolatile, unsigned NumOutputs,
1385                                unsigned NumInputs, IdentifierInfo **Names,
1386                                MultiExprArg Constraints, MultiExprArg Exprs,
1387                                Expr *AsmString, MultiExprArg Clobbers,
1388                                unsigned NumLabels,
1389                                SourceLocation RParenLoc) {
1390     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1391                                      NumInputs, Names, Constraints, Exprs,
1392                                      AsmString, Clobbers, NumLabels, RParenLoc);
1393   }
1394
1395   /// Build a new MS style inline asm statement.
1396   ///
1397   /// By default, performs semantic analysis to build the new statement.
1398   /// Subclasses may override this routine to provide different behavior.
1399   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1400                               ArrayRef<Token> AsmToks,
1401                               StringRef AsmString,
1402                               unsigned NumOutputs, unsigned NumInputs,
1403                               ArrayRef<StringRef> Constraints,
1404                               ArrayRef<StringRef> Clobbers,
1405                               ArrayRef<Expr*> Exprs,
1406                               SourceLocation EndLoc) {
1407     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1408                                     NumOutputs, NumInputs,
1409                                     Constraints, Clobbers, Exprs, EndLoc);
1410   }
1411
1412   /// Build a new co_return statement.
1413   ///
1414   /// By default, performs semantic analysis to build the new statement.
1415   /// Subclasses may override this routine to provide different behavior.
1416   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1417                                  bool IsImplicit) {
1418     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1419   }
1420
1421   /// Build a new co_await expression.
1422   ///
1423   /// By default, performs semantic analysis to build the new expression.
1424   /// Subclasses may override this routine to provide different behavior.
1425   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1426                                 bool IsImplicit) {
1427     return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1428   }
1429
1430   /// Build a new co_await expression.
1431   ///
1432   /// By default, performs semantic analysis to build the new expression.
1433   /// Subclasses may override this routine to provide different behavior.
1434   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1435                                          Expr *Result,
1436                                          UnresolvedLookupExpr *Lookup) {
1437     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1438   }
1439
1440   /// Build a new co_yield expression.
1441   ///
1442   /// By default, performs semantic analysis to build the new expression.
1443   /// Subclasses may override this routine to provide different behavior.
1444   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1445     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1446   }
1447
1448   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1449     return getSema().BuildCoroutineBodyStmt(Args);
1450   }
1451
1452   /// Build a new Objective-C \@try statement.
1453   ///
1454   /// By default, performs semantic analysis to build the new statement.
1455   /// Subclasses may override this routine to provide different behavior.
1456   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1457                                         Stmt *TryBody,
1458                                         MultiStmtArg CatchStmts,
1459                                         Stmt *Finally) {
1460     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1461                                         Finally);
1462   }
1463
1464   /// Rebuild an Objective-C exception declaration.
1465   ///
1466   /// By default, performs semantic analysis to build the new declaration.
1467   /// Subclasses may override this routine to provide different behavior.
1468   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1469                                     TypeSourceInfo *TInfo, QualType T) {
1470     return getSema().BuildObjCExceptionDecl(TInfo, T,
1471                                             ExceptionDecl->getInnerLocStart(),
1472                                             ExceptionDecl->getLocation(),
1473                                             ExceptionDecl->getIdentifier());
1474   }
1475
1476   /// Build a new Objective-C \@catch statement.
1477   ///
1478   /// By default, performs semantic analysis to build the new statement.
1479   /// Subclasses may override this routine to provide different behavior.
1480   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1481                                           SourceLocation RParenLoc,
1482                                           VarDecl *Var,
1483                                           Stmt *Body) {
1484     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1485                                           Var, Body);
1486   }
1487
1488   /// Build a new Objective-C \@finally statement.
1489   ///
1490   /// By default, performs semantic analysis to build the new statement.
1491   /// Subclasses may override this routine to provide different behavior.
1492   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1493                                             Stmt *Body) {
1494     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1495   }
1496
1497   /// Build a new Objective-C \@throw statement.
1498   ///
1499   /// By default, performs semantic analysis to build the new statement.
1500   /// Subclasses may override this routine to provide different behavior.
1501   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1502                                           Expr *Operand) {
1503     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1504   }
1505
1506   /// Build a new OpenMP executable directive.
1507   ///
1508   /// By default, performs semantic analysis to build the new statement.
1509   /// Subclasses may override this routine to provide different behavior.
1510   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1511                                            DeclarationNameInfo DirName,
1512                                            OpenMPDirectiveKind CancelRegion,
1513                                            ArrayRef<OMPClause *> Clauses,
1514                                            Stmt *AStmt, SourceLocation StartLoc,
1515                                            SourceLocation EndLoc) {
1516     return getSema().ActOnOpenMPExecutableDirective(
1517         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1518   }
1519
1520   /// Build a new OpenMP 'if' clause.
1521   ///
1522   /// By default, performs semantic analysis to build the new OpenMP clause.
1523   /// Subclasses may override this routine to provide different behavior.
1524   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1525                                 Expr *Condition, SourceLocation StartLoc,
1526                                 SourceLocation LParenLoc,
1527                                 SourceLocation NameModifierLoc,
1528                                 SourceLocation ColonLoc,
1529                                 SourceLocation EndLoc) {
1530     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1531                                          LParenLoc, NameModifierLoc, ColonLoc,
1532                                          EndLoc);
1533   }
1534
1535   /// Build a new OpenMP 'final' clause.
1536   ///
1537   /// By default, performs semantic analysis to build the new OpenMP clause.
1538   /// Subclasses may override this routine to provide different behavior.
1539   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1540                                    SourceLocation LParenLoc,
1541                                    SourceLocation EndLoc) {
1542     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1543                                             EndLoc);
1544   }
1545
1546   /// Build a new OpenMP 'num_threads' clause.
1547   ///
1548   /// By default, performs semantic analysis to build the new OpenMP clause.
1549   /// Subclasses may override this routine to provide different behavior.
1550   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1551                                         SourceLocation StartLoc,
1552                                         SourceLocation LParenLoc,
1553                                         SourceLocation EndLoc) {
1554     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1555                                                  LParenLoc, EndLoc);
1556   }
1557
1558   /// Build a new OpenMP 'safelen' clause.
1559   ///
1560   /// By default, performs semantic analysis to build the new OpenMP clause.
1561   /// Subclasses may override this routine to provide different behavior.
1562   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1563                                      SourceLocation LParenLoc,
1564                                      SourceLocation EndLoc) {
1565     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1566   }
1567
1568   /// Build a new OpenMP 'simdlen' clause.
1569   ///
1570   /// By default, performs semantic analysis to build the new OpenMP clause.
1571   /// Subclasses may override this routine to provide different behavior.
1572   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1573                                      SourceLocation LParenLoc,
1574                                      SourceLocation EndLoc) {
1575     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1576   }
1577
1578   /// Build a new OpenMP 'allocator' clause.
1579   ///
1580   /// By default, performs semantic analysis to build the new OpenMP clause.
1581   /// Subclasses may override this routine to provide different behavior.
1582   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1583                                        SourceLocation LParenLoc,
1584                                        SourceLocation EndLoc) {
1585     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1586   }
1587
1588   /// Build a new OpenMP 'collapse' clause.
1589   ///
1590   /// By default, performs semantic analysis to build the new OpenMP clause.
1591   /// Subclasses may override this routine to provide different behavior.
1592   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1593                                       SourceLocation LParenLoc,
1594                                       SourceLocation EndLoc) {
1595     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1596                                                EndLoc);
1597   }
1598
1599   /// Build a new OpenMP 'default' clause.
1600   ///
1601   /// By default, performs semantic analysis to build the new OpenMP clause.
1602   /// Subclasses may override this routine to provide different behavior.
1603   OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1604                                      SourceLocation KindKwLoc,
1605                                      SourceLocation StartLoc,
1606                                      SourceLocation LParenLoc,
1607                                      SourceLocation EndLoc) {
1608     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1609                                               StartLoc, LParenLoc, EndLoc);
1610   }
1611
1612   /// Build a new OpenMP 'proc_bind' clause.
1613   ///
1614   /// By default, performs semantic analysis to build the new OpenMP clause.
1615   /// Subclasses may override this routine to provide different behavior.
1616   OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1617                                       SourceLocation KindKwLoc,
1618                                       SourceLocation StartLoc,
1619                                       SourceLocation LParenLoc,
1620                                       SourceLocation EndLoc) {
1621     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1622                                                StartLoc, LParenLoc, EndLoc);
1623   }
1624
1625   /// Build a new OpenMP 'schedule' clause.
1626   ///
1627   /// By default, performs semantic analysis to build the new OpenMP clause.
1628   /// Subclasses may override this routine to provide different behavior.
1629   OMPClause *RebuildOMPScheduleClause(
1630       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1631       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1632       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1633       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1634     return getSema().ActOnOpenMPScheduleClause(
1635         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1636         CommaLoc, EndLoc);
1637   }
1638
1639   /// Build a new OpenMP 'ordered' clause.
1640   ///
1641   /// By default, performs semantic analysis to build the new OpenMP clause.
1642   /// Subclasses may override this routine to provide different behavior.
1643   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1644                                      SourceLocation EndLoc,
1645                                      SourceLocation LParenLoc, Expr *Num) {
1646     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1647   }
1648
1649   /// Build a new OpenMP 'private' clause.
1650   ///
1651   /// By default, performs semantic analysis to build the new OpenMP clause.
1652   /// Subclasses may override this routine to provide different behavior.
1653   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1654                                      SourceLocation StartLoc,
1655                                      SourceLocation LParenLoc,
1656                                      SourceLocation EndLoc) {
1657     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1658                                               EndLoc);
1659   }
1660
1661   /// Build a new OpenMP 'firstprivate' clause.
1662   ///
1663   /// By default, performs semantic analysis to build the new OpenMP clause.
1664   /// Subclasses may override this routine to provide different behavior.
1665   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1666                                           SourceLocation StartLoc,
1667                                           SourceLocation LParenLoc,
1668                                           SourceLocation EndLoc) {
1669     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1670                                                    EndLoc);
1671   }
1672
1673   /// Build a new OpenMP 'lastprivate' clause.
1674   ///
1675   /// By default, performs semantic analysis to build the new OpenMP clause.
1676   /// Subclasses may override this routine to provide different behavior.
1677   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1678                                          SourceLocation StartLoc,
1679                                          SourceLocation LParenLoc,
1680                                          SourceLocation EndLoc) {
1681     return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1682                                                   EndLoc);
1683   }
1684
1685   /// Build a new OpenMP 'shared' clause.
1686   ///
1687   /// By default, performs semantic analysis to build the new OpenMP clause.
1688   /// Subclasses may override this routine to provide different behavior.
1689   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1690                                     SourceLocation StartLoc,
1691                                     SourceLocation LParenLoc,
1692                                     SourceLocation EndLoc) {
1693     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1694                                              EndLoc);
1695   }
1696
1697   /// Build a new OpenMP 'reduction' clause.
1698   ///
1699   /// By default, performs semantic analysis to build the new statement.
1700   /// Subclasses may override this routine to provide different behavior.
1701   OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1702                                        SourceLocation StartLoc,
1703                                        SourceLocation LParenLoc,
1704                                        SourceLocation ColonLoc,
1705                                        SourceLocation EndLoc,
1706                                        CXXScopeSpec &ReductionIdScopeSpec,
1707                                        const DeclarationNameInfo &ReductionId,
1708                                        ArrayRef<Expr *> UnresolvedReductions) {
1709     return getSema().ActOnOpenMPReductionClause(
1710         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1711         ReductionId, UnresolvedReductions);
1712   }
1713
1714   /// Build a new OpenMP 'task_reduction' clause.
1715   ///
1716   /// By default, performs semantic analysis to build the new statement.
1717   /// Subclasses may override this routine to provide different behavior.
1718   OMPClause *RebuildOMPTaskReductionClause(
1719       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1720       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1721       CXXScopeSpec &ReductionIdScopeSpec,
1722       const DeclarationNameInfo &ReductionId,
1723       ArrayRef<Expr *> UnresolvedReductions) {
1724     return getSema().ActOnOpenMPTaskReductionClause(
1725         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1726         ReductionId, UnresolvedReductions);
1727   }
1728
1729   /// Build a new OpenMP 'in_reduction' clause.
1730   ///
1731   /// By default, performs semantic analysis to build the new statement.
1732   /// Subclasses may override this routine to provide different behavior.
1733   OMPClause *
1734   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1735                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1736                               SourceLocation EndLoc,
1737                               CXXScopeSpec &ReductionIdScopeSpec,
1738                               const DeclarationNameInfo &ReductionId,
1739                               ArrayRef<Expr *> UnresolvedReductions) {
1740     return getSema().ActOnOpenMPInReductionClause(
1741         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1742         ReductionId, UnresolvedReductions);
1743   }
1744
1745   /// Build a new OpenMP 'linear' clause.
1746   ///
1747   /// By default, performs semantic analysis to build the new OpenMP clause.
1748   /// Subclasses may override this routine to provide different behavior.
1749   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1750                                     SourceLocation StartLoc,
1751                                     SourceLocation LParenLoc,
1752                                     OpenMPLinearClauseKind Modifier,
1753                                     SourceLocation ModifierLoc,
1754                                     SourceLocation ColonLoc,
1755                                     SourceLocation EndLoc) {
1756     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1757                                              Modifier, ModifierLoc, ColonLoc,
1758                                              EndLoc);
1759   }
1760
1761   /// Build a new OpenMP 'aligned' clause.
1762   ///
1763   /// By default, performs semantic analysis to build the new OpenMP clause.
1764   /// Subclasses may override this routine to provide different behavior.
1765   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1766                                      SourceLocation StartLoc,
1767                                      SourceLocation LParenLoc,
1768                                      SourceLocation ColonLoc,
1769                                      SourceLocation EndLoc) {
1770     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1771                                               LParenLoc, ColonLoc, EndLoc);
1772   }
1773
1774   /// Build a new OpenMP 'copyin' clause.
1775   ///
1776   /// By default, performs semantic analysis to build the new OpenMP clause.
1777   /// Subclasses may override this routine to provide different behavior.
1778   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1779                                     SourceLocation StartLoc,
1780                                     SourceLocation LParenLoc,
1781                                     SourceLocation EndLoc) {
1782     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1783                                              EndLoc);
1784   }
1785
1786   /// Build a new OpenMP 'copyprivate' clause.
1787   ///
1788   /// By default, performs semantic analysis to build the new OpenMP clause.
1789   /// Subclasses may override this routine to provide different behavior.
1790   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1791                                          SourceLocation StartLoc,
1792                                          SourceLocation LParenLoc,
1793                                          SourceLocation EndLoc) {
1794     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1795                                                   EndLoc);
1796   }
1797
1798   /// Build a new OpenMP 'flush' pseudo clause.
1799   ///
1800   /// By default, performs semantic analysis to build the new OpenMP clause.
1801   /// Subclasses may override this routine to provide different behavior.
1802   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1803                                    SourceLocation StartLoc,
1804                                    SourceLocation LParenLoc,
1805                                    SourceLocation EndLoc) {
1806     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1807                                             EndLoc);
1808   }
1809
1810   /// Build a new OpenMP 'depend' pseudo clause.
1811   ///
1812   /// By default, performs semantic analysis to build the new OpenMP clause.
1813   /// Subclasses may override this routine to provide different behavior.
1814   OMPClause *
1815   RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1816                          SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1817                          SourceLocation StartLoc, SourceLocation LParenLoc,
1818                          SourceLocation EndLoc) {
1819     return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1820                                              StartLoc, LParenLoc, EndLoc);
1821   }
1822
1823   /// Build a new OpenMP 'device' clause.
1824   ///
1825   /// By default, performs semantic analysis to build the new statement.
1826   /// Subclasses may override this routine to provide different behavior.
1827   OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1828                                     SourceLocation LParenLoc,
1829                                     SourceLocation EndLoc) {
1830     return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1831                                              EndLoc);
1832   }
1833
1834   /// Build a new OpenMP 'map' clause.
1835   ///
1836   /// By default, performs semantic analysis to build the new OpenMP clause.
1837   /// Subclasses may override this routine to provide different behavior.
1838   OMPClause *RebuildOMPMapClause(
1839       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1840       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1841       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1842       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1843       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1844       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1845     return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1846                                           MapperIdScopeSpec, MapperId, MapType,
1847                                           IsMapTypeImplicit, MapLoc, ColonLoc,
1848                                           VarList, Locs, UnresolvedMappers);
1849   }
1850
1851   /// Build a new OpenMP 'allocate' clause.
1852   ///
1853   /// By default, performs semantic analysis to build the new OpenMP clause.
1854   /// Subclasses may override this routine to provide different behavior.
1855   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1856                                       SourceLocation StartLoc,
1857                                       SourceLocation LParenLoc,
1858                                       SourceLocation ColonLoc,
1859                                       SourceLocation EndLoc) {
1860     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1861                                                LParenLoc, ColonLoc, EndLoc);
1862   }
1863
1864   /// Build a new OpenMP 'num_teams' clause.
1865   ///
1866   /// By default, performs semantic analysis to build the new statement.
1867   /// Subclasses may override this routine to provide different behavior.
1868   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1869                                       SourceLocation LParenLoc,
1870                                       SourceLocation EndLoc) {
1871     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1872                                                EndLoc);
1873   }
1874
1875   /// Build a new OpenMP 'thread_limit' clause.
1876   ///
1877   /// By default, performs semantic analysis to build the new statement.
1878   /// Subclasses may override this routine to provide different behavior.
1879   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1880                                          SourceLocation StartLoc,
1881                                          SourceLocation LParenLoc,
1882                                          SourceLocation EndLoc) {
1883     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1884                                                   LParenLoc, EndLoc);
1885   }
1886
1887   /// Build a new OpenMP 'priority' clause.
1888   ///
1889   /// By default, performs semantic analysis to build the new statement.
1890   /// Subclasses may override this routine to provide different behavior.
1891   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1892                                       SourceLocation LParenLoc,
1893                                       SourceLocation EndLoc) {
1894     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1895                                                EndLoc);
1896   }
1897
1898   /// Build a new OpenMP 'grainsize' clause.
1899   ///
1900   /// By default, performs semantic analysis to build the new statement.
1901   /// Subclasses may override this routine to provide different behavior.
1902   OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1903                                        SourceLocation LParenLoc,
1904                                        SourceLocation EndLoc) {
1905     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1906                                                 EndLoc);
1907   }
1908
1909   /// Build a new OpenMP 'num_tasks' clause.
1910   ///
1911   /// By default, performs semantic analysis to build the new statement.
1912   /// Subclasses may override this routine to provide different behavior.
1913   OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1914                                       SourceLocation LParenLoc,
1915                                       SourceLocation EndLoc) {
1916     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1917                                                EndLoc);
1918   }
1919
1920   /// Build a new OpenMP 'hint' clause.
1921   ///
1922   /// By default, performs semantic analysis to build the new statement.
1923   /// Subclasses may override this routine to provide different behavior.
1924   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1925                                   SourceLocation LParenLoc,
1926                                   SourceLocation EndLoc) {
1927     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1928   }
1929
1930   /// Build a new OpenMP 'dist_schedule' clause.
1931   ///
1932   /// By default, performs semantic analysis to build the new OpenMP clause.
1933   /// Subclasses may override this routine to provide different behavior.
1934   OMPClause *
1935   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1936                                Expr *ChunkSize, SourceLocation StartLoc,
1937                                SourceLocation LParenLoc, SourceLocation KindLoc,
1938                                SourceLocation CommaLoc, SourceLocation EndLoc) {
1939     return getSema().ActOnOpenMPDistScheduleClause(
1940         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1941   }
1942
1943   /// Build a new OpenMP 'to' clause.
1944   ///
1945   /// By default, performs semantic analysis to build the new statement.
1946   /// Subclasses may override this routine to provide different behavior.
1947   OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1948                                 CXXScopeSpec &MapperIdScopeSpec,
1949                                 DeclarationNameInfo &MapperId,
1950                                 const OMPVarListLocTy &Locs,
1951                                 ArrayRef<Expr *> UnresolvedMappers) {
1952     return getSema().ActOnOpenMPToClause(VarList, MapperIdScopeSpec, MapperId,
1953                                          Locs, UnresolvedMappers);
1954   }
1955
1956   /// Build a new OpenMP 'from' clause.
1957   ///
1958   /// By default, performs semantic analysis to build the new statement.
1959   /// Subclasses may override this routine to provide different behavior.
1960   OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1961                                   CXXScopeSpec &MapperIdScopeSpec,
1962                                   DeclarationNameInfo &MapperId,
1963                                   const OMPVarListLocTy &Locs,
1964                                   ArrayRef<Expr *> UnresolvedMappers) {
1965     return getSema().ActOnOpenMPFromClause(VarList, MapperIdScopeSpec, MapperId,
1966                                            Locs, UnresolvedMappers);
1967   }
1968
1969   /// Build a new OpenMP 'use_device_ptr' clause.
1970   ///
1971   /// By default, performs semantic analysis to build the new OpenMP clause.
1972   /// Subclasses may override this routine to provide different behavior.
1973   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1974                                           const OMPVarListLocTy &Locs) {
1975     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
1976   }
1977
1978   /// Build a new OpenMP 'is_device_ptr' clause.
1979   ///
1980   /// By default, performs semantic analysis to build the new OpenMP clause.
1981   /// Subclasses may override this routine to provide different behavior.
1982   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1983                                          const OMPVarListLocTy &Locs) {
1984     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
1985   }
1986
1987   /// Rebuild the operand to an Objective-C \@synchronized statement.
1988   ///
1989   /// By default, performs semantic analysis to build the new statement.
1990   /// Subclasses may override this routine to provide different behavior.
1991   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1992                                               Expr *object) {
1993     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1994   }
1995
1996   /// Build a new Objective-C \@synchronized statement.
1997   ///
1998   /// By default, performs semantic analysis to build the new statement.
1999   /// Subclasses may override this routine to provide different behavior.
2000   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2001                                            Expr *Object, Stmt *Body) {
2002     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2003   }
2004
2005   /// Build a new Objective-C \@autoreleasepool statement.
2006   ///
2007   /// By default, performs semantic analysis to build the new statement.
2008   /// Subclasses may override this routine to provide different behavior.
2009   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2010                                             Stmt *Body) {
2011     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2012   }
2013
2014   /// Build a new Objective-C fast enumeration statement.
2015   ///
2016   /// By default, performs semantic analysis to build the new statement.
2017   /// Subclasses may override this routine to provide different behavior.
2018   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2019                                           Stmt *Element,
2020                                           Expr *Collection,
2021                                           SourceLocation RParenLoc,
2022                                           Stmt *Body) {
2023     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2024                                                 Element,
2025                                                 Collection,
2026                                                 RParenLoc);
2027     if (ForEachStmt.isInvalid())
2028       return StmtError();
2029
2030     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2031   }
2032
2033   /// Build a new C++ exception declaration.
2034   ///
2035   /// By default, performs semantic analysis to build the new decaration.
2036   /// Subclasses may override this routine to provide different behavior.
2037   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2038                                 TypeSourceInfo *Declarator,
2039                                 SourceLocation StartLoc,
2040                                 SourceLocation IdLoc,
2041                                 IdentifierInfo *Id) {
2042     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2043                                                        StartLoc, IdLoc, Id);
2044     if (Var)
2045       getSema().CurContext->addDecl(Var);
2046     return Var;
2047   }
2048
2049   /// Build a new C++ catch statement.
2050   ///
2051   /// By default, performs semantic analysis to build the new statement.
2052   /// Subclasses may override this routine to provide different behavior.
2053   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2054                                  VarDecl *ExceptionDecl,
2055                                  Stmt *Handler) {
2056     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2057                                                       Handler));
2058   }
2059
2060   /// Build a new C++ try statement.
2061   ///
2062   /// By default, performs semantic analysis to build the new statement.
2063   /// Subclasses may override this routine to provide different behavior.
2064   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2065                                ArrayRef<Stmt *> Handlers) {
2066     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2067   }
2068
2069   /// Build a new C++0x range-based for statement.
2070   ///
2071   /// By default, performs semantic analysis to build the new statement.
2072   /// Subclasses may override this routine to provide different behavior.
2073   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2074                                     SourceLocation CoawaitLoc, Stmt *Init,
2075                                     SourceLocation ColonLoc, Stmt *Range,
2076                                     Stmt *Begin, Stmt *End, Expr *Cond,
2077                                     Expr *Inc, Stmt *LoopVar,
2078                                     SourceLocation RParenLoc) {
2079     // If we've just learned that the range is actually an Objective-C
2080     // collection, treat this as an Objective-C fast enumeration loop.
2081     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2082       if (RangeStmt->isSingleDecl()) {
2083         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2084           if (RangeVar->isInvalidDecl())
2085             return StmtError();
2086
2087           Expr *RangeExpr = RangeVar->getInit();
2088           if (!RangeExpr->isTypeDependent() &&
2089               RangeExpr->getType()->isObjCObjectPointerType()) {
2090             // FIXME: Support init-statements in Objective-C++20 ranged for
2091             // statement.
2092             if (Init) {
2093               return SemaRef.Diag(Init->getBeginLoc(),
2094                                   diag::err_objc_for_range_init_stmt)
2095                          << Init->getSourceRange();
2096             }
2097             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2098                                                         RangeExpr, RParenLoc);
2099           }
2100         }
2101       }
2102     }
2103
2104     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2105                                           Range, Begin, End, Cond, Inc, LoopVar,
2106                                           RParenLoc, Sema::BFRK_Rebuild);
2107   }
2108
2109   /// Build a new C++0x range-based for statement.
2110   ///
2111   /// By default, performs semantic analysis to build the new statement.
2112   /// Subclasses may override this routine to provide different behavior.
2113   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2114                                           bool IsIfExists,
2115                                           NestedNameSpecifierLoc QualifierLoc,
2116                                           DeclarationNameInfo NameInfo,
2117                                           Stmt *Nested) {
2118     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2119                                                 QualifierLoc, NameInfo, Nested);
2120   }
2121
2122   /// Attach body to a C++0x range-based for statement.
2123   ///
2124   /// By default, performs semantic analysis to finish the new statement.
2125   /// Subclasses may override this routine to provide different behavior.
2126   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2127     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2128   }
2129
2130   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2131                                Stmt *TryBlock, Stmt *Handler) {
2132     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2133   }
2134
2135   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2136                                   Stmt *Block) {
2137     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2138   }
2139
2140   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2141     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2142   }
2143
2144   /// Build a new predefined expression.
2145   ///
2146   /// By default, performs semantic analysis to build the new expression.
2147   /// Subclasses may override this routine to provide different behavior.
2148   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2149                                    PredefinedExpr::IdentKind IK) {
2150     return getSema().BuildPredefinedExpr(Loc, IK);
2151   }
2152
2153   /// Build a new expression that references a declaration.
2154   ///
2155   /// By default, performs semantic analysis to build the new expression.
2156   /// Subclasses may override this routine to provide different behavior.
2157   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2158                                         LookupResult &R,
2159                                         bool RequiresADL) {
2160     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2161   }
2162
2163
2164   /// Build a new expression that references a declaration.
2165   ///
2166   /// By default, performs semantic analysis to build the new expression.
2167   /// Subclasses may override this routine to provide different behavior.
2168   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2169                                 ValueDecl *VD,
2170                                 const DeclarationNameInfo &NameInfo,
2171                                 NamedDecl *Found,
2172                                 TemplateArgumentListInfo *TemplateArgs) {
2173     CXXScopeSpec SS;
2174     SS.Adopt(QualifierLoc);
2175     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2176                                               TemplateArgs);
2177   }
2178
2179   /// Build a new expression in parentheses.
2180   ///
2181   /// By default, performs semantic analysis to build the new expression.
2182   /// Subclasses may override this routine to provide different behavior.
2183   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2184                                     SourceLocation RParen) {
2185     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2186   }
2187
2188   /// Build a new pseudo-destructor expression.
2189   ///
2190   /// By default, performs semantic analysis to build the new expression.
2191   /// Subclasses may override this routine to provide different behavior.
2192   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2193                                             SourceLocation OperatorLoc,
2194                                             bool isArrow,
2195                                             CXXScopeSpec &SS,
2196                                             TypeSourceInfo *ScopeType,
2197                                             SourceLocation CCLoc,
2198                                             SourceLocation TildeLoc,
2199                                         PseudoDestructorTypeStorage Destroyed);
2200
2201   /// Build a new unary operator expression.
2202   ///
2203   /// By default, performs semantic analysis to build the new expression.
2204   /// Subclasses may override this routine to provide different behavior.
2205   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2206                                         UnaryOperatorKind Opc,
2207                                         Expr *SubExpr) {
2208     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2209   }
2210
2211   /// Build a new builtin offsetof expression.
2212   ///
2213   /// By default, performs semantic analysis to build the new expression.
2214   /// Subclasses may override this routine to provide different behavior.
2215   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2216                                  TypeSourceInfo *Type,
2217                                  ArrayRef<Sema::OffsetOfComponent> Components,
2218                                  SourceLocation RParenLoc) {
2219     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2220                                           RParenLoc);
2221   }
2222
2223   /// Build a new sizeof, alignof or vec_step expression with a
2224   /// type argument.
2225   ///
2226   /// By default, performs semantic analysis to build the new expression.
2227   /// Subclasses may override this routine to provide different behavior.
2228   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2229                                          SourceLocation OpLoc,
2230                                          UnaryExprOrTypeTrait ExprKind,
2231                                          SourceRange R) {
2232     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2233   }
2234
2235   /// Build a new sizeof, alignof or vec step expression with an
2236   /// expression argument.
2237   ///
2238   /// By default, performs semantic analysis to build the new expression.
2239   /// Subclasses may override this routine to provide different behavior.
2240   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2241                                          UnaryExprOrTypeTrait ExprKind,
2242                                          SourceRange R) {
2243     ExprResult Result
2244       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2245     if (Result.isInvalid())
2246       return ExprError();
2247
2248     return Result;
2249   }
2250
2251   /// Build a new array subscript expression.
2252   ///
2253   /// By default, performs semantic analysis to build the new expression.
2254   /// Subclasses may override this routine to provide different behavior.
2255   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2256                                              SourceLocation LBracketLoc,
2257                                              Expr *RHS,
2258                                              SourceLocation RBracketLoc) {
2259     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2260                                              LBracketLoc, RHS,
2261                                              RBracketLoc);
2262   }
2263
2264   /// Build a new array section expression.
2265   ///
2266   /// By default, performs semantic analysis to build the new expression.
2267   /// Subclasses may override this routine to provide different behavior.
2268   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2269                                         Expr *LowerBound,
2270                                         SourceLocation ColonLoc, Expr *Length,
2271                                         SourceLocation RBracketLoc) {
2272     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2273                                               ColonLoc, Length, RBracketLoc);
2274   }
2275
2276   /// Build a new call expression.
2277   ///
2278   /// By default, performs semantic analysis to build the new expression.
2279   /// Subclasses may override this routine to provide different behavior.
2280   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2281                                    MultiExprArg Args,
2282                                    SourceLocation RParenLoc,
2283                                    Expr *ExecConfig = nullptr) {
2284     return getSema().BuildCallExpr(/*Scope=*/nullptr, Callee, LParenLoc, Args,
2285                                    RParenLoc, ExecConfig);
2286   }
2287
2288   /// Build a new member access expression.
2289   ///
2290   /// By default, performs semantic analysis to build the new expression.
2291   /// Subclasses may override this routine to provide different behavior.
2292   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2293                                bool isArrow,
2294                                NestedNameSpecifierLoc QualifierLoc,
2295                                SourceLocation TemplateKWLoc,
2296                                const DeclarationNameInfo &MemberNameInfo,
2297                                ValueDecl *Member,
2298                                NamedDecl *FoundDecl,
2299                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2300                                NamedDecl *FirstQualifierInScope) {
2301     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2302                                                                       isArrow);
2303     if (!Member->getDeclName()) {
2304       // We have a reference to an unnamed field.  This is always the
2305       // base of an anonymous struct/union member access, i.e. the
2306       // field is always of record type.
2307       assert(Member->getType()->isRecordType() &&
2308              "unnamed member not of record type?");
2309
2310       BaseResult =
2311         getSema().PerformObjectMemberConversion(BaseResult.get(),
2312                                                 QualifierLoc.getNestedNameSpecifier(),
2313                                                 FoundDecl, Member);
2314       if (BaseResult.isInvalid())
2315         return ExprError();
2316       Base = BaseResult.get();
2317
2318       CXXScopeSpec EmptySS;
2319       return getSema().BuildFieldReferenceExpr(
2320           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2321           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2322     }
2323
2324     CXXScopeSpec SS;
2325     SS.Adopt(QualifierLoc);
2326
2327     Base = BaseResult.get();
2328     QualType BaseType = Base->getType();
2329
2330     if (isArrow && !BaseType->isPointerType())
2331       return ExprError();
2332
2333     // FIXME: this involves duplicating earlier analysis in a lot of
2334     // cases; we should avoid this when possible.
2335     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2336     R.addDecl(FoundDecl);
2337     R.resolveKind();
2338
2339     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2340                                               SS, TemplateKWLoc,
2341                                               FirstQualifierInScope,
2342                                               R, ExplicitTemplateArgs,
2343                                               /*S*/nullptr);
2344   }
2345
2346   /// Build a new binary operator expression.
2347   ///
2348   /// By default, performs semantic analysis to build the new expression.
2349   /// Subclasses may override this routine to provide different behavior.
2350   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2351                                          BinaryOperatorKind Opc,
2352                                          Expr *LHS, Expr *RHS) {
2353     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2354   }
2355
2356   /// Build a new rewritten operator expression.
2357   ///
2358   /// By default, performs semantic analysis to build the new expression.
2359   /// Subclasses may override this routine to provide different behavior.
2360   ExprResult RebuildCXXRewrittenBinaryOperator(
2361       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2362       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2363     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2364                                            RHS, /*RequiresADL*/false);
2365   }
2366
2367   /// Build a new conditional operator expression.
2368   ///
2369   /// By default, performs semantic analysis to build the new expression.
2370   /// Subclasses may override this routine to provide different behavior.
2371   ExprResult RebuildConditionalOperator(Expr *Cond,
2372                                         SourceLocation QuestionLoc,
2373                                         Expr *LHS,
2374                                         SourceLocation ColonLoc,
2375                                         Expr *RHS) {
2376     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2377                                         LHS, RHS);
2378   }
2379
2380   /// Build a new C-style cast expression.
2381   ///
2382   /// By default, performs semantic analysis to build the new expression.
2383   /// Subclasses may override this routine to provide different behavior.
2384   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2385                                          TypeSourceInfo *TInfo,
2386                                          SourceLocation RParenLoc,
2387                                          Expr *SubExpr) {
2388     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2389                                          SubExpr);
2390   }
2391
2392   /// Build a new compound literal expression.
2393   ///
2394   /// By default, performs semantic analysis to build the new expression.
2395   /// Subclasses may override this routine to provide different behavior.
2396   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2397                                               TypeSourceInfo *TInfo,
2398                                               SourceLocation RParenLoc,
2399                                               Expr *Init) {
2400     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2401                                               Init);
2402   }
2403
2404   /// Build a new extended vector element access expression.
2405   ///
2406   /// By default, performs semantic analysis to build the new expression.
2407   /// Subclasses may override this routine to provide different behavior.
2408   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2409                                                SourceLocation OpLoc,
2410                                                SourceLocation AccessorLoc,
2411                                                IdentifierInfo &Accessor) {
2412
2413     CXXScopeSpec SS;
2414     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2415     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2416                                               OpLoc, /*IsArrow*/ false,
2417                                               SS, SourceLocation(),
2418                                               /*FirstQualifierInScope*/ nullptr,
2419                                               NameInfo,
2420                                               /* TemplateArgs */ nullptr,
2421                                               /*S*/ nullptr);
2422   }
2423
2424   /// Build a new initializer list expression.
2425   ///
2426   /// By default, performs semantic analysis to build the new expression.
2427   /// Subclasses may override this routine to provide different behavior.
2428   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2429                              MultiExprArg Inits,
2430                              SourceLocation RBraceLoc) {
2431     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2432   }
2433
2434   /// Build a new designated initializer expression.
2435   ///
2436   /// By default, performs semantic analysis to build the new expression.
2437   /// Subclasses may override this routine to provide different behavior.
2438   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2439                                              MultiExprArg ArrayExprs,
2440                                              SourceLocation EqualOrColonLoc,
2441                                              bool GNUSyntax,
2442                                              Expr *Init) {
2443     ExprResult Result
2444       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2445                                            Init);
2446     if (Result.isInvalid())
2447       return ExprError();
2448
2449     return Result;
2450   }
2451
2452   /// Build a new value-initialized expression.
2453   ///
2454   /// By default, builds the implicit value initialization without performing
2455   /// any semantic analysis. Subclasses may override this routine to provide
2456   /// different behavior.
2457   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2458     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2459   }
2460
2461   /// Build a new \c va_arg expression.
2462   ///
2463   /// By default, performs semantic analysis to build the new expression.
2464   /// Subclasses may override this routine to provide different behavior.
2465   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2466                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2467                                     SourceLocation RParenLoc) {
2468     return getSema().BuildVAArgExpr(BuiltinLoc,
2469                                     SubExpr, TInfo,
2470                                     RParenLoc);
2471   }
2472
2473   /// Build a new expression list in parentheses.
2474   ///
2475   /// By default, performs semantic analysis to build the new expression.
2476   /// Subclasses may override this routine to provide different behavior.
2477   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2478                                   MultiExprArg SubExprs,
2479                                   SourceLocation RParenLoc) {
2480     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2481   }
2482
2483   /// Build a new address-of-label expression.
2484   ///
2485   /// By default, performs semantic analysis, using the name of the label
2486   /// rather than attempting to map the label statement itself.
2487   /// Subclasses may override this routine to provide different behavior.
2488   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2489                                   SourceLocation LabelLoc, LabelDecl *Label) {
2490     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2491   }
2492
2493   /// Build a new GNU statement expression.
2494   ///
2495   /// By default, performs semantic analysis to build the new expression.
2496   /// Subclasses may override this routine to provide different behavior.
2497   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2498                                    Stmt *SubStmt,
2499                                    SourceLocation RParenLoc) {
2500     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2501   }
2502
2503   /// Build a new __builtin_choose_expr expression.
2504   ///
2505   /// By default, performs semantic analysis to build the new expression.
2506   /// Subclasses may override this routine to provide different behavior.
2507   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2508                                      Expr *Cond, Expr *LHS, Expr *RHS,
2509                                      SourceLocation RParenLoc) {
2510     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2511                                    Cond, LHS, RHS,
2512                                    RParenLoc);
2513   }
2514
2515   /// Build a new generic selection expression.
2516   ///
2517   /// By default, performs semantic analysis to build the new expression.
2518   /// Subclasses may override this routine to provide different behavior.
2519   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2520                                          SourceLocation DefaultLoc,
2521                                          SourceLocation RParenLoc,
2522                                          Expr *ControllingExpr,
2523                                          ArrayRef<TypeSourceInfo *> Types,
2524                                          ArrayRef<Expr *> Exprs) {
2525     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2526                                                 ControllingExpr, Types, Exprs);
2527   }
2528
2529   /// Build a new overloaded operator call expression.
2530   ///
2531   /// By default, performs semantic analysis to build the new expression.
2532   /// The semantic analysis provides the behavior of template instantiation,
2533   /// copying with transformations that turn what looks like an overloaded
2534   /// operator call into a use of a builtin operator, performing
2535   /// argument-dependent lookup, etc. Subclasses may override this routine to
2536   /// provide different behavior.
2537   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2538                                               SourceLocation OpLoc,
2539                                               Expr *Callee,
2540                                               Expr *First,
2541                                               Expr *Second);
2542
2543   /// Build a new C++ "named" cast expression, such as static_cast or
2544   /// reinterpret_cast.
2545   ///
2546   /// By default, this routine dispatches to one of the more-specific routines
2547   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2548   /// Subclasses may override this routine to provide different behavior.
2549   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2550                                            Stmt::StmtClass Class,
2551                                            SourceLocation LAngleLoc,
2552                                            TypeSourceInfo *TInfo,
2553                                            SourceLocation RAngleLoc,
2554                                            SourceLocation LParenLoc,
2555                                            Expr *SubExpr,
2556                                            SourceLocation RParenLoc) {
2557     switch (Class) {
2558     case Stmt::CXXStaticCastExprClass:
2559       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2560                                                    RAngleLoc, LParenLoc,
2561                                                    SubExpr, RParenLoc);
2562
2563     case Stmt::CXXDynamicCastExprClass:
2564       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2565                                                     RAngleLoc, LParenLoc,
2566                                                     SubExpr, RParenLoc);
2567
2568     case Stmt::CXXReinterpretCastExprClass:
2569       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2570                                                         RAngleLoc, LParenLoc,
2571                                                         SubExpr,
2572                                                         RParenLoc);
2573
2574     case Stmt::CXXConstCastExprClass:
2575       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2576                                                    RAngleLoc, LParenLoc,
2577                                                    SubExpr, RParenLoc);
2578
2579     default:
2580       llvm_unreachable("Invalid C++ named cast");
2581     }
2582   }
2583
2584   /// Build a new C++ static_cast expression.
2585   ///
2586   /// By default, performs semantic analysis to build the new expression.
2587   /// Subclasses may override this routine to provide different behavior.
2588   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2589                                             SourceLocation LAngleLoc,
2590                                             TypeSourceInfo *TInfo,
2591                                             SourceLocation RAngleLoc,
2592                                             SourceLocation LParenLoc,
2593                                             Expr *SubExpr,
2594                                             SourceLocation RParenLoc) {
2595     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2596                                        TInfo, SubExpr,
2597                                        SourceRange(LAngleLoc, RAngleLoc),
2598                                        SourceRange(LParenLoc, RParenLoc));
2599   }
2600
2601   /// Build a new C++ dynamic_cast expression.
2602   ///
2603   /// By default, performs semantic analysis to build the new expression.
2604   /// Subclasses may override this routine to provide different behavior.
2605   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2606                                              SourceLocation LAngleLoc,
2607                                              TypeSourceInfo *TInfo,
2608                                              SourceLocation RAngleLoc,
2609                                              SourceLocation LParenLoc,
2610                                              Expr *SubExpr,
2611                                              SourceLocation RParenLoc) {
2612     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2613                                        TInfo, SubExpr,
2614                                        SourceRange(LAngleLoc, RAngleLoc),
2615                                        SourceRange(LParenLoc, RParenLoc));
2616   }
2617
2618   /// Build a new C++ reinterpret_cast expression.
2619   ///
2620   /// By default, performs semantic analysis to build the new expression.
2621   /// Subclasses may override this routine to provide different behavior.
2622   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2623                                                  SourceLocation LAngleLoc,
2624                                                  TypeSourceInfo *TInfo,
2625                                                  SourceLocation RAngleLoc,
2626                                                  SourceLocation LParenLoc,
2627                                                  Expr *SubExpr,
2628                                                  SourceLocation RParenLoc) {
2629     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2630                                        TInfo, SubExpr,
2631                                        SourceRange(LAngleLoc, RAngleLoc),
2632                                        SourceRange(LParenLoc, RParenLoc));
2633   }
2634
2635   /// Build a new C++ const_cast expression.
2636   ///
2637   /// By default, performs semantic analysis to build the new expression.
2638   /// Subclasses may override this routine to provide different behavior.
2639   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2640                                            SourceLocation LAngleLoc,
2641                                            TypeSourceInfo *TInfo,
2642                                            SourceLocation RAngleLoc,
2643                                            SourceLocation LParenLoc,
2644                                            Expr *SubExpr,
2645                                            SourceLocation RParenLoc) {
2646     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2647                                        TInfo, SubExpr,
2648                                        SourceRange(LAngleLoc, RAngleLoc),
2649                                        SourceRange(LParenLoc, RParenLoc));
2650   }
2651
2652   /// Build a new C++ functional-style cast expression.
2653   ///
2654   /// By default, performs semantic analysis to build the new expression.
2655   /// Subclasses may override this routine to provide different behavior.
2656   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2657                                           SourceLocation LParenLoc,
2658                                           Expr *Sub,
2659                                           SourceLocation RParenLoc,
2660                                           bool ListInitialization) {
2661     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2662                                                MultiExprArg(&Sub, 1), RParenLoc,
2663                                                ListInitialization);
2664   }
2665
2666   /// Build a new C++ __builtin_bit_cast expression.
2667   ///
2668   /// By default, performs semantic analysis to build the new expression.
2669   /// Subclasses may override this routine to provide different behavior.
2670   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
2671                                        TypeSourceInfo *TSI, Expr *Sub,
2672                                        SourceLocation RParenLoc) {
2673     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
2674   }
2675
2676   /// Build a new C++ typeid(type) expression.
2677   ///
2678   /// By default, performs semantic analysis to build the new expression.
2679   /// Subclasses may override this routine to provide different behavior.
2680   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2681                                         SourceLocation TypeidLoc,
2682                                         TypeSourceInfo *Operand,
2683                                         SourceLocation RParenLoc) {
2684     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2685                                     RParenLoc);
2686   }
2687
2688
2689   /// Build a new C++ typeid(expr) expression.
2690   ///
2691   /// By default, performs semantic analysis to build the new expression.
2692   /// Subclasses may override this routine to provide different behavior.
2693   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2694                                         SourceLocation TypeidLoc,
2695                                         Expr *Operand,
2696                                         SourceLocation RParenLoc) {
2697     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2698                                     RParenLoc);
2699   }
2700
2701   /// Build a new C++ __uuidof(type) expression.
2702   ///
2703   /// By default, performs semantic analysis to build the new expression.
2704   /// Subclasses may override this routine to provide different behavior.
2705   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2706                                         SourceLocation TypeidLoc,
2707                                         TypeSourceInfo *Operand,
2708                                         SourceLocation RParenLoc) {
2709     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2710                                     RParenLoc);
2711   }
2712
2713   /// Build a new C++ __uuidof(expr) expression.
2714   ///
2715   /// By default, performs semantic analysis to build the new expression.
2716   /// Subclasses may override this routine to provide different behavior.
2717   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2718                                         SourceLocation TypeidLoc,
2719                                         Expr *Operand,
2720                                         SourceLocation RParenLoc) {
2721     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2722                                     RParenLoc);
2723   }
2724
2725   /// Build a new C++ "this" expression.
2726   ///
2727   /// By default, builds a new "this" expression without performing any
2728   /// semantic analysis. Subclasses may override this routine to provide
2729   /// different behavior.
2730   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2731                                 QualType ThisType,
2732                                 bool isImplicit) {
2733     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
2734   }
2735
2736   /// Build a new C++ throw expression.
2737   ///
2738   /// By default, performs semantic analysis to build the new expression.
2739   /// Subclasses may override this routine to provide different behavior.
2740   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2741                                  bool IsThrownVariableInScope) {
2742     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2743   }
2744
2745   /// Build a new C++ default-argument expression.
2746   ///
2747   /// By default, builds a new default-argument expression, which does not
2748   /// require any semantic analysis. Subclasses may override this routine to
2749   /// provide different behavior.
2750   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
2751     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
2752                                      getSema().CurContext);
2753   }
2754
2755   /// Build a new C++11 default-initialization expression.
2756   ///
2757   /// By default, builds a new default field initialization expression, which
2758   /// does not require any semantic analysis. Subclasses may override this
2759   /// routine to provide different behavior.
2760   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2761                                        FieldDecl *Field) {
2762     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
2763                                       getSema().CurContext);
2764   }
2765
2766   /// Build a new C++ zero-initialization expression.
2767   ///
2768   /// By default, performs semantic analysis to build the new expression.
2769   /// Subclasses may override this routine to provide different behavior.
2770   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2771                                            SourceLocation LParenLoc,
2772                                            SourceLocation RParenLoc) {
2773     return getSema().BuildCXXTypeConstructExpr(
2774         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2775   }
2776
2777   /// Build a new C++ "new" expression.
2778   ///
2779   /// By default, performs semantic analysis to build the new expression.
2780   /// Subclasses may override this routine to provide different behavior.
2781   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2782                                bool UseGlobal,
2783                                SourceLocation PlacementLParen,
2784                                MultiExprArg PlacementArgs,
2785                                SourceLocation PlacementRParen,
2786                                SourceRange TypeIdParens,
2787                                QualType AllocatedType,
2788                                TypeSourceInfo *AllocatedTypeInfo,
2789                                Optional<Expr *> ArraySize,
2790                                SourceRange DirectInitRange,
2791                                Expr *Initializer) {
2792     return getSema().BuildCXXNew(StartLoc, UseGlobal,
2793                                  PlacementLParen,
2794                                  PlacementArgs,
2795                                  PlacementRParen,
2796                                  TypeIdParens,
2797                                  AllocatedType,
2798                                  AllocatedTypeInfo,
2799                                  ArraySize,
2800                                  DirectInitRange,
2801                                  Initializer);
2802   }
2803
2804   /// Build a new C++ "delete" expression.
2805   ///
2806   /// By default, performs semantic analysis to build the new expression.
2807   /// Subclasses may override this routine to provide different behavior.
2808   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2809                                         bool IsGlobalDelete,
2810                                         bool IsArrayForm,
2811                                         Expr *Operand) {
2812     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2813                                     Operand);
2814   }
2815
2816   /// Build a new type trait expression.
2817   ///
2818   /// By default, performs semantic analysis to build the new expression.
2819   /// Subclasses may override this routine to provide different behavior.
2820   ExprResult RebuildTypeTrait(TypeTrait Trait,
2821                               SourceLocation StartLoc,
2822                               ArrayRef<TypeSourceInfo *> Args,
2823                               SourceLocation RParenLoc) {
2824     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2825   }
2826
2827   /// Build a new array type trait expression.
2828   ///
2829   /// By default, performs semantic analysis to build the new expression.
2830   /// Subclasses may override this routine to provide different behavior.
2831   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2832                                    SourceLocation StartLoc,
2833                                    TypeSourceInfo *TSInfo,
2834                                    Expr *DimExpr,
2835                                    SourceLocation RParenLoc) {
2836     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2837   }
2838
2839   /// Build a new expression trait expression.
2840   ///
2841   /// By default, performs semantic analysis to build the new expression.
2842   /// Subclasses may override this routine to provide different behavior.
2843   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2844                                    SourceLocation StartLoc,
2845                                    Expr *Queried,
2846                                    SourceLocation RParenLoc) {
2847     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2848   }
2849
2850   /// Build a new (previously unresolved) declaration reference
2851   /// expression.
2852   ///
2853   /// By default, performs semantic analysis to build the new expression.
2854   /// Subclasses may override this routine to provide different behavior.
2855   ExprResult RebuildDependentScopeDeclRefExpr(
2856                                           NestedNameSpecifierLoc QualifierLoc,
2857                                           SourceLocation TemplateKWLoc,
2858                                        const DeclarationNameInfo &NameInfo,
2859                               const TemplateArgumentListInfo *TemplateArgs,
2860                                           bool IsAddressOfOperand,
2861                                           TypeSourceInfo **RecoveryTSI) {
2862     CXXScopeSpec SS;
2863     SS.Adopt(QualifierLoc);
2864
2865     if (TemplateArgs || TemplateKWLoc.isValid())
2866       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2867                                                     TemplateArgs);
2868
2869     return getSema().BuildQualifiedDeclarationNameExpr(
2870         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2871   }
2872
2873   /// Build a new template-id expression.
2874   ///
2875   /// By default, performs semantic analysis to build the new expression.
2876   /// Subclasses may override this routine to provide different behavior.
2877   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2878                                    SourceLocation TemplateKWLoc,
2879                                    LookupResult &R,
2880                                    bool RequiresADL,
2881                               const TemplateArgumentListInfo *TemplateArgs) {
2882     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2883                                          TemplateArgs);
2884   }
2885
2886   /// Build a new object-construction expression.
2887   ///
2888   /// By default, performs semantic analysis to build the new expression.
2889   /// Subclasses may override this routine to provide different behavior.
2890   ExprResult RebuildCXXConstructExpr(QualType T,
2891                                      SourceLocation Loc,
2892                                      CXXConstructorDecl *Constructor,
2893                                      bool IsElidable,
2894                                      MultiExprArg Args,
2895                                      bool HadMultipleCandidates,
2896                                      bool ListInitialization,
2897                                      bool StdInitListInitialization,
2898                                      bool RequiresZeroInit,
2899                              CXXConstructExpr::ConstructionKind ConstructKind,
2900                                      SourceRange ParenRange) {
2901     SmallVector<Expr*, 8> ConvertedArgs;
2902     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2903                                           ConvertedArgs))
2904       return ExprError();
2905
2906     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2907                                            IsElidable,
2908                                            ConvertedArgs,
2909                                            HadMultipleCandidates,
2910                                            ListInitialization,
2911                                            StdInitListInitialization,
2912                                            RequiresZeroInit, ConstructKind,
2913                                            ParenRange);
2914   }
2915
2916   /// Build a new implicit construction via inherited constructor
2917   /// expression.
2918   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2919                                              CXXConstructorDecl *Constructor,
2920                                              bool ConstructsVBase,
2921                                              bool InheritedFromVBase) {
2922     return new (getSema().Context) CXXInheritedCtorInitExpr(
2923         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2924   }
2925
2926   /// Build a new object-construction expression.
2927   ///
2928   /// By default, performs semantic analysis to build the new expression.
2929   /// Subclasses may override this routine to provide different behavior.
2930   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2931                                            SourceLocation LParenOrBraceLoc,
2932                                            MultiExprArg Args,
2933                                            SourceLocation RParenOrBraceLoc,
2934                                            bool ListInitialization) {
2935     return getSema().BuildCXXTypeConstructExpr(
2936         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
2937   }
2938
2939   /// Build a new object-construction expression.
2940   ///
2941   /// By default, performs semantic analysis to build the new expression.
2942   /// Subclasses may override this routine to provide different behavior.
2943   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2944                                                SourceLocation LParenLoc,
2945                                                MultiExprArg Args,
2946                                                SourceLocation RParenLoc,
2947                                                bool ListInitialization) {
2948     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
2949                                                RParenLoc, ListInitialization);
2950   }
2951
2952   /// Build a new member reference expression.
2953   ///
2954   /// By default, performs semantic analysis to build the new expression.
2955   /// Subclasses may override this routine to provide different behavior.
2956   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2957                                                 QualType BaseType,
2958                                                 bool IsArrow,
2959                                                 SourceLocation OperatorLoc,
2960                                           NestedNameSpecifierLoc QualifierLoc,
2961                                                 SourceLocation TemplateKWLoc,
2962                                             NamedDecl *FirstQualifierInScope,
2963                                    const DeclarationNameInfo &MemberNameInfo,
2964                               const TemplateArgumentListInfo *TemplateArgs) {
2965     CXXScopeSpec SS;
2966     SS.Adopt(QualifierLoc);
2967
2968     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2969                                             OperatorLoc, IsArrow,
2970                                             SS, TemplateKWLoc,
2971                                             FirstQualifierInScope,
2972                                             MemberNameInfo,
2973                                             TemplateArgs, /*S*/nullptr);
2974   }
2975
2976   /// Build a new member reference expression.
2977   ///
2978   /// By default, performs semantic analysis to build the new expression.
2979   /// Subclasses may override this routine to provide different behavior.
2980   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2981                                          SourceLocation OperatorLoc,
2982                                          bool IsArrow,
2983                                          NestedNameSpecifierLoc QualifierLoc,
2984                                          SourceLocation TemplateKWLoc,
2985                                          NamedDecl *FirstQualifierInScope,
2986                                          LookupResult &R,
2987                                 const TemplateArgumentListInfo *TemplateArgs) {
2988     CXXScopeSpec SS;
2989     SS.Adopt(QualifierLoc);
2990
2991     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2992                                             OperatorLoc, IsArrow,
2993                                             SS, TemplateKWLoc,
2994                                             FirstQualifierInScope,
2995                                             R, TemplateArgs, /*S*/nullptr);
2996   }
2997
2998   /// Build a new noexcept expression.
2999   ///
3000   /// By default, performs semantic analysis to build the new expression.
3001   /// Subclasses may override this routine to provide different behavior.
3002   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3003     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3004   }
3005
3006   /// Build a new expression to compute the length of a parameter pack.
3007   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3008                                    NamedDecl *Pack,
3009                                    SourceLocation PackLoc,
3010                                    SourceLocation RParenLoc,
3011                                    Optional<unsigned> Length,
3012                                    ArrayRef<TemplateArgument> PartialArgs) {
3013     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3014                                   RParenLoc, Length, PartialArgs);
3015   }
3016
3017   /// Build a new expression representing a call to a source location
3018   ///  builtin.
3019   ///
3020   /// By default, performs semantic analysis to build the new expression.
3021   /// Subclasses may override this routine to provide different behavior.
3022   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3023                                   SourceLocation BuiltinLoc,
3024                                   SourceLocation RPLoc,
3025                                   DeclContext *ParentContext) {
3026     return getSema().BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, ParentContext);
3027   }
3028
3029   /// Build a new Objective-C boxed expression.
3030   ///
3031   /// By default, performs semantic analysis to build the new expression.
3032   /// Subclasses may override this routine to provide different behavior.
3033   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3034       SourceLocation TemplateKWLoc, SourceLocation ConceptNameLoc,
3035       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3036       TemplateArgumentListInfo *TALI) {
3037     CXXScopeSpec SS;
3038     SS.Adopt(NNS);
3039     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3040                                                          ConceptNameLoc,
3041                                                          FoundDecl,
3042                                                          NamedConcept, TALI);
3043     if (Result.isInvalid())
3044       return ExprError();
3045     return Result;
3046   }
3047
3048     /// \brief Build a new Objective-C boxed expression.
3049   ///
3050   /// By default, performs semantic analysis to build the new expression.
3051   /// Subclasses may override this routine to provide different behavior.
3052   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3053     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3054   }
3055
3056   /// Build a new Objective-C array literal.
3057   ///
3058   /// By default, performs semantic analysis to build the new expression.
3059   /// Subclasses may override this routine to provide different behavior.
3060   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3061                                      Expr **Elements, unsigned NumElements) {
3062     return getSema().BuildObjCArrayLiteral(Range,
3063                                            MultiExprArg(Elements, NumElements));
3064   }
3065
3066   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3067                                          Expr *Base, Expr *Key,
3068                                          ObjCMethodDecl *getterMethod,
3069                                          ObjCMethodDecl *setterMethod) {
3070     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3071                                                    getterMethod, setterMethod);
3072   }
3073
3074   /// Build a new Objective-C dictionary literal.
3075   ///
3076   /// By default, performs semantic analysis to build the new expression.
3077   /// Subclasses may override this routine to provide different behavior.
3078   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3079                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3080     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3081   }
3082
3083   /// Build a new Objective-C \@encode expression.
3084   ///
3085   /// By default, performs semantic analysis to build the new expression.
3086   /// Subclasses may override this routine to provide different behavior.
3087   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3088                                          TypeSourceInfo *EncodeTypeInfo,
3089                                          SourceLocation RParenLoc) {
3090     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3091   }
3092
3093   /// Build a new Objective-C class message.
3094   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3095                                           Selector Sel,
3096                                           ArrayRef<SourceLocation> SelectorLocs,
3097                                           ObjCMethodDecl *Method,
3098                                           SourceLocation LBracLoc,
3099                                           MultiExprArg Args,
3100                                           SourceLocation RBracLoc) {
3101     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3102                                      ReceiverTypeInfo->getType(),
3103                                      /*SuperLoc=*/SourceLocation(),
3104                                      Sel, Method, LBracLoc, SelectorLocs,
3105                                      RBracLoc, Args);
3106   }
3107
3108   /// Build a new Objective-C instance message.
3109   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3110                                           Selector Sel,
3111                                           ArrayRef<SourceLocation> SelectorLocs,
3112                                           ObjCMethodDecl *Method,
3113                                           SourceLocation LBracLoc,
3114                                           MultiExprArg Args,
3115                                           SourceLocation RBracLoc) {
3116     return SemaRef.BuildInstanceMessage(Receiver,
3117                                         Receiver->getType(),
3118                                         /*SuperLoc=*/SourceLocation(),
3119                                         Sel, Method, LBracLoc, SelectorLocs,
3120                                         RBracLoc, Args);
3121   }
3122
3123   /// Build a new Objective-C instance/class message to 'super'.
3124   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3125                                     Selector Sel,
3126                                     ArrayRef<SourceLocation> SelectorLocs,
3127                                     QualType SuperType,
3128                                     ObjCMethodDecl *Method,
3129                                     SourceLocation LBracLoc,
3130                                     MultiExprArg Args,
3131                                     SourceLocation RBracLoc) {
3132     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3133                                           SuperType,
3134                                           SuperLoc,
3135                                           Sel, Method, LBracLoc, SelectorLocs,
3136                                           RBracLoc, Args)
3137                                       : SemaRef.BuildClassMessage(nullptr,
3138                                           SuperType,
3139                                           SuperLoc,
3140                                           Sel, Method, LBracLoc, SelectorLocs,
3141                                           RBracLoc, Args);
3142
3143
3144   }
3145
3146   /// Build a new Objective-C ivar reference expression.
3147   ///
3148   /// By default, performs semantic analysis to build the new expression.
3149   /// Subclasses may override this routine to provide different behavior.
3150   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3151                                           SourceLocation IvarLoc,
3152                                           bool IsArrow, bool IsFreeIvar) {
3153     CXXScopeSpec SS;
3154     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3155     ExprResult Result = getSema().BuildMemberReferenceExpr(
3156         BaseArg, BaseArg->getType(),
3157         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3158         /*FirstQualifierInScope=*/nullptr, NameInfo,
3159         /*TemplateArgs=*/nullptr,
3160         /*S=*/nullptr);
3161     if (IsFreeIvar && Result.isUsable())
3162       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3163     return Result;
3164   }
3165
3166   /// Build a new Objective-C property reference expression.
3167   ///
3168   /// By default, performs semantic analysis to build the new expression.
3169   /// Subclasses may override this routine to provide different behavior.
3170   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3171                                         ObjCPropertyDecl *Property,
3172                                         SourceLocation PropertyLoc) {
3173     CXXScopeSpec SS;
3174     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3175     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3176                                               /*FIXME:*/PropertyLoc,
3177                                               /*IsArrow=*/false,
3178                                               SS, SourceLocation(),
3179                                               /*FirstQualifierInScope=*/nullptr,
3180                                               NameInfo,
3181                                               /*TemplateArgs=*/nullptr,
3182                                               /*S=*/nullptr);
3183   }
3184
3185   /// Build a new Objective-C property reference expression.
3186   ///
3187   /// By default, performs semantic analysis to build the new expression.
3188   /// Subclasses may override this routine to provide different behavior.
3189   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3190                                         ObjCMethodDecl *Getter,
3191                                         ObjCMethodDecl *Setter,
3192                                         SourceLocation PropertyLoc) {
3193     // Since these expressions can only be value-dependent, we do not
3194     // need to perform semantic analysis again.
3195     return Owned(
3196       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3197                                                   VK_LValue, OK_ObjCProperty,
3198                                                   PropertyLoc, Base));
3199   }
3200
3201   /// Build a new Objective-C "isa" expression.
3202   ///
3203   /// By default, performs semantic analysis to build the new expression.
3204   /// Subclasses may override this routine to provide different behavior.
3205   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3206                                 SourceLocation OpLoc, bool IsArrow) {
3207     CXXScopeSpec SS;
3208     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3209     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3210                                               OpLoc, IsArrow,
3211                                               SS, SourceLocation(),
3212                                               /*FirstQualifierInScope=*/nullptr,
3213                                               NameInfo,
3214                                               /*TemplateArgs=*/nullptr,
3215                                               /*S=*/nullptr);
3216   }
3217
3218   /// Build a new shuffle vector 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 RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3223                                       MultiExprArg SubExprs,
3224                                       SourceLocation RParenLoc) {
3225     // Find the declaration for __builtin_shufflevector
3226     const IdentifierInfo &Name
3227       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3228     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3229     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3230     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3231
3232     // Build a reference to the __builtin_shufflevector builtin
3233     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3234     Expr *Callee = new (SemaRef.Context)
3235         DeclRefExpr(SemaRef.Context, Builtin, false,
3236                     SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3237     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3238     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3239                                        CK_BuiltinFnToFnPtr).get();
3240
3241     // Build the CallExpr
3242     ExprResult TheCall = CallExpr::Create(
3243         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3244         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3245
3246     // Type-check the __builtin_shufflevector expression.
3247     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3248   }
3249
3250   /// Build a new convert vector expression.
3251   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3252                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3253                                       SourceLocation RParenLoc) {
3254     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3255                                          BuiltinLoc, RParenLoc);
3256   }
3257
3258   /// Build a new template argument pack expansion.
3259   ///
3260   /// By default, performs semantic analysis to build a new pack expansion
3261   /// for a template argument. Subclasses may override this routine to provide
3262   /// different behavior.
3263   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3264                                            SourceLocation EllipsisLoc,
3265                                            Optional<unsigned> NumExpansions) {
3266     switch (Pattern.getArgument().getKind()) {
3267     case TemplateArgument::Expression: {
3268       ExprResult Result
3269         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3270                                        EllipsisLoc, NumExpansions);
3271       if (Result.isInvalid())
3272         return TemplateArgumentLoc();
3273
3274       return TemplateArgumentLoc(Result.get(), Result.get());
3275     }
3276
3277     case TemplateArgument::Template:
3278       return TemplateArgumentLoc(TemplateArgument(
3279                                           Pattern.getArgument().getAsTemplate(),
3280                                                   NumExpansions),
3281                                  Pattern.getTemplateQualifierLoc(),
3282                                  Pattern.getTemplateNameLoc(),
3283                                  EllipsisLoc);
3284
3285     case TemplateArgument::Null:
3286     case TemplateArgument::Integral:
3287     case TemplateArgument::Declaration:
3288     case TemplateArgument::Pack:
3289     case TemplateArgument::TemplateExpansion:
3290     case TemplateArgument::NullPtr:
3291       llvm_unreachable("Pack expansion pattern has no parameter packs");
3292
3293     case TemplateArgument::Type:
3294       if (TypeSourceInfo *Expansion
3295             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3296                                            EllipsisLoc,
3297                                            NumExpansions))
3298         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3299                                    Expansion);
3300       break;
3301     }
3302
3303     return TemplateArgumentLoc();
3304   }
3305
3306   /// Build a new expression pack expansion.
3307   ///
3308   /// By default, performs semantic analysis to build a new pack expansion
3309   /// for an expression. Subclasses may override this routine to provide
3310   /// different behavior.
3311   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3312                                   Optional<unsigned> NumExpansions) {
3313     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3314   }
3315
3316   /// Build a new C++1z fold-expression.
3317   ///
3318   /// By default, performs semantic analysis in order to build a new fold
3319   /// expression.
3320   ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3321                                 BinaryOperatorKind Operator,
3322                                 SourceLocation EllipsisLoc, Expr *RHS,
3323                                 SourceLocation RParenLoc,
3324                                 Optional<unsigned> NumExpansions) {
3325     return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3326                                       RHS, RParenLoc, NumExpansions);
3327   }
3328
3329   /// Build an empty C++1z fold-expression with the given operator.
3330   ///
3331   /// By default, produces the fallback value for the fold-expression, or
3332   /// produce an error if there is no fallback value.
3333   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3334                                      BinaryOperatorKind Operator) {
3335     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3336   }
3337
3338   /// Build a new atomic operation expression.
3339   ///
3340   /// By default, performs semantic analysis to build the new expression.
3341   /// Subclasses may override this routine to provide different behavior.
3342   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3343                                AtomicExpr::AtomicOp Op,
3344                                SourceLocation RParenLoc) {
3345     // Use this for all of the locations, since we don't know the difference
3346     // between the call and the expr at this point.
3347     SourceRange Range{BuiltinLoc, RParenLoc};
3348     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3349                                      Sema::AtomicArgumentOrder::AST);
3350   }
3351
3352 private:
3353   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3354                                      QualType ObjectType,
3355                                      NamedDecl *FirstQualifierInScope,
3356                                      CXXScopeSpec &SS);
3357
3358   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3359                                              QualType ObjectType,
3360                                              NamedDecl *FirstQualifierInScope,
3361                                              CXXScopeSpec &SS);
3362
3363   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3364                                             NamedDecl *FirstQualifierInScope,
3365                                             CXXScopeSpec &SS);
3366
3367   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3368                                       DependentNameTypeLoc TL,
3369                                       bool DeducibleTSTContext);
3370 };
3371
3372 template <typename Derived>
3373 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3374   if (!S)
3375     return S;
3376
3377   switch (S->getStmtClass()) {
3378   case Stmt::NoStmtClass: break;
3379
3380   // Transform individual statement nodes
3381   // Pass SDK into statements that can produce a value
3382 #define STMT(Node, Parent)                                              \
3383   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3384 #define VALUESTMT(Node, Parent)                                         \
3385   case Stmt::Node##Class:                                               \
3386     return getDerived().Transform##Node(cast<Node>(S), SDK);
3387 #define ABSTRACT_STMT(Node)
3388 #define EXPR(Node, Parent)
3389 #include "clang/AST/StmtNodes.inc"
3390
3391   // Transform expressions by calling TransformExpr.
3392 #define STMT(Node, Parent)
3393 #define ABSTRACT_STMT(Stmt)
3394 #define EXPR(Node, Parent) case Stmt::Node##Class:
3395 #include "clang/AST/StmtNodes.inc"
3396     {
3397       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3398
3399       if (SDK == SDK_StmtExprResult)
3400         E = getSema().ActOnStmtExprResult(E);
3401       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3402     }
3403   }
3404
3405   return S;
3406 }
3407
3408 template<typename Derived>
3409 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3410   if (!S)
3411     return S;
3412
3413   switch (S->getClauseKind()) {
3414   default: break;
3415   // Transform individual clause nodes
3416 #define OPENMP_CLAUSE(Name, Class)                                             \
3417   case OMPC_ ## Name :                                                         \
3418     return getDerived().Transform ## Class(cast<Class>(S));
3419 #include "clang/Basic/OpenMPKinds.def"
3420   }
3421
3422   return S;
3423 }
3424
3425
3426 template<typename Derived>
3427 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3428   if (!E)
3429     return E;
3430
3431   switch (E->getStmtClass()) {
3432     case Stmt::NoStmtClass: break;
3433 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3434 #define ABSTRACT_STMT(Stmt)
3435 #define EXPR(Node, Parent)                                              \
3436     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3437 #include "clang/AST/StmtNodes.inc"
3438   }
3439
3440   return E;
3441 }
3442
3443 template<typename Derived>
3444 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3445                                                         bool NotCopyInit) {
3446   // Initializers are instantiated like expressions, except that various outer
3447   // layers are stripped.
3448   if (!Init)
3449     return Init;
3450
3451   if (auto *FE = dyn_cast<FullExpr>(Init))
3452     Init = FE->getSubExpr();
3453
3454   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3455     Init = AIL->getCommonExpr();
3456
3457   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3458     Init = MTE->GetTemporaryExpr();
3459
3460   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3461     Init = Binder->getSubExpr();
3462
3463   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3464     Init = ICE->getSubExprAsWritten();
3465
3466   if (CXXStdInitializerListExpr *ILE =
3467           dyn_cast<CXXStdInitializerListExpr>(Init))
3468     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3469
3470   // If this is copy-initialization, we only need to reconstruct
3471   // InitListExprs. Other forms of copy-initialization will be a no-op if
3472   // the initializer is already the right type.
3473   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3474   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3475     return getDerived().TransformExpr(Init);
3476
3477   // Revert value-initialization back to empty parens.
3478   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3479     SourceRange Parens = VIE->getSourceRange();
3480     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3481                                              Parens.getEnd());
3482   }
3483
3484   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3485   if (isa<ImplicitValueInitExpr>(Init))
3486     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3487                                              SourceLocation());
3488
3489   // Revert initialization by constructor back to a parenthesized or braced list
3490   // of expressions. Any other form of initializer can just be reused directly.
3491   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3492     return getDerived().TransformExpr(Init);
3493
3494   // If the initialization implicitly converted an initializer list to a
3495   // std::initializer_list object, unwrap the std::initializer_list too.
3496   if (Construct && Construct->isStdInitListInitialization())
3497     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3498
3499   // Enter a list-init context if this was list initialization.
3500   EnterExpressionEvaluationContext Context(
3501       getSema(), EnterExpressionEvaluationContext::InitList,
3502       Construct->isListInitialization());
3503
3504   SmallVector<Expr*, 8> NewArgs;
3505   bool ArgChanged = false;
3506   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3507                                   /*IsCall*/true, NewArgs, &ArgChanged))
3508     return ExprError();
3509
3510   // If this was list initialization, revert to syntactic list form.
3511   if (Construct->isListInitialization())
3512     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3513                                         Construct->getEndLoc());
3514
3515   // Build a ParenListExpr to represent anything else.
3516   SourceRange Parens = Construct->getParenOrBraceRange();
3517   if (Parens.isInvalid()) {
3518     // This was a variable declaration's initialization for which no initializer
3519     // was specified.
3520     assert(NewArgs.empty() &&
3521            "no parens or braces but have direct init with arguments?");
3522     return ExprEmpty();
3523   }
3524   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3525                                            Parens.getEnd());
3526 }
3527
3528 template<typename Derived>
3529 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3530                                             unsigned NumInputs,
3531                                             bool IsCall,
3532                                       SmallVectorImpl<Expr *> &Outputs,
3533                                             bool *ArgChanged) {
3534   for (unsigned I = 0; I != NumInputs; ++I) {
3535     // If requested, drop call arguments that need to be dropped.
3536     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3537       if (ArgChanged)
3538         *ArgChanged = true;
3539
3540       break;
3541     }
3542
3543     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3544       Expr *Pattern = Expansion->getPattern();
3545
3546       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3547       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3548       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3549
3550       // Determine whether the set of unexpanded parameter packs can and should
3551       // be expanded.
3552       bool Expand = true;
3553       bool RetainExpansion = false;
3554       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3555       Optional<unsigned> NumExpansions = OrigNumExpansions;
3556       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3557                                                Pattern->getSourceRange(),
3558                                                Unexpanded,
3559                                                Expand, RetainExpansion,
3560                                                NumExpansions))
3561         return true;
3562
3563       if (!Expand) {
3564         // The transform has determined that we should perform a simple
3565         // transformation on the pack expansion, producing another pack
3566         // expansion.
3567         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3568         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3569         if (OutPattern.isInvalid())
3570           return true;
3571
3572         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3573                                                 Expansion->getEllipsisLoc(),
3574                                                            NumExpansions);
3575         if (Out.isInvalid())
3576           return true;
3577
3578         if (ArgChanged)
3579           *ArgChanged = true;
3580         Outputs.push_back(Out.get());
3581         continue;
3582       }
3583
3584       // Record right away that the argument was changed.  This needs
3585       // to happen even if the array expands to nothing.
3586       if (ArgChanged) *ArgChanged = true;
3587
3588       // The transform has determined that we should perform an elementwise
3589       // expansion of the pattern. Do so.
3590       for (unsigned I = 0; I != *NumExpansions; ++I) {
3591         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3592         ExprResult Out = getDerived().TransformExpr(Pattern);
3593         if (Out.isInvalid())
3594           return true;
3595
3596         if (Out.get()->containsUnexpandedParameterPack()) {
3597           Out = getDerived().RebuildPackExpansion(
3598               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3599           if (Out.isInvalid())
3600             return true;
3601         }
3602
3603         Outputs.push_back(Out.get());
3604       }
3605
3606       // If we're supposed to retain a pack expansion, do so by temporarily
3607       // forgetting the partially-substituted parameter pack.
3608       if (RetainExpansion) {
3609         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3610
3611         ExprResult Out = getDerived().TransformExpr(Pattern);
3612         if (Out.isInvalid())
3613           return true;
3614
3615         Out = getDerived().RebuildPackExpansion(
3616             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3617         if (Out.isInvalid())
3618           return true;
3619
3620         Outputs.push_back(Out.get());
3621       }
3622
3623       continue;
3624     }
3625
3626     ExprResult Result =
3627       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3628              : getDerived().TransformExpr(Inputs[I]);
3629     if (Result.isInvalid())
3630       return true;
3631
3632     if (Result.get() != Inputs[I] && ArgChanged)
3633       *ArgChanged = true;
3634
3635     Outputs.push_back(Result.get());
3636   }
3637
3638   return false;
3639 }
3640
3641 template <typename Derived>
3642 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3643     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3644   if (Var) {
3645     VarDecl *ConditionVar = cast_or_null<VarDecl>(
3646         getDerived().TransformDefinition(Var->getLocation(), Var));
3647
3648     if (!ConditionVar)
3649       return Sema::ConditionError();
3650
3651     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3652   }
3653
3654   if (Expr) {
3655     ExprResult CondExpr = getDerived().TransformExpr(Expr);
3656
3657     if (CondExpr.isInvalid())
3658       return Sema::ConditionError();
3659
3660     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3661   }
3662
3663   return Sema::ConditionResult();
3664 }
3665
3666 template<typename Derived>
3667 NestedNameSpecifierLoc
3668 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3669                                                     NestedNameSpecifierLoc NNS,
3670                                                      QualType ObjectType,
3671                                              NamedDecl *FirstQualifierInScope) {
3672   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3673   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3674        Qualifier = Qualifier.getPrefix())
3675     Qualifiers.push_back(Qualifier);
3676
3677   CXXScopeSpec SS;
3678   while (!Qualifiers.empty()) {
3679     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3680     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3681
3682     switch (QNNS->getKind()) {
3683     case NestedNameSpecifier::Identifier: {
3684       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3685                           Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3686       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3687                                               SS, FirstQualifierInScope, false))
3688         return NestedNameSpecifierLoc();
3689     }
3690       break;
3691
3692     case NestedNameSpecifier::Namespace: {
3693       NamespaceDecl *NS
3694         = cast_or_null<NamespaceDecl>(
3695                                     getDerived().TransformDecl(
3696                                                           Q.getLocalBeginLoc(),
3697                                                        QNNS->getAsNamespace()));
3698       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3699       break;
3700     }
3701
3702     case NestedNameSpecifier::NamespaceAlias: {
3703       NamespaceAliasDecl *Alias
3704         = cast_or_null<NamespaceAliasDecl>(
3705                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
3706                                                  QNNS->getAsNamespaceAlias()));
3707       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3708                 Q.getLocalEndLoc());
3709       break;
3710     }
3711
3712     case NestedNameSpecifier::Global:
3713       // There is no meaningful transformation that one could perform on the
3714       // global scope.
3715       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3716       break;
3717
3718     case NestedNameSpecifier::Super: {
3719       CXXRecordDecl *RD =
3720           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3721               SourceLocation(), QNNS->getAsRecordDecl()));
3722       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3723       break;
3724     }
3725
3726     case NestedNameSpecifier::TypeSpecWithTemplate:
3727     case NestedNameSpecifier::TypeSpec: {
3728       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3729                                               FirstQualifierInScope, SS);
3730
3731       if (!TL)
3732         return NestedNameSpecifierLoc();
3733
3734       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3735           (SemaRef.getLangOpts().CPlusPlus11 &&
3736            TL.getType()->isEnumeralType())) {
3737         assert(!TL.getType().hasLocalQualifiers() &&
3738                "Can't get cv-qualifiers here");
3739         if (TL.getType()->isEnumeralType())
3740           SemaRef.Diag(TL.getBeginLoc(),
3741                        diag::warn_cxx98_compat_enum_nested_name_spec);
3742         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3743                   Q.getLocalEndLoc());
3744         break;
3745       }
3746       // If the nested-name-specifier is an invalid type def, don't emit an
3747       // error because a previous error should have already been emitted.
3748       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3749       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3750         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3751           << TL.getType() << SS.getRange();
3752       }
3753       return NestedNameSpecifierLoc();
3754     }
3755     }
3756
3757     // The qualifier-in-scope and object type only apply to the leftmost entity.
3758     FirstQualifierInScope = nullptr;
3759     ObjectType = QualType();
3760   }
3761
3762   // Don't rebuild the nested-name-specifier if we don't have to.
3763   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3764       !getDerived().AlwaysRebuild())
3765     return NNS;
3766
3767   // If we can re-use the source-location data from the original
3768   // nested-name-specifier, do so.
3769   if (SS.location_size() == NNS.getDataLength() &&
3770       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3771     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3772
3773   // Allocate new nested-name-specifier location information.
3774   return SS.getWithLocInContext(SemaRef.Context);
3775 }
3776
3777 template<typename Derived>
3778 DeclarationNameInfo
3779 TreeTransform<Derived>
3780 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3781   DeclarationName Name = NameInfo.getName();
3782   if (!Name)
3783     return DeclarationNameInfo();
3784
3785   switch (Name.getNameKind()) {
3786   case DeclarationName::Identifier:
3787   case DeclarationName::ObjCZeroArgSelector:
3788   case DeclarationName::ObjCOneArgSelector:
3789   case DeclarationName::ObjCMultiArgSelector:
3790   case DeclarationName::CXXOperatorName:
3791   case DeclarationName::CXXLiteralOperatorName:
3792   case DeclarationName::CXXUsingDirective:
3793     return NameInfo;
3794
3795   case DeclarationName::CXXDeductionGuideName: {
3796     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3797     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3798         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3799     if (!NewTemplate)
3800       return DeclarationNameInfo();
3801
3802     DeclarationNameInfo NewNameInfo(NameInfo);
3803     NewNameInfo.setName(
3804         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3805     return NewNameInfo;
3806   }
3807
3808   case DeclarationName::CXXConstructorName:
3809   case DeclarationName::CXXDestructorName:
3810   case DeclarationName::CXXConversionFunctionName: {
3811     TypeSourceInfo *NewTInfo;
3812     CanQualType NewCanTy;
3813     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3814       NewTInfo = getDerived().TransformType(OldTInfo);
3815       if (!NewTInfo)
3816         return DeclarationNameInfo();
3817       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3818     }
3819     else {
3820       NewTInfo = nullptr;
3821       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3822       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3823       if (NewT.isNull())
3824         return DeclarationNameInfo();
3825       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3826     }
3827
3828     DeclarationName NewName
3829       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3830                                                            NewCanTy);
3831     DeclarationNameInfo NewNameInfo(NameInfo);
3832     NewNameInfo.setName(NewName);
3833     NewNameInfo.setNamedTypeInfo(NewTInfo);
3834     return NewNameInfo;
3835   }
3836   }
3837
3838   llvm_unreachable("Unknown name kind.");
3839 }
3840
3841 template<typename Derived>
3842 TemplateName
3843 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3844                                               TemplateName Name,
3845                                               SourceLocation NameLoc,
3846                                               QualType ObjectType,
3847                                               NamedDecl *FirstQualifierInScope,
3848                                               bool AllowInjectedClassName) {
3849   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3850     TemplateDecl *Template = QTN->getTemplateDecl();
3851     assert(Template && "qualified template name must refer to a template");
3852
3853     TemplateDecl *TransTemplate
3854       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3855                                                               Template));
3856     if (!TransTemplate)
3857       return TemplateName();
3858
3859     if (!getDerived().AlwaysRebuild() &&
3860         SS.getScopeRep() == QTN->getQualifier() &&
3861         TransTemplate == Template)
3862       return Name;
3863
3864     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3865                                             TransTemplate);
3866   }
3867
3868   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3869     if (SS.getScopeRep()) {
3870       // These apply to the scope specifier, not the template.
3871       ObjectType = QualType();
3872       FirstQualifierInScope = nullptr;
3873     }
3874
3875     if (!getDerived().AlwaysRebuild() &&
3876         SS.getScopeRep() == DTN->getQualifier() &&
3877         ObjectType.isNull())
3878       return Name;
3879
3880     // FIXME: Preserve the location of the "template" keyword.
3881     SourceLocation TemplateKWLoc = NameLoc;
3882
3883     if (DTN->isIdentifier()) {
3884       return getDerived().RebuildTemplateName(SS,
3885                                               TemplateKWLoc,
3886                                               *DTN->getIdentifier(),
3887                                               NameLoc,
3888                                               ObjectType,
3889                                               FirstQualifierInScope,
3890                                               AllowInjectedClassName);
3891     }
3892
3893     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
3894                                             DTN->getOperator(), NameLoc,
3895                                             ObjectType, AllowInjectedClassName);
3896   }
3897
3898   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3899     TemplateDecl *TransTemplate
3900       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3901                                                               Template));
3902     if (!TransTemplate)
3903       return TemplateName();
3904
3905     if (!getDerived().AlwaysRebuild() &&
3906         TransTemplate == Template)
3907       return Name;
3908
3909     return TemplateName(TransTemplate);
3910   }
3911
3912   if (SubstTemplateTemplateParmPackStorage *SubstPack
3913       = Name.getAsSubstTemplateTemplateParmPack()) {
3914     TemplateTemplateParmDecl *TransParam
3915     = cast_or_null<TemplateTemplateParmDecl>(
3916             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3917     if (!TransParam)
3918       return TemplateName();
3919
3920     if (!getDerived().AlwaysRebuild() &&
3921         TransParam == SubstPack->getParameterPack())
3922       return Name;
3923
3924     return getDerived().RebuildTemplateName(TransParam,
3925                                             SubstPack->getArgumentPack());
3926   }
3927
3928   // These should be getting filtered out before they reach the AST.
3929   llvm_unreachable("overloaded function decl survived to here");
3930 }
3931
3932 template<typename Derived>
3933 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3934                                          const TemplateArgument &Arg,
3935                                          TemplateArgumentLoc &Output) {
3936   SourceLocation Loc = getDerived().getBaseLocation();
3937   switch (Arg.getKind()) {
3938   case TemplateArgument::Null:
3939     llvm_unreachable("null template argument in TreeTransform");
3940     break;
3941
3942   case TemplateArgument::Type:
3943     Output = TemplateArgumentLoc(Arg,
3944                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3945
3946     break;
3947
3948   case TemplateArgument::Template:
3949   case TemplateArgument::TemplateExpansion: {
3950     NestedNameSpecifierLocBuilder Builder;
3951     TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3952     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3953       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3954     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3955       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3956
3957     if (Arg.getKind() == TemplateArgument::Template)
3958       Output = TemplateArgumentLoc(Arg,
3959                                    Builder.getWithLocInContext(SemaRef.Context),
3960                                    Loc);
3961     else
3962       Output = TemplateArgumentLoc(Arg,
3963                                    Builder.getWithLocInContext(SemaRef.Context),
3964                                    Loc, Loc);
3965
3966     break;
3967   }
3968
3969   case TemplateArgument::Expression:
3970     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3971     break;
3972
3973   case TemplateArgument::Declaration:
3974   case TemplateArgument::Integral:
3975   case TemplateArgument::Pack:
3976   case TemplateArgument::NullPtr:
3977     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3978     break;
3979   }
3980 }
3981
3982 template<typename Derived>
3983 bool TreeTransform<Derived>::TransformTemplateArgument(
3984                                          const TemplateArgumentLoc &Input,
3985                                          TemplateArgumentLoc &Output, bool Uneval) {
3986   const TemplateArgument &Arg = Input.getArgument();
3987   switch (Arg.getKind()) {
3988   case TemplateArgument::Null:
3989   case TemplateArgument::Integral:
3990   case TemplateArgument::Pack:
3991   case TemplateArgument::Declaration:
3992   case TemplateArgument::NullPtr:
3993     llvm_unreachable("Unexpected TemplateArgument");
3994
3995   case TemplateArgument::Type: {
3996     TypeSourceInfo *DI = Input.getTypeSourceInfo();
3997     if (!DI)
3998       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3999
4000     DI = getDerived().TransformType(DI);
4001     if (!DI) return true;
4002
4003     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4004     return false;
4005   }
4006
4007   case TemplateArgument::Template: {
4008     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4009     if (QualifierLoc) {
4010       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4011       if (!QualifierLoc)
4012         return true;
4013     }
4014
4015     CXXScopeSpec SS;
4016     SS.Adopt(QualifierLoc);
4017     TemplateName Template
4018       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
4019                                            Input.getTemplateNameLoc());
4020     if (Template.isNull())
4021       return true;
4022
4023     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
4024                                  Input.getTemplateNameLoc());
4025     return false;
4026   }
4027
4028   case TemplateArgument::TemplateExpansion:
4029     llvm_unreachable("Caller should expand pack expansions");
4030
4031   case TemplateArgument::Expression: {
4032     // Template argument expressions are constant expressions.
4033     EnterExpressionEvaluationContext Unevaluated(
4034         getSema(),
4035         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4036                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4037         /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4038         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4039
4040     Expr *InputExpr = Input.getSourceExpression();
4041     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
4042
4043     ExprResult E = getDerived().TransformExpr(InputExpr);
4044     E = SemaRef.ActOnConstantExpression(E);
4045     if (E.isInvalid()) return true;
4046     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4047     return false;
4048   }
4049   }
4050
4051   // Work around bogus GCC warning
4052   return true;
4053 }
4054
4055 /// Iterator adaptor that invents template argument location information
4056 /// for each of the template arguments in its underlying iterator.
4057 template<typename Derived, typename InputIterator>
4058 class TemplateArgumentLocInventIterator {
4059   TreeTransform<Derived> &Self;
4060   InputIterator Iter;
4061
4062 public:
4063   typedef TemplateArgumentLoc value_type;
4064   typedef TemplateArgumentLoc reference;
4065   typedef typename std::iterator_traits<InputIterator>::difference_type
4066     difference_type;
4067   typedef std::input_iterator_tag iterator_category;
4068
4069   class pointer {
4070     TemplateArgumentLoc Arg;
4071
4072   public:
4073     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4074
4075     const TemplateArgumentLoc *operator->() const { return &Arg; }
4076   };
4077
4078   TemplateArgumentLocInventIterator() { }
4079
4080   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4081                                              InputIterator Iter)
4082     : Self(Self), Iter(Iter) { }
4083
4084   TemplateArgumentLocInventIterator &operator++() {
4085     ++Iter;
4086     return *this;
4087   }
4088
4089   TemplateArgumentLocInventIterator operator++(int) {
4090     TemplateArgumentLocInventIterator Old(*this);
4091     ++(*this);
4092     return Old;
4093   }
4094
4095   reference operator*() const {
4096     TemplateArgumentLoc Result;
4097     Self.InventTemplateArgumentLoc(*Iter, Result);
4098     return Result;
4099   }
4100
4101   pointer operator->() const { return pointer(**this); }
4102
4103   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4104                          const TemplateArgumentLocInventIterator &Y) {
4105     return X.Iter == Y.Iter;
4106   }
4107
4108   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4109                          const TemplateArgumentLocInventIterator &Y) {
4110     return X.Iter != Y.Iter;
4111   }
4112 };
4113
4114 template<typename Derived>
4115 template<typename InputIterator>
4116 bool TreeTransform<Derived>::TransformTemplateArguments(
4117     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4118     bool Uneval) {
4119   for (; First != Last; ++First) {
4120     TemplateArgumentLoc Out;
4121     TemplateArgumentLoc In = *First;
4122
4123     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4124       // Unpack argument packs, which we translate them into separate
4125       // arguments.
4126       // FIXME: We could do much better if we could guarantee that the
4127       // TemplateArgumentLocInfo for the pack expansion would be usable for
4128       // all of the template arguments in the argument pack.
4129       typedef TemplateArgumentLocInventIterator<Derived,
4130                                                 TemplateArgument::pack_iterator>
4131         PackLocIterator;
4132       if (TransformTemplateArguments(PackLocIterator(*this,
4133                                                  In.getArgument().pack_begin()),
4134                                      PackLocIterator(*this,
4135                                                    In.getArgument().pack_end()),
4136                                      Outputs, Uneval))
4137         return true;
4138
4139       continue;
4140     }
4141
4142     if (In.getArgument().isPackExpansion()) {
4143       // We have a pack expansion, for which we will be substituting into
4144       // the pattern.
4145       SourceLocation Ellipsis;
4146       Optional<unsigned> OrigNumExpansions;
4147       TemplateArgumentLoc Pattern
4148         = getSema().getTemplateArgumentPackExpansionPattern(
4149               In, Ellipsis, OrigNumExpansions);
4150
4151       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4152       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4153       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4154
4155       // Determine whether the set of unexpanded parameter packs can and should
4156       // be expanded.
4157       bool Expand = true;
4158       bool RetainExpansion = false;
4159       Optional<unsigned> NumExpansions = OrigNumExpansions;
4160       if (getDerived().TryExpandParameterPacks(Ellipsis,
4161                                                Pattern.getSourceRange(),
4162                                                Unexpanded,
4163                                                Expand,
4164                                                RetainExpansion,
4165                                                NumExpansions))
4166         return true;
4167
4168       if (!Expand) {
4169         // The transform has determined that we should perform a simple
4170         // transformation on the pack expansion, producing another pack
4171         // expansion.
4172         TemplateArgumentLoc OutPattern;
4173         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4174         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4175           return true;
4176
4177         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4178                                                 NumExpansions);
4179         if (Out.getArgument().isNull())
4180           return true;
4181
4182         Outputs.addArgument(Out);
4183         continue;
4184       }
4185
4186       // The transform has determined that we should perform an elementwise
4187       // expansion of the pattern. Do so.
4188       for (unsigned I = 0; I != *NumExpansions; ++I) {
4189         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4190
4191         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4192           return true;
4193
4194         if (Out.getArgument().containsUnexpandedParameterPack()) {
4195           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4196                                                   OrigNumExpansions);
4197           if (Out.getArgument().isNull())
4198             return true;
4199         }
4200
4201         Outputs.addArgument(Out);
4202       }
4203
4204       // If we're supposed to retain a pack expansion, do so by temporarily
4205       // forgetting the partially-substituted parameter pack.
4206       if (RetainExpansion) {
4207         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4208
4209         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4210           return true;
4211
4212         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4213                                                 OrigNumExpansions);
4214         if (Out.getArgument().isNull())
4215           return true;
4216
4217         Outputs.addArgument(Out);
4218       }
4219
4220       continue;
4221     }
4222
4223     // The simple case:
4224     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4225       return true;
4226
4227     Outputs.addArgument(Out);
4228   }
4229
4230   return false;
4231
4232 }
4233
4234 //===----------------------------------------------------------------------===//
4235 // Type transformation
4236 //===----------------------------------------------------------------------===//
4237
4238 template<typename Derived>
4239 QualType TreeTransform<Derived>::TransformType(QualType T) {
4240   if (getDerived().AlreadyTransformed(T))
4241     return T;
4242
4243   // Temporary workaround.  All of these transformations should
4244   // eventually turn into transformations on TypeLocs.
4245   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4246                                                 getDerived().getBaseLocation());
4247
4248   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4249
4250   if (!NewDI)
4251     return QualType();
4252
4253   return NewDI->getType();
4254 }
4255
4256 template<typename Derived>
4257 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4258   // Refine the base location to the type's location.
4259   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4260                        getDerived().getBaseEntity());
4261   if (getDerived().AlreadyTransformed(DI->getType()))
4262     return DI;
4263
4264   TypeLocBuilder TLB;
4265
4266   TypeLoc TL = DI->getTypeLoc();
4267   TLB.reserve(TL.getFullDataSize());
4268
4269   QualType Result = getDerived().TransformType(TLB, TL);
4270   if (Result.isNull())
4271     return nullptr;
4272
4273   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4274 }
4275
4276 template<typename Derived>
4277 QualType
4278 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4279   switch (T.getTypeLocClass()) {
4280 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4281 #define TYPELOC(CLASS, PARENT)                                                 \
4282   case TypeLoc::CLASS:                                                         \
4283     return getDerived().Transform##CLASS##Type(TLB,                            \
4284                                                T.castAs<CLASS##TypeLoc>());
4285 #include "clang/AST/TypeLocNodes.def"
4286   }
4287
4288   llvm_unreachable("unhandled type loc!");
4289 }
4290
4291 template<typename Derived>
4292 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4293   if (!isa<DependentNameType>(T))
4294     return TransformType(T);
4295
4296   if (getDerived().AlreadyTransformed(T))
4297     return T;
4298   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4299                                                 getDerived().getBaseLocation());
4300   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4301   return NewDI ? NewDI->getType() : QualType();
4302 }
4303
4304 template<typename Derived>
4305 TypeSourceInfo *
4306 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4307   if (!isa<DependentNameType>(DI->getType()))
4308     return TransformType(DI);
4309
4310   // Refine the base location to the type's location.
4311   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4312                        getDerived().getBaseEntity());
4313   if (getDerived().AlreadyTransformed(DI->getType()))
4314     return DI;
4315
4316   TypeLocBuilder TLB;
4317
4318   TypeLoc TL = DI->getTypeLoc();
4319   TLB.reserve(TL.getFullDataSize());
4320
4321   auto QTL = TL.getAs<QualifiedTypeLoc>();
4322   if (QTL)
4323     TL = QTL.getUnqualifiedLoc();
4324
4325   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4326
4327   QualType Result = getDerived().TransformDependentNameType(
4328       TLB, DNTL, /*DeducedTSTContext*/true);
4329   if (Result.isNull())
4330     return nullptr;
4331
4332   if (QTL) {
4333     Result = getDerived().RebuildQualifiedType(Result, QTL);
4334     if (Result.isNull())
4335       return nullptr;
4336     TLB.TypeWasModifiedSafely(Result);
4337   }
4338
4339   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4340 }
4341
4342 template<typename Derived>
4343 QualType
4344 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4345                                                QualifiedTypeLoc T) {
4346   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4347   if (Result.isNull())
4348     return QualType();
4349
4350   Result = getDerived().RebuildQualifiedType(Result, T);
4351
4352   if (Result.isNull())
4353     return QualType();
4354
4355   // RebuildQualifiedType might have updated the type, but not in a way
4356   // that invalidates the TypeLoc. (There's no location information for
4357   // qualifiers.)
4358   TLB.TypeWasModifiedSafely(Result);
4359
4360   return Result;
4361 }
4362
4363 template <typename Derived>
4364 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4365                                                       QualifiedTypeLoc TL) {
4366
4367   SourceLocation Loc = TL.getBeginLoc();
4368   Qualifiers Quals = TL.getType().getLocalQualifiers();
4369
4370   if (((T.getAddressSpace() != LangAS::Default &&
4371         Quals.getAddressSpace() != LangAS::Default)) &&
4372       T.getAddressSpace() != Quals.getAddressSpace()) {
4373     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4374         << TL.getType() << T;
4375     return QualType();
4376   }
4377
4378   // C++ [dcl.fct]p7:
4379   //   [When] adding cv-qualifications on top of the function type [...] the
4380   //   cv-qualifiers are ignored.
4381   if (T->isFunctionType()) {
4382     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4383                                                      Quals.getAddressSpace());
4384     return T;
4385   }
4386
4387   // C++ [dcl.ref]p1:
4388   //   when the cv-qualifiers are introduced through the use of a typedef-name
4389   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4390   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4391   // applied to a reference type.
4392   if (T->isReferenceType()) {
4393     // The only qualifier that applies to a reference type is restrict.
4394     if (!Quals.hasRestrict())
4395       return T;
4396     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4397   }
4398
4399   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4400   // resulting type.
4401   if (Quals.hasObjCLifetime()) {
4402     if (!T->isObjCLifetimeType() && !T->isDependentType())
4403       Quals.removeObjCLifetime();
4404     else if (T.getObjCLifetime()) {
4405       // Objective-C ARC:
4406       //   A lifetime qualifier applied to a substituted template parameter
4407       //   overrides the lifetime qualifier from the template argument.
4408       const AutoType *AutoTy;
4409       if (const SubstTemplateTypeParmType *SubstTypeParam
4410                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4411         QualType Replacement = SubstTypeParam->getReplacementType();
4412         Qualifiers Qs = Replacement.getQualifiers();
4413         Qs.removeObjCLifetime();
4414         Replacement = SemaRef.Context.getQualifiedType(
4415             Replacement.getUnqualifiedType(), Qs);
4416         T = SemaRef.Context.getSubstTemplateTypeParmType(
4417             SubstTypeParam->getReplacedParameter(), Replacement);
4418       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4419         // 'auto' types behave the same way as template parameters.
4420         QualType Deduced = AutoTy->getDeducedType();
4421         Qualifiers Qs = Deduced.getQualifiers();
4422         Qs.removeObjCLifetime();
4423         Deduced =
4424             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4425         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4426                                         AutoTy->isDependentType());
4427       } else {
4428         // Otherwise, complain about the addition of a qualifier to an
4429         // already-qualified type.
4430         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4431         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4432         Quals.removeObjCLifetime();
4433       }
4434     }
4435   }
4436
4437   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4438 }
4439
4440 template<typename Derived>
4441 TypeLoc
4442 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4443                                                    QualType ObjectType,
4444                                                    NamedDecl *UnqualLookup,
4445                                                    CXXScopeSpec &SS) {
4446   if (getDerived().AlreadyTransformed(TL.getType()))
4447     return TL;
4448
4449   TypeSourceInfo *TSI =
4450       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4451   if (TSI)
4452     return TSI->getTypeLoc();
4453   return TypeLoc();
4454 }
4455
4456 template<typename Derived>
4457 TypeSourceInfo *
4458 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4459                                                    QualType ObjectType,
4460                                                    NamedDecl *UnqualLookup,
4461                                                    CXXScopeSpec &SS) {
4462   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4463     return TSInfo;
4464
4465   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4466                                    UnqualLookup, SS);
4467 }
4468
4469 template <typename Derived>
4470 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4471     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4472     CXXScopeSpec &SS) {
4473   QualType T = TL.getType();
4474   assert(!getDerived().AlreadyTransformed(T));
4475
4476   TypeLocBuilder TLB;
4477   QualType Result;
4478
4479   if (isa<TemplateSpecializationType>(T)) {
4480     TemplateSpecializationTypeLoc SpecTL =
4481         TL.castAs<TemplateSpecializationTypeLoc>();
4482
4483     TemplateName Template = getDerived().TransformTemplateName(
4484         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4485         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4486     if (Template.isNull())
4487       return nullptr;
4488
4489     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4490                                                               Template);
4491   } else if (isa<DependentTemplateSpecializationType>(T)) {
4492     DependentTemplateSpecializationTypeLoc SpecTL =
4493         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4494
4495     TemplateName Template
4496       = getDerived().RebuildTemplateName(SS,
4497                                          SpecTL.getTemplateKeywordLoc(),
4498                                          *SpecTL.getTypePtr()->getIdentifier(),
4499                                          SpecTL.getTemplateNameLoc(),
4500                                          ObjectType, UnqualLookup,
4501                                          /*AllowInjectedClassName*/true);
4502     if (Template.isNull())
4503       return nullptr;
4504
4505     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4506                                                                        SpecTL,
4507                                                                        Template,
4508                                                                        SS);
4509   } else {
4510     // Nothing special needs to be done for these.
4511     Result = getDerived().TransformType(TLB, TL);
4512   }
4513
4514   if (Result.isNull())
4515     return nullptr;
4516
4517   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4518 }
4519
4520 template <class TyLoc> static inline
4521 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4522   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4523   NewT.setNameLoc(T.getNameLoc());
4524   return T.getType();
4525 }
4526
4527 template<typename Derived>
4528 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4529                                                       BuiltinTypeLoc T) {
4530   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4531   NewT.setBuiltinLoc(T.getBuiltinLoc());
4532   if (T.needsExtraLocalData())
4533     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4534   return T.getType();
4535 }
4536
4537 template<typename Derived>
4538 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4539                                                       ComplexTypeLoc T) {
4540   // FIXME: recurse?
4541   return TransformTypeSpecType(TLB, T);
4542 }
4543
4544 template <typename Derived>
4545 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4546                                                        AdjustedTypeLoc TL) {
4547   // Adjustments applied during transformation are handled elsewhere.
4548   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4549 }
4550
4551 template<typename Derived>
4552 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4553                                                       DecayedTypeLoc TL) {
4554   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4555   if (OriginalType.isNull())
4556     return QualType();
4557
4558   QualType Result = TL.getType();
4559   if (getDerived().AlwaysRebuild() ||
4560       OriginalType != TL.getOriginalLoc().getType())
4561     Result = SemaRef.Context.getDecayedType(OriginalType);
4562   TLB.push<DecayedTypeLoc>(Result);
4563   // Nothing to set for DecayedTypeLoc.
4564   return Result;
4565 }
4566
4567 /// Helper to deduce addr space of a pointee type in OpenCL mode.
4568 /// If the type is updated it will be overwritten in PointeeType param.
4569 static void deduceOpenCLPointeeAddrSpace(Sema &SemaRef, QualType &PointeeType) {
4570   if (PointeeType.getAddressSpace() == LangAS::Default)
4571     PointeeType = SemaRef.Context.getAddrSpaceQualType(PointeeType,
4572                                                        LangAS::opencl_generic);
4573 }
4574
4575 template<typename Derived>
4576 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4577                                                       PointerTypeLoc TL) {
4578   QualType PointeeType
4579     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4580   if (PointeeType.isNull())
4581     return QualType();
4582
4583   if (SemaRef.getLangOpts().OpenCL)
4584     deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4585
4586   QualType Result = TL.getType();
4587   if (PointeeType->getAs<ObjCObjectType>()) {
4588     // A dependent pointer type 'T *' has is being transformed such
4589     // that an Objective-C class type is being replaced for 'T'. The
4590     // resulting pointer type is an ObjCObjectPointerType, not a
4591     // PointerType.
4592     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4593
4594     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4595     NewT.setStarLoc(TL.getStarLoc());
4596     return Result;
4597   }
4598
4599   if (getDerived().AlwaysRebuild() ||
4600       PointeeType != TL.getPointeeLoc().getType()) {
4601     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4602     if (Result.isNull())
4603       return QualType();
4604   }
4605
4606   // Objective-C ARC can add lifetime qualifiers to the type that we're
4607   // pointing to.
4608   TLB.TypeWasModifiedSafely(Result->getPointeeType());
4609
4610   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4611   NewT.setSigilLoc(TL.getSigilLoc());
4612   return Result;
4613 }
4614
4615 template<typename Derived>
4616 QualType
4617 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4618                                                   BlockPointerTypeLoc TL) {
4619   QualType PointeeType
4620     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4621   if (PointeeType.isNull())
4622     return QualType();
4623
4624   if (SemaRef.getLangOpts().OpenCL)
4625     deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4626
4627   QualType Result = TL.getType();
4628   if (getDerived().AlwaysRebuild() ||
4629       PointeeType != TL.getPointeeLoc().getType()) {
4630     Result = getDerived().RebuildBlockPointerType(PointeeType,
4631                                                   TL.getSigilLoc());
4632     if (Result.isNull())
4633       return QualType();
4634   }
4635
4636   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4637   NewT.setSigilLoc(TL.getSigilLoc());
4638   return Result;
4639 }
4640
4641 /// Transforms a reference type.  Note that somewhat paradoxically we
4642 /// don't care whether the type itself is an l-value type or an r-value
4643 /// type;  we only care if the type was *written* as an l-value type
4644 /// or an r-value type.
4645 template<typename Derived>
4646 QualType
4647 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4648                                                ReferenceTypeLoc TL) {
4649   const ReferenceType *T = TL.getTypePtr();
4650
4651   // Note that this works with the pointee-as-written.
4652   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4653   if (PointeeType.isNull())
4654     return QualType();
4655
4656   if (SemaRef.getLangOpts().OpenCL)
4657     deduceOpenCLPointeeAddrSpace(SemaRef, PointeeType);
4658
4659   QualType Result = TL.getType();
4660   if (getDerived().AlwaysRebuild() ||
4661       PointeeType != T->getPointeeTypeAsWritten()) {
4662     Result = getDerived().RebuildReferenceType(PointeeType,
4663                                                T->isSpelledAsLValue(),
4664                                                TL.getSigilLoc());
4665     if (Result.isNull())
4666       return QualType();
4667   }
4668
4669   // Objective-C ARC can add lifetime qualifiers to the type that we're
4670   // referring to.
4671   TLB.TypeWasModifiedSafely(
4672       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
4673
4674   // r-value references can be rebuilt as l-value references.
4675   ReferenceTypeLoc NewTL;
4676   if (isa<LValueReferenceType>(Result))
4677     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4678   else
4679     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4680   NewTL.setSigilLoc(TL.getSigilLoc());
4681
4682   return Result;
4683 }
4684
4685 template<typename Derived>
4686 QualType
4687 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4688                                                  LValueReferenceTypeLoc TL) {
4689   return TransformReferenceType(TLB, TL);
4690 }
4691
4692 template<typename Derived>
4693 QualType
4694 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4695                                                  RValueReferenceTypeLoc TL) {
4696   return TransformReferenceType(TLB, TL);
4697 }
4698
4699 template<typename Derived>
4700 QualType
4701 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4702                                                    MemberPointerTypeLoc TL) {
4703   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4704   if (PointeeType.isNull())
4705     return QualType();
4706
4707   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4708   TypeSourceInfo *NewClsTInfo = nullptr;
4709   if (OldClsTInfo) {
4710     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4711     if (!NewClsTInfo)
4712       return QualType();
4713   }
4714
4715   const MemberPointerType *T = TL.getTypePtr();
4716   QualType OldClsType = QualType(T->getClass(), 0);
4717   QualType NewClsType;
4718   if (NewClsTInfo)
4719     NewClsType = NewClsTInfo->getType();
4720   else {
4721     NewClsType = getDerived().TransformType(OldClsType);
4722     if (NewClsType.isNull())
4723       return QualType();
4724   }
4725
4726   QualType Result = TL.getType();
4727   if (getDerived().AlwaysRebuild() ||
4728       PointeeType != T->getPointeeType() ||
4729       NewClsType != OldClsType) {
4730     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4731                                                    TL.getStarLoc());
4732     if (Result.isNull())
4733       return QualType();
4734   }
4735
4736   // If we had to adjust the pointee type when building a member pointer, make
4737   // sure to push TypeLoc info for it.
4738   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4739   if (MPT && PointeeType != MPT->getPointeeType()) {
4740     assert(isa<AdjustedType>(MPT->getPointeeType()));
4741     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4742   }
4743
4744   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4745   NewTL.setSigilLoc(TL.getSigilLoc());
4746   NewTL.setClassTInfo(NewClsTInfo);
4747
4748   return Result;
4749 }
4750
4751 template<typename Derived>
4752 QualType
4753 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4754                                                    ConstantArrayTypeLoc TL) {
4755   const ConstantArrayType *T = TL.getTypePtr();
4756   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4757   if (ElementType.isNull())
4758     return QualType();
4759
4760   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
4761   Expr *OldSize = TL.getSizeExpr();
4762   if (!OldSize)
4763     OldSize = const_cast<Expr*>(T->getSizeExpr());
4764   Expr *NewSize = nullptr;
4765   if (OldSize) {
4766     EnterExpressionEvaluationContext Unevaluated(
4767         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4768     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
4769     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
4770   }
4771
4772   QualType Result = TL.getType();
4773   if (getDerived().AlwaysRebuild() ||
4774       ElementType != T->getElementType() ||
4775       (T->getSizeExpr() && NewSize != OldSize)) {
4776     Result = getDerived().RebuildConstantArrayType(ElementType,
4777                                                    T->getSizeModifier(),
4778                                                    T->getSize(), NewSize,
4779                                              T->getIndexTypeCVRQualifiers(),
4780                                                    TL.getBracketsRange());
4781     if (Result.isNull())
4782       return QualType();
4783   }
4784
4785   // We might have either a ConstantArrayType or a VariableArrayType now:
4786   // a ConstantArrayType is allowed to have an element type which is a
4787   // VariableArrayType if the type is dependent.  Fortunately, all array
4788   // types have the same location layout.
4789   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4790   NewTL.setLBracketLoc(TL.getLBracketLoc());
4791   NewTL.setRBracketLoc(TL.getRBracketLoc());
4792   NewTL.setSizeExpr(NewSize);
4793
4794   return Result;
4795 }
4796
4797 template<typename Derived>
4798 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4799                                               TypeLocBuilder &TLB,
4800                                               IncompleteArrayTypeLoc TL) {
4801   const IncompleteArrayType *T = TL.getTypePtr();
4802   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4803   if (ElementType.isNull())
4804     return QualType();
4805
4806   QualType Result = TL.getType();
4807   if (getDerived().AlwaysRebuild() ||
4808       ElementType != T->getElementType()) {
4809     Result = getDerived().RebuildIncompleteArrayType(ElementType,
4810                                                      T->getSizeModifier(),
4811                                            T->getIndexTypeCVRQualifiers(),
4812                                                      TL.getBracketsRange());
4813     if (Result.isNull())
4814       return QualType();
4815   }
4816
4817   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4818   NewTL.setLBracketLoc(TL.getLBracketLoc());
4819   NewTL.setRBracketLoc(TL.getRBracketLoc());
4820   NewTL.setSizeExpr(nullptr);
4821
4822   return Result;
4823 }
4824
4825 template<typename Derived>
4826 QualType
4827 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4828                                                    VariableArrayTypeLoc TL) {
4829   const VariableArrayType *T = TL.getTypePtr();
4830   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4831   if (ElementType.isNull())
4832     return QualType();
4833
4834   ExprResult SizeResult;
4835   {
4836     EnterExpressionEvaluationContext Context(
4837         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4838     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4839   }
4840   if (SizeResult.isInvalid())
4841     return QualType();
4842   SizeResult =
4843       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
4844   if (SizeResult.isInvalid())
4845     return QualType();
4846
4847   Expr *Size = SizeResult.get();
4848
4849   QualType Result = TL.getType();
4850   if (getDerived().AlwaysRebuild() ||
4851       ElementType != T->getElementType() ||
4852       Size != T->getSizeExpr()) {
4853     Result = getDerived().RebuildVariableArrayType(ElementType,
4854                                                    T->getSizeModifier(),
4855                                                    Size,
4856                                              T->getIndexTypeCVRQualifiers(),
4857                                                    TL.getBracketsRange());
4858     if (Result.isNull())
4859       return QualType();
4860   }
4861
4862   // We might have constant size array now, but fortunately it has the same
4863   // location layout.
4864   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4865   NewTL.setLBracketLoc(TL.getLBracketLoc());
4866   NewTL.setRBracketLoc(TL.getRBracketLoc());
4867   NewTL.setSizeExpr(Size);
4868
4869   return Result;
4870 }
4871
4872 template<typename Derived>
4873 QualType
4874 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4875                                              DependentSizedArrayTypeLoc TL) {
4876   const DependentSizedArrayType *T = TL.getTypePtr();
4877   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4878   if (ElementType.isNull())
4879     return QualType();
4880
4881   // Array bounds are constant expressions.
4882   EnterExpressionEvaluationContext Unevaluated(
4883       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4884
4885   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
4886   Expr *origSize = TL.getSizeExpr();
4887   if (!origSize) origSize = T->getSizeExpr();
4888
4889   ExprResult sizeResult
4890     = getDerived().TransformExpr(origSize);
4891   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4892   if (sizeResult.isInvalid())
4893     return QualType();
4894
4895   Expr *size = sizeResult.get();
4896
4897   QualType Result = TL.getType();
4898   if (getDerived().AlwaysRebuild() ||
4899       ElementType != T->getElementType() ||
4900       size != origSize) {
4901     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4902                                                          T->getSizeModifier(),
4903                                                          size,
4904                                                 T->getIndexTypeCVRQualifiers(),
4905                                                         TL.getBracketsRange());
4906     if (Result.isNull())
4907       return QualType();
4908   }
4909
4910   // We might have any sort of array type now, but fortunately they
4911   // all have the same location layout.
4912   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4913   NewTL.setLBracketLoc(TL.getLBracketLoc());
4914   NewTL.setRBracketLoc(TL.getRBracketLoc());
4915   NewTL.setSizeExpr(size);
4916
4917   return Result;
4918 }
4919
4920 template <typename Derived>
4921 QualType TreeTransform<Derived>::TransformDependentVectorType(
4922     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
4923   const DependentVectorType *T = TL.getTypePtr();
4924   QualType ElementType = getDerived().TransformType(T->getElementType());
4925   if (ElementType.isNull())
4926     return QualType();
4927
4928   EnterExpressionEvaluationContext Unevaluated(
4929       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4930
4931   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4932   Size = SemaRef.ActOnConstantExpression(Size);
4933   if (Size.isInvalid())
4934     return QualType();
4935
4936   QualType Result = TL.getType();
4937   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
4938       Size.get() != T->getSizeExpr()) {
4939     Result = getDerived().RebuildDependentVectorType(
4940         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
4941     if (Result.isNull())
4942       return QualType();
4943   }
4944
4945   // Result might be dependent or not.
4946   if (isa<DependentVectorType>(Result)) {
4947     DependentVectorTypeLoc NewTL =
4948         TLB.push<DependentVectorTypeLoc>(Result);
4949     NewTL.setNameLoc(TL.getNameLoc());
4950   } else {
4951     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4952     NewTL.setNameLoc(TL.getNameLoc());
4953   }
4954
4955   return Result;
4956 }
4957
4958 template<typename Derived>
4959 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4960                                       TypeLocBuilder &TLB,
4961                                       DependentSizedExtVectorTypeLoc TL) {
4962   const DependentSizedExtVectorType *T = TL.getTypePtr();
4963
4964   // FIXME: ext vector locs should be nested
4965   QualType ElementType = getDerived().TransformType(T->getElementType());
4966   if (ElementType.isNull())
4967     return QualType();
4968
4969   // Vector sizes are constant expressions.
4970   EnterExpressionEvaluationContext Unevaluated(
4971       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4972
4973   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4974   Size = SemaRef.ActOnConstantExpression(Size);
4975   if (Size.isInvalid())
4976     return QualType();
4977
4978   QualType Result = TL.getType();
4979   if (getDerived().AlwaysRebuild() ||
4980       ElementType != T->getElementType() ||
4981       Size.get() != T->getSizeExpr()) {
4982     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4983                                                              Size.get(),
4984                                                          T->getAttributeLoc());
4985     if (Result.isNull())
4986       return QualType();
4987   }
4988
4989   // Result might be dependent or not.
4990   if (isa<DependentSizedExtVectorType>(Result)) {
4991     DependentSizedExtVectorTypeLoc NewTL
4992       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4993     NewTL.setNameLoc(TL.getNameLoc());
4994   } else {
4995     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4996     NewTL.setNameLoc(TL.getNameLoc());
4997   }
4998
4999   return Result;
5000 }
5001
5002 template <typename Derived>
5003 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5004     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5005   const DependentAddressSpaceType *T = TL.getTypePtr();
5006
5007   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5008
5009   if (pointeeType.isNull())
5010     return QualType();
5011
5012   // Address spaces are constant expressions.
5013   EnterExpressionEvaluationContext Unevaluated(
5014       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5015
5016   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5017   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5018   if (AddrSpace.isInvalid())
5019     return QualType();
5020
5021   QualType Result = TL.getType();
5022   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5023       AddrSpace.get() != T->getAddrSpaceExpr()) {
5024     Result = getDerived().RebuildDependentAddressSpaceType(
5025         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5026     if (Result.isNull())
5027       return QualType();
5028   }
5029
5030   // Result might be dependent or not.
5031   if (isa<DependentAddressSpaceType>(Result)) {
5032     DependentAddressSpaceTypeLoc NewTL =
5033         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5034
5035     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5036     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5037     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5038
5039   } else {
5040     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5041         Result, getDerived().getBaseLocation());
5042     TransformType(TLB, DI->getTypeLoc());
5043   }
5044
5045   return Result;
5046 }
5047
5048 template <typename Derived>
5049 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5050                                                      VectorTypeLoc TL) {
5051   const VectorType *T = TL.getTypePtr();
5052   QualType ElementType = getDerived().TransformType(T->getElementType());
5053   if (ElementType.isNull())
5054     return QualType();
5055
5056   QualType Result = TL.getType();
5057   if (getDerived().AlwaysRebuild() ||
5058       ElementType != T->getElementType()) {
5059     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5060                                             T->getVectorKind());
5061     if (Result.isNull())
5062       return QualType();
5063   }
5064
5065   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5066   NewTL.setNameLoc(TL.getNameLoc());
5067
5068   return Result;
5069 }
5070
5071 template<typename Derived>
5072 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5073                                                         ExtVectorTypeLoc TL) {
5074   const VectorType *T = TL.getTypePtr();
5075   QualType ElementType = getDerived().TransformType(T->getElementType());
5076   if (ElementType.isNull())
5077     return QualType();
5078
5079   QualType Result = TL.getType();
5080   if (getDerived().AlwaysRebuild() ||
5081       ElementType != T->getElementType()) {
5082     Result = getDerived().RebuildExtVectorType(ElementType,
5083                                                T->getNumElements(),
5084                                                /*FIXME*/ SourceLocation());
5085     if (Result.isNull())
5086       return QualType();
5087   }
5088
5089   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5090   NewTL.setNameLoc(TL.getNameLoc());
5091
5092   return Result;
5093 }
5094
5095 template <typename Derived>
5096 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5097     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5098     bool ExpectParameterPack) {
5099   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5100   TypeSourceInfo *NewDI = nullptr;
5101
5102   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5103     // If we're substituting into a pack expansion type and we know the
5104     // length we want to expand to, just substitute for the pattern.
5105     TypeLoc OldTL = OldDI->getTypeLoc();
5106     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5107
5108     TypeLocBuilder TLB;
5109     TypeLoc NewTL = OldDI->getTypeLoc();
5110     TLB.reserve(NewTL.getFullDataSize());
5111
5112     QualType Result = getDerived().TransformType(TLB,
5113                                                OldExpansionTL.getPatternLoc());
5114     if (Result.isNull())
5115       return nullptr;
5116
5117     Result = RebuildPackExpansionType(Result,
5118                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5119                                       OldExpansionTL.getEllipsisLoc(),
5120                                       NumExpansions);
5121     if (Result.isNull())
5122       return nullptr;
5123
5124     PackExpansionTypeLoc NewExpansionTL
5125       = TLB.push<PackExpansionTypeLoc>(Result);
5126     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5127     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5128   } else
5129     NewDI = getDerived().TransformType(OldDI);
5130   if (!NewDI)
5131     return nullptr;
5132
5133   if (NewDI == OldDI && indexAdjustment == 0)
5134     return OldParm;
5135
5136   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5137                                              OldParm->getDeclContext(),
5138                                              OldParm->getInnerLocStart(),
5139                                              OldParm->getLocation(),
5140                                              OldParm->getIdentifier(),
5141                                              NewDI->getType(),
5142                                              NewDI,
5143                                              OldParm->getStorageClass(),
5144                                              /* DefArg */ nullptr);
5145   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5146                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5147   return newParm;
5148 }
5149
5150 template <typename Derived>
5151 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5152     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5153     const QualType *ParamTypes,
5154     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5155     SmallVectorImpl<QualType> &OutParamTypes,
5156     SmallVectorImpl<ParmVarDecl *> *PVars,
5157     Sema::ExtParameterInfoBuilder &PInfos) {
5158   int indexAdjustment = 0;
5159
5160   unsigned NumParams = Params.size();
5161   for (unsigned i = 0; i != NumParams; ++i) {
5162     if (ParmVarDecl *OldParm = Params[i]) {
5163       assert(OldParm->getFunctionScopeIndex() == i);
5164
5165       Optional<unsigned> NumExpansions;
5166       ParmVarDecl *NewParm = nullptr;
5167       if (OldParm->isParameterPack()) {
5168         // We have a function parameter pack that may need to be expanded.
5169         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5170
5171         // Find the parameter packs that could be expanded.
5172         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5173         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5174         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5175         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5176         assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
5177
5178         // Determine whether we should expand the parameter packs.
5179         bool ShouldExpand = false;
5180         bool RetainExpansion = false;
5181         Optional<unsigned> OrigNumExpansions =
5182             ExpansionTL.getTypePtr()->getNumExpansions();
5183         NumExpansions = OrigNumExpansions;
5184         if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5185                                                  Pattern.getSourceRange(),
5186                                                  Unexpanded,
5187                                                  ShouldExpand,
5188                                                  RetainExpansion,
5189                                                  NumExpansions)) {
5190           return true;
5191         }
5192
5193         if (ShouldExpand) {
5194           // Expand the function parameter pack into multiple, separate
5195           // parameters.
5196           getDerived().ExpandingFunctionParameterPack(OldParm);
5197           for (unsigned I = 0; I != *NumExpansions; ++I) {
5198             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5199             ParmVarDecl *NewParm
5200               = getDerived().TransformFunctionTypeParam(OldParm,
5201                                                         indexAdjustment++,
5202                                                         OrigNumExpansions,
5203                                                 /*ExpectParameterPack=*/false);
5204             if (!NewParm)
5205               return true;
5206
5207             if (ParamInfos)
5208               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5209             OutParamTypes.push_back(NewParm->getType());
5210             if (PVars)
5211               PVars->push_back(NewParm);
5212           }
5213
5214           // If we're supposed to retain a pack expansion, do so by temporarily
5215           // forgetting the partially-substituted parameter pack.
5216           if (RetainExpansion) {
5217             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5218             ParmVarDecl *NewParm
5219               = getDerived().TransformFunctionTypeParam(OldParm,
5220                                                         indexAdjustment++,
5221                                                         OrigNumExpansions,
5222                                                 /*ExpectParameterPack=*/false);
5223             if (!NewParm)
5224               return true;
5225
5226             if (ParamInfos)
5227               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5228             OutParamTypes.push_back(NewParm->getType());
5229             if (PVars)
5230               PVars->push_back(NewParm);
5231           }
5232
5233           // The next parameter should have the same adjustment as the
5234           // last thing we pushed, but we post-incremented indexAdjustment
5235           // on every push.  Also, if we push nothing, the adjustment should
5236           // go down by one.
5237           indexAdjustment--;
5238
5239           // We're done with the pack expansion.
5240           continue;
5241         }
5242
5243         // We'll substitute the parameter now without expanding the pack
5244         // expansion.
5245         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5246         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5247                                                           indexAdjustment,
5248                                                           NumExpansions,
5249                                                   /*ExpectParameterPack=*/true);
5250       } else {
5251         NewParm = getDerived().TransformFunctionTypeParam(
5252             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5253       }
5254
5255       if (!NewParm)
5256         return true;
5257
5258       if (ParamInfos)
5259         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5260       OutParamTypes.push_back(NewParm->getType());
5261       if (PVars)
5262         PVars->push_back(NewParm);
5263       continue;
5264     }
5265
5266     // Deal with the possibility that we don't have a parameter
5267     // declaration for this parameter.
5268     QualType OldType = ParamTypes[i];
5269     bool IsPackExpansion = false;
5270     Optional<unsigned> NumExpansions;
5271     QualType NewType;
5272     if (const PackExpansionType *Expansion
5273                                        = dyn_cast<PackExpansionType>(OldType)) {
5274       // We have a function parameter pack that may need to be expanded.
5275       QualType Pattern = Expansion->getPattern();
5276       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5277       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5278
5279       // Determine whether we should expand the parameter packs.
5280       bool ShouldExpand = false;
5281       bool RetainExpansion = false;
5282       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5283                                                Unexpanded,
5284                                                ShouldExpand,
5285                                                RetainExpansion,
5286                                                NumExpansions)) {
5287         return true;
5288       }
5289
5290       if (ShouldExpand) {
5291         // Expand the function parameter pack into multiple, separate
5292         // parameters.
5293         for (unsigned I = 0; I != *NumExpansions; ++I) {
5294           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5295           QualType NewType = getDerived().TransformType(Pattern);
5296           if (NewType.isNull())
5297             return true;
5298
5299           if (NewType->containsUnexpandedParameterPack()) {
5300             NewType =
5301                 getSema().getASTContext().getPackExpansionType(NewType, None);
5302
5303             if (NewType.isNull())
5304               return true;
5305           }
5306
5307           if (ParamInfos)
5308             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5309           OutParamTypes.push_back(NewType);
5310           if (PVars)
5311             PVars->push_back(nullptr);
5312         }
5313
5314         // We're done with the pack expansion.
5315         continue;
5316       }
5317
5318       // If we're supposed to retain a pack expansion, do so by temporarily
5319       // forgetting the partially-substituted parameter pack.
5320       if (RetainExpansion) {
5321         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5322         QualType NewType = getDerived().TransformType(Pattern);
5323         if (NewType.isNull())
5324           return true;
5325
5326         if (ParamInfos)
5327           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5328         OutParamTypes.push_back(NewType);
5329         if (PVars)
5330           PVars->push_back(nullptr);
5331       }
5332
5333       // We'll substitute the parameter now without expanding the pack
5334       // expansion.
5335       OldType = Expansion->getPattern();
5336       IsPackExpansion = true;
5337       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5338       NewType = getDerived().TransformType(OldType);
5339     } else {
5340       NewType = getDerived().TransformType(OldType);
5341     }
5342
5343     if (NewType.isNull())
5344       return true;
5345
5346     if (IsPackExpansion)
5347       NewType = getSema().Context.getPackExpansionType(NewType,
5348                                                        NumExpansions);
5349
5350     if (ParamInfos)
5351       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5352     OutParamTypes.push_back(NewType);
5353     if (PVars)
5354       PVars->push_back(nullptr);
5355   }
5356
5357 #ifndef NDEBUG
5358   if (PVars) {
5359     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5360       if (ParmVarDecl *parm = (*PVars)[i])
5361         assert(parm->getFunctionScopeIndex() == i);
5362   }
5363 #endif
5364
5365   return false;
5366 }
5367
5368 template<typename Derived>
5369 QualType
5370 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5371                                                    FunctionProtoTypeLoc TL) {
5372   SmallVector<QualType, 4> ExceptionStorage;
5373   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5374   return getDerived().TransformFunctionProtoType(
5375       TLB, TL, nullptr, Qualifiers(),
5376       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5377         return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5378                                             ExceptionStorage, Changed);
5379       });
5380 }
5381
5382 template<typename Derived> template<typename Fn>
5383 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5384     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5385     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5386
5387   // Transform the parameters and return type.
5388   //
5389   // We are required to instantiate the params and return type in source order.
5390   // When the function has a trailing return type, we instantiate the
5391   // parameters before the return type,  since the return type can then refer
5392   // to the parameters themselves (via decltype, sizeof, etc.).
5393   //
5394   SmallVector<QualType, 4> ParamTypes;
5395   SmallVector<ParmVarDecl*, 4> ParamDecls;
5396   Sema::ExtParameterInfoBuilder ExtParamInfos;
5397   const FunctionProtoType *T = TL.getTypePtr();
5398
5399   QualType ResultType;
5400
5401   if (T->hasTrailingReturn()) {
5402     if (getDerived().TransformFunctionTypeParams(
5403             TL.getBeginLoc(), TL.getParams(),
5404             TL.getTypePtr()->param_type_begin(),
5405             T->getExtParameterInfosOrNull(),
5406             ParamTypes, &ParamDecls, ExtParamInfos))
5407       return QualType();
5408
5409     {
5410       // C++11 [expr.prim.general]p3:
5411       //   If a declaration declares a member function or member function
5412       //   template of a class X, the expression this is a prvalue of type
5413       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5414       //   and the end of the function-definition, member-declarator, or
5415       //   declarator.
5416       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5417
5418       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5419       if (ResultType.isNull())
5420         return QualType();
5421     }
5422   }
5423   else {
5424     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5425     if (ResultType.isNull())
5426       return QualType();
5427
5428     if (getDerived().TransformFunctionTypeParams(
5429             TL.getBeginLoc(), TL.getParams(),
5430             TL.getTypePtr()->param_type_begin(),
5431             T->getExtParameterInfosOrNull(),
5432             ParamTypes, &ParamDecls, ExtParamInfos))
5433       return QualType();
5434   }
5435
5436   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5437
5438   bool EPIChanged = false;
5439   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5440     return QualType();
5441
5442   // Handle extended parameter information.
5443   if (auto NewExtParamInfos =
5444         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5445     if (!EPI.ExtParameterInfos ||
5446         llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5447           != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5448       EPIChanged = true;
5449     }
5450     EPI.ExtParameterInfos = NewExtParamInfos;
5451   } else if (EPI.ExtParameterInfos) {
5452     EPIChanged = true;
5453     EPI.ExtParameterInfos = nullptr;
5454   }
5455
5456   QualType Result = TL.getType();
5457   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5458       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5459     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5460     if (Result.isNull())
5461       return QualType();
5462   }
5463
5464   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5465   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5466   NewTL.setLParenLoc(TL.getLParenLoc());
5467   NewTL.setRParenLoc(TL.getRParenLoc());
5468   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5469   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5470   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5471     NewTL.setParam(i, ParamDecls[i]);
5472
5473   return Result;
5474 }
5475
5476 template<typename Derived>
5477 bool TreeTransform<Derived>::TransformExceptionSpec(
5478     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5479     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5480   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5481
5482   // Instantiate a dynamic noexcept expression, if any.
5483   if (isComputedNoexcept(ESI.Type)) {
5484     EnterExpressionEvaluationContext Unevaluated(
5485         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5486     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5487     if (NoexceptExpr.isInvalid())
5488       return true;
5489
5490     ExceptionSpecificationType EST = ESI.Type;
5491     NoexceptExpr =
5492         getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5493     if (NoexceptExpr.isInvalid())
5494       return true;
5495
5496     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5497       Changed = true;
5498     ESI.NoexceptExpr = NoexceptExpr.get();
5499     ESI.Type = EST;
5500   }
5501
5502   if (ESI.Type != EST_Dynamic)
5503     return false;
5504
5505   // Instantiate a dynamic exception specification's type.
5506   for (QualType T : ESI.Exceptions) {
5507     if (const PackExpansionType *PackExpansion =
5508             T->getAs<PackExpansionType>()) {
5509       Changed = true;
5510
5511       // We have a pack expansion. Instantiate it.
5512       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5513       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5514                                               Unexpanded);
5515       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5516
5517       // Determine whether the set of unexpanded parameter packs can and
5518       // should
5519       // be expanded.
5520       bool Expand = false;
5521       bool RetainExpansion = false;
5522       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5523       // FIXME: Track the location of the ellipsis (and track source location
5524       // information for the types in the exception specification in general).
5525       if (getDerived().TryExpandParameterPacks(
5526               Loc, SourceRange(), Unexpanded, Expand,
5527               RetainExpansion, NumExpansions))
5528         return true;
5529
5530       if (!Expand) {
5531         // We can't expand this pack expansion into separate arguments yet;
5532         // just substitute into the pattern and create a new pack expansion
5533         // type.
5534         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5535         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5536         if (U.isNull())
5537           return true;
5538
5539         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5540         Exceptions.push_back(U);
5541         continue;
5542       }
5543
5544       // Substitute into the pack expansion pattern for each slice of the
5545       // pack.
5546       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5547         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5548
5549         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5550         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5551           return true;
5552
5553         Exceptions.push_back(U);
5554       }
5555     } else {
5556       QualType U = getDerived().TransformType(T);
5557       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5558         return true;
5559       if (T != U)
5560         Changed = true;
5561
5562       Exceptions.push_back(U);
5563     }
5564   }
5565
5566   ESI.Exceptions = Exceptions;
5567   if (ESI.Exceptions.empty())
5568     ESI.Type = EST_DynamicNone;
5569   return false;
5570 }
5571
5572 template<typename Derived>
5573 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5574                                                  TypeLocBuilder &TLB,
5575                                                  FunctionNoProtoTypeLoc TL) {
5576   const FunctionNoProtoType *T = TL.getTypePtr();
5577   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5578   if (ResultType.isNull())
5579     return QualType();
5580
5581   QualType Result = TL.getType();
5582   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5583     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5584
5585   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5586   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5587   NewTL.setLParenLoc(TL.getLParenLoc());
5588   NewTL.setRParenLoc(TL.getRParenLoc());
5589   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5590
5591   return Result;
5592 }
5593
5594 template<typename Derived> QualType
5595 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5596                                                  UnresolvedUsingTypeLoc TL) {
5597   const UnresolvedUsingType *T = TL.getTypePtr();
5598   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5599   if (!D)
5600     return QualType();
5601
5602   QualType Result = TL.getType();
5603   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5604     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5605     if (Result.isNull())
5606       return QualType();
5607   }
5608
5609   // We might get an arbitrary type spec type back.  We should at
5610   // least always get a type spec type, though.
5611   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5612   NewTL.setNameLoc(TL.getNameLoc());
5613
5614   return Result;
5615 }
5616
5617 template<typename Derived>
5618 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5619                                                       TypedefTypeLoc TL) {
5620   const TypedefType *T = TL.getTypePtr();
5621   TypedefNameDecl *Typedef
5622     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5623                                                                T->getDecl()));
5624   if (!Typedef)
5625     return QualType();
5626
5627   QualType Result = TL.getType();
5628   if (getDerived().AlwaysRebuild() ||
5629       Typedef != T->getDecl()) {
5630     Result = getDerived().RebuildTypedefType(Typedef);
5631     if (Result.isNull())
5632       return QualType();
5633   }
5634
5635   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5636   NewTL.setNameLoc(TL.getNameLoc());
5637
5638   return Result;
5639 }
5640
5641 template<typename Derived>
5642 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5643                                                       TypeOfExprTypeLoc TL) {
5644   // typeof expressions are not potentially evaluated contexts
5645   EnterExpressionEvaluationContext Unevaluated(
5646       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5647       Sema::ReuseLambdaContextDecl);
5648
5649   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5650   if (E.isInvalid())
5651     return QualType();
5652
5653   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5654   if (E.isInvalid())
5655     return QualType();
5656
5657   QualType Result = TL.getType();
5658   if (getDerived().AlwaysRebuild() ||
5659       E.get() != TL.getUnderlyingExpr()) {
5660     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5661     if (Result.isNull())
5662       return QualType();
5663   }
5664   else E.get();
5665
5666   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5667   NewTL.setTypeofLoc(TL.getTypeofLoc());
5668   NewTL.setLParenLoc(TL.getLParenLoc());
5669   NewTL.setRParenLoc(TL.getRParenLoc());
5670
5671   return Result;
5672 }
5673
5674 template<typename Derived>
5675 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
5676                                                      TypeOfTypeLoc TL) {
5677   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
5678   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
5679   if (!New_Under_TI)
5680     return QualType();
5681
5682   QualType Result = TL.getType();
5683   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
5684     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
5685     if (Result.isNull())
5686       return QualType();
5687   }
5688
5689   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
5690   NewTL.setTypeofLoc(TL.getTypeofLoc());
5691   NewTL.setLParenLoc(TL.getLParenLoc());
5692   NewTL.setRParenLoc(TL.getRParenLoc());
5693   NewTL.setUnderlyingTInfo(New_Under_TI);
5694
5695   return Result;
5696 }
5697
5698 template<typename Derived>
5699 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
5700                                                        DecltypeTypeLoc TL) {
5701   const DecltypeType *T = TL.getTypePtr();
5702
5703   // decltype expressions are not potentially evaluated contexts
5704   EnterExpressionEvaluationContext Unevaluated(
5705       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
5706       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
5707
5708   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
5709   if (E.isInvalid())
5710     return QualType();
5711
5712   E = getSema().ActOnDecltypeExpression(E.get());
5713   if (E.isInvalid())
5714     return QualType();
5715
5716   QualType Result = TL.getType();
5717   if (getDerived().AlwaysRebuild() ||
5718       E.get() != T->getUnderlyingExpr()) {
5719     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
5720     if (Result.isNull())
5721       return QualType();
5722   }
5723   else E.get();
5724
5725   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
5726   NewTL.setNameLoc(TL.getNameLoc());
5727
5728   return Result;
5729 }
5730
5731 template<typename Derived>
5732 QualType TreeTransform<Derived>::TransformUnaryTransformType(
5733                                                             TypeLocBuilder &TLB,
5734                                                      UnaryTransformTypeLoc TL) {
5735   QualType Result = TL.getType();
5736   if (Result->isDependentType()) {
5737     const UnaryTransformType *T = TL.getTypePtr();
5738     QualType NewBase =
5739       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
5740     Result = getDerived().RebuildUnaryTransformType(NewBase,
5741                                                     T->getUTTKind(),
5742                                                     TL.getKWLoc());
5743     if (Result.isNull())
5744       return QualType();
5745   }
5746
5747   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
5748   NewTL.setKWLoc(TL.getKWLoc());
5749   NewTL.setParensRange(TL.getParensRange());
5750   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5751   return Result;
5752 }
5753
5754 template<typename Derived>
5755 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
5756                                                    AutoTypeLoc TL) {
5757   const AutoType *T = TL.getTypePtr();
5758   QualType OldDeduced = T->getDeducedType();
5759   QualType NewDeduced;
5760   if (!OldDeduced.isNull()) {
5761     NewDeduced = getDerived().TransformType(OldDeduced);
5762     if (NewDeduced.isNull())
5763       return QualType();
5764   }
5765
5766   QualType Result = TL.getType();
5767   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
5768       T->isDependentType()) {
5769     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword());
5770     if (Result.isNull())
5771       return QualType();
5772   }
5773
5774   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5775   NewTL.setNameLoc(TL.getNameLoc());
5776
5777   return Result;
5778 }
5779
5780 template<typename Derived>
5781 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
5782     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5783   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
5784
5785   CXXScopeSpec SS;
5786   TemplateName TemplateName = getDerived().TransformTemplateName(
5787       SS, T->getTemplateName(), TL.getTemplateNameLoc());
5788   if (TemplateName.isNull())
5789     return QualType();
5790
5791   QualType OldDeduced = T->getDeducedType();
5792   QualType NewDeduced;
5793   if (!OldDeduced.isNull()) {
5794     NewDeduced = getDerived().TransformType(OldDeduced);
5795     if (NewDeduced.isNull())
5796       return QualType();
5797   }
5798
5799   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
5800       TemplateName, NewDeduced);
5801   if (Result.isNull())
5802     return QualType();
5803
5804   DeducedTemplateSpecializationTypeLoc NewTL =
5805       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5806   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5807
5808   return Result;
5809 }
5810
5811 template<typename Derived>
5812 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5813                                                      RecordTypeLoc TL) {
5814   const RecordType *T = TL.getTypePtr();
5815   RecordDecl *Record
5816     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5817                                                           T->getDecl()));
5818   if (!Record)
5819     return QualType();
5820
5821   QualType Result = TL.getType();
5822   if (getDerived().AlwaysRebuild() ||
5823       Record != T->getDecl()) {
5824     Result = getDerived().RebuildRecordType(Record);
5825     if (Result.isNull())
5826       return QualType();
5827   }
5828
5829   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5830   NewTL.setNameLoc(TL.getNameLoc());
5831
5832   return Result;
5833 }
5834
5835 template<typename Derived>
5836 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5837                                                    EnumTypeLoc TL) {
5838   const EnumType *T = TL.getTypePtr();
5839   EnumDecl *Enum
5840     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5841                                                         T->getDecl()));
5842   if (!Enum)
5843     return QualType();
5844
5845   QualType Result = TL.getType();
5846   if (getDerived().AlwaysRebuild() ||
5847       Enum != T->getDecl()) {
5848     Result = getDerived().RebuildEnumType(Enum);
5849     if (Result.isNull())
5850       return QualType();
5851   }
5852
5853   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5854   NewTL.setNameLoc(TL.getNameLoc());
5855
5856   return Result;
5857 }
5858
5859 template<typename Derived>
5860 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5861                                          TypeLocBuilder &TLB,
5862                                          InjectedClassNameTypeLoc TL) {
5863   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5864                                        TL.getTypePtr()->getDecl());
5865   if (!D) return QualType();
5866
5867   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5868   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5869   return T;
5870 }
5871
5872 template<typename Derived>
5873 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5874                                                 TypeLocBuilder &TLB,
5875                                                 TemplateTypeParmTypeLoc TL) {
5876   return TransformTypeSpecType(TLB, TL);
5877 }
5878
5879 template<typename Derived>
5880 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5881                                          TypeLocBuilder &TLB,
5882                                          SubstTemplateTypeParmTypeLoc TL) {
5883   const SubstTemplateTypeParmType *T = TL.getTypePtr();
5884
5885   // Substitute into the replacement type, which itself might involve something
5886   // that needs to be transformed. This only tends to occur with default
5887   // template arguments of template template parameters.
5888   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5889   QualType Replacement = getDerived().TransformType(T->getReplacementType());
5890   if (Replacement.isNull())
5891     return QualType();
5892
5893   // Always canonicalize the replacement type.
5894   Replacement = SemaRef.Context.getCanonicalType(Replacement);
5895   QualType Result
5896     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5897                                                    Replacement);
5898
5899   // Propagate type-source information.
5900   SubstTemplateTypeParmTypeLoc NewTL
5901     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5902   NewTL.setNameLoc(TL.getNameLoc());
5903   return Result;
5904
5905 }
5906
5907 template<typename Derived>
5908 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5909                                           TypeLocBuilder &TLB,
5910                                           SubstTemplateTypeParmPackTypeLoc TL) {
5911   return TransformTypeSpecType(TLB, TL);
5912 }
5913
5914 template<typename Derived>
5915 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5916                                                         TypeLocBuilder &TLB,
5917                                            TemplateSpecializationTypeLoc TL) {
5918   const TemplateSpecializationType *T = TL.getTypePtr();
5919
5920   // The nested-name-specifier never matters in a TemplateSpecializationType,
5921   // because we can't have a dependent nested-name-specifier anyway.
5922   CXXScopeSpec SS;
5923   TemplateName Template
5924     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5925                                          TL.getTemplateNameLoc());
5926   if (Template.isNull())
5927     return QualType();
5928
5929   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5930 }
5931
5932 template<typename Derived>
5933 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5934                                                      AtomicTypeLoc TL) {
5935   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5936   if (ValueType.isNull())
5937     return QualType();
5938
5939   QualType Result = TL.getType();
5940   if (getDerived().AlwaysRebuild() ||
5941       ValueType != TL.getValueLoc().getType()) {
5942     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5943     if (Result.isNull())
5944       return QualType();
5945   }
5946
5947   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5948   NewTL.setKWLoc(TL.getKWLoc());
5949   NewTL.setLParenLoc(TL.getLParenLoc());
5950   NewTL.setRParenLoc(TL.getRParenLoc());
5951
5952   return Result;
5953 }
5954
5955 template <typename Derived>
5956 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
5957                                                    PipeTypeLoc TL) {
5958   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5959   if (ValueType.isNull())
5960     return QualType();
5961
5962   QualType Result = TL.getType();
5963   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
5964     const PipeType *PT = Result->castAs<PipeType>();
5965     bool isReadPipe = PT->isReadOnly();
5966     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
5967     if (Result.isNull())
5968       return QualType();
5969   }
5970
5971   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
5972   NewTL.setKWLoc(TL.getKWLoc());
5973
5974   return Result;
5975 }
5976
5977   /// Simple iterator that traverses the template arguments in a
5978   /// container that provides a \c getArgLoc() member function.
5979   ///
5980   /// This iterator is intended to be used with the iterator form of
5981   /// \c TreeTransform<Derived>::TransformTemplateArguments().
5982   template<typename ArgLocContainer>
5983   class TemplateArgumentLocContainerIterator {
5984     ArgLocContainer *Container;
5985     unsigned Index;
5986
5987   public:
5988     typedef TemplateArgumentLoc value_type;
5989     typedef TemplateArgumentLoc reference;
5990     typedef int difference_type;
5991     typedef std::input_iterator_tag iterator_category;
5992
5993     class pointer {
5994       TemplateArgumentLoc Arg;
5995
5996     public:
5997       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5998
5999       const TemplateArgumentLoc *operator->() const {
6000         return &Arg;
6001       }
6002     };
6003
6004
6005     TemplateArgumentLocContainerIterator() {}
6006
6007     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6008                                  unsigned Index)
6009       : Container(&Container), Index(Index) { }
6010
6011     TemplateArgumentLocContainerIterator &operator++() {
6012       ++Index;
6013       return *this;
6014     }
6015
6016     TemplateArgumentLocContainerIterator operator++(int) {
6017       TemplateArgumentLocContainerIterator Old(*this);
6018       ++(*this);
6019       return Old;
6020     }
6021
6022     TemplateArgumentLoc operator*() const {
6023       return Container->getArgLoc(Index);
6024     }
6025
6026     pointer operator->() const {
6027       return pointer(Container->getArgLoc(Index));
6028     }
6029
6030     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6031                            const TemplateArgumentLocContainerIterator &Y) {
6032       return X.Container == Y.Container && X.Index == Y.Index;
6033     }
6034
6035     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6036                            const TemplateArgumentLocContainerIterator &Y) {
6037       return !(X == Y);
6038     }
6039   };
6040
6041
6042 template <typename Derived>
6043 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6044                                                         TypeLocBuilder &TLB,
6045                                            TemplateSpecializationTypeLoc TL,
6046                                                       TemplateName Template) {
6047   TemplateArgumentListInfo NewTemplateArgs;
6048   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6049   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6050   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6051     ArgIterator;
6052   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6053                                               ArgIterator(TL, TL.getNumArgs()),
6054                                               NewTemplateArgs))
6055     return QualType();
6056
6057   // FIXME: maybe don't rebuild if all the template arguments are the same.
6058
6059   QualType Result =
6060     getDerived().RebuildTemplateSpecializationType(Template,
6061                                                    TL.getTemplateNameLoc(),
6062                                                    NewTemplateArgs);
6063
6064   if (!Result.isNull()) {
6065     // Specializations of template template parameters are represented as
6066     // TemplateSpecializationTypes, and substitution of type alias templates
6067     // within a dependent context can transform them into
6068     // DependentTemplateSpecializationTypes.
6069     if (isa<DependentTemplateSpecializationType>(Result)) {
6070       DependentTemplateSpecializationTypeLoc NewTL
6071         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6072       NewTL.setElaboratedKeywordLoc(SourceLocation());
6073       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6074       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6075       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6076       NewTL.setLAngleLoc(TL.getLAngleLoc());
6077       NewTL.setRAngleLoc(TL.getRAngleLoc());
6078       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6079         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6080       return Result;
6081     }
6082
6083     TemplateSpecializationTypeLoc NewTL
6084       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6085     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6086     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6087     NewTL.setLAngleLoc(TL.getLAngleLoc());
6088     NewTL.setRAngleLoc(TL.getRAngleLoc());
6089     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6090       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6091   }
6092
6093   return Result;
6094 }
6095
6096 template <typename Derived>
6097 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6098                                      TypeLocBuilder &TLB,
6099                                      DependentTemplateSpecializationTypeLoc TL,
6100                                      TemplateName Template,
6101                                      CXXScopeSpec &SS) {
6102   TemplateArgumentListInfo NewTemplateArgs;
6103   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6104   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6105   typedef TemplateArgumentLocContainerIterator<
6106             DependentTemplateSpecializationTypeLoc> ArgIterator;
6107   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6108                                               ArgIterator(TL, TL.getNumArgs()),
6109                                               NewTemplateArgs))
6110     return QualType();
6111
6112   // FIXME: maybe don't rebuild if all the template arguments are the same.
6113
6114   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6115     QualType Result
6116       = getSema().Context.getDependentTemplateSpecializationType(
6117                                                 TL.getTypePtr()->getKeyword(),
6118                                                          DTN->getQualifier(),
6119                                                          DTN->getIdentifier(),
6120                                                                NewTemplateArgs);
6121
6122     DependentTemplateSpecializationTypeLoc NewTL
6123       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6124     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6125     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6126     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6127     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6128     NewTL.setLAngleLoc(TL.getLAngleLoc());
6129     NewTL.setRAngleLoc(TL.getRAngleLoc());
6130     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6131       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6132     return Result;
6133   }
6134
6135   QualType Result
6136     = getDerived().RebuildTemplateSpecializationType(Template,
6137                                                      TL.getTemplateNameLoc(),
6138                                                      NewTemplateArgs);
6139
6140   if (!Result.isNull()) {
6141     /// FIXME: Wrap this in an elaborated-type-specifier?
6142     TemplateSpecializationTypeLoc NewTL
6143       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6144     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6145     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6146     NewTL.setLAngleLoc(TL.getLAngleLoc());
6147     NewTL.setRAngleLoc(TL.getRAngleLoc());
6148     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6149       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6150   }
6151
6152   return Result;
6153 }
6154
6155 template<typename Derived>
6156 QualType
6157 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6158                                                 ElaboratedTypeLoc TL) {
6159   const ElaboratedType *T = TL.getTypePtr();
6160
6161   NestedNameSpecifierLoc QualifierLoc;
6162   // NOTE: the qualifier in an ElaboratedType is optional.
6163   if (TL.getQualifierLoc()) {
6164     QualifierLoc
6165       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6166     if (!QualifierLoc)
6167       return QualType();
6168   }
6169
6170   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6171   if (NamedT.isNull())
6172     return QualType();
6173
6174   // C++0x [dcl.type.elab]p2:
6175   //   If the identifier resolves to a typedef-name or the simple-template-id
6176   //   resolves to an alias template specialization, the
6177   //   elaborated-type-specifier is ill-formed.
6178   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6179     if (const TemplateSpecializationType *TST =
6180           NamedT->getAs<TemplateSpecializationType>()) {
6181       TemplateName Template = TST->getTemplateName();
6182       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6183               Template.getAsTemplateDecl())) {
6184         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6185                      diag::err_tag_reference_non_tag)
6186             << TAT << Sema::NTK_TypeAliasTemplate
6187             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6188         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6189       }
6190     }
6191   }
6192
6193   QualType Result = TL.getType();
6194   if (getDerived().AlwaysRebuild() ||
6195       QualifierLoc != TL.getQualifierLoc() ||
6196       NamedT != T->getNamedType()) {
6197     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6198                                                 T->getKeyword(),
6199                                                 QualifierLoc, NamedT);
6200     if (Result.isNull())
6201       return QualType();
6202   }
6203
6204   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6205   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6206   NewTL.setQualifierLoc(QualifierLoc);
6207   return Result;
6208 }
6209
6210 template<typename Derived>
6211 QualType TreeTransform<Derived>::TransformAttributedType(
6212                                                 TypeLocBuilder &TLB,
6213                                                 AttributedTypeLoc TL) {
6214   const AttributedType *oldType = TL.getTypePtr();
6215   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6216   if (modifiedType.isNull())
6217     return QualType();
6218
6219   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6220   const Attr *oldAttr = TL.getAttr();
6221   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6222   if (oldAttr && !newAttr)
6223     return QualType();
6224
6225   QualType result = TL.getType();
6226
6227   // FIXME: dependent operand expressions?
6228   if (getDerived().AlwaysRebuild() ||
6229       modifiedType != oldType->getModifiedType()) {
6230     // TODO: this is really lame; we should really be rebuilding the
6231     // equivalent type from first principles.
6232     QualType equivalentType
6233       = getDerived().TransformType(oldType->getEquivalentType());
6234     if (equivalentType.isNull())
6235       return QualType();
6236
6237     // Check whether we can add nullability; it is only represented as
6238     // type sugar, and therefore cannot be diagnosed in any other way.
6239     if (auto nullability = oldType->getImmediateNullability()) {
6240       if (!modifiedType->canHaveNullability()) {
6241         SemaRef.Diag(TL.getAttr()->getLocation(),
6242                      diag::err_nullability_nonpointer)
6243             << DiagNullabilityKind(*nullability, false) << modifiedType;
6244         return QualType();
6245       }
6246     }
6247
6248     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6249                                                modifiedType,
6250                                                equivalentType);
6251   }
6252
6253   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6254   newTL.setAttr(newAttr);
6255   return result;
6256 }
6257
6258 template<typename Derived>
6259 QualType
6260 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6261                                            ParenTypeLoc TL) {
6262   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6263   if (Inner.isNull())
6264     return QualType();
6265
6266   QualType Result = TL.getType();
6267   if (getDerived().AlwaysRebuild() ||
6268       Inner != TL.getInnerLoc().getType()) {
6269     Result = getDerived().RebuildParenType(Inner);
6270     if (Result.isNull())
6271       return QualType();
6272   }
6273
6274   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6275   NewTL.setLParenLoc(TL.getLParenLoc());
6276   NewTL.setRParenLoc(TL.getRParenLoc());
6277   return Result;
6278 }
6279
6280 template <typename Derived>
6281 QualType
6282 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6283                                                     MacroQualifiedTypeLoc TL) {
6284   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6285   if (Inner.isNull())
6286     return QualType();
6287
6288   QualType Result = TL.getType();
6289   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6290     Result =
6291         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6292     if (Result.isNull())
6293       return QualType();
6294   }
6295
6296   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6297   NewTL.setExpansionLoc(TL.getExpansionLoc());
6298   return Result;
6299 }
6300
6301 template<typename Derived>
6302 QualType TreeTransform<Derived>::TransformDependentNameType(
6303     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6304   return TransformDependentNameType(TLB, TL, false);
6305 }
6306
6307 template<typename Derived>
6308 QualType TreeTransform<Derived>::TransformDependentNameType(
6309     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6310   const DependentNameType *T = TL.getTypePtr();
6311
6312   NestedNameSpecifierLoc QualifierLoc
6313     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6314   if (!QualifierLoc)
6315     return QualType();
6316
6317   QualType Result
6318     = getDerived().RebuildDependentNameType(T->getKeyword(),
6319                                             TL.getElaboratedKeywordLoc(),
6320                                             QualifierLoc,
6321                                             T->getIdentifier(),
6322                                             TL.getNameLoc(),
6323                                             DeducedTSTContext);
6324   if (Result.isNull())
6325     return QualType();
6326
6327   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6328     QualType NamedT = ElabT->getNamedType();
6329     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6330
6331     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6332     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6333     NewTL.setQualifierLoc(QualifierLoc);
6334   } else {
6335     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6336     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6337     NewTL.setQualifierLoc(QualifierLoc);
6338     NewTL.setNameLoc(TL.getNameLoc());
6339   }
6340   return Result;
6341 }
6342
6343 template<typename Derived>
6344 QualType TreeTransform<Derived>::
6345           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6346                                  DependentTemplateSpecializationTypeLoc TL) {
6347   NestedNameSpecifierLoc QualifierLoc;
6348   if (TL.getQualifierLoc()) {
6349     QualifierLoc
6350       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6351     if (!QualifierLoc)
6352       return QualType();
6353   }
6354
6355   return getDerived()
6356            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6357 }
6358
6359 template<typename Derived>
6360 QualType TreeTransform<Derived>::
6361 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6362                                    DependentTemplateSpecializationTypeLoc TL,
6363                                        NestedNameSpecifierLoc QualifierLoc) {
6364   const DependentTemplateSpecializationType *T = TL.getTypePtr();
6365
6366   TemplateArgumentListInfo NewTemplateArgs;
6367   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6368   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6369
6370   typedef TemplateArgumentLocContainerIterator<
6371   DependentTemplateSpecializationTypeLoc> ArgIterator;
6372   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6373                                               ArgIterator(TL, TL.getNumArgs()),
6374                                               NewTemplateArgs))
6375     return QualType();
6376
6377   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6378       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6379       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6380       /*AllowInjectedClassName*/ false);
6381   if (Result.isNull())
6382     return QualType();
6383
6384   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6385     QualType NamedT = ElabT->getNamedType();
6386
6387     // Copy information relevant to the template specialization.
6388     TemplateSpecializationTypeLoc NamedTL
6389       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6390     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6391     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6392     NamedTL.setLAngleLoc(TL.getLAngleLoc());
6393     NamedTL.setRAngleLoc(TL.getRAngleLoc());
6394     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6395       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6396
6397     // Copy information relevant to the elaborated type.
6398     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6399     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6400     NewTL.setQualifierLoc(QualifierLoc);
6401   } else if (isa<DependentTemplateSpecializationType>(Result)) {
6402     DependentTemplateSpecializationTypeLoc SpecTL
6403       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6404     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6405     SpecTL.setQualifierLoc(QualifierLoc);
6406     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6407     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6408     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6409     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6410     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6411       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6412   } else {
6413     TemplateSpecializationTypeLoc SpecTL
6414       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6415     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6416     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6417     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6418     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6419     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6420       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6421   }
6422   return Result;
6423 }
6424
6425 template<typename Derived>
6426 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6427                                                       PackExpansionTypeLoc TL) {
6428   QualType Pattern
6429     = getDerived().TransformType(TLB, TL.getPatternLoc());
6430   if (Pattern.isNull())
6431     return QualType();
6432
6433   QualType Result = TL.getType();
6434   if (getDerived().AlwaysRebuild() ||
6435       Pattern != TL.getPatternLoc().getType()) {
6436     Result = getDerived().RebuildPackExpansionType(Pattern,
6437                                            TL.getPatternLoc().getSourceRange(),
6438                                                    TL.getEllipsisLoc(),
6439                                            TL.getTypePtr()->getNumExpansions());
6440     if (Result.isNull())
6441       return QualType();
6442   }
6443
6444   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6445   NewT.setEllipsisLoc(TL.getEllipsisLoc());
6446   return Result;
6447 }
6448
6449 template<typename Derived>
6450 QualType
6451 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6452                                                    ObjCInterfaceTypeLoc TL) {
6453   // ObjCInterfaceType is never dependent.
6454   TLB.pushFullCopy(TL);
6455   return TL.getType();
6456 }
6457
6458 template<typename Derived>
6459 QualType
6460 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6461                                                    ObjCTypeParamTypeLoc TL) {
6462   const ObjCTypeParamType *T = TL.getTypePtr();
6463   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6464       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6465   if (!OTP)
6466     return QualType();
6467
6468   QualType Result = TL.getType();
6469   if (getDerived().AlwaysRebuild() ||
6470       OTP != T->getDecl()) {
6471     Result = getDerived().RebuildObjCTypeParamType(OTP,
6472                  TL.getProtocolLAngleLoc(),
6473                  llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6474                                     TL.getNumProtocols()),
6475                  TL.getProtocolLocs(),
6476                  TL.getProtocolRAngleLoc());
6477     if (Result.isNull())
6478       return QualType();
6479   }
6480
6481   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6482   if (TL.getNumProtocols()) {
6483     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6484     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6485       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6486     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6487   }
6488   return Result;
6489 }
6490
6491 template<typename Derived>
6492 QualType
6493 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6494                                                 ObjCObjectTypeLoc TL) {
6495   // Transform base type.
6496   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6497   if (BaseType.isNull())
6498     return QualType();
6499
6500   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6501
6502   // Transform type arguments.
6503   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6504   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6505     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6506     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6507     QualType TypeArg = TypeArgInfo->getType();
6508     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6509       AnyChanged = true;
6510
6511       // We have a pack expansion. Instantiate it.
6512       const auto *PackExpansion = PackExpansionLoc.getType()
6513                                     ->castAs<PackExpansionType>();
6514       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6515       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6516                                               Unexpanded);
6517       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6518
6519       // Determine whether the set of unexpanded parameter packs can
6520       // and should be expanded.
6521       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6522       bool Expand = false;
6523       bool RetainExpansion = false;
6524       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6525       if (getDerived().TryExpandParameterPacks(
6526             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6527             Unexpanded, Expand, RetainExpansion, NumExpansions))
6528         return QualType();
6529
6530       if (!Expand) {
6531         // We can't expand this pack expansion into separate arguments yet;
6532         // just substitute into the pattern and create a new pack expansion
6533         // type.
6534         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6535
6536         TypeLocBuilder TypeArgBuilder;
6537         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6538         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6539                                                              PatternLoc);
6540         if (NewPatternType.isNull())
6541           return QualType();
6542
6543         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6544                                       NewPatternType, NumExpansions);
6545         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6546         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6547         NewTypeArgInfos.push_back(
6548           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6549         continue;
6550       }
6551
6552       // Substitute into the pack expansion pattern for each slice of the
6553       // pack.
6554       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6555         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6556
6557         TypeLocBuilder TypeArgBuilder;
6558         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6559
6560         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6561                                                          PatternLoc);
6562         if (NewTypeArg.isNull())
6563           return QualType();
6564
6565         NewTypeArgInfos.push_back(
6566           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6567       }
6568
6569       continue;
6570     }
6571
6572     TypeLocBuilder TypeArgBuilder;
6573     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6574     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6575     if (NewTypeArg.isNull())
6576       return QualType();
6577
6578     // If nothing changed, just keep the old TypeSourceInfo.
6579     if (NewTypeArg == TypeArg) {
6580       NewTypeArgInfos.push_back(TypeArgInfo);
6581       continue;
6582     }
6583
6584     NewTypeArgInfos.push_back(
6585       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6586     AnyChanged = true;
6587   }
6588
6589   QualType Result = TL.getType();
6590   if (getDerived().AlwaysRebuild() || AnyChanged) {
6591     // Rebuild the type.
6592     Result = getDerived().RebuildObjCObjectType(
6593         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
6594         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
6595         llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
6596         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
6597
6598     if (Result.isNull())
6599       return QualType();
6600   }
6601
6602   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
6603   NewT.setHasBaseTypeAsWritten(true);
6604   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
6605   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
6606     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
6607   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
6608   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6609   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6610     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
6611   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6612   return Result;
6613 }
6614
6615 template<typename Derived>
6616 QualType
6617 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
6618                                                ObjCObjectPointerTypeLoc TL) {
6619   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
6620   if (PointeeType.isNull())
6621     return QualType();
6622
6623   QualType Result = TL.getType();
6624   if (getDerived().AlwaysRebuild() ||
6625       PointeeType != TL.getPointeeLoc().getType()) {
6626     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
6627                                                        TL.getStarLoc());
6628     if (Result.isNull())
6629       return QualType();
6630   }
6631
6632   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
6633   NewT.setStarLoc(TL.getStarLoc());
6634   return Result;
6635 }
6636
6637 //===----------------------------------------------------------------------===//
6638 // Statement transformation
6639 //===----------------------------------------------------------------------===//
6640 template<typename Derived>
6641 StmtResult
6642 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
6643   return S;
6644 }
6645
6646 template<typename Derived>
6647 StmtResult
6648 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
6649   return getDerived().TransformCompoundStmt(S, false);
6650 }
6651
6652 template<typename Derived>
6653 StmtResult
6654 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
6655                                               bool IsStmtExpr) {
6656   Sema::CompoundScopeRAII CompoundScope(getSema());
6657
6658   const Stmt *ExprResult = S->getStmtExprResult();
6659   bool SubStmtInvalid = false;
6660   bool SubStmtChanged = false;
6661   SmallVector<Stmt*, 8> Statements;
6662   for (auto *B : S->body()) {
6663     StmtResult Result = getDerived().TransformStmt(
6664         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
6665
6666     if (Result.isInvalid()) {
6667       // Immediately fail if this was a DeclStmt, since it's very
6668       // likely that this will cause problems for future statements.
6669       if (isa<DeclStmt>(B))
6670         return StmtError();
6671
6672       // Otherwise, just keep processing substatements and fail later.
6673       SubStmtInvalid = true;
6674       continue;
6675     }
6676
6677     SubStmtChanged = SubStmtChanged || Result.get() != B;
6678     Statements.push_back(Result.getAs<Stmt>());
6679   }
6680
6681   if (SubStmtInvalid)
6682     return StmtError();
6683
6684   if (!getDerived().AlwaysRebuild() &&
6685       !SubStmtChanged)
6686     return S;
6687
6688   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
6689                                           Statements,
6690                                           S->getRBracLoc(),
6691                                           IsStmtExpr);
6692 }
6693
6694 template<typename Derived>
6695 StmtResult
6696 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
6697   ExprResult LHS, RHS;
6698   {
6699     EnterExpressionEvaluationContext Unevaluated(
6700         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6701
6702     // Transform the left-hand case value.
6703     LHS = getDerived().TransformExpr(S->getLHS());
6704     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
6705     if (LHS.isInvalid())
6706       return StmtError();
6707
6708     // Transform the right-hand case value (for the GNU case-range extension).
6709     RHS = getDerived().TransformExpr(S->getRHS());
6710     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
6711     if (RHS.isInvalid())
6712       return StmtError();
6713   }
6714
6715   // Build the case statement.
6716   // Case statements are always rebuilt so that they will attached to their
6717   // transformed switch statement.
6718   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
6719                                                        LHS.get(),
6720                                                        S->getEllipsisLoc(),
6721                                                        RHS.get(),
6722                                                        S->getColonLoc());
6723   if (Case.isInvalid())
6724     return StmtError();
6725
6726   // Transform the statement following the case
6727   StmtResult SubStmt =
6728       getDerived().TransformStmt(S->getSubStmt());
6729   if (SubStmt.isInvalid())
6730     return StmtError();
6731
6732   // Attach the body to the case statement
6733   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
6734 }
6735
6736 template <typename Derived>
6737 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
6738   // Transform the statement following the default case
6739   StmtResult SubStmt =
6740       getDerived().TransformStmt(S->getSubStmt());
6741   if (SubStmt.isInvalid())
6742     return StmtError();
6743
6744   // Default statements are always rebuilt
6745   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
6746                                          SubStmt.get());
6747 }
6748
6749 template<typename Derived>
6750 StmtResult
6751 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
6752   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6753   if (SubStmt.isInvalid())
6754     return StmtError();
6755
6756   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
6757                                         S->getDecl());
6758   if (!LD)
6759     return StmtError();
6760
6761   // If we're transforming "in-place" (we're not creating new local
6762   // declarations), assume we're replacing the old label statement
6763   // and clear out the reference to it.
6764   if (LD == S->getDecl())
6765     S->getDecl()->setStmt(nullptr);
6766
6767   // FIXME: Pass the real colon location in.
6768   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
6769                                        cast<LabelDecl>(LD), SourceLocation(),
6770                                        SubStmt.get());
6771 }
6772
6773 template <typename Derived>
6774 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
6775   if (!R)
6776     return R;
6777
6778   switch (R->getKind()) {
6779 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
6780 #define ATTR(X)
6781 #define PRAGMA_SPELLING_ATTR(X)                                                \
6782   case attr::X:                                                                \
6783     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
6784 #include "clang/Basic/AttrList.inc"
6785   default:
6786     return R;
6787   }
6788 }
6789
6790 template <typename Derived>
6791 StmtResult
6792 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
6793                                                 StmtDiscardKind SDK) {
6794   bool AttrsChanged = false;
6795   SmallVector<const Attr *, 1> Attrs;
6796
6797   // Visit attributes and keep track if any are transformed.
6798   for (const auto *I : S->getAttrs()) {
6799     const Attr *R = getDerived().TransformAttr(I);
6800     AttrsChanged |= (I != R);
6801     Attrs.push_back(R);
6802   }
6803
6804   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
6805   if (SubStmt.isInvalid())
6806     return StmtError();
6807
6808   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
6809     return S;
6810
6811   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
6812                                             SubStmt.get());
6813 }
6814
6815 template<typename Derived>
6816 StmtResult
6817 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
6818   // Transform the initialization statement
6819   StmtResult Init = getDerived().TransformStmt(S->getInit());
6820   if (Init.isInvalid())
6821     return StmtError();
6822
6823   // Transform the condition
6824   Sema::ConditionResult Cond = getDerived().TransformCondition(
6825       S->getIfLoc(), S->getConditionVariable(), S->getCond(),
6826       S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
6827                        : Sema::ConditionKind::Boolean);
6828   if (Cond.isInvalid())
6829     return StmtError();
6830
6831   // If this is a constexpr if, determine which arm we should instantiate.
6832   llvm::Optional<bool> ConstexprConditionValue;
6833   if (S->isConstexpr())
6834     ConstexprConditionValue = Cond.getKnownValue();
6835
6836   // Transform the "then" branch.
6837   StmtResult Then;
6838   if (!ConstexprConditionValue || *ConstexprConditionValue) {
6839     Then = getDerived().TransformStmt(S->getThen());
6840     if (Then.isInvalid())
6841       return StmtError();
6842   } else {
6843     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
6844   }
6845
6846   // Transform the "else" branch.
6847   StmtResult Else;
6848   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
6849     Else = getDerived().TransformStmt(S->getElse());
6850     if (Else.isInvalid())
6851       return StmtError();
6852   }
6853
6854   if (!getDerived().AlwaysRebuild() &&
6855       Init.get() == S->getInit() &&
6856       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6857       Then.get() == S->getThen() &&
6858       Else.get() == S->getElse())
6859     return S;
6860
6861   return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
6862                                     Init.get(), Then.get(), S->getElseLoc(),
6863                                     Else.get());
6864 }
6865
6866 template<typename Derived>
6867 StmtResult
6868 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6869   // Transform the initialization statement
6870   StmtResult Init = getDerived().TransformStmt(S->getInit());
6871   if (Init.isInvalid())
6872     return StmtError();
6873
6874   // Transform the condition.
6875   Sema::ConditionResult Cond = getDerived().TransformCondition(
6876       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
6877       Sema::ConditionKind::Switch);
6878   if (Cond.isInvalid())
6879     return StmtError();
6880
6881   // Rebuild the switch statement.
6882   StmtResult Switch
6883     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
6884   if (Switch.isInvalid())
6885     return StmtError();
6886
6887   // Transform the body of the switch statement.
6888   StmtResult Body = getDerived().TransformStmt(S->getBody());
6889   if (Body.isInvalid())
6890     return StmtError();
6891
6892   // Complete the switch statement.
6893   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
6894                                             Body.get());
6895 }
6896
6897 template<typename Derived>
6898 StmtResult
6899 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
6900   // Transform the condition
6901   Sema::ConditionResult Cond = getDerived().TransformCondition(
6902       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
6903       Sema::ConditionKind::Boolean);
6904   if (Cond.isInvalid())
6905     return StmtError();
6906
6907   // Transform the body
6908   StmtResult Body = getDerived().TransformStmt(S->getBody());
6909   if (Body.isInvalid())
6910     return StmtError();
6911
6912   if (!getDerived().AlwaysRebuild() &&
6913       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6914       Body.get() == S->getBody())
6915     return Owned(S);
6916
6917   return getDerived().RebuildWhileStmt(S->getWhileLoc(), Cond, Body.get());
6918 }
6919
6920 template<typename Derived>
6921 StmtResult
6922 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
6923   // Transform the body
6924   StmtResult Body = getDerived().TransformStmt(S->getBody());
6925   if (Body.isInvalid())
6926     return StmtError();
6927
6928   // Transform the condition
6929   ExprResult Cond = getDerived().TransformExpr(S->getCond());
6930   if (Cond.isInvalid())
6931     return StmtError();
6932
6933   if (!getDerived().AlwaysRebuild() &&
6934       Cond.get() == S->getCond() &&
6935       Body.get() == S->getBody())
6936     return S;
6937
6938   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
6939                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
6940                                     S->getRParenLoc());
6941 }
6942
6943 template<typename Derived>
6944 StmtResult
6945 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
6946   if (getSema().getLangOpts().OpenMP)
6947     getSema().startOpenMPLoop();
6948
6949   // Transform the initialization statement
6950   StmtResult Init = getDerived().TransformStmt(S->getInit());
6951   if (Init.isInvalid())
6952     return StmtError();
6953
6954   // In OpenMP loop region loop control variable must be captured and be
6955   // private. Perform analysis of first part (if any).
6956   if (getSema().getLangOpts().OpenMP && Init.isUsable())
6957     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
6958
6959   // Transform the condition
6960   Sema::ConditionResult Cond = getDerived().TransformCondition(
6961       S->getForLoc(), S->getConditionVariable(), S->getCond(),
6962       Sema::ConditionKind::Boolean);
6963   if (Cond.isInvalid())
6964     return StmtError();
6965
6966   // Transform the increment
6967   ExprResult Inc = getDerived().TransformExpr(S->getInc());
6968   if (Inc.isInvalid())
6969     return StmtError();
6970
6971   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6972   if (S->getInc() && !FullInc.get())
6973     return StmtError();
6974
6975   // Transform the body
6976   StmtResult Body = getDerived().TransformStmt(S->getBody());
6977   if (Body.isInvalid())
6978     return StmtError();
6979
6980   if (!getDerived().AlwaysRebuild() &&
6981       Init.get() == S->getInit() &&
6982       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6983       Inc.get() == S->getInc() &&
6984       Body.get() == S->getBody())
6985     return S;
6986
6987   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6988                                      Init.get(), Cond, FullInc,
6989                                      S->getRParenLoc(), Body.get());
6990 }
6991
6992 template<typename Derived>
6993 StmtResult
6994 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6995   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
6996                                         S->getLabel());
6997   if (!LD)
6998     return StmtError();
6999
7000   // Goto statements must always be rebuilt, to resolve the label.
7001   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7002                                       cast<LabelDecl>(LD));
7003 }
7004
7005 template<typename Derived>
7006 StmtResult
7007 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7008   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7009   if (Target.isInvalid())
7010     return StmtError();
7011   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7012
7013   if (!getDerived().AlwaysRebuild() &&
7014       Target.get() == S->getTarget())
7015     return S;
7016
7017   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7018                                               Target.get());
7019 }
7020
7021 template<typename Derived>
7022 StmtResult
7023 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7024   return S;
7025 }
7026
7027 template<typename Derived>
7028 StmtResult
7029 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7030   return S;
7031 }
7032
7033 template<typename Derived>
7034 StmtResult
7035 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7036   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7037                                                         /*NotCopyInit*/false);
7038   if (Result.isInvalid())
7039     return StmtError();
7040
7041   // FIXME: We always rebuild the return statement because there is no way
7042   // to tell whether the return type of the function has changed.
7043   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7044 }
7045
7046 template<typename Derived>
7047 StmtResult
7048 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7049   bool DeclChanged = false;
7050   SmallVector<Decl *, 4> Decls;
7051   for (auto *D : S->decls()) {
7052     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7053     if (!Transformed)
7054       return StmtError();
7055
7056     if (Transformed != D)
7057       DeclChanged = true;
7058
7059     Decls.push_back(Transformed);
7060   }
7061
7062   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7063     return S;
7064
7065   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7066 }
7067
7068 template<typename Derived>
7069 StmtResult
7070 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7071
7072   SmallVector<Expr*, 8> Constraints;
7073   SmallVector<Expr*, 8> Exprs;
7074   SmallVector<IdentifierInfo *, 4> Names;
7075
7076   ExprResult AsmString;
7077   SmallVector<Expr*, 8> Clobbers;
7078
7079   bool ExprsChanged = false;
7080
7081   // Go through the outputs.
7082   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7083     Names.push_back(S->getOutputIdentifier(I));
7084
7085     // No need to transform the constraint literal.
7086     Constraints.push_back(S->getOutputConstraintLiteral(I));
7087
7088     // Transform the output expr.
7089     Expr *OutputExpr = S->getOutputExpr(I);
7090     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7091     if (Result.isInvalid())
7092       return StmtError();
7093
7094     ExprsChanged |= Result.get() != OutputExpr;
7095
7096     Exprs.push_back(Result.get());
7097   }
7098
7099   // Go through the inputs.
7100   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7101     Names.push_back(S->getInputIdentifier(I));
7102
7103     // No need to transform the constraint literal.
7104     Constraints.push_back(S->getInputConstraintLiteral(I));
7105
7106     // Transform the input expr.
7107     Expr *InputExpr = S->getInputExpr(I);
7108     ExprResult Result = getDerived().TransformExpr(InputExpr);
7109     if (Result.isInvalid())
7110       return StmtError();
7111
7112     ExprsChanged |= Result.get() != InputExpr;
7113
7114     Exprs.push_back(Result.get());
7115   }
7116
7117   // Go through the Labels.
7118   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7119     Names.push_back(S->getLabelIdentifier(I));
7120
7121     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7122     if (Result.isInvalid())
7123       return StmtError();
7124     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7125     Exprs.push_back(Result.get());
7126   }
7127   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7128     return S;
7129
7130   // Go through the clobbers.
7131   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7132     Clobbers.push_back(S->getClobberStringLiteral(I));
7133
7134   // No need to transform the asm string literal.
7135   AsmString = S->getAsmString();
7136   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7137                                         S->isVolatile(), S->getNumOutputs(),
7138                                         S->getNumInputs(), Names.data(),
7139                                         Constraints, Exprs, AsmString.get(),
7140                                         Clobbers, S->getNumLabels(),
7141                                         S->getRParenLoc());
7142 }
7143
7144 template<typename Derived>
7145 StmtResult
7146 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7147   ArrayRef<Token> AsmToks =
7148     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7149
7150   bool HadError = false, HadChange = false;
7151
7152   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7153   SmallVector<Expr*, 8> TransformedExprs;
7154   TransformedExprs.reserve(SrcExprs.size());
7155   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7156     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7157     if (!Result.isUsable()) {
7158       HadError = true;
7159     } else {
7160       HadChange |= (Result.get() != SrcExprs[i]);
7161       TransformedExprs.push_back(Result.get());
7162     }
7163   }
7164
7165   if (HadError) return StmtError();
7166   if (!HadChange && !getDerived().AlwaysRebuild())
7167     return Owned(S);
7168
7169   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7170                                        AsmToks, S->getAsmString(),
7171                                        S->getNumOutputs(), S->getNumInputs(),
7172                                        S->getAllConstraints(), S->getClobbers(),
7173                                        TransformedExprs, S->getEndLoc());
7174 }
7175
7176 // C++ Coroutines TS
7177
7178 template<typename Derived>
7179 StmtResult
7180 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7181   auto *ScopeInfo = SemaRef.getCurFunction();
7182   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7183   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7184          ScopeInfo->NeedsCoroutineSuspends &&
7185          ScopeInfo->CoroutineSuspends.first == nullptr &&
7186          ScopeInfo->CoroutineSuspends.second == nullptr &&
7187          "expected clean scope info");
7188
7189   // Set that we have (possibly-invalid) suspend points before we do anything
7190   // that may fail.
7191   ScopeInfo->setNeedsCoroutineSuspends(false);
7192
7193   // The new CoroutinePromise object needs to be built and put into the current
7194   // FunctionScopeInfo before any transformations or rebuilding occurs.
7195   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7196     return StmtError();
7197   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7198   if (!Promise)
7199     return StmtError();
7200   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7201   ScopeInfo->CoroutinePromise = Promise;
7202
7203   // Transform the implicit coroutine statements we built during the initial
7204   // parse.
7205   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7206   if (InitSuspend.isInvalid())
7207     return StmtError();
7208   StmtResult FinalSuspend =
7209       getDerived().TransformStmt(S->getFinalSuspendStmt());
7210   if (FinalSuspend.isInvalid())
7211     return StmtError();
7212   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7213   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7214
7215   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7216   if (BodyRes.isInvalid())
7217     return StmtError();
7218
7219   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7220   if (Builder.isInvalid())
7221     return StmtError();
7222
7223   Expr *ReturnObject = S->getReturnValueInit();
7224   assert(ReturnObject && "the return object is expected to be valid");
7225   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7226                                                      /*NoCopyInit*/ false);
7227   if (Res.isInvalid())
7228     return StmtError();
7229   Builder.ReturnValue = Res.get();
7230
7231   if (S->hasDependentPromiseType()) {
7232     // PR41909: We may find a generic coroutine lambda definition within a
7233     // template function that is being instantiated. In this case, the lambda
7234     // will have a dependent promise type, until it is used in an expression
7235     // that creates an instantiation with a non-dependent promise type. We
7236     // should not assert or build coroutine dependent statements for such a
7237     // generic lambda.
7238     auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD);
7239     if (!MD || !MD->getParent()->isGenericLambda()) {
7240       assert(!Promise->getType()->isDependentType() &&
7241              "the promise type must no longer be dependent");
7242       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7243              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7244              "these nodes should not have been built yet");
7245       if (!Builder.buildDependentStatements())
7246         return StmtError();
7247     }
7248   } else {
7249     if (auto *OnFallthrough = S->getFallthroughHandler()) {
7250       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7251       if (Res.isInvalid())
7252         return StmtError();
7253       Builder.OnFallthrough = Res.get();
7254     }
7255
7256     if (auto *OnException = S->getExceptionHandler()) {
7257       StmtResult Res = getDerived().TransformStmt(OnException);
7258       if (Res.isInvalid())
7259         return StmtError();
7260       Builder.OnException = Res.get();
7261     }
7262
7263     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7264       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7265       if (Res.isInvalid())
7266         return StmtError();
7267       Builder.ReturnStmtOnAllocFailure = Res.get();
7268     }
7269
7270     // Transform any additional statements we may have already built
7271     assert(S->getAllocate() && S->getDeallocate() &&
7272            "allocation and deallocation calls must already be built");
7273     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7274     if (AllocRes.isInvalid())
7275       return StmtError();
7276     Builder.Allocate = AllocRes.get();
7277
7278     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7279     if (DeallocRes.isInvalid())
7280       return StmtError();
7281     Builder.Deallocate = DeallocRes.get();
7282
7283     assert(S->getResultDecl() && "ResultDecl must already be built");
7284     StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7285     if (ResultDecl.isInvalid())
7286       return StmtError();
7287     Builder.ResultDecl = ResultDecl.get();
7288
7289     if (auto *ReturnStmt = S->getReturnStmt()) {
7290       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7291       if (Res.isInvalid())
7292         return StmtError();
7293       Builder.ReturnStmt = Res.get();
7294     }
7295   }
7296
7297   return getDerived().RebuildCoroutineBodyStmt(Builder);
7298 }
7299
7300 template<typename Derived>
7301 StmtResult
7302 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7303   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7304                                                         /*NotCopyInit*/false);
7305   if (Result.isInvalid())
7306     return StmtError();
7307
7308   // Always rebuild; we don't know if this needs to be injected into a new
7309   // context or if the promise type has changed.
7310   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7311                                           S->isImplicit());
7312 }
7313
7314 template<typename Derived>
7315 ExprResult
7316 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7317   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7318                                                         /*NotCopyInit*/false);
7319   if (Result.isInvalid())
7320     return ExprError();
7321
7322   // Always rebuild; we don't know if this needs to be injected into a new
7323   // context or if the promise type has changed.
7324   return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7325                                          E->isImplicit());
7326 }
7327
7328 template <typename Derived>
7329 ExprResult
7330 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7331   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7332                                                         /*NotCopyInit*/ false);
7333   if (OperandResult.isInvalid())
7334     return ExprError();
7335
7336   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7337           E->getOperatorCoawaitLookup());
7338
7339   if (LookupResult.isInvalid())
7340     return ExprError();
7341
7342   // Always rebuild; we don't know if this needs to be injected into a new
7343   // context or if the promise type has changed.
7344   return getDerived().RebuildDependentCoawaitExpr(
7345       E->getKeywordLoc(), OperandResult.get(),
7346       cast<UnresolvedLookupExpr>(LookupResult.get()));
7347 }
7348
7349 template<typename Derived>
7350 ExprResult
7351 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7352   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7353                                                         /*NotCopyInit*/false);
7354   if (Result.isInvalid())
7355     return ExprError();
7356
7357   // Always rebuild; we don't know if this needs to be injected into a new
7358   // context or if the promise type has changed.
7359   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7360 }
7361
7362 // Objective-C Statements.
7363
7364 template<typename Derived>
7365 StmtResult
7366 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7367   // Transform the body of the @try.
7368   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7369   if (TryBody.isInvalid())
7370     return StmtError();
7371
7372   // Transform the @catch statements (if present).
7373   bool AnyCatchChanged = false;
7374   SmallVector<Stmt*, 8> CatchStmts;
7375   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7376     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7377     if (Catch.isInvalid())
7378       return StmtError();
7379     if (Catch.get() != S->getCatchStmt(I))
7380       AnyCatchChanged = true;
7381     CatchStmts.push_back(Catch.get());
7382   }
7383
7384   // Transform the @finally statement (if present).
7385   StmtResult Finally;
7386   if (S->getFinallyStmt()) {
7387     Finally = getDerived().TransformStmt(S->getFinallyStmt());
7388     if (Finally.isInvalid())
7389       return StmtError();
7390   }
7391
7392   // If nothing changed, just retain this statement.
7393   if (!getDerived().AlwaysRebuild() &&
7394       TryBody.get() == S->getTryBody() &&
7395       !AnyCatchChanged &&
7396       Finally.get() == S->getFinallyStmt())
7397     return S;
7398
7399   // Build a new statement.
7400   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7401                                            CatchStmts, Finally.get());
7402 }
7403
7404 template<typename Derived>
7405 StmtResult
7406 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7407   // Transform the @catch parameter, if there is one.
7408   VarDecl *Var = nullptr;
7409   if (VarDecl *FromVar = S->getCatchParamDecl()) {
7410     TypeSourceInfo *TSInfo = nullptr;
7411     if (FromVar->getTypeSourceInfo()) {
7412       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7413       if (!TSInfo)
7414         return StmtError();
7415     }
7416
7417     QualType T;
7418     if (TSInfo)
7419       T = TSInfo->getType();
7420     else {
7421       T = getDerived().TransformType(FromVar->getType());
7422       if (T.isNull())
7423         return StmtError();
7424     }
7425
7426     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7427     if (!Var)
7428       return StmtError();
7429   }
7430
7431   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7432   if (Body.isInvalid())
7433     return StmtError();
7434
7435   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7436                                              S->getRParenLoc(),
7437                                              Var, Body.get());
7438 }
7439
7440 template<typename Derived>
7441 StmtResult
7442 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7443   // Transform the body.
7444   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7445   if (Body.isInvalid())
7446     return StmtError();
7447
7448   // If nothing changed, just retain this statement.
7449   if (!getDerived().AlwaysRebuild() &&
7450       Body.get() == S->getFinallyBody())
7451     return S;
7452
7453   // Build a new statement.
7454   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7455                                                Body.get());
7456 }
7457
7458 template<typename Derived>
7459 StmtResult
7460 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7461   ExprResult Operand;
7462   if (S->getThrowExpr()) {
7463     Operand = getDerived().TransformExpr(S->getThrowExpr());
7464     if (Operand.isInvalid())
7465       return StmtError();
7466   }
7467
7468   if (!getDerived().AlwaysRebuild() &&
7469       Operand.get() == S->getThrowExpr())
7470     return S;
7471
7472   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7473 }
7474
7475 template<typename Derived>
7476 StmtResult
7477 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7478                                                   ObjCAtSynchronizedStmt *S) {
7479   // Transform the object we are locking.
7480   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7481   if (Object.isInvalid())
7482     return StmtError();
7483   Object =
7484     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7485                                                   Object.get());
7486   if (Object.isInvalid())
7487     return StmtError();
7488
7489   // Transform the body.
7490   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7491   if (Body.isInvalid())
7492     return StmtError();
7493
7494   // If nothing change, just retain the current statement.
7495   if (!getDerived().AlwaysRebuild() &&
7496       Object.get() == S->getSynchExpr() &&
7497       Body.get() == S->getSynchBody())
7498     return S;
7499
7500   // Build a new statement.
7501   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7502                                                     Object.get(), Body.get());
7503 }
7504
7505 template<typename Derived>
7506 StmtResult
7507 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7508                                               ObjCAutoreleasePoolStmt *S) {
7509   // Transform the body.
7510   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7511   if (Body.isInvalid())
7512     return StmtError();
7513
7514   // If nothing changed, just retain this statement.
7515   if (!getDerived().AlwaysRebuild() &&
7516       Body.get() == S->getSubStmt())
7517     return S;
7518
7519   // Build a new statement.
7520   return getDerived().RebuildObjCAutoreleasePoolStmt(
7521                         S->getAtLoc(), Body.get());
7522 }
7523
7524 template<typename Derived>
7525 StmtResult
7526 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7527                                                   ObjCForCollectionStmt *S) {
7528   // Transform the element statement.
7529   StmtResult Element =
7530       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
7531   if (Element.isInvalid())
7532     return StmtError();
7533
7534   // Transform the collection expression.
7535   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7536   if (Collection.isInvalid())
7537     return StmtError();
7538
7539   // Transform the body.
7540   StmtResult Body = getDerived().TransformStmt(S->getBody());
7541   if (Body.isInvalid())
7542     return StmtError();
7543
7544   // If nothing changed, just retain this statement.
7545   if (!getDerived().AlwaysRebuild() &&
7546       Element.get() == S->getElement() &&
7547       Collection.get() == S->getCollection() &&
7548       Body.get() == S->getBody())
7549     return S;
7550
7551   // Build a new statement.
7552   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7553                                                    Element.get(),
7554                                                    Collection.get(),
7555                                                    S->getRParenLoc(),
7556                                                    Body.get());
7557 }
7558
7559 template <typename Derived>
7560 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7561   // Transform the exception declaration, if any.
7562   VarDecl *Var = nullptr;
7563   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7564     TypeSourceInfo *T =
7565         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7566     if (!T)
7567       return StmtError();
7568
7569     Var = getDerived().RebuildExceptionDecl(
7570         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7571         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7572     if (!Var || Var->isInvalidDecl())
7573       return StmtError();
7574   }
7575
7576   // Transform the actual exception handler.
7577   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7578   if (Handler.isInvalid())
7579     return StmtError();
7580
7581   if (!getDerived().AlwaysRebuild() && !Var &&
7582       Handler.get() == S->getHandlerBlock())
7583     return S;
7584
7585   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7586 }
7587
7588 template <typename Derived>
7589 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7590   // Transform the try block itself.
7591   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7592   if (TryBlock.isInvalid())
7593     return StmtError();
7594
7595   // Transform the handlers.
7596   bool HandlerChanged = false;
7597   SmallVector<Stmt *, 8> Handlers;
7598   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7599     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7600     if (Handler.isInvalid())
7601       return StmtError();
7602
7603     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7604     Handlers.push_back(Handler.getAs<Stmt>());
7605   }
7606
7607   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7608       !HandlerChanged)
7609     return S;
7610
7611   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7612                                         Handlers);
7613 }
7614
7615 template<typename Derived>
7616 StmtResult
7617 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7618   StmtResult Init =
7619       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
7620   if (Init.isInvalid())
7621     return StmtError();
7622
7623   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7624   if (Range.isInvalid())
7625     return StmtError();
7626
7627   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7628   if (Begin.isInvalid())
7629     return StmtError();
7630   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7631   if (End.isInvalid())
7632     return StmtError();
7633
7634   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7635   if (Cond.isInvalid())
7636     return StmtError();
7637   if (Cond.get())
7638     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7639   if (Cond.isInvalid())
7640     return StmtError();
7641   if (Cond.get())
7642     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7643
7644   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7645   if (Inc.isInvalid())
7646     return StmtError();
7647   if (Inc.get())
7648     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7649
7650   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7651   if (LoopVar.isInvalid())
7652     return StmtError();
7653
7654   StmtResult NewStmt = S;
7655   if (getDerived().AlwaysRebuild() ||
7656       Init.get() != S->getInit() ||
7657       Range.get() != S->getRangeStmt() ||
7658       Begin.get() != S->getBeginStmt() ||
7659       End.get() != S->getEndStmt() ||
7660       Cond.get() != S->getCond() ||
7661       Inc.get() != S->getInc() ||
7662       LoopVar.get() != S->getLoopVarStmt()) {
7663     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7664                                                   S->getCoawaitLoc(), Init.get(),
7665                                                   S->getColonLoc(), Range.get(),
7666                                                   Begin.get(), End.get(),
7667                                                   Cond.get(),
7668                                                   Inc.get(), LoopVar.get(),
7669                                                   S->getRParenLoc());
7670     if (NewStmt.isInvalid())
7671       return StmtError();
7672   }
7673
7674   StmtResult Body = getDerived().TransformStmt(S->getBody());
7675   if (Body.isInvalid())
7676     return StmtError();
7677
7678   // Body has changed but we didn't rebuild the for-range statement. Rebuild
7679   // it now so we have a new statement to attach the body to.
7680   if (Body.get() != S->getBody() && NewStmt.get() == S) {
7681     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7682                                                   S->getCoawaitLoc(), Init.get(),
7683                                                   S->getColonLoc(), Range.get(),
7684                                                   Begin.get(), End.get(),
7685                                                   Cond.get(),
7686                                                   Inc.get(), LoopVar.get(),
7687                                                   S->getRParenLoc());
7688     if (NewStmt.isInvalid())
7689       return StmtError();
7690   }
7691
7692   if (NewStmt.get() == S)
7693     return S;
7694
7695   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7696 }
7697
7698 template<typename Derived>
7699 StmtResult
7700 TreeTransform<Derived>::TransformMSDependentExistsStmt(
7701                                                     MSDependentExistsStmt *S) {
7702   // Transform the nested-name-specifier, if any.
7703   NestedNameSpecifierLoc QualifierLoc;
7704   if (S->getQualifierLoc()) {
7705     QualifierLoc
7706       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7707     if (!QualifierLoc)
7708       return StmtError();
7709   }
7710
7711   // Transform the declaration name.
7712   DeclarationNameInfo NameInfo = S->getNameInfo();
7713   if (NameInfo.getName()) {
7714     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7715     if (!NameInfo.getName())
7716       return StmtError();
7717   }
7718
7719   // Check whether anything changed.
7720   if (!getDerived().AlwaysRebuild() &&
7721       QualifierLoc == S->getQualifierLoc() &&
7722       NameInfo.getName() == S->getNameInfo().getName())
7723     return S;
7724
7725   // Determine whether this name exists, if we can.
7726   CXXScopeSpec SS;
7727   SS.Adopt(QualifierLoc);
7728   bool Dependent = false;
7729   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7730   case Sema::IER_Exists:
7731     if (S->isIfExists())
7732       break;
7733
7734     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7735
7736   case Sema::IER_DoesNotExist:
7737     if (S->isIfNotExists())
7738       break;
7739
7740     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7741
7742   case Sema::IER_Dependent:
7743     Dependent = true;
7744     break;
7745
7746   case Sema::IER_Error:
7747     return StmtError();
7748   }
7749
7750   // We need to continue with the instantiation, so do so now.
7751   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7752   if (SubStmt.isInvalid())
7753     return StmtError();
7754
7755   // If we have resolved the name, just transform to the substatement.
7756   if (!Dependent)
7757     return SubStmt;
7758
7759   // The name is still dependent, so build a dependent expression again.
7760   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7761                                                    S->isIfExists(),
7762                                                    QualifierLoc,
7763                                                    NameInfo,
7764                                                    SubStmt.get());
7765 }
7766
7767 template<typename Derived>
7768 ExprResult
7769 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7770   NestedNameSpecifierLoc QualifierLoc;
7771   if (E->getQualifierLoc()) {
7772     QualifierLoc
7773     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7774     if (!QualifierLoc)
7775       return ExprError();
7776   }
7777
7778   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7779     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7780   if (!PD)
7781     return ExprError();
7782
7783   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7784   if (Base.isInvalid())
7785     return ExprError();
7786
7787   return new (SemaRef.getASTContext())
7788       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7789                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7790                         QualifierLoc, E->getMemberLoc());
7791 }
7792
7793 template <typename Derived>
7794 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7795     MSPropertySubscriptExpr *E) {
7796   auto BaseRes = getDerived().TransformExpr(E->getBase());
7797   if (BaseRes.isInvalid())
7798     return ExprError();
7799   auto IdxRes = getDerived().TransformExpr(E->getIdx());
7800   if (IdxRes.isInvalid())
7801     return ExprError();
7802
7803   if (!getDerived().AlwaysRebuild() &&
7804       BaseRes.get() == E->getBase() &&
7805       IdxRes.get() == E->getIdx())
7806     return E;
7807
7808   return getDerived().RebuildArraySubscriptExpr(
7809       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7810 }
7811
7812 template <typename Derived>
7813 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7814   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7815   if (TryBlock.isInvalid())
7816     return StmtError();
7817
7818   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7819   if (Handler.isInvalid())
7820     return StmtError();
7821
7822   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7823       Handler.get() == S->getHandler())
7824     return S;
7825
7826   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7827                                         TryBlock.get(), Handler.get());
7828 }
7829
7830 template <typename Derived>
7831 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7832   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7833   if (Block.isInvalid())
7834     return StmtError();
7835
7836   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7837 }
7838
7839 template <typename Derived>
7840 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7841   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7842   if (FilterExpr.isInvalid())
7843     return StmtError();
7844
7845   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7846   if (Block.isInvalid())
7847     return StmtError();
7848
7849   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7850                                            Block.get());
7851 }
7852
7853 template <typename Derived>
7854 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7855   if (isa<SEHFinallyStmt>(Handler))
7856     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7857   else
7858     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7859 }
7860
7861 template<typename Derived>
7862 StmtResult
7863 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7864   return S;
7865 }
7866
7867 //===----------------------------------------------------------------------===//
7868 // OpenMP directive transformation
7869 //===----------------------------------------------------------------------===//
7870 template <typename Derived>
7871 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7872     OMPExecutableDirective *D) {
7873
7874   // Transform the clauses
7875   llvm::SmallVector<OMPClause *, 16> TClauses;
7876   ArrayRef<OMPClause *> Clauses = D->clauses();
7877   TClauses.reserve(Clauses.size());
7878   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
7879        I != E; ++I) {
7880     if (*I) {
7881       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
7882       OMPClause *Clause = getDerived().TransformOMPClause(*I);
7883       getDerived().getSema().EndOpenMPClause();
7884       if (Clause)
7885         TClauses.push_back(Clause);
7886     } else {
7887       TClauses.push_back(nullptr);
7888     }
7889   }
7890   StmtResult AssociatedStmt;
7891   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
7892     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
7893                                                   /*CurScope=*/nullptr);
7894     StmtResult Body;
7895     {
7896       Sema::CompoundScopeRAII CompoundScope(getSema());
7897       Stmt *CS = D->getInnermostCapturedStmt()->getCapturedStmt();
7898       Body = getDerived().TransformStmt(CS);
7899     }
7900     AssociatedStmt =
7901         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
7902     if (AssociatedStmt.isInvalid()) {
7903       return StmtError();
7904     }
7905   }
7906   if (TClauses.size() != Clauses.size()) {
7907     return StmtError();
7908   }
7909
7910   // Transform directive name for 'omp critical' directive.
7911   DeclarationNameInfo DirName;
7912   if (D->getDirectiveKind() == OMPD_critical) {
7913     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
7914     DirName = getDerived().TransformDeclarationNameInfo(DirName);
7915   }
7916   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
7917   if (D->getDirectiveKind() == OMPD_cancellation_point) {
7918     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
7919   } else if (D->getDirectiveKind() == OMPD_cancel) {
7920     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
7921   }
7922
7923   return getDerived().RebuildOMPExecutableDirective(
7924       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
7925       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
7926 }
7927
7928 template <typename Derived>
7929 StmtResult
7930 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
7931   DeclarationNameInfo DirName;
7932   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
7933                                              D->getBeginLoc());
7934   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7935   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7936   return Res;
7937 }
7938
7939 template <typename Derived>
7940 StmtResult
7941 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
7942   DeclarationNameInfo DirName;
7943   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
7944                                              D->getBeginLoc());
7945   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7946   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7947   return Res;
7948 }
7949
7950 template <typename Derived>
7951 StmtResult
7952 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
7953   DeclarationNameInfo DirName;
7954   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
7955                                              D->getBeginLoc());
7956   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7957   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7958   return Res;
7959 }
7960
7961 template <typename Derived>
7962 StmtResult
7963 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
7964   DeclarationNameInfo DirName;
7965   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
7966                                              D->getBeginLoc());
7967   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7968   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7969   return Res;
7970 }
7971
7972 template <typename Derived>
7973 StmtResult
7974 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
7975   DeclarationNameInfo DirName;
7976   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
7977                                              D->getBeginLoc());
7978   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7979   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7980   return Res;
7981 }
7982
7983 template <typename Derived>
7984 StmtResult
7985 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
7986   DeclarationNameInfo DirName;
7987   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
7988                                              D->getBeginLoc());
7989   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7990   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7991   return Res;
7992 }
7993
7994 template <typename Derived>
7995 StmtResult
7996 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
7997   DeclarationNameInfo DirName;
7998   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
7999                                              D->getBeginLoc());
8000   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8001   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8002   return Res;
8003 }
8004
8005 template <typename Derived>
8006 StmtResult
8007 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8008   DeclarationNameInfo DirName;
8009   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8010                                              D->getBeginLoc());
8011   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8012   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8013   return Res;
8014 }
8015
8016 template <typename Derived>
8017 StmtResult
8018 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8019   getDerived().getSema().StartOpenMPDSABlock(
8020       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8021   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8022   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8023   return Res;
8024 }
8025
8026 template <typename Derived>
8027 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8028     OMPParallelForDirective *D) {
8029   DeclarationNameInfo DirName;
8030   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8031                                              nullptr, D->getBeginLoc());
8032   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8033   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8034   return Res;
8035 }
8036
8037 template <typename Derived>
8038 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8039     OMPParallelForSimdDirective *D) {
8040   DeclarationNameInfo DirName;
8041   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8042                                              nullptr, D->getBeginLoc());
8043   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8044   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8045   return Res;
8046 }
8047
8048 template <typename Derived>
8049 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8050     OMPParallelSectionsDirective *D) {
8051   DeclarationNameInfo DirName;
8052   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8053                                              nullptr, D->getBeginLoc());
8054   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8055   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8056   return Res;
8057 }
8058
8059 template <typename Derived>
8060 StmtResult
8061 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8062   DeclarationNameInfo DirName;
8063   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8064                                              D->getBeginLoc());
8065   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8066   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8067   return Res;
8068 }
8069
8070 template <typename Derived>
8071 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8072     OMPTaskyieldDirective *D) {
8073   DeclarationNameInfo DirName;
8074   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8075                                              D->getBeginLoc());
8076   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8077   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8078   return Res;
8079 }
8080
8081 template <typename Derived>
8082 StmtResult
8083 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8084   DeclarationNameInfo DirName;
8085   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8086                                              D->getBeginLoc());
8087   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8088   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8089   return Res;
8090 }
8091
8092 template <typename Derived>
8093 StmtResult
8094 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8095   DeclarationNameInfo DirName;
8096   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8097                                              D->getBeginLoc());
8098   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8099   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8100   return Res;
8101 }
8102
8103 template <typename Derived>
8104 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8105     OMPTaskgroupDirective *D) {
8106   DeclarationNameInfo DirName;
8107   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8108                                              D->getBeginLoc());
8109   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8110   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8111   return Res;
8112 }
8113
8114 template <typename Derived>
8115 StmtResult
8116 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8117   DeclarationNameInfo DirName;
8118   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8119                                              D->getBeginLoc());
8120   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8121   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8122   return Res;
8123 }
8124
8125 template <typename Derived>
8126 StmtResult
8127 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8128   DeclarationNameInfo DirName;
8129   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8130                                              D->getBeginLoc());
8131   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8132   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8133   return Res;
8134 }
8135
8136 template <typename Derived>
8137 StmtResult
8138 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8139   DeclarationNameInfo DirName;
8140   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8141                                              D->getBeginLoc());
8142   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8143   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8144   return Res;
8145 }
8146
8147 template <typename Derived>
8148 StmtResult
8149 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8150   DeclarationNameInfo DirName;
8151   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8152                                              D->getBeginLoc());
8153   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8154   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8155   return Res;
8156 }
8157
8158 template <typename Derived>
8159 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8160     OMPTargetDataDirective *D) {
8161   DeclarationNameInfo DirName;
8162   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8163                                              D->getBeginLoc());
8164   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8165   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8166   return Res;
8167 }
8168
8169 template <typename Derived>
8170 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8171     OMPTargetEnterDataDirective *D) {
8172   DeclarationNameInfo DirName;
8173   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8174                                              nullptr, D->getBeginLoc());
8175   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8176   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8177   return Res;
8178 }
8179
8180 template <typename Derived>
8181 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8182     OMPTargetExitDataDirective *D) {
8183   DeclarationNameInfo DirName;
8184   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8185                                              nullptr, D->getBeginLoc());
8186   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8187   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8188   return Res;
8189 }
8190
8191 template <typename Derived>
8192 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8193     OMPTargetParallelDirective *D) {
8194   DeclarationNameInfo DirName;
8195   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8196                                              nullptr, D->getBeginLoc());
8197   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8198   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8199   return Res;
8200 }
8201
8202 template <typename Derived>
8203 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8204     OMPTargetParallelForDirective *D) {
8205   DeclarationNameInfo DirName;
8206   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8207                                              nullptr, D->getBeginLoc());
8208   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8209   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8210   return Res;
8211 }
8212
8213 template <typename Derived>
8214 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8215     OMPTargetUpdateDirective *D) {
8216   DeclarationNameInfo DirName;
8217   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8218                                              nullptr, D->getBeginLoc());
8219   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8220   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8221   return Res;
8222 }
8223
8224 template <typename Derived>
8225 StmtResult
8226 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8227   DeclarationNameInfo DirName;
8228   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8229                                              D->getBeginLoc());
8230   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8231   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8232   return Res;
8233 }
8234
8235 template <typename Derived>
8236 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8237     OMPCancellationPointDirective *D) {
8238   DeclarationNameInfo DirName;
8239   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8240                                              nullptr, D->getBeginLoc());
8241   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8242   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8243   return Res;
8244 }
8245
8246 template <typename Derived>
8247 StmtResult
8248 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8249   DeclarationNameInfo DirName;
8250   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8251                                              D->getBeginLoc());
8252   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8253   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8254   return Res;
8255 }
8256
8257 template <typename Derived>
8258 StmtResult
8259 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8260   DeclarationNameInfo DirName;
8261   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8262                                              D->getBeginLoc());
8263   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8264   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8265   return Res;
8266 }
8267
8268 template <typename Derived>
8269 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8270     OMPTaskLoopSimdDirective *D) {
8271   DeclarationNameInfo DirName;
8272   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8273                                              nullptr, D->getBeginLoc());
8274   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8275   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8276   return Res;
8277 }
8278
8279 template <typename Derived>
8280 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
8281     OMPMasterTaskLoopDirective *D) {
8282   DeclarationNameInfo DirName;
8283   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
8284                                              nullptr, D->getBeginLoc());
8285   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8286   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8287   return Res;
8288 }
8289
8290 template <typename Derived>
8291 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
8292     OMPMasterTaskLoopSimdDirective *D) {
8293   DeclarationNameInfo DirName;
8294   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
8295                                              nullptr, D->getBeginLoc());
8296   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8297   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8298   return Res;
8299 }
8300
8301 template <typename Derived>
8302 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
8303     OMPParallelMasterTaskLoopDirective *D) {
8304   DeclarationNameInfo DirName;
8305   getDerived().getSema().StartOpenMPDSABlock(
8306       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
8307   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8308   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8309   return Res;
8310 }
8311
8312 template <typename Derived>
8313 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8314     OMPDistributeDirective *D) {
8315   DeclarationNameInfo DirName;
8316   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8317                                              D->getBeginLoc());
8318   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8319   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8320   return Res;
8321 }
8322
8323 template <typename Derived>
8324 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8325     OMPDistributeParallelForDirective *D) {
8326   DeclarationNameInfo DirName;
8327   getDerived().getSema().StartOpenMPDSABlock(
8328       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8329   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8330   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8331   return Res;
8332 }
8333
8334 template <typename Derived>
8335 StmtResult
8336 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8337     OMPDistributeParallelForSimdDirective *D) {
8338   DeclarationNameInfo DirName;
8339   getDerived().getSema().StartOpenMPDSABlock(
8340       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8341   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8342   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8343   return Res;
8344 }
8345
8346 template <typename Derived>
8347 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8348     OMPDistributeSimdDirective *D) {
8349   DeclarationNameInfo DirName;
8350   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8351                                              nullptr, D->getBeginLoc());
8352   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8353   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8354   return Res;
8355 }
8356
8357 template <typename Derived>
8358 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
8359     OMPTargetParallelForSimdDirective *D) {
8360   DeclarationNameInfo DirName;
8361   getDerived().getSema().StartOpenMPDSABlock(
8362       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8363   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8364   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8365   return Res;
8366 }
8367
8368 template <typename Derived>
8369 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8370     OMPTargetSimdDirective *D) {
8371   DeclarationNameInfo DirName;
8372   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8373                                              D->getBeginLoc());
8374   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8375   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8376   return Res;
8377 }
8378
8379 template <typename Derived>
8380 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8381     OMPTeamsDistributeDirective *D) {
8382   DeclarationNameInfo DirName;
8383   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8384                                              nullptr, D->getBeginLoc());
8385   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8386   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8387   return Res;
8388 }
8389
8390 template <typename Derived>
8391 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8392     OMPTeamsDistributeSimdDirective *D) {
8393   DeclarationNameInfo DirName;
8394   getDerived().getSema().StartOpenMPDSABlock(
8395       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8396   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8397   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8398   return Res;
8399 }
8400
8401 template <typename Derived>
8402 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8403     OMPTeamsDistributeParallelForSimdDirective *D) {
8404   DeclarationNameInfo DirName;
8405   getDerived().getSema().StartOpenMPDSABlock(
8406       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
8407       D->getBeginLoc());
8408   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8409   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8410   return Res;
8411 }
8412
8413 template <typename Derived>
8414 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8415     OMPTeamsDistributeParallelForDirective *D) {
8416   DeclarationNameInfo DirName;
8417   getDerived().getSema().StartOpenMPDSABlock(
8418       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8419   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8420   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8421   return Res;
8422 }
8423
8424 template <typename Derived>
8425 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8426     OMPTargetTeamsDirective *D) {
8427   DeclarationNameInfo DirName;
8428   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8429                                              nullptr, D->getBeginLoc());
8430   auto Res = getDerived().TransformOMPExecutableDirective(D);
8431   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8432   return Res;
8433 }
8434
8435 template <typename Derived>
8436 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8437     OMPTargetTeamsDistributeDirective *D) {
8438   DeclarationNameInfo DirName;
8439   getDerived().getSema().StartOpenMPDSABlock(
8440       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
8441   auto Res = getDerived().TransformOMPExecutableDirective(D);
8442   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8443   return Res;
8444 }
8445
8446 template <typename Derived>
8447 StmtResult
8448 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8449     OMPTargetTeamsDistributeParallelForDirective *D) {
8450   DeclarationNameInfo DirName;
8451   getDerived().getSema().StartOpenMPDSABlock(
8452       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8453       D->getBeginLoc());
8454   auto Res = getDerived().TransformOMPExecutableDirective(D);
8455   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8456   return Res;
8457 }
8458
8459 template <typename Derived>
8460 StmtResult TreeTransform<Derived>::
8461     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8462         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8463   DeclarationNameInfo DirName;
8464   getDerived().getSema().StartOpenMPDSABlock(
8465       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8466       D->getBeginLoc());
8467   auto Res = getDerived().TransformOMPExecutableDirective(D);
8468   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8469   return Res;
8470 }
8471
8472 template <typename Derived>
8473 StmtResult
8474 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8475     OMPTargetTeamsDistributeSimdDirective *D) {
8476   DeclarationNameInfo DirName;
8477   getDerived().getSema().StartOpenMPDSABlock(
8478       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8479   auto Res = getDerived().TransformOMPExecutableDirective(D);
8480   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8481   return Res;
8482 }
8483
8484
8485 //===----------------------------------------------------------------------===//
8486 // OpenMP clause transformation
8487 //===----------------------------------------------------------------------===//
8488 template <typename Derived>
8489 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8490   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8491   if (Cond.isInvalid())
8492     return nullptr;
8493   return getDerived().RebuildOMPIfClause(
8494       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
8495       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
8496 }
8497
8498 template <typename Derived>
8499 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8500   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8501   if (Cond.isInvalid())
8502     return nullptr;
8503   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
8504                                             C->getLParenLoc(), C->getEndLoc());
8505 }
8506
8507 template <typename Derived>
8508 OMPClause *
8509 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8510   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8511   if (NumThreads.isInvalid())
8512     return nullptr;
8513   return getDerived().RebuildOMPNumThreadsClause(
8514       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8515 }
8516
8517 template <typename Derived>
8518 OMPClause *
8519 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8520   ExprResult E = getDerived().TransformExpr(C->getSafelen());
8521   if (E.isInvalid())
8522     return nullptr;
8523   return getDerived().RebuildOMPSafelenClause(
8524       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8525 }
8526
8527 template <typename Derived>
8528 OMPClause *
8529 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
8530   ExprResult E = getDerived().TransformExpr(C->getAllocator());
8531   if (E.isInvalid())
8532     return nullptr;
8533   return getDerived().RebuildOMPAllocatorClause(
8534       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8535 }
8536
8537 template <typename Derived>
8538 OMPClause *
8539 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8540   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8541   if (E.isInvalid())
8542     return nullptr;
8543   return getDerived().RebuildOMPSimdlenClause(
8544       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8545 }
8546
8547 template <typename Derived>
8548 OMPClause *
8549 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8550   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8551   if (E.isInvalid())
8552     return nullptr;
8553   return getDerived().RebuildOMPCollapseClause(
8554       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8555 }
8556
8557 template <typename Derived>
8558 OMPClause *
8559 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8560   return getDerived().RebuildOMPDefaultClause(
8561       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
8562       C->getLParenLoc(), C->getEndLoc());
8563 }
8564
8565 template <typename Derived>
8566 OMPClause *
8567 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8568   return getDerived().RebuildOMPProcBindClause(
8569       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
8570       C->getLParenLoc(), C->getEndLoc());
8571 }
8572
8573 template <typename Derived>
8574 OMPClause *
8575 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8576   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8577   if (E.isInvalid())
8578     return nullptr;
8579   return getDerived().RebuildOMPScheduleClause(
8580       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8581       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
8582       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8583       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
8584 }
8585
8586 template <typename Derived>
8587 OMPClause *
8588 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8589   ExprResult E;
8590   if (auto *Num = C->getNumForLoops()) {
8591     E = getDerived().TransformExpr(Num);
8592     if (E.isInvalid())
8593       return nullptr;
8594   }
8595   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
8596                                               C->getLParenLoc(), E.get());
8597 }
8598
8599 template <typename Derived>
8600 OMPClause *
8601 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8602   // No need to rebuild this clause, no template-dependent parameters.
8603   return C;
8604 }
8605
8606 template <typename Derived>
8607 OMPClause *
8608 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8609   // No need to rebuild this clause, no template-dependent parameters.
8610   return C;
8611 }
8612
8613 template <typename Derived>
8614 OMPClause *
8615 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8616   // No need to rebuild this clause, no template-dependent parameters.
8617   return C;
8618 }
8619
8620 template <typename Derived>
8621 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8622   // No need to rebuild this clause, no template-dependent parameters.
8623   return C;
8624 }
8625
8626 template <typename Derived>
8627 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8628   // No need to rebuild this clause, no template-dependent parameters.
8629   return C;
8630 }
8631
8632 template <typename Derived>
8633 OMPClause *
8634 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8635   // No need to rebuild this clause, no template-dependent parameters.
8636   return C;
8637 }
8638
8639 template <typename Derived>
8640 OMPClause *
8641 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *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>::TransformOMPSeqCstClause(OMPSeqCstClause *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>::TransformOMPThreadsClause(OMPThreadsClause *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>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8662   // No need to rebuild this clause, no template-dependent parameters.
8663   return C;
8664 }
8665
8666 template <typename Derived>
8667 OMPClause *
8668 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8669   // No need to rebuild this clause, no template-dependent parameters.
8670   return C;
8671 }
8672
8673 template <typename Derived>
8674 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
8675     OMPUnifiedAddressClause *C) {
8676   llvm_unreachable("unified_address clause cannot appear in dependent context");
8677 }
8678
8679 template <typename Derived>
8680 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
8681     OMPUnifiedSharedMemoryClause *C) {
8682   llvm_unreachable(
8683       "unified_shared_memory clause cannot appear in dependent context");
8684 }
8685
8686 template <typename Derived>
8687 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
8688     OMPReverseOffloadClause *C) {
8689   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
8690 }
8691
8692 template <typename Derived>
8693 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
8694     OMPDynamicAllocatorsClause *C) {
8695   llvm_unreachable(
8696       "dynamic_allocators clause cannot appear in dependent context");
8697 }
8698
8699 template <typename Derived>
8700 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
8701     OMPAtomicDefaultMemOrderClause *C) {
8702   llvm_unreachable(
8703       "atomic_default_mem_order clause cannot appear in dependent context");
8704 }
8705
8706 template <typename Derived>
8707 OMPClause *
8708 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8709   llvm::SmallVector<Expr *, 16> Vars;
8710   Vars.reserve(C->varlist_size());
8711   for (auto *VE : C->varlists()) {
8712     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8713     if (EVar.isInvalid())
8714       return nullptr;
8715     Vars.push_back(EVar.get());
8716   }
8717   return getDerived().RebuildOMPPrivateClause(
8718       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8719 }
8720
8721 template <typename Derived>
8722 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8723     OMPFirstprivateClause *C) {
8724   llvm::SmallVector<Expr *, 16> Vars;
8725   Vars.reserve(C->varlist_size());
8726   for (auto *VE : C->varlists()) {
8727     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8728     if (EVar.isInvalid())
8729       return nullptr;
8730     Vars.push_back(EVar.get());
8731   }
8732   return getDerived().RebuildOMPFirstprivateClause(
8733       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8734 }
8735
8736 template <typename Derived>
8737 OMPClause *
8738 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8739   llvm::SmallVector<Expr *, 16> Vars;
8740   Vars.reserve(C->varlist_size());
8741   for (auto *VE : C->varlists()) {
8742     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8743     if (EVar.isInvalid())
8744       return nullptr;
8745     Vars.push_back(EVar.get());
8746   }
8747   return getDerived().RebuildOMPLastprivateClause(
8748       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8749 }
8750
8751 template <typename Derived>
8752 OMPClause *
8753 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8754   llvm::SmallVector<Expr *, 16> Vars;
8755   Vars.reserve(C->varlist_size());
8756   for (auto *VE : C->varlists()) {
8757     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8758     if (EVar.isInvalid())
8759       return nullptr;
8760     Vars.push_back(EVar.get());
8761   }
8762   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
8763                                              C->getLParenLoc(), C->getEndLoc());
8764 }
8765
8766 template <typename Derived>
8767 OMPClause *
8768 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8769   llvm::SmallVector<Expr *, 16> Vars;
8770   Vars.reserve(C->varlist_size());
8771   for (auto *VE : C->varlists()) {
8772     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8773     if (EVar.isInvalid())
8774       return nullptr;
8775     Vars.push_back(EVar.get());
8776   }
8777   CXXScopeSpec ReductionIdScopeSpec;
8778   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8779
8780   DeclarationNameInfo NameInfo = C->getNameInfo();
8781   if (NameInfo.getName()) {
8782     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8783     if (!NameInfo.getName())
8784       return nullptr;
8785   }
8786   // Build a list of all UDR decls with the same names ranged by the Scopes.
8787   // The Scope boundary is a duplication of the previous decl.
8788   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8789   for (auto *E : C->reduction_ops()) {
8790     // Transform all the decls.
8791     if (E) {
8792       auto *ULE = cast<UnresolvedLookupExpr>(E);
8793       UnresolvedSet<8> Decls;
8794       for (auto *D : ULE->decls()) {
8795         NamedDecl *InstD =
8796             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8797         Decls.addDecl(InstD, InstD->getAccess());
8798       }
8799       UnresolvedReductions.push_back(
8800        UnresolvedLookupExpr::Create(
8801           SemaRef.Context, /*NamingClass=*/nullptr,
8802           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8803           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8804           Decls.begin(), Decls.end()));
8805     } else
8806       UnresolvedReductions.push_back(nullptr);
8807   }
8808   return getDerived().RebuildOMPReductionClause(
8809       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8810       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8811 }
8812
8813 template <typename Derived>
8814 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
8815     OMPTaskReductionClause *C) {
8816   llvm::SmallVector<Expr *, 16> Vars;
8817   Vars.reserve(C->varlist_size());
8818   for (auto *VE : C->varlists()) {
8819     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8820     if (EVar.isInvalid())
8821       return nullptr;
8822     Vars.push_back(EVar.get());
8823   }
8824   CXXScopeSpec ReductionIdScopeSpec;
8825   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8826
8827   DeclarationNameInfo NameInfo = C->getNameInfo();
8828   if (NameInfo.getName()) {
8829     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8830     if (!NameInfo.getName())
8831       return nullptr;
8832   }
8833   // Build a list of all UDR decls with the same names ranged by the Scopes.
8834   // The Scope boundary is a duplication of the previous decl.
8835   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8836   for (auto *E : C->reduction_ops()) {
8837     // Transform all the decls.
8838     if (E) {
8839       auto *ULE = cast<UnresolvedLookupExpr>(E);
8840       UnresolvedSet<8> Decls;
8841       for (auto *D : ULE->decls()) {
8842         NamedDecl *InstD =
8843             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8844         Decls.addDecl(InstD, InstD->getAccess());
8845       }
8846       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8847           SemaRef.Context, /*NamingClass=*/nullptr,
8848           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8849           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8850     } else
8851       UnresolvedReductions.push_back(nullptr);
8852   }
8853   return getDerived().RebuildOMPTaskReductionClause(
8854       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8855       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8856 }
8857
8858 template <typename Derived>
8859 OMPClause *
8860 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
8861   llvm::SmallVector<Expr *, 16> Vars;
8862   Vars.reserve(C->varlist_size());
8863   for (auto *VE : C->varlists()) {
8864     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8865     if (EVar.isInvalid())
8866       return nullptr;
8867     Vars.push_back(EVar.get());
8868   }
8869   CXXScopeSpec ReductionIdScopeSpec;
8870   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8871
8872   DeclarationNameInfo NameInfo = C->getNameInfo();
8873   if (NameInfo.getName()) {
8874     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8875     if (!NameInfo.getName())
8876       return nullptr;
8877   }
8878   // Build a list of all UDR decls with the same names ranged by the Scopes.
8879   // The Scope boundary is a duplication of the previous decl.
8880   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8881   for (auto *E : C->reduction_ops()) {
8882     // Transform all the decls.
8883     if (E) {
8884       auto *ULE = cast<UnresolvedLookupExpr>(E);
8885       UnresolvedSet<8> Decls;
8886       for (auto *D : ULE->decls()) {
8887         NamedDecl *InstD =
8888             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8889         Decls.addDecl(InstD, InstD->getAccess());
8890       }
8891       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8892           SemaRef.Context, /*NamingClass=*/nullptr,
8893           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8894           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8895     } else
8896       UnresolvedReductions.push_back(nullptr);
8897   }
8898   return getDerived().RebuildOMPInReductionClause(
8899       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8900       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8901 }
8902
8903 template <typename Derived>
8904 OMPClause *
8905 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8906   llvm::SmallVector<Expr *, 16> Vars;
8907   Vars.reserve(C->varlist_size());
8908   for (auto *VE : C->varlists()) {
8909     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8910     if (EVar.isInvalid())
8911       return nullptr;
8912     Vars.push_back(EVar.get());
8913   }
8914   ExprResult Step = getDerived().TransformExpr(C->getStep());
8915   if (Step.isInvalid())
8916     return nullptr;
8917   return getDerived().RebuildOMPLinearClause(
8918       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
8919       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
8920 }
8921
8922 template <typename Derived>
8923 OMPClause *
8924 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8925   llvm::SmallVector<Expr *, 16> Vars;
8926   Vars.reserve(C->varlist_size());
8927   for (auto *VE : C->varlists()) {
8928     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8929     if (EVar.isInvalid())
8930       return nullptr;
8931     Vars.push_back(EVar.get());
8932   }
8933   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8934   if (Alignment.isInvalid())
8935     return nullptr;
8936   return getDerived().RebuildOMPAlignedClause(
8937       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
8938       C->getColonLoc(), C->getEndLoc());
8939 }
8940
8941 template <typename Derived>
8942 OMPClause *
8943 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8944   llvm::SmallVector<Expr *, 16> Vars;
8945   Vars.reserve(C->varlist_size());
8946   for (auto *VE : C->varlists()) {
8947     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8948     if (EVar.isInvalid())
8949       return nullptr;
8950     Vars.push_back(EVar.get());
8951   }
8952   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
8953                                              C->getLParenLoc(), C->getEndLoc());
8954 }
8955
8956 template <typename Derived>
8957 OMPClause *
8958 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
8959   llvm::SmallVector<Expr *, 16> Vars;
8960   Vars.reserve(C->varlist_size());
8961   for (auto *VE : C->varlists()) {
8962     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8963     if (EVar.isInvalid())
8964       return nullptr;
8965     Vars.push_back(EVar.get());
8966   }
8967   return getDerived().RebuildOMPCopyprivateClause(
8968       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8969 }
8970
8971 template <typename Derived>
8972 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
8973   llvm::SmallVector<Expr *, 16> Vars;
8974   Vars.reserve(C->varlist_size());
8975   for (auto *VE : C->varlists()) {
8976     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8977     if (EVar.isInvalid())
8978       return nullptr;
8979     Vars.push_back(EVar.get());
8980   }
8981   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
8982                                             C->getLParenLoc(), C->getEndLoc());
8983 }
8984
8985 template <typename Derived>
8986 OMPClause *
8987 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
8988   llvm::SmallVector<Expr *, 16> Vars;
8989   Vars.reserve(C->varlist_size());
8990   for (auto *VE : C->varlists()) {
8991     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8992     if (EVar.isInvalid())
8993       return nullptr;
8994     Vars.push_back(EVar.get());
8995   }
8996   return getDerived().RebuildOMPDependClause(
8997       C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
8998       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8999 }
9000
9001 template <typename Derived>
9002 OMPClause *
9003 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
9004   ExprResult E = getDerived().TransformExpr(C->getDevice());
9005   if (E.isInvalid())
9006     return nullptr;
9007   return getDerived().RebuildOMPDeviceClause(E.get(), C->getBeginLoc(),
9008                                              C->getLParenLoc(), C->getEndLoc());
9009 }
9010
9011 template <typename Derived, class T>
9012 bool transformOMPMappableExprListClause(
9013     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
9014     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
9015     DeclarationNameInfo &MapperIdInfo,
9016     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
9017   // Transform expressions in the list.
9018   Vars.reserve(C->varlist_size());
9019   for (auto *VE : C->varlists()) {
9020     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
9021     if (EVar.isInvalid())
9022       return true;
9023     Vars.push_back(EVar.get());
9024   }
9025   // Transform mapper scope specifier and identifier.
9026   NestedNameSpecifierLoc QualifierLoc;
9027   if (C->getMapperQualifierLoc()) {
9028     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
9029         C->getMapperQualifierLoc());
9030     if (!QualifierLoc)
9031       return true;
9032   }
9033   MapperIdScopeSpec.Adopt(QualifierLoc);
9034   MapperIdInfo = C->getMapperIdInfo();
9035   if (MapperIdInfo.getName()) {
9036     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
9037     if (!MapperIdInfo.getName())
9038       return true;
9039   }
9040   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
9041   // the previous user-defined mapper lookup in dependent environment.
9042   for (auto *E : C->mapperlists()) {
9043     // Transform all the decls.
9044     if (E) {
9045       auto *ULE = cast<UnresolvedLookupExpr>(E);
9046       UnresolvedSet<8> Decls;
9047       for (auto *D : ULE->decls()) {
9048         NamedDecl *InstD =
9049             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
9050         Decls.addDecl(InstD, InstD->getAccess());
9051       }
9052       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
9053           TT.getSema().Context, /*NamingClass=*/nullptr,
9054           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
9055           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
9056           Decls.end()));
9057     } else {
9058       UnresolvedMappers.push_back(nullptr);
9059     }
9060   }
9061   return false;
9062 }
9063
9064 template <typename Derived>
9065 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
9066   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9067   llvm::SmallVector<Expr *, 16> Vars;
9068   CXXScopeSpec MapperIdScopeSpec;
9069   DeclarationNameInfo MapperIdInfo;
9070   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9071   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
9072           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9073     return nullptr;
9074   return getDerived().RebuildOMPMapClause(
9075       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
9076       MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
9077       C->getColonLoc(), Vars, Locs, UnresolvedMappers);
9078 }
9079
9080 template <typename Derived>
9081 OMPClause *
9082 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
9083   Expr *Allocator = C->getAllocator();
9084   if (Allocator) {
9085     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
9086     if (AllocatorRes.isInvalid())
9087       return nullptr;
9088     Allocator = AllocatorRes.get();
9089   }
9090   llvm::SmallVector<Expr *, 16> Vars;
9091   Vars.reserve(C->varlist_size());
9092   for (auto *VE : C->varlists()) {
9093     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9094     if (EVar.isInvalid())
9095       return nullptr;
9096     Vars.push_back(EVar.get());
9097   }
9098   return getDerived().RebuildOMPAllocateClause(
9099       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9100       C->getEndLoc());
9101 }
9102
9103 template <typename Derived>
9104 OMPClause *
9105 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
9106   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
9107   if (E.isInvalid())
9108     return nullptr;
9109   return getDerived().RebuildOMPNumTeamsClause(
9110       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9111 }
9112
9113 template <typename Derived>
9114 OMPClause *
9115 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
9116   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
9117   if (E.isInvalid())
9118     return nullptr;
9119   return getDerived().RebuildOMPThreadLimitClause(
9120       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9121 }
9122
9123 template <typename Derived>
9124 OMPClause *
9125 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
9126   ExprResult E = getDerived().TransformExpr(C->getPriority());
9127   if (E.isInvalid())
9128     return nullptr;
9129   return getDerived().RebuildOMPPriorityClause(
9130       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9131 }
9132
9133 template <typename Derived>
9134 OMPClause *
9135 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
9136   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
9137   if (E.isInvalid())
9138     return nullptr;
9139   return getDerived().RebuildOMPGrainsizeClause(
9140       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9141 }
9142
9143 template <typename Derived>
9144 OMPClause *
9145 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
9146   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
9147   if (E.isInvalid())
9148     return nullptr;
9149   return getDerived().RebuildOMPNumTasksClause(
9150       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9151 }
9152
9153 template <typename Derived>
9154 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
9155   ExprResult E = getDerived().TransformExpr(C->getHint());
9156   if (E.isInvalid())
9157     return nullptr;
9158   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
9159                                            C->getLParenLoc(), C->getEndLoc());
9160 }
9161
9162 template <typename Derived>
9163 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
9164     OMPDistScheduleClause *C) {
9165   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9166   if (E.isInvalid())
9167     return nullptr;
9168   return getDerived().RebuildOMPDistScheduleClause(
9169       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9170       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9171 }
9172
9173 template <typename Derived>
9174 OMPClause *
9175 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
9176   return C;
9177 }
9178
9179 template <typename Derived>
9180 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
9181   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9182   llvm::SmallVector<Expr *, 16> Vars;
9183   CXXScopeSpec MapperIdScopeSpec;
9184   DeclarationNameInfo MapperIdInfo;
9185   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9186   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
9187           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9188     return nullptr;
9189   return getDerived().RebuildOMPToClause(Vars, MapperIdScopeSpec, MapperIdInfo,
9190                                          Locs, UnresolvedMappers);
9191 }
9192
9193 template <typename Derived>
9194 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
9195   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9196   llvm::SmallVector<Expr *, 16> Vars;
9197   CXXScopeSpec MapperIdScopeSpec;
9198   DeclarationNameInfo MapperIdInfo;
9199   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
9200   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
9201           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
9202     return nullptr;
9203   return getDerived().RebuildOMPFromClause(
9204       Vars, MapperIdScopeSpec, MapperIdInfo, Locs, UnresolvedMappers);
9205 }
9206
9207 template <typename Derived>
9208 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
9209     OMPUseDevicePtrClause *C) {
9210   llvm::SmallVector<Expr *, 16> Vars;
9211   Vars.reserve(C->varlist_size());
9212   for (auto *VE : C->varlists()) {
9213     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9214     if (EVar.isInvalid())
9215       return nullptr;
9216     Vars.push_back(EVar.get());
9217   }
9218   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9219   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
9220 }
9221
9222 template <typename Derived>
9223 OMPClause *
9224 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
9225   llvm::SmallVector<Expr *, 16> Vars;
9226   Vars.reserve(C->varlist_size());
9227   for (auto *VE : C->varlists()) {
9228     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9229     if (EVar.isInvalid())
9230       return nullptr;
9231     Vars.push_back(EVar.get());
9232   }
9233   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9234   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
9235 }
9236
9237 //===----------------------------------------------------------------------===//
9238 // Expression transformation
9239 //===----------------------------------------------------------------------===//
9240 template<typename Derived>
9241 ExprResult
9242 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
9243   return TransformExpr(E->getSubExpr());
9244 }
9245
9246 template<typename Derived>
9247 ExprResult
9248 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
9249   if (!E->isTypeDependent())
9250     return E;
9251
9252   return getDerived().RebuildPredefinedExpr(E->getLocation(),
9253                                             E->getIdentKind());
9254 }
9255
9256 template<typename Derived>
9257 ExprResult
9258 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
9259   NestedNameSpecifierLoc QualifierLoc;
9260   if (E->getQualifierLoc()) {
9261     QualifierLoc
9262       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9263     if (!QualifierLoc)
9264       return ExprError();
9265   }
9266
9267   ValueDecl *ND
9268     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
9269                                                          E->getDecl()));
9270   if (!ND)
9271     return ExprError();
9272
9273   NamedDecl *Found = ND;
9274   if (E->getFoundDecl() != E->getDecl()) {
9275     Found = cast_or_null<NamedDecl>(
9276         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
9277     if (!Found)
9278       return ExprError();
9279   }
9280
9281   DeclarationNameInfo NameInfo = E->getNameInfo();
9282   if (NameInfo.getName()) {
9283     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9284     if (!NameInfo.getName())
9285       return ExprError();
9286   }
9287
9288   if (!getDerived().AlwaysRebuild() &&
9289       QualifierLoc == E->getQualifierLoc() &&
9290       ND == E->getDecl() &&
9291       Found == E->getFoundDecl() &&
9292       NameInfo.getName() == E->getDecl()->getDeclName() &&
9293       !E->hasExplicitTemplateArgs()) {
9294
9295     // Mark it referenced in the new context regardless.
9296     // FIXME: this is a bit instantiation-specific.
9297     SemaRef.MarkDeclRefReferenced(E);
9298
9299     return E;
9300   }
9301
9302   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
9303   if (E->hasExplicitTemplateArgs()) {
9304     TemplateArgs = &TransArgs;
9305     TransArgs.setLAngleLoc(E->getLAngleLoc());
9306     TransArgs.setRAngleLoc(E->getRAngleLoc());
9307     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9308                                                 E->getNumTemplateArgs(),
9309                                                 TransArgs))
9310       return ExprError();
9311   }
9312
9313   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
9314                                          Found, TemplateArgs);
9315 }
9316
9317 template<typename Derived>
9318 ExprResult
9319 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
9320   return E;
9321 }
9322
9323 template <typename Derived>
9324 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
9325     FixedPointLiteral *E) {
9326   return E;
9327 }
9328
9329 template<typename Derived>
9330 ExprResult
9331 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
9332   return E;
9333 }
9334
9335 template<typename Derived>
9336 ExprResult
9337 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
9338   return E;
9339 }
9340
9341 template<typename Derived>
9342 ExprResult
9343 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
9344   return E;
9345 }
9346
9347 template<typename Derived>
9348 ExprResult
9349 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
9350   return E;
9351 }
9352
9353 template<typename Derived>
9354 ExprResult
9355 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
9356   if (FunctionDecl *FD = E->getDirectCallee())
9357     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
9358   return SemaRef.MaybeBindToTemporary(E);
9359 }
9360
9361 template<typename Derived>
9362 ExprResult
9363 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
9364   ExprResult ControllingExpr =
9365     getDerived().TransformExpr(E->getControllingExpr());
9366   if (ControllingExpr.isInvalid())
9367     return ExprError();
9368
9369   SmallVector<Expr *, 4> AssocExprs;
9370   SmallVector<TypeSourceInfo *, 4> AssocTypes;
9371   for (const GenericSelectionExpr::Association &Assoc : E->associations()) {
9372     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
9373     if (TSI) {
9374       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
9375       if (!AssocType)
9376         return ExprError();
9377       AssocTypes.push_back(AssocType);
9378     } else {
9379       AssocTypes.push_back(nullptr);
9380     }
9381
9382     ExprResult AssocExpr =
9383         getDerived().TransformExpr(Assoc.getAssociationExpr());
9384     if (AssocExpr.isInvalid())
9385       return ExprError();
9386     AssocExprs.push_back(AssocExpr.get());
9387   }
9388
9389   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
9390                                                   E->getDefaultLoc(),
9391                                                   E->getRParenLoc(),
9392                                                   ControllingExpr.get(),
9393                                                   AssocTypes,
9394                                                   AssocExprs);
9395 }
9396
9397 template<typename Derived>
9398 ExprResult
9399 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
9400   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9401   if (SubExpr.isInvalid())
9402     return ExprError();
9403
9404   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9405     return E;
9406
9407   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
9408                                        E->getRParen());
9409 }
9410
9411 /// The operand of a unary address-of operator has special rules: it's
9412 /// allowed to refer to a non-static member of a class even if there's no 'this'
9413 /// object available.
9414 template<typename Derived>
9415 ExprResult
9416 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
9417   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
9418     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
9419   else
9420     return getDerived().TransformExpr(E);
9421 }
9422
9423 template<typename Derived>
9424 ExprResult
9425 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
9426   ExprResult SubExpr;
9427   if (E->getOpcode() == UO_AddrOf)
9428     SubExpr = TransformAddressOfOperand(E->getSubExpr());
9429   else
9430     SubExpr = TransformExpr(E->getSubExpr());
9431   if (SubExpr.isInvalid())
9432     return ExprError();
9433
9434   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9435     return E;
9436
9437   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
9438                                            E->getOpcode(),
9439                                            SubExpr.get());
9440 }
9441
9442 template<typename Derived>
9443 ExprResult
9444 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
9445   // Transform the type.
9446   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
9447   if (!Type)
9448     return ExprError();
9449
9450   // Transform all of the components into components similar to what the
9451   // parser uses.
9452   // FIXME: It would be slightly more efficient in the non-dependent case to
9453   // just map FieldDecls, rather than requiring the rebuilder to look for
9454   // the fields again. However, __builtin_offsetof is rare enough in
9455   // template code that we don't care.
9456   bool ExprChanged = false;
9457   typedef Sema::OffsetOfComponent Component;
9458   SmallVector<Component, 4> Components;
9459   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
9460     const OffsetOfNode &ON = E->getComponent(I);
9461     Component Comp;
9462     Comp.isBrackets = true;
9463     Comp.LocStart = ON.getSourceRange().getBegin();
9464     Comp.LocEnd = ON.getSourceRange().getEnd();
9465     switch (ON.getKind()) {
9466     case OffsetOfNode::Array: {
9467       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
9468       ExprResult Index = getDerived().TransformExpr(FromIndex);
9469       if (Index.isInvalid())
9470         return ExprError();
9471
9472       ExprChanged = ExprChanged || Index.get() != FromIndex;
9473       Comp.isBrackets = true;
9474       Comp.U.E = Index.get();
9475       break;
9476     }
9477
9478     case OffsetOfNode::Field:
9479     case OffsetOfNode::Identifier:
9480       Comp.isBrackets = false;
9481       Comp.U.IdentInfo = ON.getFieldName();
9482       if (!Comp.U.IdentInfo)
9483         continue;
9484
9485       break;
9486
9487     case OffsetOfNode::Base:
9488       // Will be recomputed during the rebuild.
9489       continue;
9490     }
9491
9492     Components.push_back(Comp);
9493   }
9494
9495   // If nothing changed, retain the existing expression.
9496   if (!getDerived().AlwaysRebuild() &&
9497       Type == E->getTypeSourceInfo() &&
9498       !ExprChanged)
9499     return E;
9500
9501   // Build a new offsetof expression.
9502   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
9503                                           Components, E->getRParenLoc());
9504 }
9505
9506 template<typename Derived>
9507 ExprResult
9508 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
9509   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
9510          "opaque value expression requires transformation");
9511   return E;
9512 }
9513
9514 template<typename Derived>
9515 ExprResult
9516 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
9517   return E;
9518 }
9519
9520 template<typename Derived>
9521 ExprResult
9522 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
9523   // Rebuild the syntactic form.  The original syntactic form has
9524   // opaque-value expressions in it, so strip those away and rebuild
9525   // the result.  This is a really awful way of doing this, but the
9526   // better solution (rebuilding the semantic expressions and
9527   // rebinding OVEs as necessary) doesn't work; we'd need
9528   // TreeTransform to not strip away implicit conversions.
9529   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
9530   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
9531   if (result.isInvalid()) return ExprError();
9532
9533   // If that gives us a pseudo-object result back, the pseudo-object
9534   // expression must have been an lvalue-to-rvalue conversion which we
9535   // should reapply.
9536   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
9537     result = SemaRef.checkPseudoObjectRValue(result.get());
9538
9539   return result;
9540 }
9541
9542 template<typename Derived>
9543 ExprResult
9544 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
9545                                                 UnaryExprOrTypeTraitExpr *E) {
9546   if (E->isArgumentType()) {
9547     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
9548
9549     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9550     if (!NewT)
9551       return ExprError();
9552
9553     if (!getDerived().AlwaysRebuild() && OldT == NewT)
9554       return E;
9555
9556     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
9557                                                     E->getKind(),
9558                                                     E->getSourceRange());
9559   }
9560
9561   // C++0x [expr.sizeof]p1:
9562   //   The operand is either an expression, which is an unevaluated operand
9563   //   [...]
9564   EnterExpressionEvaluationContext Unevaluated(
9565       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9566       Sema::ReuseLambdaContextDecl);
9567
9568   // Try to recover if we have something like sizeof(T::X) where X is a type.
9569   // Notably, there must be *exactly* one set of parens if X is a type.
9570   TypeSourceInfo *RecoveryTSI = nullptr;
9571   ExprResult SubExpr;
9572   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
9573   if (auto *DRE =
9574           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
9575     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
9576         PE, DRE, false, &RecoveryTSI);
9577   else
9578     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
9579
9580   if (RecoveryTSI) {
9581     return getDerived().RebuildUnaryExprOrTypeTrait(
9582         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
9583   } else if (SubExpr.isInvalid())
9584     return ExprError();
9585
9586   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
9587     return E;
9588
9589   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
9590                                                   E->getOperatorLoc(),
9591                                                   E->getKind(),
9592                                                   E->getSourceRange());
9593 }
9594
9595 template<typename Derived>
9596 ExprResult
9597 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
9598   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9599   if (LHS.isInvalid())
9600     return ExprError();
9601
9602   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9603   if (RHS.isInvalid())
9604     return ExprError();
9605
9606
9607   if (!getDerived().AlwaysRebuild() &&
9608       LHS.get() == E->getLHS() &&
9609       RHS.get() == E->getRHS())
9610     return E;
9611
9612   return getDerived().RebuildArraySubscriptExpr(
9613       LHS.get(),
9614       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
9615 }
9616
9617 template <typename Derived>
9618 ExprResult
9619 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9620   ExprResult Base = getDerived().TransformExpr(E->getBase());
9621   if (Base.isInvalid())
9622     return ExprError();
9623
9624   ExprResult LowerBound;
9625   if (E->getLowerBound()) {
9626     LowerBound = getDerived().TransformExpr(E->getLowerBound());
9627     if (LowerBound.isInvalid())
9628       return ExprError();
9629   }
9630
9631   ExprResult Length;
9632   if (E->getLength()) {
9633     Length = getDerived().TransformExpr(E->getLength());
9634     if (Length.isInvalid())
9635       return ExprError();
9636   }
9637
9638   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9639       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9640     return E;
9641
9642   return getDerived().RebuildOMPArraySectionExpr(
9643       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(), E->getColonLoc(),
9644       Length.get(), E->getRBracketLoc());
9645 }
9646
9647 template<typename Derived>
9648 ExprResult
9649 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9650   // Transform the callee.
9651   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9652   if (Callee.isInvalid())
9653     return ExprError();
9654
9655   // Transform arguments.
9656   bool ArgChanged = false;
9657   SmallVector<Expr*, 8> Args;
9658   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9659                                   &ArgChanged))
9660     return ExprError();
9661
9662   if (!getDerived().AlwaysRebuild() &&
9663       Callee.get() == E->getCallee() &&
9664       !ArgChanged)
9665     return SemaRef.MaybeBindToTemporary(E);
9666
9667   // FIXME: Wrong source location information for the '('.
9668   SourceLocation FakeLParenLoc
9669     = ((Expr *)Callee.get())->getSourceRange().getBegin();
9670   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9671                                       Args,
9672                                       E->getRParenLoc());
9673 }
9674
9675 template<typename Derived>
9676 ExprResult
9677 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9678   ExprResult Base = getDerived().TransformExpr(E->getBase());
9679   if (Base.isInvalid())
9680     return ExprError();
9681
9682   NestedNameSpecifierLoc QualifierLoc;
9683   if (E->hasQualifier()) {
9684     QualifierLoc
9685       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9686
9687     if (!QualifierLoc)
9688       return ExprError();
9689   }
9690   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9691
9692   ValueDecl *Member
9693     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9694                                                          E->getMemberDecl()));
9695   if (!Member)
9696     return ExprError();
9697
9698   NamedDecl *FoundDecl = E->getFoundDecl();
9699   if (FoundDecl == E->getMemberDecl()) {
9700     FoundDecl = Member;
9701   } else {
9702     FoundDecl = cast_or_null<NamedDecl>(
9703                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9704     if (!FoundDecl)
9705       return ExprError();
9706   }
9707
9708   if (!getDerived().AlwaysRebuild() &&
9709       Base.get() == E->getBase() &&
9710       QualifierLoc == E->getQualifierLoc() &&
9711       Member == E->getMemberDecl() &&
9712       FoundDecl == E->getFoundDecl() &&
9713       !E->hasExplicitTemplateArgs()) {
9714
9715     // Mark it referenced in the new context regardless.
9716     // FIXME: this is a bit instantiation-specific.
9717     SemaRef.MarkMemberReferenced(E);
9718
9719     return E;
9720   }
9721
9722   TemplateArgumentListInfo TransArgs;
9723   if (E->hasExplicitTemplateArgs()) {
9724     TransArgs.setLAngleLoc(E->getLAngleLoc());
9725     TransArgs.setRAngleLoc(E->getRAngleLoc());
9726     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9727                                                 E->getNumTemplateArgs(),
9728                                                 TransArgs))
9729       return ExprError();
9730   }
9731
9732   // FIXME: Bogus source location for the operator
9733   SourceLocation FakeOperatorLoc =
9734       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9735
9736   // FIXME: to do this check properly, we will need to preserve the
9737   // first-qualifier-in-scope here, just in case we had a dependent
9738   // base (and therefore couldn't do the check) and a
9739   // nested-name-qualifier (and therefore could do the lookup).
9740   NamedDecl *FirstQualifierInScope = nullptr;
9741   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9742   if (MemberNameInfo.getName()) {
9743     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9744     if (!MemberNameInfo.getName())
9745       return ExprError();
9746   }
9747
9748   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9749                                         E->isArrow(),
9750                                         QualifierLoc,
9751                                         TemplateKWLoc,
9752                                         MemberNameInfo,
9753                                         Member,
9754                                         FoundDecl,
9755                                         (E->hasExplicitTemplateArgs()
9756                                            ? &TransArgs : nullptr),
9757                                         FirstQualifierInScope);
9758 }
9759
9760 template<typename Derived>
9761 ExprResult
9762 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9763   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9764   if (LHS.isInvalid())
9765     return ExprError();
9766
9767   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9768   if (RHS.isInvalid())
9769     return ExprError();
9770
9771   if (!getDerived().AlwaysRebuild() &&
9772       LHS.get() == E->getLHS() &&
9773       RHS.get() == E->getRHS())
9774     return E;
9775
9776   Sema::FPContractStateRAII FPContractState(getSema());
9777   getSema().FPFeatures = E->getFPFeatures();
9778
9779   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9780                                             LHS.get(), RHS.get());
9781 }
9782
9783 template <typename Derived>
9784 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
9785     CXXRewrittenBinaryOperator *E) {
9786   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
9787
9788   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
9789   if (LHS.isInvalid())
9790     return ExprError();
9791
9792   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
9793   if (RHS.isInvalid())
9794     return ExprError();
9795
9796   if (!getDerived().AlwaysRebuild() &&
9797       LHS.get() == Decomp.LHS &&
9798       RHS.get() == Decomp.RHS)
9799     return E;
9800
9801   // Extract the already-resolved callee declarations so that we can restrict
9802   // ourselves to using them as the unqualified lookup results when rebuilding.
9803   UnresolvedSet<2> UnqualLookups;
9804   Expr *PossibleBinOps[] = {E->getSemanticForm(),
9805                             const_cast<Expr *>(Decomp.InnerBinOp)};
9806   for (Expr *PossibleBinOp : PossibleBinOps) {
9807     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
9808     if (!Op)
9809       continue;
9810     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
9811     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
9812       continue;
9813
9814     // Transform the callee in case we built a call to a local extern
9815     // declaration.
9816     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
9817         E->getOperatorLoc(), Callee->getFoundDecl()));
9818     if (!Found)
9819       return ExprError();
9820     UnqualLookups.addDecl(Found);
9821   }
9822
9823   return getDerived().RebuildCXXRewrittenBinaryOperator(
9824       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
9825 }
9826
9827 template<typename Derived>
9828 ExprResult
9829 TreeTransform<Derived>::TransformCompoundAssignOperator(
9830                                                       CompoundAssignOperator *E) {
9831   return getDerived().TransformBinaryOperator(E);
9832 }
9833
9834 template<typename Derived>
9835 ExprResult TreeTransform<Derived>::
9836 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9837   // Just rebuild the common and RHS expressions and see whether we
9838   // get any changes.
9839
9840   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9841   if (commonExpr.isInvalid())
9842     return ExprError();
9843
9844   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9845   if (rhs.isInvalid())
9846     return ExprError();
9847
9848   if (!getDerived().AlwaysRebuild() &&
9849       commonExpr.get() == e->getCommon() &&
9850       rhs.get() == e->getFalseExpr())
9851     return e;
9852
9853   return getDerived().RebuildConditionalOperator(commonExpr.get(),
9854                                                  e->getQuestionLoc(),
9855                                                  nullptr,
9856                                                  e->getColonLoc(),
9857                                                  rhs.get());
9858 }
9859
9860 template<typename Derived>
9861 ExprResult
9862 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9863   ExprResult Cond = getDerived().TransformExpr(E->getCond());
9864   if (Cond.isInvalid())
9865     return ExprError();
9866
9867   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9868   if (LHS.isInvalid())
9869     return ExprError();
9870
9871   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9872   if (RHS.isInvalid())
9873     return ExprError();
9874
9875   if (!getDerived().AlwaysRebuild() &&
9876       Cond.get() == E->getCond() &&
9877       LHS.get() == E->getLHS() &&
9878       RHS.get() == E->getRHS())
9879     return E;
9880
9881   return getDerived().RebuildConditionalOperator(Cond.get(),
9882                                                  E->getQuestionLoc(),
9883                                                  LHS.get(),
9884                                                  E->getColonLoc(),
9885                                                  RHS.get());
9886 }
9887
9888 template<typename Derived>
9889 ExprResult
9890 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9891   // Implicit casts are eliminated during transformation, since they
9892   // will be recomputed by semantic analysis after transformation.
9893   return getDerived().TransformExpr(E->getSubExprAsWritten());
9894 }
9895
9896 template<typename Derived>
9897 ExprResult
9898 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9899   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9900   if (!Type)
9901     return ExprError();
9902
9903   ExprResult SubExpr
9904     = getDerived().TransformExpr(E->getSubExprAsWritten());
9905   if (SubExpr.isInvalid())
9906     return ExprError();
9907
9908   if (!getDerived().AlwaysRebuild() &&
9909       Type == E->getTypeInfoAsWritten() &&
9910       SubExpr.get() == E->getSubExpr())
9911     return E;
9912
9913   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9914                                             Type,
9915                                             E->getRParenLoc(),
9916                                             SubExpr.get());
9917 }
9918
9919 template<typename Derived>
9920 ExprResult
9921 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9922   TypeSourceInfo *OldT = E->getTypeSourceInfo();
9923   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9924   if (!NewT)
9925     return ExprError();
9926
9927   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9928   if (Init.isInvalid())
9929     return ExprError();
9930
9931   if (!getDerived().AlwaysRebuild() &&
9932       OldT == NewT &&
9933       Init.get() == E->getInitializer())
9934     return SemaRef.MaybeBindToTemporary(E);
9935
9936   // Note: the expression type doesn't necessarily match the
9937   // type-as-written, but that's okay, because it should always be
9938   // derivable from the initializer.
9939
9940   return getDerived().RebuildCompoundLiteralExpr(
9941       E->getLParenLoc(), NewT,
9942       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
9943 }
9944
9945 template<typename Derived>
9946 ExprResult
9947 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
9948   ExprResult Base = getDerived().TransformExpr(E->getBase());
9949   if (Base.isInvalid())
9950     return ExprError();
9951
9952   if (!getDerived().AlwaysRebuild() &&
9953       Base.get() == E->getBase())
9954     return E;
9955
9956   // FIXME: Bad source location
9957   SourceLocation FakeOperatorLoc =
9958       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
9959   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
9960                                                   E->getAccessorLoc(),
9961                                                   E->getAccessor());
9962 }
9963
9964 template<typename Derived>
9965 ExprResult
9966 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
9967   if (InitListExpr *Syntactic = E->getSyntacticForm())
9968     E = Syntactic;
9969
9970   bool InitChanged = false;
9971
9972   EnterExpressionEvaluationContext Context(
9973       getSema(), EnterExpressionEvaluationContext::InitList);
9974
9975   SmallVector<Expr*, 4> Inits;
9976   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
9977                                   Inits, &InitChanged))
9978     return ExprError();
9979
9980   if (!getDerived().AlwaysRebuild() && !InitChanged) {
9981     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
9982     // in some cases. We can't reuse it in general, because the syntactic and
9983     // semantic forms are linked, and we can't know that semantic form will
9984     // match even if the syntactic form does.
9985   }
9986
9987   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
9988                                       E->getRBraceLoc());
9989 }
9990
9991 template<typename Derived>
9992 ExprResult
9993 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
9994   Designation Desig;
9995
9996   // transform the initializer value
9997   ExprResult Init = getDerived().TransformExpr(E->getInit());
9998   if (Init.isInvalid())
9999     return ExprError();
10000
10001   // transform the designators.
10002   SmallVector<Expr*, 4> ArrayExprs;
10003   bool ExprChanged = false;
10004   for (const DesignatedInitExpr::Designator &D : E->designators()) {
10005     if (D.isFieldDesignator()) {
10006       Desig.AddDesignator(Designator::getField(D.getFieldName(),
10007                                                D.getDotLoc(),
10008                                                D.getFieldLoc()));
10009       if (D.getField()) {
10010         FieldDecl *Field = cast_or_null<FieldDecl>(
10011             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
10012         if (Field != D.getField())
10013           // Rebuild the expression when the transformed FieldDecl is
10014           // different to the already assigned FieldDecl.
10015           ExprChanged = true;
10016       } else {
10017         // Ensure that the designator expression is rebuilt when there isn't
10018         // a resolved FieldDecl in the designator as we don't want to assign
10019         // a FieldDecl to a pattern designator that will be instantiated again.
10020         ExprChanged = true;
10021       }
10022       continue;
10023     }
10024
10025     if (D.isArrayDesignator()) {
10026       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
10027       if (Index.isInvalid())
10028         return ExprError();
10029
10030       Desig.AddDesignator(
10031           Designator::getArray(Index.get(), D.getLBracketLoc()));
10032
10033       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
10034       ArrayExprs.push_back(Index.get());
10035       continue;
10036     }
10037
10038     assert(D.isArrayRangeDesignator() && "New kind of designator?");
10039     ExprResult Start
10040       = getDerived().TransformExpr(E->getArrayRangeStart(D));
10041     if (Start.isInvalid())
10042       return ExprError();
10043
10044     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
10045     if (End.isInvalid())
10046       return ExprError();
10047
10048     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
10049                                                   End.get(),
10050                                                   D.getLBracketLoc(),
10051                                                   D.getEllipsisLoc()));
10052
10053     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
10054                   End.get() != E->getArrayRangeEnd(D);
10055
10056     ArrayExprs.push_back(Start.get());
10057     ArrayExprs.push_back(End.get());
10058   }
10059
10060   if (!getDerived().AlwaysRebuild() &&
10061       Init.get() == E->getInit() &&
10062       !ExprChanged)
10063     return E;
10064
10065   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
10066                                                 E->getEqualOrColonLoc(),
10067                                                 E->usesGNUSyntax(), Init.get());
10068 }
10069
10070 // Seems that if TransformInitListExpr() only works on the syntactic form of an
10071 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
10072 template<typename Derived>
10073 ExprResult
10074 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
10075     DesignatedInitUpdateExpr *E) {
10076   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
10077                    "initializer");
10078   return ExprError();
10079 }
10080
10081 template<typename Derived>
10082 ExprResult
10083 TreeTransform<Derived>::TransformNoInitExpr(
10084     NoInitExpr *E) {
10085   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
10086   return ExprError();
10087 }
10088
10089 template<typename Derived>
10090 ExprResult
10091 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
10092   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
10093   return ExprError();
10094 }
10095
10096 template<typename Derived>
10097 ExprResult
10098 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
10099   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
10100   return ExprError();
10101 }
10102
10103 template<typename Derived>
10104 ExprResult
10105 TreeTransform<Derived>::TransformImplicitValueInitExpr(
10106                                                      ImplicitValueInitExpr *E) {
10107   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
10108
10109   // FIXME: Will we ever have proper type location here? Will we actually
10110   // need to transform the type?
10111   QualType T = getDerived().TransformType(E->getType());
10112   if (T.isNull())
10113     return ExprError();
10114
10115   if (!getDerived().AlwaysRebuild() &&
10116       T == E->getType())
10117     return E;
10118
10119   return getDerived().RebuildImplicitValueInitExpr(T);
10120 }
10121
10122 template<typename Derived>
10123 ExprResult
10124 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
10125   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
10126   if (!TInfo)
10127     return ExprError();
10128
10129   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10130   if (SubExpr.isInvalid())
10131     return ExprError();
10132
10133   if (!getDerived().AlwaysRebuild() &&
10134       TInfo == E->getWrittenTypeInfo() &&
10135       SubExpr.get() == E->getSubExpr())
10136     return E;
10137
10138   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
10139                                        TInfo, E->getRParenLoc());
10140 }
10141
10142 template<typename Derived>
10143 ExprResult
10144 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
10145   bool ArgumentChanged = false;
10146   SmallVector<Expr*, 4> Inits;
10147   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
10148                      &ArgumentChanged))
10149     return ExprError();
10150
10151   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
10152                                            Inits,
10153                                            E->getRParenLoc());
10154 }
10155
10156 /// Transform an address-of-label expression.
10157 ///
10158 /// By default, the transformation of an address-of-label expression always
10159 /// rebuilds the expression, so that the label identifier can be resolved to
10160 /// the corresponding label statement by semantic analysis.
10161 template<typename Derived>
10162 ExprResult
10163 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
10164   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
10165                                         E->getLabel());
10166   if (!LD)
10167     return ExprError();
10168
10169   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
10170                                            cast<LabelDecl>(LD));
10171 }
10172
10173 template<typename Derived>
10174 ExprResult
10175 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
10176   SemaRef.ActOnStartStmtExpr();
10177   StmtResult SubStmt
10178     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
10179   if (SubStmt.isInvalid()) {
10180     SemaRef.ActOnStmtExprError();
10181     return ExprError();
10182   }
10183
10184   if (!getDerived().AlwaysRebuild() &&
10185       SubStmt.get() == E->getSubStmt()) {
10186     // Calling this an 'error' is unintuitive, but it does the right thing.
10187     SemaRef.ActOnStmtExprError();
10188     return SemaRef.MaybeBindToTemporary(E);
10189   }
10190
10191   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
10192                                       SubStmt.get(),
10193                                       E->getRParenLoc());
10194 }
10195
10196 template<typename Derived>
10197 ExprResult
10198 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
10199   ExprResult Cond = getDerived().TransformExpr(E->getCond());
10200   if (Cond.isInvalid())
10201     return ExprError();
10202
10203   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10204   if (LHS.isInvalid())
10205     return ExprError();
10206
10207   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10208   if (RHS.isInvalid())
10209     return ExprError();
10210
10211   if (!getDerived().AlwaysRebuild() &&
10212       Cond.get() == E->getCond() &&
10213       LHS.get() == E->getLHS() &&
10214       RHS.get() == E->getRHS())
10215     return E;
10216
10217   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
10218                                         Cond.get(), LHS.get(), RHS.get(),
10219                                         E->getRParenLoc());
10220 }
10221
10222 template<typename Derived>
10223 ExprResult
10224 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
10225   return E;
10226 }
10227
10228 template<typename Derived>
10229 ExprResult
10230 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10231   switch (E->getOperator()) {
10232   case OO_New:
10233   case OO_Delete:
10234   case OO_Array_New:
10235   case OO_Array_Delete:
10236     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
10237
10238   case OO_Call: {
10239     // This is a call to an object's operator().
10240     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
10241
10242     // Transform the object itself.
10243     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
10244     if (Object.isInvalid())
10245       return ExprError();
10246
10247     // FIXME: Poor location information
10248     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
10249         static_cast<Expr *>(Object.get())->getEndLoc());
10250
10251     // Transform the call arguments.
10252     SmallVector<Expr*, 8> Args;
10253     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
10254                                     Args))
10255       return ExprError();
10256
10257     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
10258                                         E->getEndLoc());
10259   }
10260
10261 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10262   case OO_##Name:
10263 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
10264 #include "clang/Basic/OperatorKinds.def"
10265   case OO_Subscript:
10266     // Handled below.
10267     break;
10268
10269   case OO_Conditional:
10270     llvm_unreachable("conditional operator is not actually overloadable");
10271
10272   case OO_None:
10273   case NUM_OVERLOADED_OPERATORS:
10274     llvm_unreachable("not an overloaded operator?");
10275   }
10276
10277   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10278   if (Callee.isInvalid())
10279     return ExprError();
10280
10281   ExprResult First;
10282   if (E->getOperator() == OO_Amp)
10283     First = getDerived().TransformAddressOfOperand(E->getArg(0));
10284   else
10285     First = getDerived().TransformExpr(E->getArg(0));
10286   if (First.isInvalid())
10287     return ExprError();
10288
10289   ExprResult Second;
10290   if (E->getNumArgs() == 2) {
10291     Second = getDerived().TransformExpr(E->getArg(1));
10292     if (Second.isInvalid())
10293       return ExprError();
10294   }
10295
10296   if (!getDerived().AlwaysRebuild() &&
10297       Callee.get() == E->getCallee() &&
10298       First.get() == E->getArg(0) &&
10299       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
10300     return SemaRef.MaybeBindToTemporary(E);
10301
10302   Sema::FPContractStateRAII FPContractState(getSema());
10303   getSema().FPFeatures = E->getFPFeatures();
10304
10305   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
10306                                                  E->getOperatorLoc(),
10307                                                  Callee.get(),
10308                                                  First.get(),
10309                                                  Second.get());
10310 }
10311
10312 template<typename Derived>
10313 ExprResult
10314 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
10315   return getDerived().TransformCallExpr(E);
10316 }
10317
10318 template <typename Derived>
10319 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
10320   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
10321                          getSema().CurContext != E->getParentContext();
10322
10323   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
10324     return E;
10325
10326   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getBeginLoc(),
10327                                            E->getEndLoc(),
10328                                            getSema().CurContext);
10329 }
10330
10331 template<typename Derived>
10332 ExprResult
10333 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
10334   // Transform the callee.
10335   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
10336   if (Callee.isInvalid())
10337     return ExprError();
10338
10339   // Transform exec config.
10340   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
10341   if (EC.isInvalid())
10342     return ExprError();
10343
10344   // Transform arguments.
10345   bool ArgChanged = false;
10346   SmallVector<Expr*, 8> Args;
10347   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10348                                   &ArgChanged))
10349     return ExprError();
10350
10351   if (!getDerived().AlwaysRebuild() &&
10352       Callee.get() == E->getCallee() &&
10353       !ArgChanged)
10354     return SemaRef.MaybeBindToTemporary(E);
10355
10356   // FIXME: Wrong source location information for the '('.
10357   SourceLocation FakeLParenLoc
10358     = ((Expr *)Callee.get())->getSourceRange().getBegin();
10359   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10360                                       Args,
10361                                       E->getRParenLoc(), EC.get());
10362 }
10363
10364 template<typename Derived>
10365 ExprResult
10366 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
10367   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10368   if (!Type)
10369     return ExprError();
10370
10371   ExprResult SubExpr
10372     = getDerived().TransformExpr(E->getSubExprAsWritten());
10373   if (SubExpr.isInvalid())
10374     return ExprError();
10375
10376   if (!getDerived().AlwaysRebuild() &&
10377       Type == E->getTypeInfoAsWritten() &&
10378       SubExpr.get() == E->getSubExpr())
10379     return E;
10380   return getDerived().RebuildCXXNamedCastExpr(
10381       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
10382       Type, E->getAngleBrackets().getEnd(),
10383       // FIXME. this should be '(' location
10384       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
10385 }
10386
10387 template<typename Derived>
10388 ExprResult
10389 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
10390   TypeSourceInfo *TSI =
10391       getDerived().TransformType(BCE->getTypeInfoAsWritten());
10392   if (!TSI)
10393     return ExprError();
10394
10395   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
10396   if (Sub.isInvalid())
10397     return ExprError();
10398
10399   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
10400                                                 Sub.get(), BCE->getEndLoc());
10401 }
10402
10403 template<typename Derived>
10404 ExprResult
10405 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
10406   return getDerived().TransformCXXNamedCastExpr(E);
10407 }
10408
10409 template<typename Derived>
10410 ExprResult
10411 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
10412   return getDerived().TransformCXXNamedCastExpr(E);
10413 }
10414
10415 template<typename Derived>
10416 ExprResult
10417 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
10418                                                       CXXReinterpretCastExpr *E) {
10419   return getDerived().TransformCXXNamedCastExpr(E);
10420 }
10421
10422 template<typename Derived>
10423 ExprResult
10424 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
10425   return getDerived().TransformCXXNamedCastExpr(E);
10426 }
10427
10428 template<typename Derived>
10429 ExprResult
10430 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
10431                                                      CXXFunctionalCastExpr *E) {
10432   TypeSourceInfo *Type =
10433       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
10434   if (!Type)
10435     return ExprError();
10436
10437   ExprResult SubExpr
10438     = getDerived().TransformExpr(E->getSubExprAsWritten());
10439   if (SubExpr.isInvalid())
10440     return ExprError();
10441
10442   if (!getDerived().AlwaysRebuild() &&
10443       Type == E->getTypeInfoAsWritten() &&
10444       SubExpr.get() == E->getSubExpr())
10445     return E;
10446
10447   return getDerived().RebuildCXXFunctionalCastExpr(Type,
10448                                                    E->getLParenLoc(),
10449                                                    SubExpr.get(),
10450                                                    E->getRParenLoc(),
10451                                                    E->isListInitialization());
10452 }
10453
10454 template<typename Derived>
10455 ExprResult
10456 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
10457   if (E->isTypeOperand()) {
10458     TypeSourceInfo *TInfo
10459       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10460     if (!TInfo)
10461       return ExprError();
10462
10463     if (!getDerived().AlwaysRebuild() &&
10464         TInfo == E->getTypeOperandSourceInfo())
10465       return E;
10466
10467     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10468                                              TInfo, E->getEndLoc());
10469   }
10470
10471   // We don't know whether the subexpression is potentially evaluated until
10472   // after we perform semantic analysis.  We speculatively assume it is
10473   // unevaluated; it will get fixed later if the subexpression is in fact
10474   // potentially evaluated.
10475   EnterExpressionEvaluationContext Unevaluated(
10476       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10477       Sema::ReuseLambdaContextDecl);
10478
10479   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10480   if (SubExpr.isInvalid())
10481     return ExprError();
10482
10483   if (!getDerived().AlwaysRebuild() &&
10484       SubExpr.get() == E->getExprOperand())
10485     return E;
10486
10487   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10488                                            SubExpr.get(), E->getEndLoc());
10489 }
10490
10491 template<typename Derived>
10492 ExprResult
10493 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
10494   if (E->isTypeOperand()) {
10495     TypeSourceInfo *TInfo
10496       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10497     if (!TInfo)
10498       return ExprError();
10499
10500     if (!getDerived().AlwaysRebuild() &&
10501         TInfo == E->getTypeOperandSourceInfo())
10502       return E;
10503
10504     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10505                                              TInfo, E->getEndLoc());
10506   }
10507
10508   EnterExpressionEvaluationContext Unevaluated(
10509       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10510
10511   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10512   if (SubExpr.isInvalid())
10513     return ExprError();
10514
10515   if (!getDerived().AlwaysRebuild() &&
10516       SubExpr.get() == E->getExprOperand())
10517     return E;
10518
10519   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10520                                            SubExpr.get(), E->getEndLoc());
10521 }
10522
10523 template<typename Derived>
10524 ExprResult
10525 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
10526   return E;
10527 }
10528
10529 template<typename Derived>
10530 ExprResult
10531 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
10532                                                      CXXNullPtrLiteralExpr *E) {
10533   return E;
10534 }
10535
10536 template<typename Derived>
10537 ExprResult
10538 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
10539   QualType T = getSema().getCurrentThisType();
10540
10541   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
10542     // Mark it referenced in the new context regardless.
10543     // FIXME: this is a bit instantiation-specific.
10544     getSema().MarkThisReferenced(E);
10545     return E;
10546   }
10547
10548   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
10549 }
10550
10551 template<typename Derived>
10552 ExprResult
10553 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
10554   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10555   if (SubExpr.isInvalid())
10556     return ExprError();
10557
10558   if (!getDerived().AlwaysRebuild() &&
10559       SubExpr.get() == E->getSubExpr())
10560     return E;
10561
10562   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
10563                                           E->isThrownVariableInScope());
10564 }
10565
10566 template<typename Derived>
10567 ExprResult
10568 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10569   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
10570       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
10571   if (!Param)
10572     return ExprError();
10573
10574   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
10575       E->getUsedContext() == SemaRef.CurContext)
10576     return E;
10577
10578   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
10579 }
10580
10581 template<typename Derived>
10582 ExprResult
10583 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
10584   FieldDecl *Field = cast_or_null<FieldDecl>(
10585       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
10586   if (!Field)
10587     return ExprError();
10588
10589   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
10590       E->getUsedContext() == SemaRef.CurContext)
10591     return E;
10592
10593   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
10594 }
10595
10596 template<typename Derived>
10597 ExprResult
10598 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
10599                                                     CXXScalarValueInitExpr *E) {
10600   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
10601   if (!T)
10602     return ExprError();
10603
10604   if (!getDerived().AlwaysRebuild() &&
10605       T == E->getTypeSourceInfo())
10606     return E;
10607
10608   return getDerived().RebuildCXXScalarValueInitExpr(T,
10609                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
10610                                                     E->getRParenLoc());
10611 }
10612
10613 template<typename Derived>
10614 ExprResult
10615 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
10616   // Transform the type that we're allocating
10617   TypeSourceInfo *AllocTypeInfo =
10618       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
10619   if (!AllocTypeInfo)
10620     return ExprError();
10621
10622   // Transform the size of the array we're allocating (if any).
10623   Optional<Expr *> ArraySize;
10624   if (Optional<Expr *> OldArraySize = E->getArraySize()) {
10625     ExprResult NewArraySize;
10626     if (*OldArraySize) {
10627       NewArraySize = getDerived().TransformExpr(*OldArraySize);
10628       if (NewArraySize.isInvalid())
10629         return ExprError();
10630     }
10631     ArraySize = NewArraySize.get();
10632   }
10633
10634   // Transform the placement arguments (if any).
10635   bool ArgumentChanged = false;
10636   SmallVector<Expr*, 8> PlacementArgs;
10637   if (getDerived().TransformExprs(E->getPlacementArgs(),
10638                                   E->getNumPlacementArgs(), true,
10639                                   PlacementArgs, &ArgumentChanged))
10640     return ExprError();
10641
10642   // Transform the initializer (if any).
10643   Expr *OldInit = E->getInitializer();
10644   ExprResult NewInit;
10645   if (OldInit)
10646     NewInit = getDerived().TransformInitializer(OldInit, true);
10647   if (NewInit.isInvalid())
10648     return ExprError();
10649
10650   // Transform new operator and delete operator.
10651   FunctionDecl *OperatorNew = nullptr;
10652   if (E->getOperatorNew()) {
10653     OperatorNew = cast_or_null<FunctionDecl>(
10654         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
10655     if (!OperatorNew)
10656       return ExprError();
10657   }
10658
10659   FunctionDecl *OperatorDelete = nullptr;
10660   if (E->getOperatorDelete()) {
10661     OperatorDelete = cast_or_null<FunctionDecl>(
10662         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10663     if (!OperatorDelete)
10664       return ExprError();
10665   }
10666
10667   if (!getDerived().AlwaysRebuild() &&
10668       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
10669       ArraySize == E->getArraySize() &&
10670       NewInit.get() == OldInit &&
10671       OperatorNew == E->getOperatorNew() &&
10672       OperatorDelete == E->getOperatorDelete() &&
10673       !ArgumentChanged) {
10674     // Mark any declarations we need as referenced.
10675     // FIXME: instantiation-specific.
10676     if (OperatorNew)
10677       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
10678     if (OperatorDelete)
10679       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10680
10681     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
10682       QualType ElementType
10683         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
10684       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
10685         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10686         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10687           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
10688         }
10689       }
10690     }
10691
10692     return E;
10693   }
10694
10695   QualType AllocType = AllocTypeInfo->getType();
10696   if (!ArraySize) {
10697     // If no array size was specified, but the new expression was
10698     // instantiated with an array type (e.g., "new T" where T is
10699     // instantiated with "int[4]"), extract the outer bound from the
10700     // array type as our array size. We do this with constant and
10701     // dependently-sized array types.
10702     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10703     if (!ArrayT) {
10704       // Do nothing
10705     } else if (const ConstantArrayType *ConsArrayT
10706                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
10707       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10708                                          SemaRef.Context.getSizeType(),
10709                                          /*FIXME:*/ E->getBeginLoc());
10710       AllocType = ConsArrayT->getElementType();
10711     } else if (const DependentSizedArrayType *DepArrayT
10712                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10713       if (DepArrayT->getSizeExpr()) {
10714         ArraySize = DepArrayT->getSizeExpr();
10715         AllocType = DepArrayT->getElementType();
10716       }
10717     }
10718   }
10719
10720   return getDerived().RebuildCXXNewExpr(
10721       E->getBeginLoc(), E->isGlobalNew(),
10722       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
10723       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
10724       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
10725 }
10726
10727 template<typename Derived>
10728 ExprResult
10729 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10730   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10731   if (Operand.isInvalid())
10732     return ExprError();
10733
10734   // Transform the delete operator, if known.
10735   FunctionDecl *OperatorDelete = nullptr;
10736   if (E->getOperatorDelete()) {
10737     OperatorDelete = cast_or_null<FunctionDecl>(
10738         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10739     if (!OperatorDelete)
10740       return ExprError();
10741   }
10742
10743   if (!getDerived().AlwaysRebuild() &&
10744       Operand.get() == E->getArgument() &&
10745       OperatorDelete == E->getOperatorDelete()) {
10746     // Mark any declarations we need as referenced.
10747     // FIXME: instantiation-specific.
10748     if (OperatorDelete)
10749       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10750
10751     if (!E->getArgument()->isTypeDependent()) {
10752       QualType Destroyed = SemaRef.Context.getBaseElementType(
10753                                                          E->getDestroyedType());
10754       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10755         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10756         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
10757                                        SemaRef.LookupDestructor(Record));
10758       }
10759     }
10760
10761     return E;
10762   }
10763
10764   return getDerived().RebuildCXXDeleteExpr(
10765       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
10766 }
10767
10768 template<typename Derived>
10769 ExprResult
10770 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10771                                                      CXXPseudoDestructorExpr *E) {
10772   ExprResult Base = getDerived().TransformExpr(E->getBase());
10773   if (Base.isInvalid())
10774     return ExprError();
10775
10776   ParsedType ObjectTypePtr;
10777   bool MayBePseudoDestructor = false;
10778   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10779                                               E->getOperatorLoc(),
10780                                         E->isArrow()? tok::arrow : tok::period,
10781                                               ObjectTypePtr,
10782                                               MayBePseudoDestructor);
10783   if (Base.isInvalid())
10784     return ExprError();
10785
10786   QualType ObjectType = ObjectTypePtr.get();
10787   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10788   if (QualifierLoc) {
10789     QualifierLoc
10790       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10791     if (!QualifierLoc)
10792       return ExprError();
10793   }
10794   CXXScopeSpec SS;
10795   SS.Adopt(QualifierLoc);
10796
10797   PseudoDestructorTypeStorage Destroyed;
10798   if (E->getDestroyedTypeInfo()) {
10799     TypeSourceInfo *DestroyedTypeInfo
10800       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10801                                                 ObjectType, nullptr, SS);
10802     if (!DestroyedTypeInfo)
10803       return ExprError();
10804     Destroyed = DestroyedTypeInfo;
10805   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10806     // We aren't likely to be able to resolve the identifier down to a type
10807     // now anyway, so just retain the identifier.
10808     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10809                                             E->getDestroyedTypeLoc());
10810   } else {
10811     // Look for a destructor known with the given name.
10812     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10813                                               *E->getDestroyedTypeIdentifier(),
10814                                                 E->getDestroyedTypeLoc(),
10815                                                 /*Scope=*/nullptr,
10816                                                 SS, ObjectTypePtr,
10817                                                 false);
10818     if (!T)
10819       return ExprError();
10820
10821     Destroyed
10822       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10823                                                  E->getDestroyedTypeLoc());
10824   }
10825
10826   TypeSourceInfo *ScopeTypeInfo = nullptr;
10827   if (E->getScopeTypeInfo()) {
10828     CXXScopeSpec EmptySS;
10829     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10830                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10831     if (!ScopeTypeInfo)
10832       return ExprError();
10833   }
10834
10835   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10836                                                      E->getOperatorLoc(),
10837                                                      E->isArrow(),
10838                                                      SS,
10839                                                      ScopeTypeInfo,
10840                                                      E->getColonColonLoc(),
10841                                                      E->getTildeLoc(),
10842                                                      Destroyed);
10843 }
10844
10845 template <typename Derived>
10846 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10847                                                         bool RequiresADL,
10848                                                         LookupResult &R) {
10849   // Transform all the decls.
10850   bool AllEmptyPacks = true;
10851   for (auto *OldD : Old->decls()) {
10852     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10853     if (!InstD) {
10854       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10855       // This can happen because of dependent hiding.
10856       if (isa<UsingShadowDecl>(OldD))
10857         continue;
10858       else {
10859         R.clear();
10860         return true;
10861       }
10862     }
10863
10864     // Expand using pack declarations.
10865     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10866     ArrayRef<NamedDecl*> Decls = SingleDecl;
10867     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10868       Decls = UPD->expansions();
10869
10870     // Expand using declarations.
10871     for (auto *D : Decls) {
10872       if (auto *UD = dyn_cast<UsingDecl>(D)) {
10873         for (auto *SD : UD->shadows())
10874           R.addDecl(SD);
10875       } else {
10876         R.addDecl(D);
10877       }
10878     }
10879
10880     AllEmptyPacks &= Decls.empty();
10881   };
10882
10883   // C++ [temp.res]/8.4.2:
10884   //   The program is ill-formed, no diagnostic required, if [...] lookup for
10885   //   a name in the template definition found a using-declaration, but the
10886   //   lookup in the corresponding scope in the instantiation odoes not find
10887   //   any declarations because the using-declaration was a pack expansion and
10888   //   the corresponding pack is empty
10889   if (AllEmptyPacks && !RequiresADL) {
10890     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10891         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
10892     return true;
10893   }
10894
10895   // Resolve a kind, but don't do any further analysis.  If it's
10896   // ambiguous, the callee needs to deal with it.
10897   R.resolveKind();
10898   return false;
10899 }
10900
10901 template<typename Derived>
10902 ExprResult
10903 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10904                                                   UnresolvedLookupExpr *Old) {
10905   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10906                  Sema::LookupOrdinaryName);
10907
10908   // Transform the declaration set.
10909   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10910     return ExprError();
10911
10912   // Rebuild the nested-name qualifier, if present.
10913   CXXScopeSpec SS;
10914   if (Old->getQualifierLoc()) {
10915     NestedNameSpecifierLoc QualifierLoc
10916       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10917     if (!QualifierLoc)
10918       return ExprError();
10919
10920     SS.Adopt(QualifierLoc);
10921   }
10922
10923   if (Old->getNamingClass()) {
10924     CXXRecordDecl *NamingClass
10925       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10926                                                             Old->getNameLoc(),
10927                                                         Old->getNamingClass()));
10928     if (!NamingClass) {
10929       R.clear();
10930       return ExprError();
10931     }
10932
10933     R.setNamingClass(NamingClass);
10934   }
10935
10936   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
10937
10938   // If we have neither explicit template arguments, nor the template keyword,
10939   // it's a normal declaration name or member reference.
10940   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
10941     NamedDecl *D = R.getAsSingle<NamedDecl>();
10942     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
10943     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
10944     // give a good diagnostic.
10945     if (D && D->isCXXInstanceMember()) {
10946       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10947                                                      /*TemplateArgs=*/nullptr,
10948                                                      /*Scope=*/nullptr);
10949     }
10950
10951     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
10952   }
10953
10954   // If we have template arguments, rebuild them, then rebuild the
10955   // templateid expression.
10956   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
10957   if (Old->hasExplicitTemplateArgs() &&
10958       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
10959                                               Old->getNumTemplateArgs(),
10960                                               TransArgs)) {
10961     R.clear();
10962     return ExprError();
10963   }
10964
10965   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
10966                                             Old->requiresADL(), &TransArgs);
10967 }
10968
10969 template<typename Derived>
10970 ExprResult
10971 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
10972   bool ArgChanged = false;
10973   SmallVector<TypeSourceInfo *, 4> Args;
10974   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
10975     TypeSourceInfo *From = E->getArg(I);
10976     TypeLoc FromTL = From->getTypeLoc();
10977     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
10978       TypeLocBuilder TLB;
10979       TLB.reserve(FromTL.getFullDataSize());
10980       QualType To = getDerived().TransformType(TLB, FromTL);
10981       if (To.isNull())
10982         return ExprError();
10983
10984       if (To == From->getType())
10985         Args.push_back(From);
10986       else {
10987         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10988         ArgChanged = true;
10989       }
10990       continue;
10991     }
10992
10993     ArgChanged = true;
10994
10995     // We have a pack expansion. Instantiate it.
10996     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
10997     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
10998     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10999     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
11000
11001     // Determine whether the set of unexpanded parameter packs can and should
11002     // be expanded.
11003     bool Expand = true;
11004     bool RetainExpansion = false;
11005     Optional<unsigned> OrigNumExpansions =
11006         ExpansionTL.getTypePtr()->getNumExpansions();
11007     Optional<unsigned> NumExpansions = OrigNumExpansions;
11008     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
11009                                              PatternTL.getSourceRange(),
11010                                              Unexpanded,
11011                                              Expand, RetainExpansion,
11012                                              NumExpansions))
11013       return ExprError();
11014
11015     if (!Expand) {
11016       // The transform has determined that we should perform a simple
11017       // transformation on the pack expansion, producing another pack
11018       // expansion.
11019       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11020
11021       TypeLocBuilder TLB;
11022       TLB.reserve(From->getTypeLoc().getFullDataSize());
11023
11024       QualType To = getDerived().TransformType(TLB, PatternTL);
11025       if (To.isNull())
11026         return ExprError();
11027
11028       To = getDerived().RebuildPackExpansionType(To,
11029                                                  PatternTL.getSourceRange(),
11030                                                  ExpansionTL.getEllipsisLoc(),
11031                                                  NumExpansions);
11032       if (To.isNull())
11033         return ExprError();
11034
11035       PackExpansionTypeLoc ToExpansionTL
11036         = TLB.push<PackExpansionTypeLoc>(To);
11037       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11038       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11039       continue;
11040     }
11041
11042     // Expand the pack expansion by substituting for each argument in the
11043     // pack(s).
11044     for (unsigned I = 0; I != *NumExpansions; ++I) {
11045       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
11046       TypeLocBuilder TLB;
11047       TLB.reserve(PatternTL.getFullDataSize());
11048       QualType To = getDerived().TransformType(TLB, PatternTL);
11049       if (To.isNull())
11050         return ExprError();
11051
11052       if (To->containsUnexpandedParameterPack()) {
11053         To = getDerived().RebuildPackExpansionType(To,
11054                                                    PatternTL.getSourceRange(),
11055                                                    ExpansionTL.getEllipsisLoc(),
11056                                                    NumExpansions);
11057         if (To.isNull())
11058           return ExprError();
11059
11060         PackExpansionTypeLoc ToExpansionTL
11061           = TLB.push<PackExpansionTypeLoc>(To);
11062         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11063       }
11064
11065       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11066     }
11067
11068     if (!RetainExpansion)
11069       continue;
11070
11071     // If we're supposed to retain a pack expansion, do so by temporarily
11072     // forgetting the partially-substituted parameter pack.
11073     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11074
11075     TypeLocBuilder TLB;
11076     TLB.reserve(From->getTypeLoc().getFullDataSize());
11077
11078     QualType To = getDerived().TransformType(TLB, PatternTL);
11079     if (To.isNull())
11080       return ExprError();
11081
11082     To = getDerived().RebuildPackExpansionType(To,
11083                                                PatternTL.getSourceRange(),
11084                                                ExpansionTL.getEllipsisLoc(),
11085                                                NumExpansions);
11086     if (To.isNull())
11087       return ExprError();
11088
11089     PackExpansionTypeLoc ToExpansionTL
11090       = TLB.push<PackExpansionTypeLoc>(To);
11091     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
11092     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
11093   }
11094
11095   if (!getDerived().AlwaysRebuild() && !ArgChanged)
11096     return E;
11097
11098   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
11099                                        E->getEndLoc());
11100 }
11101
11102 template<typename Derived>
11103 ExprResult
11104 TreeTransform<Derived>::TransformConceptSpecializationExpr(
11105                                                  ConceptSpecializationExpr *E) {
11106   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
11107   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
11108   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11109                                               Old->NumTemplateArgs, TransArgs))
11110     return ExprError();
11111
11112   return getDerived().RebuildConceptSpecializationExpr(
11113       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
11114       E->getConceptNameLoc(), E->getFoundDecl(), E->getNamedConcept(),
11115       &TransArgs);
11116 }
11117
11118
11119 template<typename Derived>
11120 ExprResult
11121 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
11122   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
11123   if (!T)
11124     return ExprError();
11125
11126   if (!getDerived().AlwaysRebuild() &&
11127       T == E->getQueriedTypeSourceInfo())
11128     return E;
11129
11130   ExprResult SubExpr;
11131   {
11132     EnterExpressionEvaluationContext Unevaluated(
11133         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11134     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
11135     if (SubExpr.isInvalid())
11136       return ExprError();
11137
11138     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
11139       return E;
11140   }
11141
11142   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
11143                                             SubExpr.get(), E->getEndLoc());
11144 }
11145
11146 template<typename Derived>
11147 ExprResult
11148 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
11149   ExprResult SubExpr;
11150   {
11151     EnterExpressionEvaluationContext Unevaluated(
11152         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11153     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
11154     if (SubExpr.isInvalid())
11155       return ExprError();
11156
11157     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
11158       return E;
11159   }
11160
11161   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
11162                                              SubExpr.get(), E->getEndLoc());
11163 }
11164
11165 template <typename Derived>
11166 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
11167     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
11168     TypeSourceInfo **RecoveryTSI) {
11169   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
11170       DRE, AddrTaken, RecoveryTSI);
11171
11172   // Propagate both errors and recovered types, which return ExprEmpty.
11173   if (!NewDRE.isUsable())
11174     return NewDRE;
11175
11176   // We got an expr, wrap it up in parens.
11177   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
11178     return PE;
11179   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
11180                                        PE->getRParen());
11181 }
11182
11183 template <typename Derived>
11184 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11185     DependentScopeDeclRefExpr *E) {
11186   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
11187                                             nullptr);
11188 }
11189
11190 template<typename Derived>
11191 ExprResult
11192 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
11193                                                DependentScopeDeclRefExpr *E,
11194                                                bool IsAddressOfOperand,
11195                                                TypeSourceInfo **RecoveryTSI) {
11196   assert(E->getQualifierLoc());
11197   NestedNameSpecifierLoc QualifierLoc
11198   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11199   if (!QualifierLoc)
11200     return ExprError();
11201   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11202
11203   // TODO: If this is a conversion-function-id, verify that the
11204   // destination type name (if present) resolves the same way after
11205   // instantiation as it did in the local scope.
11206
11207   DeclarationNameInfo NameInfo
11208     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
11209   if (!NameInfo.getName())
11210     return ExprError();
11211
11212   if (!E->hasExplicitTemplateArgs()) {
11213     if (!getDerived().AlwaysRebuild() &&
11214         QualifierLoc == E->getQualifierLoc() &&
11215         // Note: it is sufficient to compare the Name component of NameInfo:
11216         // if name has not changed, DNLoc has not changed either.
11217         NameInfo.getName() == E->getDeclName())
11218       return E;
11219
11220     return getDerived().RebuildDependentScopeDeclRefExpr(
11221         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
11222         IsAddressOfOperand, RecoveryTSI);
11223   }
11224
11225   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11226   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11227                                               E->getNumTemplateArgs(),
11228                                               TransArgs))
11229     return ExprError();
11230
11231   return getDerived().RebuildDependentScopeDeclRefExpr(
11232       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
11233       RecoveryTSI);
11234 }
11235
11236 template<typename Derived>
11237 ExprResult
11238 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
11239   // CXXConstructExprs other than for list-initialization and
11240   // CXXTemporaryObjectExpr are always implicit, so when we have
11241   // a 1-argument construction we just transform that argument.
11242   if ((E->getNumArgs() == 1 ||
11243        (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
11244       (!getDerived().DropCallArgument(E->getArg(0))) &&
11245       !E->isListInitialization())
11246     return getDerived().TransformExpr(E->getArg(0));
11247
11248   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
11249
11250   QualType T = getDerived().TransformType(E->getType());
11251   if (T.isNull())
11252     return ExprError();
11253
11254   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11255       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11256   if (!Constructor)
11257     return ExprError();
11258
11259   bool ArgumentChanged = false;
11260   SmallVector<Expr*, 8> Args;
11261   {
11262     EnterExpressionEvaluationContext Context(
11263         getSema(), EnterExpressionEvaluationContext::InitList,
11264         E->isListInitialization());
11265     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11266                                     &ArgumentChanged))
11267       return ExprError();
11268   }
11269
11270   if (!getDerived().AlwaysRebuild() &&
11271       T == E->getType() &&
11272       Constructor == E->getConstructor() &&
11273       !ArgumentChanged) {
11274     // Mark the constructor as referenced.
11275     // FIXME: Instantiation-specific
11276     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11277     return E;
11278   }
11279
11280   return getDerived().RebuildCXXConstructExpr(
11281       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
11282       E->hadMultipleCandidates(), E->isListInitialization(),
11283       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
11284       E->getConstructionKind(), E->getParenOrBraceRange());
11285 }
11286
11287 template<typename Derived>
11288 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
11289     CXXInheritedCtorInitExpr *E) {
11290   QualType T = getDerived().TransformType(E->getType());
11291   if (T.isNull())
11292     return ExprError();
11293
11294   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11295       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11296   if (!Constructor)
11297     return ExprError();
11298
11299   if (!getDerived().AlwaysRebuild() &&
11300       T == E->getType() &&
11301       Constructor == E->getConstructor()) {
11302     // Mark the constructor as referenced.
11303     // FIXME: Instantiation-specific
11304     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11305     return E;
11306   }
11307
11308   return getDerived().RebuildCXXInheritedCtorInitExpr(
11309       T, E->getLocation(), Constructor,
11310       E->constructsVBase(), E->inheritedFromVBase());
11311 }
11312
11313 /// Transform a C++ temporary-binding expression.
11314 ///
11315 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
11316 /// transform the subexpression and return that.
11317 template<typename Derived>
11318 ExprResult
11319 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11320   return getDerived().TransformExpr(E->getSubExpr());
11321 }
11322
11323 /// Transform a C++ expression that contains cleanups that should
11324 /// be run after the expression is evaluated.
11325 ///
11326 /// Since ExprWithCleanups nodes are implicitly generated, we
11327 /// just transform the subexpression and return that.
11328 template<typename Derived>
11329 ExprResult
11330 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
11331   return getDerived().TransformExpr(E->getSubExpr());
11332 }
11333
11334 template<typename Derived>
11335 ExprResult
11336 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
11337                                                     CXXTemporaryObjectExpr *E) {
11338   TypeSourceInfo *T =
11339       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11340   if (!T)
11341     return ExprError();
11342
11343   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
11344       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
11345   if (!Constructor)
11346     return ExprError();
11347
11348   bool ArgumentChanged = false;
11349   SmallVector<Expr*, 8> Args;
11350   Args.reserve(E->getNumArgs());
11351   {
11352     EnterExpressionEvaluationContext Context(
11353         getSema(), EnterExpressionEvaluationContext::InitList,
11354         E->isListInitialization());
11355     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11356                        &ArgumentChanged))
11357       return ExprError();
11358   }
11359
11360   if (!getDerived().AlwaysRebuild() &&
11361       T == E->getTypeSourceInfo() &&
11362       Constructor == E->getConstructor() &&
11363       !ArgumentChanged) {
11364     // FIXME: Instantiation-specific
11365     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
11366     return SemaRef.MaybeBindToTemporary(E);
11367   }
11368
11369   // FIXME: We should just pass E->isListInitialization(), but we're not
11370   // prepared to handle list-initialization without a child InitListExpr.
11371   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
11372   return getDerived().RebuildCXXTemporaryObjectExpr(
11373       T, LParenLoc, Args, E->getEndLoc(),
11374       /*ListInitialization=*/LParenLoc.isInvalid());
11375 }
11376
11377 template<typename Derived>
11378 ExprResult
11379 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
11380   // Transform any init-capture expressions before entering the scope of the
11381   // lambda body, because they are not semantically within that scope.
11382   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
11383   struct TransformedInitCapture {
11384     // The location of the ... if the result is retaining a pack expansion.
11385     SourceLocation EllipsisLoc;
11386     // Zero or more expansions of the init-capture.
11387     SmallVector<InitCaptureInfoTy, 4> Expansions;
11388   };
11389   SmallVector<TransformedInitCapture, 4> InitCaptures;
11390   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
11391   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11392                                     CEnd = E->capture_end();
11393        C != CEnd; ++C) {
11394     if (!E->isInitCapture(C))
11395       continue;
11396
11397     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
11398     VarDecl *OldVD = C->getCapturedVar();
11399
11400     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
11401                                 Optional<unsigned> NumExpansions) {
11402       ExprResult NewExprInitResult = getDerived().TransformInitializer(
11403           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
11404
11405       if (NewExprInitResult.isInvalid()) {
11406         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
11407         return;
11408       }
11409       Expr *NewExprInit = NewExprInitResult.get();
11410
11411       QualType NewInitCaptureType =
11412           getSema().buildLambdaInitCaptureInitialization(
11413               C->getLocation(), OldVD->getType()->isReferenceType(),
11414               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
11415               C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
11416               NewExprInit);
11417       Result.Expansions.push_back(
11418           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
11419     };
11420
11421     // If this is an init-capture pack, consider expanding the pack now.
11422     if (OldVD->isParameterPack()) {
11423       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
11424                                              ->getTypeLoc()
11425                                              .castAs<PackExpansionTypeLoc>();
11426       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11427       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
11428
11429       // Determine whether the set of unexpanded parameter packs can and should
11430       // be expanded.
11431       bool Expand = true;
11432       bool RetainExpansion = false;
11433       Optional<unsigned> OrigNumExpansions =
11434           ExpansionTL.getTypePtr()->getNumExpansions();
11435       Optional<unsigned> NumExpansions = OrigNumExpansions;
11436       if (getDerived().TryExpandParameterPacks(
11437               ExpansionTL.getEllipsisLoc(),
11438               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
11439               RetainExpansion, NumExpansions))
11440         return ExprError();
11441       if (Expand) {
11442         for (unsigned I = 0; I != *NumExpansions; ++I) {
11443           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11444           SubstInitCapture(SourceLocation(), None);
11445         }
11446       }
11447       if (!Expand || RetainExpansion) {
11448         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11449         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
11450         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
11451       }
11452     } else {
11453       SubstInitCapture(SourceLocation(), None);
11454     }
11455   }
11456
11457   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
11458   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
11459
11460   // Transform the template parameters, and add them to the current
11461   // instantiation scope. The null case is handled correctly.
11462   auto TPL = getDerived().TransformTemplateParameterList(
11463       E->getTemplateParameterList());
11464   LSI->GLTemplateParameterList = TPL;
11465
11466   // Transform the type of the original lambda's call operator.
11467   // The transformation MUST be done in the CurrentInstantiationScope since
11468   // it introduces a mapping of the original to the newly created
11469   // transformed parameters.
11470   TypeSourceInfo *NewCallOpTSI = nullptr;
11471   {
11472     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
11473     FunctionProtoTypeLoc OldCallOpFPTL =
11474         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
11475
11476     TypeLocBuilder NewCallOpTLBuilder;
11477     SmallVector<QualType, 4> ExceptionStorage;
11478     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
11479     QualType NewCallOpType = TransformFunctionProtoType(
11480         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
11481         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
11482           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
11483                                               ExceptionStorage, Changed);
11484         });
11485     if (NewCallOpType.isNull())
11486       return ExprError();
11487     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
11488                                                         NewCallOpType);
11489   }
11490
11491   // Create the local class that will describe the lambda.
11492   CXXRecordDecl *OldClass = E->getLambdaClass();
11493   CXXRecordDecl *Class
11494     = getSema().createLambdaClosureType(E->getIntroducerRange(),
11495                                         NewCallOpTSI,
11496                                         /*KnownDependent=*/false,
11497                                         E->getCaptureDefault());
11498   getDerived().transformedLocalDecl(OldClass, {Class});
11499
11500   Optional<std::tuple<unsigned, bool, Decl *>> Mangling;
11501   if (getDerived().ReplacingOriginal())
11502     Mangling = std::make_tuple(OldClass->getLambdaManglingNumber(),
11503                                OldClass->hasKnownLambdaInternalLinkage(),
11504                                OldClass->getLambdaContextDecl());
11505
11506   // Build the call operator.
11507   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
11508       Class, E->getIntroducerRange(), NewCallOpTSI,
11509       E->getCallOperator()->getEndLoc(),
11510       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
11511       E->getCallOperator()->getConstexprKind());
11512
11513   LSI->CallOperator = NewCallOperator;
11514
11515   for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
11516        I != NumParams; ++I) {
11517     auto *P = NewCallOperator->getParamDecl(I);
11518     if (P->hasUninstantiatedDefaultArg()) {
11519       EnterExpressionEvaluationContext Eval(
11520           getSema(),
11521           Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
11522       ExprResult R = getDerived().TransformExpr(
11523           E->getCallOperator()->getParamDecl(I)->getDefaultArg());
11524       P->setDefaultArg(R.get());
11525     }
11526   }
11527
11528   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
11529   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
11530
11531   // Number the lambda for linkage purposes if necessary.
11532   getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
11533
11534   // Introduce the context of the call operator.
11535   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
11536                                  /*NewThisContext*/false);
11537
11538   // Enter the scope of the lambda.
11539   getSema().buildLambdaScope(LSI, NewCallOperator,
11540                              E->getIntroducerRange(),
11541                              E->getCaptureDefault(),
11542                              E->getCaptureDefaultLoc(),
11543                              E->hasExplicitParameters(),
11544                              E->hasExplicitResultType(),
11545                              E->isMutable());
11546
11547   bool Invalid = false;
11548
11549   // Transform captures.
11550   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11551                                  CEnd = E->capture_end();
11552        C != CEnd; ++C) {
11553     // When we hit the first implicit capture, tell Sema that we've finished
11554     // the list of explicit captures.
11555     if (C->isImplicit())
11556       break;
11557
11558     // Capturing 'this' is trivial.
11559     if (C->capturesThis()) {
11560       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11561                                     /*BuildAndDiagnose*/ true, nullptr,
11562                                     C->getCaptureKind() == LCK_StarThis);
11563       continue;
11564     }
11565     // Captured expression will be recaptured during captured variables
11566     // rebuilding.
11567     if (C->capturesVLAType())
11568       continue;
11569
11570     // Rebuild init-captures, including the implied field declaration.
11571     if (E->isInitCapture(C)) {
11572       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
11573
11574       VarDecl *OldVD = C->getCapturedVar();
11575       llvm::SmallVector<Decl*, 4> NewVDs;
11576
11577       for (InitCaptureInfoTy &Info : NewC.Expansions) {
11578         ExprResult Init = Info.first;
11579         QualType InitQualType = Info.second;
11580         if (Init.isInvalid() || InitQualType.isNull()) {
11581           Invalid = true;
11582           break;
11583         }
11584         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
11585             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
11586             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
11587         if (!NewVD) {
11588           Invalid = true;
11589           break;
11590         }
11591         NewVDs.push_back(NewVD);
11592         getSema().addInitCapture(LSI, NewVD);
11593       }
11594
11595       if (Invalid)
11596         break;
11597
11598       getDerived().transformedLocalDecl(OldVD, NewVDs);
11599       continue;
11600     }
11601
11602     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11603
11604     // Determine the capture kind for Sema.
11605     Sema::TryCaptureKind Kind
11606       = C->isImplicit()? Sema::TryCapture_Implicit
11607                        : C->getCaptureKind() == LCK_ByCopy
11608                            ? Sema::TryCapture_ExplicitByVal
11609                            : Sema::TryCapture_ExplicitByRef;
11610     SourceLocation EllipsisLoc;
11611     if (C->isPackExpansion()) {
11612       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
11613       bool ShouldExpand = false;
11614       bool RetainExpansion = false;
11615       Optional<unsigned> NumExpansions;
11616       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
11617                                                C->getLocation(),
11618                                                Unexpanded,
11619                                                ShouldExpand, RetainExpansion,
11620                                                NumExpansions)) {
11621         Invalid = true;
11622         continue;
11623       }
11624
11625       if (ShouldExpand) {
11626         // The transform has determined that we should perform an expansion;
11627         // transform and capture each of the arguments.
11628         // expansion of the pattern. Do so.
11629         VarDecl *Pack = C->getCapturedVar();
11630         for (unsigned I = 0; I != *NumExpansions; ++I) {
11631           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11632           VarDecl *CapturedVar
11633             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11634                                                                Pack));
11635           if (!CapturedVar) {
11636             Invalid = true;
11637             continue;
11638           }
11639
11640           // Capture the transformed variable.
11641           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
11642         }
11643
11644         // FIXME: Retain a pack expansion if RetainExpansion is true.
11645
11646         continue;
11647       }
11648
11649       EllipsisLoc = C->getEllipsisLoc();
11650     }
11651
11652     // Transform the captured variable.
11653     VarDecl *CapturedVar
11654       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11655                                                          C->getCapturedVar()));
11656     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
11657       Invalid = true;
11658       continue;
11659     }
11660
11661     // Capture the transformed variable.
11662     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
11663                                  EllipsisLoc);
11664   }
11665   getSema().finishLambdaExplicitCaptures(LSI);
11666
11667   // FIXME: Sema's lambda-building mechanism expects us to push an expression
11668   // evaluation context even if we're not transforming the function body.
11669   getSema().PushExpressionEvaluationContext(
11670       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
11671
11672   // Instantiate the body of the lambda expression.
11673   StmtResult Body =
11674       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
11675
11676   // ActOnLambda* will pop the function scope for us.
11677   FuncScopeCleanup.disable();
11678
11679   if (Body.isInvalid()) {
11680     SavedContext.pop();
11681     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
11682                                /*IsInstantiation=*/true);
11683     return ExprError();
11684   }
11685
11686   // Copy the LSI before ActOnFinishFunctionBody removes it.
11687   // FIXME: This is dumb. Store the lambda information somewhere that outlives
11688   // the call operator.
11689   auto LSICopy = *LSI;
11690   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
11691                                     /*IsInstantiation*/ true);
11692   SavedContext.pop();
11693
11694   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
11695                                    &LSICopy);
11696 }
11697
11698 template<typename Derived>
11699 StmtResult
11700 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
11701   return TransformStmt(S);
11702 }
11703
11704 template<typename Derived>
11705 StmtResult
11706 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
11707   // Transform captures.
11708   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11709                                  CEnd = E->capture_end();
11710        C != CEnd; ++C) {
11711     // When we hit the first implicit capture, tell Sema that we've finished
11712     // the list of explicit captures.
11713     if (!C->isImplicit())
11714       continue;
11715
11716     // Capturing 'this' is trivial.
11717     if (C->capturesThis()) {
11718       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11719                                     /*BuildAndDiagnose*/ true, nullptr,
11720                                     C->getCaptureKind() == LCK_StarThis);
11721       continue;
11722     }
11723     // Captured expression will be recaptured during captured variables
11724     // rebuilding.
11725     if (C->capturesVLAType())
11726       continue;
11727
11728     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11729     assert(!E->isInitCapture(C) && "implicit init-capture?");
11730
11731     // Transform the captured variable.
11732     VarDecl *CapturedVar = cast_or_null<VarDecl>(
11733         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
11734     if (!CapturedVar || CapturedVar->isInvalidDecl())
11735       return StmtError();
11736
11737     // Capture the transformed variable.
11738     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
11739   }
11740
11741   return S;
11742 }
11743
11744 template<typename Derived>
11745 ExprResult
11746 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
11747                                                   CXXUnresolvedConstructExpr *E) {
11748   TypeSourceInfo *T =
11749       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11750   if (!T)
11751     return ExprError();
11752
11753   bool ArgumentChanged = false;
11754   SmallVector<Expr*, 8> Args;
11755   Args.reserve(E->arg_size());
11756   {
11757     EnterExpressionEvaluationContext Context(
11758         getSema(), EnterExpressionEvaluationContext::InitList,
11759         E->isListInitialization());
11760     if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
11761                                     &ArgumentChanged))
11762       return ExprError();
11763   }
11764
11765   if (!getDerived().AlwaysRebuild() &&
11766       T == E->getTypeSourceInfo() &&
11767       !ArgumentChanged)
11768     return E;
11769
11770   // FIXME: we're faking the locations of the commas
11771   return getDerived().RebuildCXXUnresolvedConstructExpr(
11772       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
11773 }
11774
11775 template<typename Derived>
11776 ExprResult
11777 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
11778                                              CXXDependentScopeMemberExpr *E) {
11779   // Transform the base of the expression.
11780   ExprResult Base((Expr*) nullptr);
11781   Expr *OldBase;
11782   QualType BaseType;
11783   QualType ObjectType;
11784   if (!E->isImplicitAccess()) {
11785     OldBase = E->getBase();
11786     Base = getDerived().TransformExpr(OldBase);
11787     if (Base.isInvalid())
11788       return ExprError();
11789
11790     // Start the member reference and compute the object's type.
11791     ParsedType ObjectTy;
11792     bool MayBePseudoDestructor = false;
11793     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11794                                                 E->getOperatorLoc(),
11795                                       E->isArrow()? tok::arrow : tok::period,
11796                                                 ObjectTy,
11797                                                 MayBePseudoDestructor);
11798     if (Base.isInvalid())
11799       return ExprError();
11800
11801     ObjectType = ObjectTy.get();
11802     BaseType = ((Expr*) Base.get())->getType();
11803   } else {
11804     OldBase = nullptr;
11805     BaseType = getDerived().TransformType(E->getBaseType());
11806     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
11807   }
11808
11809   // Transform the first part of the nested-name-specifier that qualifies
11810   // the member name.
11811   NamedDecl *FirstQualifierInScope
11812     = getDerived().TransformFirstQualifierInScope(
11813                                             E->getFirstQualifierFoundInScope(),
11814                                             E->getQualifierLoc().getBeginLoc());
11815
11816   NestedNameSpecifierLoc QualifierLoc;
11817   if (E->getQualifier()) {
11818     QualifierLoc
11819       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11820                                                      ObjectType,
11821                                                      FirstQualifierInScope);
11822     if (!QualifierLoc)
11823       return ExprError();
11824   }
11825
11826   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11827
11828   // TODO: If this is a conversion-function-id, verify that the
11829   // destination type name (if present) resolves the same way after
11830   // instantiation as it did in the local scope.
11831
11832   DeclarationNameInfo NameInfo
11833     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11834   if (!NameInfo.getName())
11835     return ExprError();
11836
11837   if (!E->hasExplicitTemplateArgs()) {
11838     // This is a reference to a member without an explicitly-specified
11839     // template argument list. Optimize for this common case.
11840     if (!getDerived().AlwaysRebuild() &&
11841         Base.get() == OldBase &&
11842         BaseType == E->getBaseType() &&
11843         QualifierLoc == E->getQualifierLoc() &&
11844         NameInfo.getName() == E->getMember() &&
11845         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11846       return E;
11847
11848     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11849                                                        BaseType,
11850                                                        E->isArrow(),
11851                                                        E->getOperatorLoc(),
11852                                                        QualifierLoc,
11853                                                        TemplateKWLoc,
11854                                                        FirstQualifierInScope,
11855                                                        NameInfo,
11856                                                        /*TemplateArgs*/nullptr);
11857   }
11858
11859   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11860   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11861                                               E->getNumTemplateArgs(),
11862                                               TransArgs))
11863     return ExprError();
11864
11865   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11866                                                      BaseType,
11867                                                      E->isArrow(),
11868                                                      E->getOperatorLoc(),
11869                                                      QualifierLoc,
11870                                                      TemplateKWLoc,
11871                                                      FirstQualifierInScope,
11872                                                      NameInfo,
11873                                                      &TransArgs);
11874 }
11875
11876 template<typename Derived>
11877 ExprResult
11878 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11879   // Transform the base of the expression.
11880   ExprResult Base((Expr*) nullptr);
11881   QualType BaseType;
11882   if (!Old->isImplicitAccess()) {
11883     Base = getDerived().TransformExpr(Old->getBase());
11884     if (Base.isInvalid())
11885       return ExprError();
11886     Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11887                                                      Old->isArrow());
11888     if (Base.isInvalid())
11889       return ExprError();
11890     BaseType = Base.get()->getType();
11891   } else {
11892     BaseType = getDerived().TransformType(Old->getBaseType());
11893   }
11894
11895   NestedNameSpecifierLoc QualifierLoc;
11896   if (Old->getQualifierLoc()) {
11897     QualifierLoc
11898     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11899     if (!QualifierLoc)
11900       return ExprError();
11901   }
11902
11903   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11904
11905   LookupResult R(SemaRef, Old->getMemberNameInfo(),
11906                  Sema::LookupOrdinaryName);
11907
11908   // Transform the declaration set.
11909   if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11910     return ExprError();
11911
11912   // Determine the naming class.
11913   if (Old->getNamingClass()) {
11914     CXXRecordDecl *NamingClass
11915       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11916                                                           Old->getMemberLoc(),
11917                                                         Old->getNamingClass()));
11918     if (!NamingClass)
11919       return ExprError();
11920
11921     R.setNamingClass(NamingClass);
11922   }
11923
11924   TemplateArgumentListInfo TransArgs;
11925   if (Old->hasExplicitTemplateArgs()) {
11926     TransArgs.setLAngleLoc(Old->getLAngleLoc());
11927     TransArgs.setRAngleLoc(Old->getRAngleLoc());
11928     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11929                                                 Old->getNumTemplateArgs(),
11930                                                 TransArgs))
11931       return ExprError();
11932   }
11933
11934   // FIXME: to do this check properly, we will need to preserve the
11935   // first-qualifier-in-scope here, just in case we had a dependent
11936   // base (and therefore couldn't do the check) and a
11937   // nested-name-qualifier (and therefore could do the lookup).
11938   NamedDecl *FirstQualifierInScope = nullptr;
11939
11940   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
11941                                                   BaseType,
11942                                                   Old->getOperatorLoc(),
11943                                                   Old->isArrow(),
11944                                                   QualifierLoc,
11945                                                   TemplateKWLoc,
11946                                                   FirstQualifierInScope,
11947                                                   R,
11948                                               (Old->hasExplicitTemplateArgs()
11949                                                   ? &TransArgs : nullptr));
11950 }
11951
11952 template<typename Derived>
11953 ExprResult
11954 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
11955   EnterExpressionEvaluationContext Unevaluated(
11956       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11957   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
11958   if (SubExpr.isInvalid())
11959     return ExprError();
11960
11961   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
11962     return E;
11963
11964   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
11965 }
11966
11967 template<typename Derived>
11968 ExprResult
11969 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
11970   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
11971   if (Pattern.isInvalid())
11972     return ExprError();
11973
11974   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
11975     return E;
11976
11977   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
11978                                            E->getNumExpansions());
11979 }
11980
11981 template<typename Derived>
11982 ExprResult
11983 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
11984   // If E is not value-dependent, then nothing will change when we transform it.
11985   // Note: This is an instantiation-centric view.
11986   if (!E->isValueDependent())
11987     return E;
11988
11989   EnterExpressionEvaluationContext Unevaluated(
11990       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
11991
11992   ArrayRef<TemplateArgument> PackArgs;
11993   TemplateArgument ArgStorage;
11994
11995   // Find the argument list to transform.
11996   if (E->isPartiallySubstituted()) {
11997     PackArgs = E->getPartialArguments();
11998   } else if (E->isValueDependent()) {
11999     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
12000     bool ShouldExpand = false;
12001     bool RetainExpansion = false;
12002     Optional<unsigned> NumExpansions;
12003     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
12004                                              Unexpanded,
12005                                              ShouldExpand, RetainExpansion,
12006                                              NumExpansions))
12007       return ExprError();
12008
12009     // If we need to expand the pack, build a template argument from it and
12010     // expand that.
12011     if (ShouldExpand) {
12012       auto *Pack = E->getPack();
12013       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
12014         ArgStorage = getSema().Context.getPackExpansionType(
12015             getSema().Context.getTypeDeclType(TTPD), None);
12016       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
12017         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
12018       } else {
12019         auto *VD = cast<ValueDecl>(Pack);
12020         ExprResult DRE = getSema().BuildDeclRefExpr(
12021             VD, VD->getType().getNonLValueExprType(getSema().Context),
12022             VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
12023             E->getPackLoc());
12024         if (DRE.isInvalid())
12025           return ExprError();
12026         ArgStorage = new (getSema().Context) PackExpansionExpr(
12027             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
12028       }
12029       PackArgs = ArgStorage;
12030     }
12031   }
12032
12033   // If we're not expanding the pack, just transform the decl.
12034   if (!PackArgs.size()) {
12035     auto *Pack = cast_or_null<NamedDecl>(
12036         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
12037     if (!Pack)
12038       return ExprError();
12039     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
12040                                               E->getPackLoc(),
12041                                               E->getRParenLoc(), None, None);
12042   }
12043
12044   // Try to compute the result without performing a partial substitution.
12045   Optional<unsigned> Result = 0;
12046   for (const TemplateArgument &Arg : PackArgs) {
12047     if (!Arg.isPackExpansion()) {
12048       Result = *Result + 1;
12049       continue;
12050     }
12051
12052     TemplateArgumentLoc ArgLoc;
12053     InventTemplateArgumentLoc(Arg, ArgLoc);
12054
12055     // Find the pattern of the pack expansion.
12056     SourceLocation Ellipsis;
12057     Optional<unsigned> OrigNumExpansions;
12058     TemplateArgumentLoc Pattern =
12059         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
12060                                                           OrigNumExpansions);
12061
12062     // Substitute under the pack expansion. Do not expand the pack (yet).
12063     TemplateArgumentLoc OutPattern;
12064     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12065     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
12066                                                /*Uneval*/ true))
12067       return true;
12068
12069     // See if we can determine the number of arguments from the result.
12070     Optional<unsigned> NumExpansions =
12071         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
12072     if (!NumExpansions) {
12073       // No: we must be in an alias template expansion, and we're going to need
12074       // to actually expand the packs.
12075       Result = None;
12076       break;
12077     }
12078
12079     Result = *Result + *NumExpansions;
12080   }
12081
12082   // Common case: we could determine the number of expansions without
12083   // substituting.
12084   if (Result)
12085     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12086                                               E->getPackLoc(),
12087                                               E->getRParenLoc(), *Result, None);
12088
12089   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
12090                                                E->getPackLoc());
12091   {
12092     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
12093     typedef TemplateArgumentLocInventIterator<
12094         Derived, const TemplateArgument*> PackLocIterator;
12095     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
12096                                    PackLocIterator(*this, PackArgs.end()),
12097                                    TransformedPackArgs, /*Uneval*/true))
12098       return ExprError();
12099   }
12100
12101   // Check whether we managed to fully-expand the pack.
12102   // FIXME: Is it possible for us to do so and not hit the early exit path?
12103   SmallVector<TemplateArgument, 8> Args;
12104   bool PartialSubstitution = false;
12105   for (auto &Loc : TransformedPackArgs.arguments()) {
12106     Args.push_back(Loc.getArgument());
12107     if (Loc.getArgument().isPackExpansion())
12108       PartialSubstitution = true;
12109   }
12110
12111   if (PartialSubstitution)
12112     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12113                                               E->getPackLoc(),
12114                                               E->getRParenLoc(), None, Args);
12115
12116   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
12117                                             E->getPackLoc(), E->getRParenLoc(),
12118                                             Args.size(), None);
12119 }
12120
12121 template<typename Derived>
12122 ExprResult
12123 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
12124                                           SubstNonTypeTemplateParmPackExpr *E) {
12125   // Default behavior is to do nothing with this transformation.
12126   return E;
12127 }
12128
12129 template<typename Derived>
12130 ExprResult
12131 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
12132                                           SubstNonTypeTemplateParmExpr *E) {
12133   // Default behavior is to do nothing with this transformation.
12134   return E;
12135 }
12136
12137 template<typename Derived>
12138 ExprResult
12139 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
12140   // Default behavior is to do nothing with this transformation.
12141   return E;
12142 }
12143
12144 template<typename Derived>
12145 ExprResult
12146 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
12147                                                   MaterializeTemporaryExpr *E) {
12148   return getDerived().TransformExpr(E->GetTemporaryExpr());
12149 }
12150
12151 template<typename Derived>
12152 ExprResult
12153 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
12154   Expr *Pattern = E->getPattern();
12155
12156   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12157   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
12158   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12159
12160   // Determine whether the set of unexpanded parameter packs can and should
12161   // be expanded.
12162   bool Expand = true;
12163   bool RetainExpansion = false;
12164   Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
12165                      NumExpansions = OrigNumExpansions;
12166   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
12167                                            Pattern->getSourceRange(),
12168                                            Unexpanded,
12169                                            Expand, RetainExpansion,
12170                                            NumExpansions))
12171     return true;
12172
12173   if (!Expand) {
12174     // Do not expand any packs here, just transform and rebuild a fold
12175     // expression.
12176     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12177
12178     ExprResult LHS =
12179         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
12180     if (LHS.isInvalid())
12181       return true;
12182
12183     ExprResult RHS =
12184         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
12185     if (RHS.isInvalid())
12186       return true;
12187
12188     if (!getDerived().AlwaysRebuild() &&
12189         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
12190       return E;
12191
12192     return getDerived().RebuildCXXFoldExpr(
12193         E->getBeginLoc(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
12194         RHS.get(), E->getEndLoc(), NumExpansions);
12195   }
12196
12197   // The transform has determined that we should perform an elementwise
12198   // expansion of the pattern. Do so.
12199   ExprResult Result = getDerived().TransformExpr(E->getInit());
12200   if (Result.isInvalid())
12201     return true;
12202   bool LeftFold = E->isLeftFold();
12203
12204   // If we're retaining an expansion for a right fold, it is the innermost
12205   // component and takes the init (if any).
12206   if (!LeftFold && RetainExpansion) {
12207     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12208
12209     ExprResult Out = getDerived().TransformExpr(Pattern);
12210     if (Out.isInvalid())
12211       return true;
12212
12213     Result = getDerived().RebuildCXXFoldExpr(
12214         E->getBeginLoc(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
12215         Result.get(), E->getEndLoc(), OrigNumExpansions);
12216     if (Result.isInvalid())
12217       return true;
12218   }
12219
12220   for (unsigned I = 0; I != *NumExpansions; ++I) {
12221     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
12222         getSema(), LeftFold ? I : *NumExpansions - I - 1);
12223     ExprResult Out = getDerived().TransformExpr(Pattern);
12224     if (Out.isInvalid())
12225       return true;
12226
12227     if (Out.get()->containsUnexpandedParameterPack()) {
12228       // We still have a pack; retain a pack expansion for this slice.
12229       Result = getDerived().RebuildCXXFoldExpr(
12230           E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
12231           E->getOperator(), E->getEllipsisLoc(),
12232           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
12233           OrigNumExpansions);
12234     } else if (Result.isUsable()) {
12235       // We've got down to a single element; build a binary operator.
12236       Result = getDerived().RebuildBinaryOperator(
12237           E->getEllipsisLoc(), E->getOperator(),
12238           LeftFold ? Result.get() : Out.get(),
12239           LeftFold ? Out.get() : Result.get());
12240     } else
12241       Result = Out;
12242
12243     if (Result.isInvalid())
12244       return true;
12245   }
12246
12247   // If we're retaining an expansion for a left fold, it is the outermost
12248   // component and takes the complete expansion so far as its init (if any).
12249   if (LeftFold && RetainExpansion) {
12250     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12251
12252     ExprResult Out = getDerived().TransformExpr(Pattern);
12253     if (Out.isInvalid())
12254       return true;
12255
12256     Result = getDerived().RebuildCXXFoldExpr(
12257         E->getBeginLoc(), Result.get(), E->getOperator(), E->getEllipsisLoc(),
12258         Out.get(), E->getEndLoc(), OrigNumExpansions);
12259     if (Result.isInvalid())
12260       return true;
12261   }
12262
12263   // If we had no init and an empty pack, and we're not retaining an expansion,
12264   // then produce a fallback value or error.
12265   if (Result.isUnset())
12266     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
12267                                                 E->getOperator());
12268
12269   return Result;
12270 }
12271
12272 template<typename Derived>
12273 ExprResult
12274 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
12275     CXXStdInitializerListExpr *E) {
12276   return getDerived().TransformExpr(E->getSubExpr());
12277 }
12278
12279 template<typename Derived>
12280 ExprResult
12281 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
12282   return SemaRef.MaybeBindToTemporary(E);
12283 }
12284
12285 template<typename Derived>
12286 ExprResult
12287 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
12288   return E;
12289 }
12290
12291 template<typename Derived>
12292 ExprResult
12293 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
12294   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12295   if (SubExpr.isInvalid())
12296     return ExprError();
12297
12298   if (!getDerived().AlwaysRebuild() &&
12299       SubExpr.get() == E->getSubExpr())
12300     return E;
12301
12302   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
12303 }
12304
12305 template<typename Derived>
12306 ExprResult
12307 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
12308   // Transform each of the elements.
12309   SmallVector<Expr *, 8> Elements;
12310   bool ArgChanged = false;
12311   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
12312                                   /*IsCall=*/false, Elements, &ArgChanged))
12313     return ExprError();
12314
12315   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12316     return SemaRef.MaybeBindToTemporary(E);
12317
12318   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
12319                                               Elements.data(),
12320                                               Elements.size());
12321 }
12322
12323 template<typename Derived>
12324 ExprResult
12325 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
12326                                                     ObjCDictionaryLiteral *E) {
12327   // Transform each of the elements.
12328   SmallVector<ObjCDictionaryElement, 8> Elements;
12329   bool ArgChanged = false;
12330   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
12331     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
12332
12333     if (OrigElement.isPackExpansion()) {
12334       // This key/value element is a pack expansion.
12335       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12336       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
12337       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
12338       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
12339
12340       // Determine whether the set of unexpanded parameter packs can
12341       // and should be expanded.
12342       bool Expand = true;
12343       bool RetainExpansion = false;
12344       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
12345       Optional<unsigned> NumExpansions = OrigNumExpansions;
12346       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
12347                                OrigElement.Value->getEndLoc());
12348       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
12349                                                PatternRange, Unexpanded, Expand,
12350                                                RetainExpansion, NumExpansions))
12351         return ExprError();
12352
12353       if (!Expand) {
12354         // The transform has determined that we should perform a simple
12355         // transformation on the pack expansion, producing another pack
12356         // expansion.
12357         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12358         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12359         if (Key.isInvalid())
12360           return ExprError();
12361
12362         if (Key.get() != OrigElement.Key)
12363           ArgChanged = true;
12364
12365         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12366         if (Value.isInvalid())
12367           return ExprError();
12368
12369         if (Value.get() != OrigElement.Value)
12370           ArgChanged = true;
12371
12372         ObjCDictionaryElement Expansion = {
12373           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
12374         };
12375         Elements.push_back(Expansion);
12376         continue;
12377       }
12378
12379       // Record right away that the argument was changed.  This needs
12380       // to happen even if the array expands to nothing.
12381       ArgChanged = true;
12382
12383       // The transform has determined that we should perform an elementwise
12384       // expansion of the pattern. Do so.
12385       for (unsigned I = 0; I != *NumExpansions; ++I) {
12386         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
12387         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12388         if (Key.isInvalid())
12389           return ExprError();
12390
12391         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
12392         if (Value.isInvalid())
12393           return ExprError();
12394
12395         ObjCDictionaryElement Element = {
12396           Key.get(), Value.get(), SourceLocation(), NumExpansions
12397         };
12398
12399         // If any unexpanded parameter packs remain, we still have a
12400         // pack expansion.
12401         // FIXME: Can this really happen?
12402         if (Key.get()->containsUnexpandedParameterPack() ||
12403             Value.get()->containsUnexpandedParameterPack())
12404           Element.EllipsisLoc = OrigElement.EllipsisLoc;
12405
12406         Elements.push_back(Element);
12407       }
12408
12409       // FIXME: Retain a pack expansion if RetainExpansion is true.
12410
12411       // We've finished with this pack expansion.
12412       continue;
12413     }
12414
12415     // Transform and check key.
12416     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
12417     if (Key.isInvalid())
12418       return ExprError();
12419
12420     if (Key.get() != OrigElement.Key)
12421       ArgChanged = true;
12422
12423     // Transform and check value.
12424     ExprResult Value
12425       = getDerived().TransformExpr(OrigElement.Value);
12426     if (Value.isInvalid())
12427       return ExprError();
12428
12429     if (Value.get() != OrigElement.Value)
12430       ArgChanged = true;
12431
12432     ObjCDictionaryElement Element = {
12433       Key.get(), Value.get(), SourceLocation(), None
12434     };
12435     Elements.push_back(Element);
12436   }
12437
12438   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12439     return SemaRef.MaybeBindToTemporary(E);
12440
12441   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
12442                                                    Elements);
12443 }
12444
12445 template<typename Derived>
12446 ExprResult
12447 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
12448   TypeSourceInfo *EncodedTypeInfo
12449     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
12450   if (!EncodedTypeInfo)
12451     return ExprError();
12452
12453   if (!getDerived().AlwaysRebuild() &&
12454       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
12455     return E;
12456
12457   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
12458                                             EncodedTypeInfo,
12459                                             E->getRParenLoc());
12460 }
12461
12462 template<typename Derived>
12463 ExprResult TreeTransform<Derived>::
12464 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
12465   // This is a kind of implicit conversion, and it needs to get dropped
12466   // and recomputed for the same general reasons that ImplicitCastExprs
12467   // do, as well a more specific one: this expression is only valid when
12468   // it appears *immediately* as an argument expression.
12469   return getDerived().TransformExpr(E->getSubExpr());
12470 }
12471
12472 template<typename Derived>
12473 ExprResult TreeTransform<Derived>::
12474 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
12475   TypeSourceInfo *TSInfo
12476     = getDerived().TransformType(E->getTypeInfoAsWritten());
12477   if (!TSInfo)
12478     return ExprError();
12479
12480   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
12481   if (Result.isInvalid())
12482     return ExprError();
12483
12484   if (!getDerived().AlwaysRebuild() &&
12485       TSInfo == E->getTypeInfoAsWritten() &&
12486       Result.get() == E->getSubExpr())
12487     return E;
12488
12489   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
12490                                       E->getBridgeKeywordLoc(), TSInfo,
12491                                       Result.get());
12492 }
12493
12494 template <typename Derived>
12495 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
12496     ObjCAvailabilityCheckExpr *E) {
12497   return E;
12498 }
12499
12500 template<typename Derived>
12501 ExprResult
12502 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
12503   // Transform arguments.
12504   bool ArgChanged = false;
12505   SmallVector<Expr*, 8> Args;
12506   Args.reserve(E->getNumArgs());
12507   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
12508                                   &ArgChanged))
12509     return ExprError();
12510
12511   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
12512     // Class message: transform the receiver type.
12513     TypeSourceInfo *ReceiverTypeInfo
12514       = getDerived().TransformType(E->getClassReceiverTypeInfo());
12515     if (!ReceiverTypeInfo)
12516       return ExprError();
12517
12518     // If nothing changed, just retain the existing message send.
12519     if (!getDerived().AlwaysRebuild() &&
12520         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
12521       return SemaRef.MaybeBindToTemporary(E);
12522
12523     // Build a new class message send.
12524     SmallVector<SourceLocation, 16> SelLocs;
12525     E->getSelectorLocs(SelLocs);
12526     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
12527                                                E->getSelector(),
12528                                                SelLocs,
12529                                                E->getMethodDecl(),
12530                                                E->getLeftLoc(),
12531                                                Args,
12532                                                E->getRightLoc());
12533   }
12534   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
12535            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12536     if (!E->getMethodDecl())
12537       return ExprError();
12538
12539     // Build a new class message send to 'super'.
12540     SmallVector<SourceLocation, 16> SelLocs;
12541     E->getSelectorLocs(SelLocs);
12542     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
12543                                                E->getSelector(),
12544                                                SelLocs,
12545                                                E->getReceiverType(),
12546                                                E->getMethodDecl(),
12547                                                E->getLeftLoc(),
12548                                                Args,
12549                                                E->getRightLoc());
12550   }
12551
12552   // Instance message: transform the receiver
12553   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
12554          "Only class and instance messages may be instantiated");
12555   ExprResult Receiver
12556     = getDerived().TransformExpr(E->getInstanceReceiver());
12557   if (Receiver.isInvalid())
12558     return ExprError();
12559
12560   // If nothing changed, just retain the existing message send.
12561   if (!getDerived().AlwaysRebuild() &&
12562       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
12563     return SemaRef.MaybeBindToTemporary(E);
12564
12565   // Build a new instance message send.
12566   SmallVector<SourceLocation, 16> SelLocs;
12567   E->getSelectorLocs(SelLocs);
12568   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
12569                                              E->getSelector(),
12570                                              SelLocs,
12571                                              E->getMethodDecl(),
12572                                              E->getLeftLoc(),
12573                                              Args,
12574                                              E->getRightLoc());
12575 }
12576
12577 template<typename Derived>
12578 ExprResult
12579 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
12580   return E;
12581 }
12582
12583 template<typename Derived>
12584 ExprResult
12585 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
12586   return E;
12587 }
12588
12589 template<typename Derived>
12590 ExprResult
12591 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
12592   // Transform the base expression.
12593   ExprResult Base = getDerived().TransformExpr(E->getBase());
12594   if (Base.isInvalid())
12595     return ExprError();
12596
12597   // We don't need to transform the ivar; it will never change.
12598
12599   // If nothing changed, just retain the existing expression.
12600   if (!getDerived().AlwaysRebuild() &&
12601       Base.get() == E->getBase())
12602     return E;
12603
12604   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
12605                                              E->getLocation(),
12606                                              E->isArrow(), E->isFreeIvar());
12607 }
12608
12609 template<typename Derived>
12610 ExprResult
12611 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
12612   // 'super' and types never change. Property never changes. Just
12613   // retain the existing expression.
12614   if (!E->isObjectReceiver())
12615     return E;
12616
12617   // Transform the base expression.
12618   ExprResult Base = getDerived().TransformExpr(E->getBase());
12619   if (Base.isInvalid())
12620     return ExprError();
12621
12622   // We don't need to transform the property; it will never change.
12623
12624   // If nothing changed, just retain the existing expression.
12625   if (!getDerived().AlwaysRebuild() &&
12626       Base.get() == E->getBase())
12627     return E;
12628
12629   if (E->isExplicitProperty())
12630     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12631                                                    E->getExplicitProperty(),
12632                                                    E->getLocation());
12633
12634   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12635                                                  SemaRef.Context.PseudoObjectTy,
12636                                                  E->getImplicitPropertyGetter(),
12637                                                  E->getImplicitPropertySetter(),
12638                                                  E->getLocation());
12639 }
12640
12641 template<typename Derived>
12642 ExprResult
12643 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
12644   // Transform the base expression.
12645   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
12646   if (Base.isInvalid())
12647     return ExprError();
12648
12649   // Transform the key expression.
12650   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
12651   if (Key.isInvalid())
12652     return ExprError();
12653
12654   // If nothing changed, just retain the existing expression.
12655   if (!getDerived().AlwaysRebuild() &&
12656       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
12657     return E;
12658
12659   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
12660                                                   Base.get(), Key.get(),
12661                                                   E->getAtIndexMethodDecl(),
12662                                                   E->setAtIndexMethodDecl());
12663 }
12664
12665 template<typename Derived>
12666 ExprResult
12667 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
12668   // Transform the base expression.
12669   ExprResult Base = getDerived().TransformExpr(E->getBase());
12670   if (Base.isInvalid())
12671     return ExprError();
12672
12673   // If nothing changed, just retain the existing expression.
12674   if (!getDerived().AlwaysRebuild() &&
12675       Base.get() == E->getBase())
12676     return E;
12677
12678   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
12679                                          E->getOpLoc(),
12680                                          E->isArrow());
12681 }
12682
12683 template<typename Derived>
12684 ExprResult
12685 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
12686   bool ArgumentChanged = false;
12687   SmallVector<Expr*, 8> SubExprs;
12688   SubExprs.reserve(E->getNumSubExprs());
12689   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12690                                   SubExprs, &ArgumentChanged))
12691     return ExprError();
12692
12693   if (!getDerived().AlwaysRebuild() &&
12694       !ArgumentChanged)
12695     return E;
12696
12697   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
12698                                                SubExprs,
12699                                                E->getRParenLoc());
12700 }
12701
12702 template<typename Derived>
12703 ExprResult
12704 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
12705   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
12706   if (SrcExpr.isInvalid())
12707     return ExprError();
12708
12709   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
12710   if (!Type)
12711     return ExprError();
12712
12713   if (!getDerived().AlwaysRebuild() &&
12714       Type == E->getTypeSourceInfo() &&
12715       SrcExpr.get() == E->getSrcExpr())
12716     return E;
12717
12718   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
12719                                                SrcExpr.get(), Type,
12720                                                E->getRParenLoc());
12721 }
12722
12723 template<typename Derived>
12724 ExprResult
12725 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
12726   BlockDecl *oldBlock = E->getBlockDecl();
12727
12728   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
12729   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
12730
12731   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
12732   blockScope->TheDecl->setBlockMissingReturnType(
12733                          oldBlock->blockMissingReturnType());
12734
12735   SmallVector<ParmVarDecl*, 4> params;
12736   SmallVector<QualType, 4> paramTypes;
12737
12738   const FunctionProtoType *exprFunctionType = E->getFunctionType();
12739
12740   // Parameter substitution.
12741   Sema::ExtParameterInfoBuilder extParamInfos;
12742   if (getDerived().TransformFunctionTypeParams(
12743           E->getCaretLocation(), oldBlock->parameters(), nullptr,
12744           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
12745           extParamInfos)) {
12746     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12747     return ExprError();
12748   }
12749
12750   QualType exprResultType =
12751       getDerived().TransformType(exprFunctionType->getReturnType());
12752
12753   auto epi = exprFunctionType->getExtProtoInfo();
12754   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
12755
12756   QualType functionType =
12757     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
12758   blockScope->FunctionType = functionType;
12759
12760   // Set the parameters on the block decl.
12761   if (!params.empty())
12762     blockScope->TheDecl->setParams(params);
12763
12764   if (!oldBlock->blockMissingReturnType()) {
12765     blockScope->HasImplicitReturnType = false;
12766     blockScope->ReturnType = exprResultType;
12767   }
12768
12769   // Transform the body
12770   StmtResult body = getDerived().TransformStmt(E->getBody());
12771   if (body.isInvalid()) {
12772     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12773     return ExprError();
12774   }
12775
12776 #ifndef NDEBUG
12777   // In builds with assertions, make sure that we captured everything we
12778   // captured before.
12779   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
12780     for (const auto &I : oldBlock->captures()) {
12781       VarDecl *oldCapture = I.getVariable();
12782
12783       // Ignore parameter packs.
12784       if (oldCapture->isParameterPack())
12785         continue;
12786
12787       VarDecl *newCapture =
12788         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
12789                                                  oldCapture));
12790       assert(blockScope->CaptureMap.count(newCapture));
12791     }
12792     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
12793   }
12794 #endif
12795
12796   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
12797                                     /*Scope=*/nullptr);
12798 }
12799
12800 template<typename Derived>
12801 ExprResult
12802 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12803   llvm_unreachable("Cannot transform asType expressions yet");
12804 }
12805
12806 template<typename Derived>
12807 ExprResult
12808 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12809   bool ArgumentChanged = false;
12810   SmallVector<Expr*, 8> SubExprs;
12811   SubExprs.reserve(E->getNumSubExprs());
12812   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12813                                   SubExprs, &ArgumentChanged))
12814     return ExprError();
12815
12816   if (!getDerived().AlwaysRebuild() &&
12817       !ArgumentChanged)
12818     return E;
12819
12820   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12821                                         E->getOp(), E->getRParenLoc());
12822 }
12823
12824 //===----------------------------------------------------------------------===//
12825 // Type reconstruction
12826 //===----------------------------------------------------------------------===//
12827
12828 template<typename Derived>
12829 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12830                                                     SourceLocation Star) {
12831   return SemaRef.BuildPointerType(PointeeType, Star,
12832                                   getDerived().getBaseEntity());
12833 }
12834
12835 template<typename Derived>
12836 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12837                                                          SourceLocation Star) {
12838   return SemaRef.BuildBlockPointerType(PointeeType, Star,
12839                                        getDerived().getBaseEntity());
12840 }
12841
12842 template<typename Derived>
12843 QualType
12844 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12845                                              bool WrittenAsLValue,
12846                                              SourceLocation Sigil) {
12847   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12848                                     Sigil, getDerived().getBaseEntity());
12849 }
12850
12851 template<typename Derived>
12852 QualType
12853 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12854                                                  QualType ClassType,
12855                                                  SourceLocation Sigil) {
12856   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12857                                         getDerived().getBaseEntity());
12858 }
12859
12860 template<typename Derived>
12861 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12862            const ObjCTypeParamDecl *Decl,
12863            SourceLocation ProtocolLAngleLoc,
12864            ArrayRef<ObjCProtocolDecl *> Protocols,
12865            ArrayRef<SourceLocation> ProtocolLocs,
12866            SourceLocation ProtocolRAngleLoc) {
12867   return SemaRef.BuildObjCTypeParamType(Decl,
12868                                         ProtocolLAngleLoc, Protocols,
12869                                         ProtocolLocs, ProtocolRAngleLoc,
12870                                         /*FailOnError=*/true);
12871 }
12872
12873 template<typename Derived>
12874 QualType TreeTransform<Derived>::RebuildObjCObjectType(
12875            QualType BaseType,
12876            SourceLocation Loc,
12877            SourceLocation TypeArgsLAngleLoc,
12878            ArrayRef<TypeSourceInfo *> TypeArgs,
12879            SourceLocation TypeArgsRAngleLoc,
12880            SourceLocation ProtocolLAngleLoc,
12881            ArrayRef<ObjCProtocolDecl *> Protocols,
12882            ArrayRef<SourceLocation> ProtocolLocs,
12883            SourceLocation ProtocolRAngleLoc) {
12884   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12885                                      TypeArgs, TypeArgsRAngleLoc,
12886                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
12887                                      ProtocolRAngleLoc,
12888                                      /*FailOnError=*/true);
12889 }
12890
12891 template<typename Derived>
12892 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12893            QualType PointeeType,
12894            SourceLocation Star) {
12895   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12896 }
12897
12898 template<typename Derived>
12899 QualType
12900 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12901                                          ArrayType::ArraySizeModifier SizeMod,
12902                                          const llvm::APInt *Size,
12903                                          Expr *SizeExpr,
12904                                          unsigned IndexTypeQuals,
12905                                          SourceRange BracketsRange) {
12906   if (SizeExpr || !Size)
12907     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12908                                   IndexTypeQuals, BracketsRange,
12909                                   getDerived().getBaseEntity());
12910
12911   QualType Types[] = {
12912     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12913     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12914     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12915   };
12916   const unsigned NumTypes = llvm::array_lengthof(Types);
12917   QualType SizeType;
12918   for (unsigned I = 0; I != NumTypes; ++I)
12919     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12920       SizeType = Types[I];
12921       break;
12922     }
12923
12924   // Note that we can return a VariableArrayType here in the case where
12925   // the element type was a dependent VariableArrayType.
12926   IntegerLiteral *ArraySize
12927       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
12928                                /*FIXME*/BracketsRange.getBegin());
12929   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
12930                                 IndexTypeQuals, BracketsRange,
12931                                 getDerived().getBaseEntity());
12932 }
12933
12934 template<typename Derived>
12935 QualType
12936 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
12937                                                  ArrayType::ArraySizeModifier SizeMod,
12938                                                  const llvm::APInt &Size,
12939                                                  Expr *SizeExpr,
12940                                                  unsigned IndexTypeQuals,
12941                                                  SourceRange BracketsRange) {
12942   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
12943                                         IndexTypeQuals, BracketsRange);
12944 }
12945
12946 template<typename Derived>
12947 QualType
12948 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
12949                                           ArrayType::ArraySizeModifier SizeMod,
12950                                                  unsigned IndexTypeQuals,
12951                                                    SourceRange BracketsRange) {
12952   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
12953                                        IndexTypeQuals, BracketsRange);
12954 }
12955
12956 template<typename Derived>
12957 QualType
12958 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
12959                                           ArrayType::ArraySizeModifier SizeMod,
12960                                                  Expr *SizeExpr,
12961                                                  unsigned IndexTypeQuals,
12962                                                  SourceRange BracketsRange) {
12963   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12964                                        SizeExpr,
12965                                        IndexTypeQuals, BracketsRange);
12966 }
12967
12968 template<typename Derived>
12969 QualType
12970 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
12971                                           ArrayType::ArraySizeModifier SizeMod,
12972                                                        Expr *SizeExpr,
12973                                                        unsigned IndexTypeQuals,
12974                                                    SourceRange BracketsRange) {
12975   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12976                                        SizeExpr,
12977                                        IndexTypeQuals, BracketsRange);
12978 }
12979
12980 template <typename Derived>
12981 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
12982     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
12983   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
12984                                           AttributeLoc);
12985 }
12986
12987 template <typename Derived>
12988 QualType
12989 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
12990                                           unsigned NumElements,
12991                                           VectorType::VectorKind VecKind) {
12992   // FIXME: semantic checking!
12993   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
12994 }
12995
12996 template <typename Derived>
12997 QualType TreeTransform<Derived>::RebuildDependentVectorType(
12998     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
12999     VectorType::VectorKind VecKind) {
13000   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
13001 }
13002
13003 template<typename Derived>
13004 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
13005                                                       unsigned NumElements,
13006                                                  SourceLocation AttributeLoc) {
13007   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
13008                           NumElements, true);
13009   IntegerLiteral *VectorSize
13010     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
13011                              AttributeLoc);
13012   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
13013 }
13014
13015 template<typename Derived>
13016 QualType
13017 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
13018                                                            Expr *SizeExpr,
13019                                                   SourceLocation AttributeLoc) {
13020   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
13021 }
13022
13023 template<typename Derived>
13024 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
13025     QualType T,
13026     MutableArrayRef<QualType> ParamTypes,
13027     const FunctionProtoType::ExtProtoInfo &EPI) {
13028   return SemaRef.BuildFunctionType(T, ParamTypes,
13029                                    getDerived().getBaseLocation(),
13030                                    getDerived().getBaseEntity(),
13031                                    EPI);
13032 }
13033
13034 template<typename Derived>
13035 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
13036   return SemaRef.Context.getFunctionNoProtoType(T);
13037 }
13038
13039 template<typename Derived>
13040 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
13041                                                             Decl *D) {
13042   assert(D && "no decl found");
13043   if (D->isInvalidDecl()) return QualType();
13044
13045   // FIXME: Doesn't account for ObjCInterfaceDecl!
13046   TypeDecl *Ty;
13047   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
13048     // A valid resolved using typename pack expansion decl can have multiple
13049     // UsingDecls, but they must each have exactly one type, and it must be
13050     // the same type in every case. But we must have at least one expansion!
13051     if (UPD->expansions().empty()) {
13052       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
13053           << UPD->isCXXClassMember() << UPD;
13054       return QualType();
13055     }
13056
13057     // We might still have some unresolved types. Try to pick a resolved type
13058     // if we can. The final instantiation will check that the remaining
13059     // unresolved types instantiate to the type we pick.
13060     QualType FallbackT;
13061     QualType T;
13062     for (auto *E : UPD->expansions()) {
13063       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
13064       if (ThisT.isNull())
13065         continue;
13066       else if (ThisT->getAs<UnresolvedUsingType>())
13067         FallbackT = ThisT;
13068       else if (T.isNull())
13069         T = ThisT;
13070       else
13071         assert(getSema().Context.hasSameType(ThisT, T) &&
13072                "mismatched resolved types in using pack expansion");
13073     }
13074     return T.isNull() ? FallbackT : T;
13075   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
13076     assert(Using->hasTypename() &&
13077            "UnresolvedUsingTypenameDecl transformed to non-typename using");
13078
13079     // A valid resolved using typename decl points to exactly one type decl.
13080     assert(++Using->shadow_begin() == Using->shadow_end());
13081     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
13082   } else {
13083     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
13084            "UnresolvedUsingTypenameDecl transformed to non-using decl");
13085     Ty = cast<UnresolvedUsingTypenameDecl>(D);
13086   }
13087
13088   return SemaRef.Context.getTypeDeclType(Ty);
13089 }
13090
13091 template<typename Derived>
13092 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
13093                                                        SourceLocation Loc) {
13094   return SemaRef.BuildTypeofExprType(E, Loc);
13095 }
13096
13097 template<typename Derived>
13098 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
13099   return SemaRef.Context.getTypeOfType(Underlying);
13100 }
13101
13102 template<typename Derived>
13103 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
13104                                                      SourceLocation Loc) {
13105   return SemaRef.BuildDecltypeType(E, Loc);
13106 }
13107
13108 template<typename Derived>
13109 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
13110                                             UnaryTransformType::UTTKind UKind,
13111                                             SourceLocation Loc) {
13112   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
13113 }
13114
13115 template<typename Derived>
13116 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
13117                                                       TemplateName Template,
13118                                              SourceLocation TemplateNameLoc,
13119                                      TemplateArgumentListInfo &TemplateArgs) {
13120   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
13121 }
13122
13123 template<typename Derived>
13124 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
13125                                                    SourceLocation KWLoc) {
13126   return SemaRef.BuildAtomicType(ValueType, KWLoc);
13127 }
13128
13129 template<typename Derived>
13130 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
13131                                                  SourceLocation KWLoc,
13132                                                  bool isReadPipe) {
13133   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
13134                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
13135 }
13136
13137 template<typename Derived>
13138 TemplateName
13139 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13140                                             bool TemplateKW,
13141                                             TemplateDecl *Template) {
13142   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
13143                                                   Template);
13144 }
13145
13146 template<typename Derived>
13147 TemplateName
13148 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13149                                             SourceLocation TemplateKWLoc,
13150                                             const IdentifierInfo &Name,
13151                                             SourceLocation NameLoc,
13152                                             QualType ObjectType,
13153                                             NamedDecl *FirstQualifierInScope,
13154                                             bool AllowInjectedClassName) {
13155   UnqualifiedId TemplateName;
13156   TemplateName.setIdentifier(&Name, NameLoc);
13157   Sema::TemplateTy Template;
13158   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13159                                        SS, TemplateKWLoc, TemplateName,
13160                                        ParsedType::make(ObjectType),
13161                                        /*EnteringContext=*/false,
13162                                        Template, AllowInjectedClassName);
13163   return Template.get();
13164 }
13165
13166 template<typename Derived>
13167 TemplateName
13168 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
13169                                             SourceLocation TemplateKWLoc,
13170                                             OverloadedOperatorKind Operator,
13171                                             SourceLocation NameLoc,
13172                                             QualType ObjectType,
13173                                             bool AllowInjectedClassName) {
13174   UnqualifiedId Name;
13175   // FIXME: Bogus location information.
13176   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
13177   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
13178   Sema::TemplateTy Template;
13179   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
13180                                        SS, TemplateKWLoc, Name,
13181                                        ParsedType::make(ObjectType),
13182                                        /*EnteringContext=*/false,
13183                                        Template, AllowInjectedClassName);
13184   return Template.get();
13185 }
13186
13187 template<typename Derived>
13188 ExprResult
13189 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
13190                                                    SourceLocation OpLoc,
13191                                                    Expr *OrigCallee,
13192                                                    Expr *First,
13193                                                    Expr *Second) {
13194   Expr *Callee = OrigCallee->IgnoreParenCasts();
13195   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
13196
13197   if (First->getObjectKind() == OK_ObjCProperty) {
13198     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13199     if (BinaryOperator::isAssignmentOp(Opc))
13200       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
13201                                                  First, Second);
13202     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
13203     if (Result.isInvalid())
13204       return ExprError();
13205     First = Result.get();
13206   }
13207
13208   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
13209     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
13210     if (Result.isInvalid())
13211       return ExprError();
13212     Second = Result.get();
13213   }
13214
13215   // Determine whether this should be a builtin operation.
13216   if (Op == OO_Subscript) {
13217     if (!First->getType()->isOverloadableType() &&
13218         !Second->getType()->isOverloadableType())
13219       return getSema().CreateBuiltinArraySubscriptExpr(
13220           First, Callee->getBeginLoc(), Second, OpLoc);
13221   } else if (Op == OO_Arrow) {
13222     // -> is never a builtin operation.
13223     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
13224   } else if (Second == nullptr || isPostIncDec) {
13225     if (!First->getType()->isOverloadableType() ||
13226         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
13227       // The argument is not of overloadable type, or this is an expression
13228       // of the form &Class::member, so try to create a built-in unary
13229       // operation.
13230       UnaryOperatorKind Opc
13231         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13232
13233       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
13234     }
13235   } else {
13236     if (!First->getType()->isOverloadableType() &&
13237         !Second->getType()->isOverloadableType()) {
13238       // Neither of the arguments is an overloadable type, so try to
13239       // create a built-in binary operation.
13240       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13241       ExprResult Result
13242         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
13243       if (Result.isInvalid())
13244         return ExprError();
13245
13246       return Result;
13247     }
13248   }
13249
13250   // Compute the transformed set of functions (and function templates) to be
13251   // used during overload resolution.
13252   UnresolvedSet<16> Functions;
13253   bool RequiresADL;
13254
13255   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
13256     Functions.append(ULE->decls_begin(), ULE->decls_end());
13257     // If the overload could not be resolved in the template definition
13258     // (because we had a dependent argument), ADL is performed as part of
13259     // template instantiation.
13260     RequiresADL = ULE->requiresADL();
13261   } else {
13262     // If we've resolved this to a particular non-member function, just call
13263     // that function. If we resolved it to a member function,
13264     // CreateOverloaded* will find that function for us.
13265     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
13266     if (!isa<CXXMethodDecl>(ND))
13267       Functions.addDecl(ND);
13268     RequiresADL = false;
13269   }
13270
13271   // Add any functions found via argument-dependent lookup.
13272   Expr *Args[2] = { First, Second };
13273   unsigned NumArgs = 1 + (Second != nullptr);
13274
13275   // Create the overloaded operator invocation for unary operators.
13276   if (NumArgs == 1 || isPostIncDec) {
13277     UnaryOperatorKind Opc
13278       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
13279     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
13280                                            RequiresADL);
13281   }
13282
13283   if (Op == OO_Subscript) {
13284     SourceLocation LBrace;
13285     SourceLocation RBrace;
13286
13287     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
13288         DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
13289         LBrace = SourceLocation::getFromRawEncoding(
13290                     NameLoc.CXXOperatorName.BeginOpNameLoc);
13291         RBrace = SourceLocation::getFromRawEncoding(
13292                     NameLoc.CXXOperatorName.EndOpNameLoc);
13293     } else {
13294       LBrace = Callee->getBeginLoc();
13295       RBrace = OpLoc;
13296     }
13297
13298     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
13299                                                       First, Second);
13300   }
13301
13302   // Create the overloaded operator invocation for binary operators.
13303   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
13304   ExprResult Result = SemaRef.CreateOverloadedBinOp(
13305       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
13306   if (Result.isInvalid())
13307     return ExprError();
13308
13309   return Result;
13310 }
13311
13312 template<typename Derived>
13313 ExprResult
13314 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
13315                                                      SourceLocation OperatorLoc,
13316                                                        bool isArrow,
13317                                                        CXXScopeSpec &SS,
13318                                                      TypeSourceInfo *ScopeType,
13319                                                        SourceLocation CCLoc,
13320                                                        SourceLocation TildeLoc,
13321                                         PseudoDestructorTypeStorage Destroyed) {
13322   QualType BaseType = Base->getType();
13323   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
13324       (!isArrow && !BaseType->getAs<RecordType>()) ||
13325       (isArrow && BaseType->getAs<PointerType>() &&
13326        !BaseType->castAs<PointerType>()->getPointeeType()
13327                                               ->template getAs<RecordType>())){
13328     // This pseudo-destructor expression is still a pseudo-destructor.
13329     return SemaRef.BuildPseudoDestructorExpr(
13330         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
13331         CCLoc, TildeLoc, Destroyed);
13332   }
13333
13334   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
13335   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
13336                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
13337   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
13338   NameInfo.setNamedTypeInfo(DestroyedType);
13339
13340   // The scope type is now known to be a valid nested name specifier
13341   // component. Tack it on to the end of the nested name specifier.
13342   if (ScopeType) {
13343     if (!ScopeType->getType()->getAs<TagType>()) {
13344       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
13345                      diag::err_expected_class_or_namespace)
13346           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
13347       return ExprError();
13348     }
13349     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
13350               CCLoc);
13351   }
13352
13353   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
13354   return getSema().BuildMemberReferenceExpr(Base, BaseType,
13355                                             OperatorLoc, isArrow,
13356                                             SS, TemplateKWLoc,
13357                                             /*FIXME: FirstQualifier*/ nullptr,
13358                                             NameInfo,
13359                                             /*TemplateArgs*/ nullptr,
13360                                             /*S*/nullptr);
13361 }
13362
13363 template<typename Derived>
13364 StmtResult
13365 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
13366   SourceLocation Loc = S->getBeginLoc();
13367   CapturedDecl *CD = S->getCapturedDecl();
13368   unsigned NumParams = CD->getNumParams();
13369   unsigned ContextParamPos = CD->getContextParamPosition();
13370   SmallVector<Sema::CapturedParamNameType, 4> Params;
13371   for (unsigned I = 0; I < NumParams; ++I) {
13372     if (I != ContextParamPos) {
13373       Params.push_back(
13374              std::make_pair(
13375                   CD->getParam(I)->getName(),
13376                   getDerived().TransformType(CD->getParam(I)->getType())));
13377     } else {
13378       Params.push_back(std::make_pair(StringRef(), QualType()));
13379     }
13380   }
13381   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
13382                                      S->getCapturedRegionKind(), Params);
13383   StmtResult Body;
13384   {
13385     Sema::CompoundScopeRAII CompoundScope(getSema());
13386     Body = getDerived().TransformStmt(S->getCapturedStmt());
13387   }
13388
13389   if (Body.isInvalid()) {
13390     getSema().ActOnCapturedRegionError();
13391     return StmtError();
13392   }
13393
13394   return getSema().ActOnCapturedRegionEnd(Body.get());
13395 }
13396
13397 } // end namespace clang
13398
13399 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H