xref: /freebsd/contrib/llvm-project/clang/lib/Sema/TreeTransform.h (revision e6bfd18d21b225af6a0ed67ceeaf1293b7b9eba5)
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/ExprConcepts.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/OpenMPClause.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/StmtObjC.h"
30 #include "clang/AST/StmtOpenMP.h"
31 #include "clang/Basic/DiagnosticParse.h"
32 #include "clang/Basic/OpenMPKinds.h"
33 #include "clang/Sema/Designator.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/Ownership.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaDiagnostic.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include <algorithm>
43 
44 using namespace llvm::omp;
45 
46 namespace clang {
47 using namespace sema;
48 
49 /// A semantic tree transformation that allows one to transform one
50 /// abstract syntax tree into another.
51 ///
52 /// A new tree transformation is defined by creating a new subclass \c X of
53 /// \c TreeTransform<X> and then overriding certain operations to provide
54 /// behavior specific to that transformation. For example, template
55 /// instantiation is implemented as a tree transformation where the
56 /// transformation of TemplateTypeParmType nodes involves substituting the
57 /// template arguments for their corresponding template parameters; a similar
58 /// transformation is performed for non-type template parameters and
59 /// template template parameters.
60 ///
61 /// This tree-transformation template uses static polymorphism to allow
62 /// subclasses to customize any of its operations. Thus, a subclass can
63 /// override any of the transformation or rebuild operators by providing an
64 /// operation with the same signature as the default implementation. The
65 /// overriding function should not be virtual.
66 ///
67 /// Semantic tree transformations are split into two stages, either of which
68 /// can be replaced by a subclass. The "transform" step transforms an AST node
69 /// or the parts of an AST node using the various transformation functions,
70 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
71 /// node of the appropriate kind from the pieces. The default transformation
72 /// routines recursively transform the operands to composite AST nodes (e.g.,
73 /// the pointee type of a PointerType node) and, if any of those operand nodes
74 /// were changed by the transformation, invokes the rebuild operation to create
75 /// a new AST node.
76 ///
77 /// Subclasses can customize the transformation at various levels. The
78 /// most coarse-grained transformations involve replacing TransformType(),
79 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
80 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
81 /// new implementations.
82 ///
83 /// For more fine-grained transformations, subclasses can replace any of the
84 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
85 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
86 /// replacing TransformTemplateTypeParmType() allows template instantiation
87 /// to substitute template arguments for their corresponding template
88 /// parameters. Additionally, subclasses can override the \c RebuildXXX
89 /// functions to control how AST nodes are rebuilt when their operands change.
90 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
91 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
92 /// be able to use more efficient rebuild steps.
93 ///
94 /// There are a handful of other functions that can be overridden, allowing one
95 /// to avoid traversing nodes that don't need any transformation
96 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
97 /// operands have not changed (\c AlwaysRebuild()), and customize the
98 /// default locations and entity names used for type-checking
99 /// (\c getBaseLocation(), \c getBaseEntity()).
100 template<typename Derived>
101 class TreeTransform {
102   /// Private RAII object that helps us forget and then re-remember
103   /// the template argument corresponding to a partially-substituted parameter
104   /// pack.
105   class ForgetPartiallySubstitutedPackRAII {
106     Derived &Self;
107     TemplateArgument Old;
108 
109   public:
110     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
111       Old = Self.ForgetPartiallySubstitutedPack();
112     }
113 
114     ~ForgetPartiallySubstitutedPackRAII() {
115       Self.RememberPartiallySubstitutedPack(Old);
116     }
117   };
118 
119 protected:
120   Sema &SemaRef;
121 
122   /// The set of local declarations that have been transformed, for
123   /// cases where we are forced to build new declarations within the transformer
124   /// rather than in the subclass (e.g., lambda closure types).
125   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
126 
127 public:
128   /// Initializes a new tree transformer.
129   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
130 
131   /// Retrieves a reference to the derived class.
132   Derived &getDerived() { return static_cast<Derived&>(*this); }
133 
134   /// Retrieves a reference to the derived class.
135   const Derived &getDerived() const {
136     return static_cast<const Derived&>(*this);
137   }
138 
139   static inline ExprResult Owned(Expr *E) { return E; }
140   static inline StmtResult Owned(Stmt *S) { return S; }
141 
142   /// Retrieves a reference to the semantic analysis object used for
143   /// this tree transform.
144   Sema &getSema() const { return SemaRef; }
145 
146   /// Whether the transformation should always rebuild AST nodes, even
147   /// if none of the children have changed.
148   ///
149   /// Subclasses may override this function to specify when the transformation
150   /// should rebuild all AST nodes.
151   ///
152   /// We must always rebuild all AST nodes when performing variadic template
153   /// pack expansion, in order to avoid violating the AST invariant that each
154   /// statement node appears at most once in its containing declaration.
155   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
156 
157   /// Whether the transformation is forming an expression or statement that
158   /// replaces the original. In this case, we'll reuse mangling numbers from
159   /// existing lambdas.
160   bool ReplacingOriginal() { return false; }
161 
162   /// Wether CXXConstructExpr can be skipped when they are implicit.
163   /// They will be reconstructed when used if needed.
164   /// This is useful when the user that cause rebuilding of the
165   /// CXXConstructExpr is outside of the expression at which the TreeTransform
166   /// started.
167   bool AllowSkippingCXXConstructExpr() { return true; }
168 
169   /// Returns the location of the entity being transformed, if that
170   /// information was not available elsewhere in the AST.
171   ///
172   /// By default, returns no source-location information. Subclasses can
173   /// provide an alternative implementation that provides better location
174   /// information.
175   SourceLocation getBaseLocation() { return SourceLocation(); }
176 
177   /// Returns the name of the entity being transformed, if that
178   /// information was not available elsewhere in the AST.
179   ///
180   /// By default, returns an empty name. Subclasses can provide an alternative
181   /// implementation with a more precise name.
182   DeclarationName getBaseEntity() { return DeclarationName(); }
183 
184   /// Sets the "base" location and entity when that
185   /// information is known based on another transformation.
186   ///
187   /// By default, the source location and entity are ignored. Subclasses can
188   /// override this function to provide a customized implementation.
189   void setBase(SourceLocation Loc, DeclarationName Entity) { }
190 
191   /// RAII object that temporarily sets the base location and entity
192   /// used for reporting diagnostics in types.
193   class TemporaryBase {
194     TreeTransform &Self;
195     SourceLocation OldLocation;
196     DeclarationName OldEntity;
197 
198   public:
199     TemporaryBase(TreeTransform &Self, SourceLocation Location,
200                   DeclarationName Entity) : Self(Self) {
201       OldLocation = Self.getDerived().getBaseLocation();
202       OldEntity = Self.getDerived().getBaseEntity();
203 
204       if (Location.isValid())
205         Self.getDerived().setBase(Location, Entity);
206     }
207 
208     ~TemporaryBase() {
209       Self.getDerived().setBase(OldLocation, OldEntity);
210     }
211   };
212 
213   /// Determine whether the given type \p T has already been
214   /// transformed.
215   ///
216   /// Subclasses can provide an alternative implementation of this routine
217   /// to short-circuit evaluation when it is known that a given type will
218   /// not change. For example, template instantiation need not traverse
219   /// non-dependent types.
220   bool AlreadyTransformed(QualType T) {
221     return T.isNull();
222   }
223 
224   /// Transform a template parameter depth level.
225   ///
226   /// During a transformation that transforms template parameters, this maps
227   /// an old template parameter depth to a new depth.
228   unsigned TransformTemplateDepth(unsigned Depth) {
229     return Depth;
230   }
231 
232   /// Determine whether the given call argument should be dropped, e.g.,
233   /// because it is a default argument.
234   ///
235   /// Subclasses can provide an alternative implementation of this routine to
236   /// determine which kinds of call arguments get dropped. By default,
237   /// CXXDefaultArgument nodes are dropped (prior to transformation).
238   bool DropCallArgument(Expr *E) {
239     return E->isDefaultArgument();
240   }
241 
242   /// Determine whether we should expand a pack expansion with the
243   /// given set of parameter packs into separate arguments by repeatedly
244   /// transforming the pattern.
245   ///
246   /// By default, the transformer never tries to expand pack expansions.
247   /// Subclasses can override this routine to provide different behavior.
248   ///
249   /// \param EllipsisLoc The location of the ellipsis that identifies the
250   /// pack expansion.
251   ///
252   /// \param PatternRange The source range that covers the entire pattern of
253   /// the pack expansion.
254   ///
255   /// \param Unexpanded The set of unexpanded parameter packs within the
256   /// pattern.
257   ///
258   /// \param ShouldExpand Will be set to \c true if the transformer should
259   /// expand the corresponding pack expansions into separate arguments. When
260   /// set, \c NumExpansions must also be set.
261   ///
262   /// \param RetainExpansion Whether the caller should add an unexpanded
263   /// pack expansion after all of the expanded arguments. This is used
264   /// when extending explicitly-specified template argument packs per
265   /// C++0x [temp.arg.explicit]p9.
266   ///
267   /// \param NumExpansions The number of separate arguments that will be in
268   /// the expanded form of the corresponding pack expansion. This is both an
269   /// input and an output parameter, which can be set by the caller if the
270   /// number of expansions is known a priori (e.g., due to a prior substitution)
271   /// and will be set by the callee when the number of expansions is known.
272   /// The callee must set this value when \c ShouldExpand is \c true; it may
273   /// set this value in other cases.
274   ///
275   /// \returns true if an error occurred (e.g., because the parameter packs
276   /// are to be instantiated with arguments of different lengths), false
277   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
278   /// must be set.
279   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
280                                SourceRange PatternRange,
281                                ArrayRef<UnexpandedParameterPack> Unexpanded,
282                                bool &ShouldExpand,
283                                bool &RetainExpansion,
284                                Optional<unsigned> &NumExpansions) {
285     ShouldExpand = false;
286     return false;
287   }
288 
289   /// "Forget" about the partially-substituted pack template argument,
290   /// when performing an instantiation that must preserve the parameter pack
291   /// use.
292   ///
293   /// This routine is meant to be overridden by the template instantiator.
294   TemplateArgument ForgetPartiallySubstitutedPack() {
295     return TemplateArgument();
296   }
297 
298   /// "Remember" the partially-substituted pack template argument
299   /// after performing an instantiation that must preserve the parameter pack
300   /// use.
301   ///
302   /// This routine is meant to be overridden by the template instantiator.
303   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
304 
305   /// Note to the derived class when a function parameter pack is
306   /// being expanded.
307   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
308 
309   /// Transforms the given type into another type.
310   ///
311   /// By default, this routine transforms a type by creating a
312   /// TypeSourceInfo for it and delegating to the appropriate
313   /// function.  This is expensive, but we don't mind, because
314   /// this method is deprecated anyway;  all users should be
315   /// switched to storing TypeSourceInfos.
316   ///
317   /// \returns the transformed type.
318   QualType TransformType(QualType T);
319 
320   /// Transforms the given type-with-location into a new
321   /// type-with-location.
322   ///
323   /// By default, this routine transforms a type by delegating to the
324   /// appropriate TransformXXXType to build a new type.  Subclasses
325   /// may override this function (to take over all type
326   /// transformations) or some set of the TransformXXXType functions
327   /// to alter the transformation.
328   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
329 
330   /// Transform the given type-with-location into a new
331   /// type, collecting location information in the given builder
332   /// as necessary.
333   ///
334   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
335 
336   /// Transform a type that is permitted to produce a
337   /// DeducedTemplateSpecializationType.
338   ///
339   /// This is used in the (relatively rare) contexts where it is acceptable
340   /// for transformation to produce a class template type with deduced
341   /// template arguments.
342   /// @{
343   QualType TransformTypeWithDeducedTST(QualType T);
344   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
345   /// @}
346 
347   /// The reason why the value of a statement is not discarded, if any.
348   enum StmtDiscardKind {
349     SDK_Discarded,
350     SDK_NotDiscarded,
351     SDK_StmtExprResult,
352   };
353 
354   /// Transform the given statement.
355   ///
356   /// By default, this routine transforms a statement by delegating to the
357   /// appropriate TransformXXXStmt function to transform a specific kind of
358   /// statement or the TransformExpr() function to transform an expression.
359   /// Subclasses may override this function to transform statements using some
360   /// other mechanism.
361   ///
362   /// \returns the transformed statement.
363   StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
364 
365   /// Transform the given statement.
366   ///
367   /// By default, this routine transforms a statement by delegating to the
368   /// appropriate TransformOMPXXXClause function to transform a specific kind
369   /// of clause. Subclasses may override this function to transform statements
370   /// using some other mechanism.
371   ///
372   /// \returns the transformed OpenMP clause.
373   OMPClause *TransformOMPClause(OMPClause *S);
374 
375   /// Transform the given attribute.
376   ///
377   /// By default, this routine transforms a statement by delegating to the
378   /// appropriate TransformXXXAttr function to transform a specific kind
379   /// of attribute. Subclasses may override this function to transform
380   /// attributed statements using some other mechanism.
381   ///
382   /// \returns the transformed attribute
383   const Attr *TransformAttr(const Attr *S);
384 
385 /// Transform the specified attribute.
386 ///
387 /// Subclasses should override the transformation of attributes with a pragma
388 /// spelling to transform expressions stored within the attribute.
389 ///
390 /// \returns the transformed attribute.
391 #define ATTR(X)
392 #define PRAGMA_SPELLING_ATTR(X)                                                \
393   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
394 #include "clang/Basic/AttrList.inc"
395 
396   /// Transform the given expression.
397   ///
398   /// By default, this routine transforms an expression by delegating to the
399   /// appropriate TransformXXXExpr function to build a new expression.
400   /// Subclasses may override this function to transform expressions using some
401   /// other mechanism.
402   ///
403   /// \returns the transformed expression.
404   ExprResult TransformExpr(Expr *E);
405 
406   /// Transform the given initializer.
407   ///
408   /// By default, this routine transforms an initializer by stripping off the
409   /// semantic nodes added by initialization, then passing the result to
410   /// TransformExpr or TransformExprs.
411   ///
412   /// \returns the transformed initializer.
413   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
414 
415   /// Transform the given list of expressions.
416   ///
417   /// This routine transforms a list of expressions by invoking
418   /// \c TransformExpr() for each subexpression. However, it also provides
419   /// support for variadic templates by expanding any pack expansions (if the
420   /// derived class permits such expansion) along the way. When pack expansions
421   /// are present, the number of outputs may not equal the number of inputs.
422   ///
423   /// \param Inputs The set of expressions to be transformed.
424   ///
425   /// \param NumInputs The number of expressions in \c Inputs.
426   ///
427   /// \param IsCall If \c true, then this transform is being performed on
428   /// function-call arguments, and any arguments that should be dropped, will
429   /// be.
430   ///
431   /// \param Outputs The transformed input expressions will be added to this
432   /// vector.
433   ///
434   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
435   /// due to transformation.
436   ///
437   /// \returns true if an error occurred, false otherwise.
438   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
439                       SmallVectorImpl<Expr *> &Outputs,
440                       bool *ArgChanged = nullptr);
441 
442   /// Transform the given declaration, which is referenced from a type
443   /// or expression.
444   ///
445   /// By default, acts as the identity function on declarations, unless the
446   /// transformer has had to transform the declaration itself. Subclasses
447   /// may override this function to provide alternate behavior.
448   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
449     llvm::DenseMap<Decl *, Decl *>::iterator Known
450       = TransformedLocalDecls.find(D);
451     if (Known != TransformedLocalDecls.end())
452       return Known->second;
453 
454     return D;
455   }
456 
457   /// Transform the specified condition.
458   ///
459   /// By default, this transforms the variable and expression and rebuilds
460   /// the condition.
461   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
462                                            Expr *Expr,
463                                            Sema::ConditionKind Kind);
464 
465   /// Transform the attributes associated with the given declaration and
466   /// place them on the new declaration.
467   ///
468   /// By default, this operation does nothing. Subclasses may override this
469   /// behavior to transform attributes.
470   void transformAttrs(Decl *Old, Decl *New) { }
471 
472   /// Note that a local declaration has been transformed by this
473   /// transformer.
474   ///
475   /// Local declarations are typically transformed via a call to
476   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
477   /// the transformer itself has to transform the declarations. This routine
478   /// can be overridden by a subclass that keeps track of such mappings.
479   void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
480     assert(New.size() == 1 &&
481            "must override transformedLocalDecl if performing pack expansion");
482     TransformedLocalDecls[Old] = New.front();
483   }
484 
485   /// Transform the definition of the given declaration.
486   ///
487   /// By default, invokes TransformDecl() to transform the declaration.
488   /// Subclasses may override this function to provide alternate behavior.
489   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
490     return getDerived().TransformDecl(Loc, D);
491   }
492 
493   /// Transform the given declaration, which was the first part of a
494   /// nested-name-specifier in a member access expression.
495   ///
496   /// This specific declaration transformation only applies to the first
497   /// identifier in a nested-name-specifier of a member access expression, e.g.,
498   /// the \c T in \c x->T::member
499   ///
500   /// By default, invokes TransformDecl() to transform the declaration.
501   /// Subclasses may override this function to provide alternate behavior.
502   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
503     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
504   }
505 
506   /// Transform the set of declarations in an OverloadExpr.
507   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
508                                   LookupResult &R);
509 
510   /// Transform the given nested-name-specifier with source-location
511   /// information.
512   ///
513   /// By default, transforms all of the types and declarations within the
514   /// nested-name-specifier. Subclasses may override this function to provide
515   /// alternate behavior.
516   NestedNameSpecifierLoc
517   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
518                                   QualType ObjectType = QualType(),
519                                   NamedDecl *FirstQualifierInScope = nullptr);
520 
521   /// Transform the given declaration name.
522   ///
523   /// By default, transforms the types of conversion function, constructor,
524   /// and destructor names and then (if needed) rebuilds the declaration name.
525   /// Identifiers and selectors are returned unmodified. Subclasses may
526   /// override this function to provide alternate behavior.
527   DeclarationNameInfo
528   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
529 
530   bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
531       llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
532   concepts::TypeRequirement *
533   TransformTypeRequirement(concepts::TypeRequirement *Req);
534   concepts::ExprRequirement *
535   TransformExprRequirement(concepts::ExprRequirement *Req);
536   concepts::NestedRequirement *
537   TransformNestedRequirement(concepts::NestedRequirement *Req);
538 
539   /// Transform the given template name.
540   ///
541   /// \param SS The nested-name-specifier that qualifies the template
542   /// name. This nested-name-specifier must already have been transformed.
543   ///
544   /// \param Name The template name to transform.
545   ///
546   /// \param NameLoc The source location of the template name.
547   ///
548   /// \param ObjectType If we're translating a template name within a member
549   /// access expression, this is the type of the object whose member template
550   /// is being referenced.
551   ///
552   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
553   /// also refers to a name within the current (lexical) scope, this is the
554   /// declaration it refers to.
555   ///
556   /// By default, transforms the template name by transforming the declarations
557   /// and nested-name-specifiers that occur within the template name.
558   /// Subclasses may override this function to provide alternate behavior.
559   TemplateName
560   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
561                         SourceLocation NameLoc,
562                         QualType ObjectType = QualType(),
563                         NamedDecl *FirstQualifierInScope = nullptr,
564                         bool AllowInjectedClassName = false);
565 
566   /// Transform the given template argument.
567   ///
568   /// By default, this operation transforms the type, expression, or
569   /// declaration stored within the template argument and constructs a
570   /// new template argument from the transformed result. Subclasses may
571   /// override this function to provide alternate behavior.
572   ///
573   /// Returns true if there was an error.
574   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
575                                  TemplateArgumentLoc &Output,
576                                  bool Uneval = false);
577 
578   /// Transform the given set of template arguments.
579   ///
580   /// By default, this operation transforms all of the template arguments
581   /// in the input set using \c TransformTemplateArgument(), and appends
582   /// the transformed arguments to the output list.
583   ///
584   /// Note that this overload of \c TransformTemplateArguments() is merely
585   /// a convenience function. Subclasses that wish to override this behavior
586   /// should override the iterator-based member template version.
587   ///
588   /// \param Inputs The set of template arguments to be transformed.
589   ///
590   /// \param NumInputs The number of template arguments in \p Inputs.
591   ///
592   /// \param Outputs The set of transformed template arguments output by this
593   /// routine.
594   ///
595   /// Returns true if an error occurred.
596   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
597                                   unsigned NumInputs,
598                                   TemplateArgumentListInfo &Outputs,
599                                   bool Uneval = false) {
600     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
601                                       Uneval);
602   }
603 
604   /// Transform the given set of template arguments.
605   ///
606   /// By default, this operation transforms all of the template arguments
607   /// in the input set using \c TransformTemplateArgument(), and appends
608   /// the transformed arguments to the output list.
609   ///
610   /// \param First An iterator to the first template argument.
611   ///
612   /// \param Last An iterator one step past the last template argument.
613   ///
614   /// \param Outputs The set of transformed template arguments output by this
615   /// routine.
616   ///
617   /// Returns true if an error occurred.
618   template<typename InputIterator>
619   bool TransformTemplateArguments(InputIterator First,
620                                   InputIterator Last,
621                                   TemplateArgumentListInfo &Outputs,
622                                   bool Uneval = false);
623 
624   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
625   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
626                                  TemplateArgumentLoc &ArgLoc);
627 
628   /// Fakes up a TypeSourceInfo for a type.
629   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
630     return SemaRef.Context.getTrivialTypeSourceInfo(T,
631                        getDerived().getBaseLocation());
632   }
633 
634 #define ABSTRACT_TYPELOC(CLASS, PARENT)
635 #define TYPELOC(CLASS, PARENT)                                   \
636   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
637 #include "clang/AST/TypeLocNodes.def"
638 
639   template<typename Fn>
640   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
641                                       FunctionProtoTypeLoc TL,
642                                       CXXRecordDecl *ThisContext,
643                                       Qualifiers ThisTypeQuals,
644                                       Fn TransformExceptionSpec);
645 
646   bool TransformExceptionSpec(SourceLocation Loc,
647                               FunctionProtoType::ExceptionSpecInfo &ESI,
648                               SmallVectorImpl<QualType> &Exceptions,
649                               bool &Changed);
650 
651   StmtResult TransformSEHHandler(Stmt *Handler);
652 
653   QualType
654   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
655                                       TemplateSpecializationTypeLoc TL,
656                                       TemplateName Template);
657 
658   QualType
659   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
660                                       DependentTemplateSpecializationTypeLoc TL,
661                                                TemplateName Template,
662                                                CXXScopeSpec &SS);
663 
664   QualType TransformDependentTemplateSpecializationType(
665       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
666       NestedNameSpecifierLoc QualifierLoc);
667 
668   /// Transforms the parameters of a function type into the
669   /// given vectors.
670   ///
671   /// The result vectors should be kept in sync; null entries in the
672   /// variables vector are acceptable.
673   ///
674   /// Return true on error.
675   bool TransformFunctionTypeParams(
676       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
677       const QualType *ParamTypes,
678       const FunctionProtoType::ExtParameterInfo *ParamInfos,
679       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
680       Sema::ExtParameterInfoBuilder &PInfos);
681 
682   /// Transforms a single function-type parameter.  Return null
683   /// on error.
684   ///
685   /// \param indexAdjustment - A number to add to the parameter's
686   ///   scope index;  can be negative
687   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
688                                           int indexAdjustment,
689                                           Optional<unsigned> NumExpansions,
690                                           bool ExpectParameterPack);
691 
692   /// Transform the body of a lambda-expression.
693   StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
694   /// Alternative implementation of TransformLambdaBody that skips transforming
695   /// the body.
696   StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
697 
698   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
699 
700   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
701   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
702 
703   TemplateParameterList *TransformTemplateParameterList(
704         TemplateParameterList *TPL) {
705     return TPL;
706   }
707 
708   ExprResult TransformAddressOfOperand(Expr *E);
709 
710   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
711                                                 bool IsAddressOfOperand,
712                                                 TypeSourceInfo **RecoveryTSI);
713 
714   ExprResult TransformParenDependentScopeDeclRefExpr(
715       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
716       TypeSourceInfo **RecoveryTSI);
717 
718   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
719 
720 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
721 // amount of stack usage with clang.
722 #define STMT(Node, Parent)                        \
723   LLVM_ATTRIBUTE_NOINLINE \
724   StmtResult Transform##Node(Node *S);
725 #define VALUESTMT(Node, Parent)                   \
726   LLVM_ATTRIBUTE_NOINLINE \
727   StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
728 #define EXPR(Node, Parent)                        \
729   LLVM_ATTRIBUTE_NOINLINE \
730   ExprResult Transform##Node(Node *E);
731 #define ABSTRACT_STMT(Stmt)
732 #include "clang/AST/StmtNodes.inc"
733 
734 #define GEN_CLANG_CLAUSE_CLASS
735 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
736   LLVM_ATTRIBUTE_NOINLINE                                                      \
737   OMPClause *Transform##Class(Class *S);
738 #include "llvm/Frontend/OpenMP/OMP.inc"
739 
740   /// Build a new qualified type given its unqualified type and type location.
741   ///
742   /// By default, this routine adds type qualifiers only to types that can
743   /// have qualifiers, and silently suppresses those qualifiers that are not
744   /// permitted. Subclasses may override this routine to provide different
745   /// behavior.
746   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
747 
748   /// Build a new pointer type given its pointee type.
749   ///
750   /// By default, performs semantic analysis when building the pointer type.
751   /// Subclasses may override this routine to provide different behavior.
752   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
753 
754   /// Build a new block pointer type given its pointee type.
755   ///
756   /// By default, performs semantic analysis when building the block pointer
757   /// type. Subclasses may override this routine to provide different behavior.
758   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
759 
760   /// Build a new reference type given the type it references.
761   ///
762   /// By default, performs semantic analysis when building the
763   /// reference type. Subclasses may override this routine to provide
764   /// different behavior.
765   ///
766   /// \param LValue whether the type was written with an lvalue sigil
767   /// or an rvalue sigil.
768   QualType RebuildReferenceType(QualType ReferentType,
769                                 bool LValue,
770                                 SourceLocation Sigil);
771 
772   /// Build a new member pointer type given the pointee type and the
773   /// class type it refers into.
774   ///
775   /// By default, performs semantic analysis when building the member pointer
776   /// type. Subclasses may override this routine to provide different behavior.
777   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
778                                     SourceLocation Sigil);
779 
780   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
781                                     SourceLocation ProtocolLAngleLoc,
782                                     ArrayRef<ObjCProtocolDecl *> Protocols,
783                                     ArrayRef<SourceLocation> ProtocolLocs,
784                                     SourceLocation ProtocolRAngleLoc);
785 
786   /// Build an Objective-C object type.
787   ///
788   /// By default, performs semantic analysis when building the object type.
789   /// Subclasses may override this routine to provide different behavior.
790   QualType RebuildObjCObjectType(QualType BaseType,
791                                  SourceLocation Loc,
792                                  SourceLocation TypeArgsLAngleLoc,
793                                  ArrayRef<TypeSourceInfo *> TypeArgs,
794                                  SourceLocation TypeArgsRAngleLoc,
795                                  SourceLocation ProtocolLAngleLoc,
796                                  ArrayRef<ObjCProtocolDecl *> Protocols,
797                                  ArrayRef<SourceLocation> ProtocolLocs,
798                                  SourceLocation ProtocolRAngleLoc);
799 
800   /// Build a new Objective-C object pointer type given the pointee type.
801   ///
802   /// By default, directly builds the pointer type, with no additional semantic
803   /// analysis.
804   QualType RebuildObjCObjectPointerType(QualType PointeeType,
805                                         SourceLocation Star);
806 
807   /// Build a new array type given the element type, size
808   /// modifier, size of the array (if known), size expression, and index type
809   /// qualifiers.
810   ///
811   /// By default, performs semantic analysis when building the array type.
812   /// Subclasses may override this routine to provide different behavior.
813   /// Also by default, all of the other Rebuild*Array
814   QualType RebuildArrayType(QualType ElementType,
815                             ArrayType::ArraySizeModifier SizeMod,
816                             const llvm::APInt *Size,
817                             Expr *SizeExpr,
818                             unsigned IndexTypeQuals,
819                             SourceRange BracketsRange);
820 
821   /// Build a new constant array type given the element type, size
822   /// modifier, (known) size of the array, and index type qualifiers.
823   ///
824   /// By default, performs semantic analysis when building the array type.
825   /// Subclasses may override this routine to provide different behavior.
826   QualType RebuildConstantArrayType(QualType ElementType,
827                                     ArrayType::ArraySizeModifier SizeMod,
828                                     const llvm::APInt &Size,
829                                     Expr *SizeExpr,
830                                     unsigned IndexTypeQuals,
831                                     SourceRange BracketsRange);
832 
833   /// Build a new incomplete array type given the element type, size
834   /// modifier, and index type qualifiers.
835   ///
836   /// By default, performs semantic analysis when building the array type.
837   /// Subclasses may override this routine to provide different behavior.
838   QualType RebuildIncompleteArrayType(QualType ElementType,
839                                       ArrayType::ArraySizeModifier SizeMod,
840                                       unsigned IndexTypeQuals,
841                                       SourceRange BracketsRange);
842 
843   /// Build a new variable-length array type given the element type,
844   /// size modifier, size expression, and index type qualifiers.
845   ///
846   /// By default, performs semantic analysis when building the array type.
847   /// Subclasses may override this routine to provide different behavior.
848   QualType RebuildVariableArrayType(QualType ElementType,
849                                     ArrayType::ArraySizeModifier SizeMod,
850                                     Expr *SizeExpr,
851                                     unsigned IndexTypeQuals,
852                                     SourceRange BracketsRange);
853 
854   /// Build a new dependent-sized array type given the element type,
855   /// size modifier, size expression, and index type qualifiers.
856   ///
857   /// By default, performs semantic analysis when building the array type.
858   /// Subclasses may override this routine to provide different behavior.
859   QualType RebuildDependentSizedArrayType(QualType ElementType,
860                                           ArrayType::ArraySizeModifier SizeMod,
861                                           Expr *SizeExpr,
862                                           unsigned IndexTypeQuals,
863                                           SourceRange BracketsRange);
864 
865   /// Build a new vector type given the element type and
866   /// number of elements.
867   ///
868   /// By default, performs semantic analysis when building the vector type.
869   /// Subclasses may override this routine to provide different behavior.
870   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
871                              VectorType::VectorKind VecKind);
872 
873   /// Build a new potentially dependently-sized extended vector type
874   /// given the element type and number of elements.
875   ///
876   /// By default, performs semantic analysis when building the vector type.
877   /// Subclasses may override this routine to provide different behavior.
878   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
879                                            SourceLocation AttributeLoc,
880                                            VectorType::VectorKind);
881 
882   /// Build a new extended vector type given the element type and
883   /// number of elements.
884   ///
885   /// By default, performs semantic analysis when building the vector type.
886   /// Subclasses may override this routine to provide different behavior.
887   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
888                                 SourceLocation AttributeLoc);
889 
890   /// Build a new potentially dependently-sized extended vector type
891   /// given the element type and number of elements.
892   ///
893   /// By default, performs semantic analysis when building the vector type.
894   /// Subclasses may override this routine to provide different behavior.
895   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
896                                               Expr *SizeExpr,
897                                               SourceLocation AttributeLoc);
898 
899   /// Build a new matrix type given the element type and dimensions.
900   QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
901                                      unsigned NumColumns);
902 
903   /// Build a new matrix type given the type and dependently-defined
904   /// dimensions.
905   QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
906                                            Expr *ColumnExpr,
907                                            SourceLocation AttributeLoc);
908 
909   /// Build a new DependentAddressSpaceType or return the pointee
910   /// type variable with the correct address space (retrieved from
911   /// AddrSpaceExpr) applied to it. The former will be returned in cases
912   /// where the address space remains dependent.
913   ///
914   /// By default, performs semantic analysis when building the type with address
915   /// space applied. Subclasses may override this routine to provide different
916   /// behavior.
917   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
918                                             Expr *AddrSpaceExpr,
919                                             SourceLocation AttributeLoc);
920 
921   /// Build a new function type.
922   ///
923   /// By default, performs semantic analysis when building the function type.
924   /// Subclasses may override this routine to provide different behavior.
925   QualType RebuildFunctionProtoType(QualType T,
926                                     MutableArrayRef<QualType> ParamTypes,
927                                     const FunctionProtoType::ExtProtoInfo &EPI);
928 
929   /// Build a new unprototyped function type.
930   QualType RebuildFunctionNoProtoType(QualType ResultType);
931 
932   /// Rebuild an unresolved typename type, given the decl that
933   /// the UnresolvedUsingTypenameDecl was transformed to.
934   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
935 
936   /// Build a new type found via an alias.
937   QualType RebuildUsingType(UsingShadowDecl *Found, QualType Underlying) {
938     return SemaRef.Context.getUsingType(Found, Underlying);
939   }
940 
941   /// Build a new typedef type.
942   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
943     return SemaRef.Context.getTypeDeclType(Typedef);
944   }
945 
946   /// Build a new MacroDefined type.
947   QualType RebuildMacroQualifiedType(QualType T,
948                                      const IdentifierInfo *MacroII) {
949     return SemaRef.Context.getMacroQualifiedType(T, MacroII);
950   }
951 
952   /// Build a new class/struct/union type.
953   QualType RebuildRecordType(RecordDecl *Record) {
954     return SemaRef.Context.getTypeDeclType(Record);
955   }
956 
957   /// Build a new Enum type.
958   QualType RebuildEnumType(EnumDecl *Enum) {
959     return SemaRef.Context.getTypeDeclType(Enum);
960   }
961 
962   /// Build a new typeof(expr) type.
963   ///
964   /// By default, performs semantic analysis when building the typeof type.
965   /// Subclasses may override this routine to provide different behavior.
966   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
967 
968   /// Build a new typeof(type) type.
969   ///
970   /// By default, builds a new TypeOfType with the given underlying type.
971   QualType RebuildTypeOfType(QualType Underlying);
972 
973   /// Build a new unary transform type.
974   QualType RebuildUnaryTransformType(QualType BaseType,
975                                      UnaryTransformType::UTTKind UKind,
976                                      SourceLocation Loc);
977 
978   /// Build a new C++11 decltype type.
979   ///
980   /// By default, performs semantic analysis when building the decltype type.
981   /// Subclasses may override this routine to provide different behavior.
982   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
983 
984   /// Build a new C++11 auto type.
985   ///
986   /// By default, builds a new AutoType with the given deduced type.
987   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
988                            ConceptDecl *TypeConstraintConcept,
989                            ArrayRef<TemplateArgument> TypeConstraintArgs) {
990     // Note, IsDependent is always false here: we implicitly convert an 'auto'
991     // which has been deduced to a dependent type into an undeduced 'auto', so
992     // that we'll retry deduction after the transformation.
993     return SemaRef.Context.getAutoType(Deduced, Keyword,
994                                        /*IsDependent*/ false, /*IsPack=*/false,
995                                        TypeConstraintConcept,
996                                        TypeConstraintArgs);
997   }
998 
999   /// By default, builds a new DeducedTemplateSpecializationType with the given
1000   /// deduced type.
1001   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
1002       QualType Deduced) {
1003     return SemaRef.Context.getDeducedTemplateSpecializationType(
1004         Template, Deduced, /*IsDependent*/ false);
1005   }
1006 
1007   /// Build a new template specialization type.
1008   ///
1009   /// By default, performs semantic analysis when building the template
1010   /// specialization type. Subclasses may override this routine to provide
1011   /// different behavior.
1012   QualType RebuildTemplateSpecializationType(TemplateName Template,
1013                                              SourceLocation TemplateLoc,
1014                                              TemplateArgumentListInfo &Args);
1015 
1016   /// Build a new parenthesized type.
1017   ///
1018   /// By default, builds a new ParenType type from the inner type.
1019   /// Subclasses may override this routine to provide different behavior.
1020   QualType RebuildParenType(QualType InnerType) {
1021     return SemaRef.BuildParenType(InnerType);
1022   }
1023 
1024   /// Build a new qualified name type.
1025   ///
1026   /// By default, builds a new ElaboratedType type from the keyword,
1027   /// the nested-name-specifier and the named type.
1028   /// Subclasses may override this routine to provide different behavior.
1029   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1030                                  ElaboratedTypeKeyword Keyword,
1031                                  NestedNameSpecifierLoc QualifierLoc,
1032                                  QualType Named) {
1033     return SemaRef.Context.getElaboratedType(Keyword,
1034                                          QualifierLoc.getNestedNameSpecifier(),
1035                                              Named);
1036   }
1037 
1038   /// Build a new typename type that refers to a template-id.
1039   ///
1040   /// By default, builds a new DependentNameType type from the
1041   /// nested-name-specifier and the given type. Subclasses may override
1042   /// this routine to provide different behavior.
1043   QualType RebuildDependentTemplateSpecializationType(
1044                                           ElaboratedTypeKeyword Keyword,
1045                                           NestedNameSpecifierLoc QualifierLoc,
1046                                           SourceLocation TemplateKWLoc,
1047                                           const IdentifierInfo *Name,
1048                                           SourceLocation NameLoc,
1049                                           TemplateArgumentListInfo &Args,
1050                                           bool AllowInjectedClassName) {
1051     // Rebuild the template name.
1052     // TODO: avoid TemplateName abstraction
1053     CXXScopeSpec SS;
1054     SS.Adopt(QualifierLoc);
1055     TemplateName InstName = getDerived().RebuildTemplateName(
1056         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1057         AllowInjectedClassName);
1058 
1059     if (InstName.isNull())
1060       return QualType();
1061 
1062     // If it's still dependent, make a dependent specialization.
1063     if (InstName.getAsDependentTemplateName())
1064       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
1065                                           QualifierLoc.getNestedNameSpecifier(),
1066                                                                     Name,
1067                                                                     Args);
1068 
1069     // Otherwise, make an elaborated type wrapping a non-dependent
1070     // specialization.
1071     QualType T =
1072     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1073     if (T.isNull()) return QualType();
1074 
1075     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
1076       return T;
1077 
1078     return SemaRef.Context.getElaboratedType(Keyword,
1079                                        QualifierLoc.getNestedNameSpecifier(),
1080                                              T);
1081   }
1082 
1083   /// Build a new typename type that refers to an identifier.
1084   ///
1085   /// By default, performs semantic analysis when building the typename type
1086   /// (or elaborated type). Subclasses may override this routine to provide
1087   /// different behavior.
1088   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1089                                     SourceLocation KeywordLoc,
1090                                     NestedNameSpecifierLoc QualifierLoc,
1091                                     const IdentifierInfo *Id,
1092                                     SourceLocation IdLoc,
1093                                     bool DeducedTSTContext) {
1094     CXXScopeSpec SS;
1095     SS.Adopt(QualifierLoc);
1096 
1097     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1098       // If the name is still dependent, just build a new dependent name type.
1099       if (!SemaRef.computeDeclContext(SS))
1100         return SemaRef.Context.getDependentNameType(Keyword,
1101                                           QualifierLoc.getNestedNameSpecifier(),
1102                                                     Id);
1103     }
1104 
1105     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1106       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1107                                        *Id, IdLoc, DeducedTSTContext);
1108     }
1109 
1110     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1111 
1112     // We had a dependent elaborated-type-specifier that has been transformed
1113     // into a non-dependent elaborated-type-specifier. Find the tag we're
1114     // referring to.
1115     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1116     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1117     if (!DC)
1118       return QualType();
1119 
1120     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1121       return QualType();
1122 
1123     TagDecl *Tag = nullptr;
1124     SemaRef.LookupQualifiedName(Result, DC);
1125     switch (Result.getResultKind()) {
1126       case LookupResult::NotFound:
1127       case LookupResult::NotFoundInCurrentInstantiation:
1128         break;
1129 
1130       case LookupResult::Found:
1131         Tag = Result.getAsSingle<TagDecl>();
1132         break;
1133 
1134       case LookupResult::FoundOverloaded:
1135       case LookupResult::FoundUnresolvedValue:
1136         llvm_unreachable("Tag lookup cannot find non-tags");
1137 
1138       case LookupResult::Ambiguous:
1139         // Let the LookupResult structure handle ambiguities.
1140         return QualType();
1141     }
1142 
1143     if (!Tag) {
1144       // Check where the name exists but isn't a tag type and use that to emit
1145       // better diagnostics.
1146       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1147       SemaRef.LookupQualifiedName(Result, DC);
1148       switch (Result.getResultKind()) {
1149         case LookupResult::Found:
1150         case LookupResult::FoundOverloaded:
1151         case LookupResult::FoundUnresolvedValue: {
1152           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1153           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1154           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1155                                                                << NTK << Kind;
1156           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1157           break;
1158         }
1159         default:
1160           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1161               << Kind << Id << DC << QualifierLoc.getSourceRange();
1162           break;
1163       }
1164       return QualType();
1165     }
1166 
1167     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1168                                               IdLoc, Id)) {
1169       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1170       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1171       return QualType();
1172     }
1173 
1174     // Build the elaborated-type-specifier type.
1175     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1176     return SemaRef.Context.getElaboratedType(Keyword,
1177                                          QualifierLoc.getNestedNameSpecifier(),
1178                                              T);
1179   }
1180 
1181   /// Build a new pack expansion type.
1182   ///
1183   /// By default, builds a new PackExpansionType type from the given pattern.
1184   /// Subclasses may override this routine to provide different behavior.
1185   QualType RebuildPackExpansionType(QualType Pattern,
1186                                     SourceRange PatternRange,
1187                                     SourceLocation EllipsisLoc,
1188                                     Optional<unsigned> NumExpansions) {
1189     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1190                                         NumExpansions);
1191   }
1192 
1193   /// Build a new atomic type given its value type.
1194   ///
1195   /// By default, performs semantic analysis when building the atomic type.
1196   /// Subclasses may override this routine to provide different behavior.
1197   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1198 
1199   /// Build a new pipe type given its value type.
1200   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1201                            bool isReadPipe);
1202 
1203   /// Build a bit-precise int given its value type.
1204   QualType RebuildBitIntType(bool IsUnsigned, unsigned NumBits,
1205                              SourceLocation Loc);
1206 
1207   /// Build a dependent bit-precise int given its value type.
1208   QualType RebuildDependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr,
1209                                       SourceLocation Loc);
1210 
1211   /// Build a new template name given a nested name specifier, a flag
1212   /// indicating whether the "template" keyword was provided, and the template
1213   /// that the template name refers to.
1214   ///
1215   /// By default, builds the new template name directly. Subclasses may override
1216   /// this routine to provide different behavior.
1217   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1218                                    bool TemplateKW,
1219                                    TemplateDecl *Template);
1220 
1221   /// Build a new template name given a nested name specifier and the
1222   /// name that is referred to as a template.
1223   ///
1224   /// By default, performs semantic analysis to determine whether the name can
1225   /// be resolved to a specific template, then builds the appropriate kind of
1226   /// template name. Subclasses may override this routine to provide different
1227   /// behavior.
1228   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1229                                    SourceLocation TemplateKWLoc,
1230                                    const IdentifierInfo &Name,
1231                                    SourceLocation NameLoc, QualType ObjectType,
1232                                    NamedDecl *FirstQualifierInScope,
1233                                    bool AllowInjectedClassName);
1234 
1235   /// Build a new template name given a nested name specifier and the
1236   /// overloaded operator name that is referred to as a template.
1237   ///
1238   /// By default, performs semantic analysis to determine whether the name can
1239   /// be resolved to a specific template, then builds the appropriate kind of
1240   /// template name. Subclasses may override this routine to provide different
1241   /// behavior.
1242   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1243                                    SourceLocation TemplateKWLoc,
1244                                    OverloadedOperatorKind Operator,
1245                                    SourceLocation NameLoc, QualType ObjectType,
1246                                    bool AllowInjectedClassName);
1247 
1248   /// Build a new template name given a template template parameter pack
1249   /// and the
1250   ///
1251   /// By default, performs semantic analysis to determine whether the name can
1252   /// be resolved to a specific template, then builds the appropriate kind of
1253   /// template name. Subclasses may override this routine to provide different
1254   /// behavior.
1255   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1256                                    const TemplateArgument &ArgPack) {
1257     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1258   }
1259 
1260   /// Build a new compound statement.
1261   ///
1262   /// By default, performs semantic analysis to build the new statement.
1263   /// Subclasses may override this routine to provide different behavior.
1264   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1265                                        MultiStmtArg Statements,
1266                                        SourceLocation RBraceLoc,
1267                                        bool IsStmtExpr) {
1268     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1269                                        IsStmtExpr);
1270   }
1271 
1272   /// Build a new case statement.
1273   ///
1274   /// By default, performs semantic analysis to build the new statement.
1275   /// Subclasses may override this routine to provide different behavior.
1276   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1277                                    Expr *LHS,
1278                                    SourceLocation EllipsisLoc,
1279                                    Expr *RHS,
1280                                    SourceLocation ColonLoc) {
1281     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1282                                    ColonLoc);
1283   }
1284 
1285   /// Attach the body to a new case statement.
1286   ///
1287   /// By default, performs semantic analysis to build the new statement.
1288   /// Subclasses may override this routine to provide different behavior.
1289   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1290     getSema().ActOnCaseStmtBody(S, Body);
1291     return S;
1292   }
1293 
1294   /// Build a new default statement.
1295   ///
1296   /// By default, performs semantic analysis to build the new statement.
1297   /// Subclasses may override this routine to provide different behavior.
1298   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1299                                       SourceLocation ColonLoc,
1300                                       Stmt *SubStmt) {
1301     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1302                                       /*CurScope=*/nullptr);
1303   }
1304 
1305   /// Build a new label statement.
1306   ///
1307   /// By default, performs semantic analysis to build the new statement.
1308   /// Subclasses may override this routine to provide different behavior.
1309   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1310                               SourceLocation ColonLoc, Stmt *SubStmt) {
1311     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1312   }
1313 
1314   /// Build a new attributed statement.
1315   ///
1316   /// By default, performs semantic analysis to build the new statement.
1317   /// Subclasses may override this routine to provide different behavior.
1318   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1319                                    ArrayRef<const Attr *> Attrs,
1320                                    Stmt *SubStmt) {
1321     return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1322   }
1323 
1324   /// Build a new "if" statement.
1325   ///
1326   /// By default, performs semantic analysis to build the new statement.
1327   /// Subclasses may override this routine to provide different behavior.
1328   StmtResult RebuildIfStmt(SourceLocation IfLoc, IfStatementKind Kind,
1329                            SourceLocation LParenLoc, Sema::ConditionResult Cond,
1330                            SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1331                            SourceLocation ElseLoc, Stmt *Else) {
1332     return getSema().ActOnIfStmt(IfLoc, Kind, LParenLoc, Init, Cond, RParenLoc,
1333                                  Then, ElseLoc, Else);
1334   }
1335 
1336   /// Start building a new switch statement.
1337   ///
1338   /// By default, performs semantic analysis to build the new statement.
1339   /// Subclasses may override this routine to provide different behavior.
1340   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1341                                     SourceLocation LParenLoc, Stmt *Init,
1342                                     Sema::ConditionResult Cond,
1343                                     SourceLocation RParenLoc) {
1344     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1345                                             RParenLoc);
1346   }
1347 
1348   /// Attach the body to the switch statement.
1349   ///
1350   /// By default, performs semantic analysis to build the new statement.
1351   /// Subclasses may override this routine to provide different behavior.
1352   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1353                                    Stmt *Switch, Stmt *Body) {
1354     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1355   }
1356 
1357   /// Build a new while statement.
1358   ///
1359   /// By default, performs semantic analysis to build the new statement.
1360   /// Subclasses may override this routine to provide different behavior.
1361   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1362                               Sema::ConditionResult Cond,
1363                               SourceLocation RParenLoc, Stmt *Body) {
1364     return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1365   }
1366 
1367   /// Build a new do-while statement.
1368   ///
1369   /// By default, performs semantic analysis to build the new statement.
1370   /// Subclasses may override this routine to provide different behavior.
1371   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1372                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1373                            Expr *Cond, SourceLocation RParenLoc) {
1374     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1375                                  Cond, RParenLoc);
1376   }
1377 
1378   /// Build a new for statement.
1379   ///
1380   /// By default, performs semantic analysis to build the new statement.
1381   /// Subclasses may override this routine to provide different behavior.
1382   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1383                             Stmt *Init, Sema::ConditionResult Cond,
1384                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1385                             Stmt *Body) {
1386     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1387                                   Inc, RParenLoc, Body);
1388   }
1389 
1390   /// Build a new goto statement.
1391   ///
1392   /// By default, performs semantic analysis to build the new statement.
1393   /// Subclasses may override this routine to provide different behavior.
1394   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1395                              LabelDecl *Label) {
1396     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1397   }
1398 
1399   /// Build a new indirect goto statement.
1400   ///
1401   /// By default, performs semantic analysis to build the new statement.
1402   /// Subclasses may override this routine to provide different behavior.
1403   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1404                                      SourceLocation StarLoc,
1405                                      Expr *Target) {
1406     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1407   }
1408 
1409   /// Build a new return statement.
1410   ///
1411   /// By default, performs semantic analysis to build the new statement.
1412   /// Subclasses may override this routine to provide different behavior.
1413   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1414     return getSema().BuildReturnStmt(ReturnLoc, Result);
1415   }
1416 
1417   /// Build a new declaration statement.
1418   ///
1419   /// By default, performs semantic analysis to build the new statement.
1420   /// Subclasses may override this routine to provide different behavior.
1421   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1422                              SourceLocation StartLoc, SourceLocation EndLoc) {
1423     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1424     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1425   }
1426 
1427   /// Build a new inline asm statement.
1428   ///
1429   /// By default, performs semantic analysis to build the new statement.
1430   /// Subclasses may override this routine to provide different behavior.
1431   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1432                                bool IsVolatile, unsigned NumOutputs,
1433                                unsigned NumInputs, IdentifierInfo **Names,
1434                                MultiExprArg Constraints, MultiExprArg Exprs,
1435                                Expr *AsmString, MultiExprArg Clobbers,
1436                                unsigned NumLabels,
1437                                SourceLocation RParenLoc) {
1438     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1439                                      NumInputs, Names, Constraints, Exprs,
1440                                      AsmString, Clobbers, NumLabels, RParenLoc);
1441   }
1442 
1443   /// Build a new MS style inline asm statement.
1444   ///
1445   /// By default, performs semantic analysis to build the new statement.
1446   /// Subclasses may override this routine to provide different behavior.
1447   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1448                               ArrayRef<Token> AsmToks,
1449                               StringRef AsmString,
1450                               unsigned NumOutputs, unsigned NumInputs,
1451                               ArrayRef<StringRef> Constraints,
1452                               ArrayRef<StringRef> Clobbers,
1453                               ArrayRef<Expr*> Exprs,
1454                               SourceLocation EndLoc) {
1455     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1456                                     NumOutputs, NumInputs,
1457                                     Constraints, Clobbers, Exprs, EndLoc);
1458   }
1459 
1460   /// Build a new co_return statement.
1461   ///
1462   /// By default, performs semantic analysis to build the new statement.
1463   /// Subclasses may override this routine to provide different behavior.
1464   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1465                                  bool IsImplicit) {
1466     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1467   }
1468 
1469   /// Build a new co_await expression.
1470   ///
1471   /// By default, performs semantic analysis to build the new expression.
1472   /// Subclasses may override this routine to provide different behavior.
1473   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand,
1474                                 UnresolvedLookupExpr *OpCoawaitLookup,
1475                                 bool IsImplicit) {
1476     // This function rebuilds a coawait-expr given its operator.
1477     // For an explicit coawait-expr, the rebuild involves the full set
1478     // of transformations performed by BuildUnresolvedCoawaitExpr(),
1479     // including calling await_transform().
1480     // For an implicit coawait-expr, we need to rebuild the "operator
1481     // coawait" but not await_transform(), so use BuildResolvedCoawaitExpr().
1482     // This mirrors how the implicit CoawaitExpr is originally created
1483     // in Sema::ActOnCoroutineBodyStart().
1484     if (IsImplicit) {
1485       ExprResult Suspend = getSema().BuildOperatorCoawaitCall(
1486           CoawaitLoc, Operand, OpCoawaitLookup);
1487       if (Suspend.isInvalid())
1488         return ExprError();
1489       return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Operand,
1490                                                 Suspend.get(), true);
1491     }
1492 
1493     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Operand,
1494                                                 OpCoawaitLookup);
1495   }
1496 
1497   /// Build a new co_await expression.
1498   ///
1499   /// By default, performs semantic analysis to build the new expression.
1500   /// Subclasses may override this routine to provide different behavior.
1501   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1502                                          Expr *Result,
1503                                          UnresolvedLookupExpr *Lookup) {
1504     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1505   }
1506 
1507   /// Build a new co_yield expression.
1508   ///
1509   /// By default, performs semantic analysis to build the new expression.
1510   /// Subclasses may override this routine to provide different behavior.
1511   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1512     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1513   }
1514 
1515   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1516     return getSema().BuildCoroutineBodyStmt(Args);
1517   }
1518 
1519   /// Build a new Objective-C \@try statement.
1520   ///
1521   /// By default, performs semantic analysis to build the new statement.
1522   /// Subclasses may override this routine to provide different behavior.
1523   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1524                                         Stmt *TryBody,
1525                                         MultiStmtArg CatchStmts,
1526                                         Stmt *Finally) {
1527     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1528                                         Finally);
1529   }
1530 
1531   /// Rebuild an Objective-C exception declaration.
1532   ///
1533   /// By default, performs semantic analysis to build the new declaration.
1534   /// Subclasses may override this routine to provide different behavior.
1535   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1536                                     TypeSourceInfo *TInfo, QualType T) {
1537     return getSema().BuildObjCExceptionDecl(TInfo, T,
1538                                             ExceptionDecl->getInnerLocStart(),
1539                                             ExceptionDecl->getLocation(),
1540                                             ExceptionDecl->getIdentifier());
1541   }
1542 
1543   /// Build a new Objective-C \@catch statement.
1544   ///
1545   /// By default, performs semantic analysis to build the new statement.
1546   /// Subclasses may override this routine to provide different behavior.
1547   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1548                                           SourceLocation RParenLoc,
1549                                           VarDecl *Var,
1550                                           Stmt *Body) {
1551     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1552                                           Var, Body);
1553   }
1554 
1555   /// Build a new Objective-C \@finally statement.
1556   ///
1557   /// By default, performs semantic analysis to build the new statement.
1558   /// Subclasses may override this routine to provide different behavior.
1559   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1560                                             Stmt *Body) {
1561     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1562   }
1563 
1564   /// Build a new Objective-C \@throw statement.
1565   ///
1566   /// By default, performs semantic analysis to build the new statement.
1567   /// Subclasses may override this routine to provide different behavior.
1568   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1569                                           Expr *Operand) {
1570     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1571   }
1572 
1573   /// Build a new OpenMP Canonical loop.
1574   ///
1575   /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1576   /// OMPCanonicalLoop.
1577   StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1578     return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1579   }
1580 
1581   /// Build a new OpenMP executable directive.
1582   ///
1583   /// By default, performs semantic analysis to build the new statement.
1584   /// Subclasses may override this routine to provide different behavior.
1585   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1586                                            DeclarationNameInfo DirName,
1587                                            OpenMPDirectiveKind CancelRegion,
1588                                            ArrayRef<OMPClause *> Clauses,
1589                                            Stmt *AStmt, SourceLocation StartLoc,
1590                                            SourceLocation EndLoc) {
1591     return getSema().ActOnOpenMPExecutableDirective(
1592         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1593   }
1594 
1595   /// Build a new OpenMP 'if' clause.
1596   ///
1597   /// By default, performs semantic analysis to build the new OpenMP clause.
1598   /// Subclasses may override this routine to provide different behavior.
1599   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1600                                 Expr *Condition, SourceLocation StartLoc,
1601                                 SourceLocation LParenLoc,
1602                                 SourceLocation NameModifierLoc,
1603                                 SourceLocation ColonLoc,
1604                                 SourceLocation EndLoc) {
1605     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1606                                          LParenLoc, NameModifierLoc, ColonLoc,
1607                                          EndLoc);
1608   }
1609 
1610   /// Build a new OpenMP 'final' clause.
1611   ///
1612   /// By default, performs semantic analysis to build the new OpenMP clause.
1613   /// Subclasses may override this routine to provide different behavior.
1614   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1615                                    SourceLocation LParenLoc,
1616                                    SourceLocation EndLoc) {
1617     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1618                                             EndLoc);
1619   }
1620 
1621   /// Build a new OpenMP 'num_threads' clause.
1622   ///
1623   /// By default, performs semantic analysis to build the new OpenMP clause.
1624   /// Subclasses may override this routine to provide different behavior.
1625   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1626                                         SourceLocation StartLoc,
1627                                         SourceLocation LParenLoc,
1628                                         SourceLocation EndLoc) {
1629     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1630                                                  LParenLoc, EndLoc);
1631   }
1632 
1633   /// Build a new OpenMP 'safelen' clause.
1634   ///
1635   /// By default, performs semantic analysis to build the new OpenMP clause.
1636   /// Subclasses may override this routine to provide different behavior.
1637   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1638                                      SourceLocation LParenLoc,
1639                                      SourceLocation EndLoc) {
1640     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1641   }
1642 
1643   /// Build a new OpenMP 'simdlen' clause.
1644   ///
1645   /// By default, performs semantic analysis to build the new OpenMP clause.
1646   /// Subclasses may override this routine to provide different behavior.
1647   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1648                                      SourceLocation LParenLoc,
1649                                      SourceLocation EndLoc) {
1650     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1651   }
1652 
1653   OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1654                                    SourceLocation StartLoc,
1655                                    SourceLocation LParenLoc,
1656                                    SourceLocation EndLoc) {
1657     return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1658   }
1659 
1660   /// Build a new OpenMP 'full' clause.
1661   OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1662                                   SourceLocation EndLoc) {
1663     return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1664   }
1665 
1666   /// Build a new OpenMP 'partial' clause.
1667   OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1668                                      SourceLocation LParenLoc,
1669                                      SourceLocation EndLoc) {
1670     return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1671                                               EndLoc);
1672   }
1673 
1674   /// Build a new OpenMP 'allocator' clause.
1675   ///
1676   /// By default, performs semantic analysis to build the new OpenMP clause.
1677   /// Subclasses may override this routine to provide different behavior.
1678   OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1679                                        SourceLocation LParenLoc,
1680                                        SourceLocation EndLoc) {
1681     return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1682   }
1683 
1684   /// Build a new OpenMP 'collapse' clause.
1685   ///
1686   /// By default, performs semantic analysis to build the new OpenMP clause.
1687   /// Subclasses may override this routine to provide different behavior.
1688   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1689                                       SourceLocation LParenLoc,
1690                                       SourceLocation EndLoc) {
1691     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1692                                                EndLoc);
1693   }
1694 
1695   /// Build a new OpenMP 'default' clause.
1696   ///
1697   /// By default, performs semantic analysis to build the new OpenMP clause.
1698   /// Subclasses may override this routine to provide different behavior.
1699   OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1700                                      SourceLocation StartLoc,
1701                                      SourceLocation LParenLoc,
1702                                      SourceLocation EndLoc) {
1703     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1704                                               StartLoc, LParenLoc, EndLoc);
1705   }
1706 
1707   /// Build a new OpenMP 'proc_bind' clause.
1708   ///
1709   /// By default, performs semantic analysis to build the new OpenMP clause.
1710   /// Subclasses may override this routine to provide different behavior.
1711   OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1712                                       SourceLocation KindKwLoc,
1713                                       SourceLocation StartLoc,
1714                                       SourceLocation LParenLoc,
1715                                       SourceLocation EndLoc) {
1716     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1717                                                StartLoc, LParenLoc, EndLoc);
1718   }
1719 
1720   /// Build a new OpenMP 'schedule' clause.
1721   ///
1722   /// By default, performs semantic analysis to build the new OpenMP clause.
1723   /// Subclasses may override this routine to provide different behavior.
1724   OMPClause *RebuildOMPScheduleClause(
1725       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1726       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1727       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1728       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1729     return getSema().ActOnOpenMPScheduleClause(
1730         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1731         CommaLoc, EndLoc);
1732   }
1733 
1734   /// Build a new OpenMP 'ordered' clause.
1735   ///
1736   /// By default, performs semantic analysis to build the new OpenMP clause.
1737   /// Subclasses may override this routine to provide different behavior.
1738   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1739                                      SourceLocation EndLoc,
1740                                      SourceLocation LParenLoc, Expr *Num) {
1741     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1742   }
1743 
1744   /// Build a new OpenMP 'private' clause.
1745   ///
1746   /// By default, performs semantic analysis to build the new OpenMP clause.
1747   /// Subclasses may override this routine to provide different behavior.
1748   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1749                                      SourceLocation StartLoc,
1750                                      SourceLocation LParenLoc,
1751                                      SourceLocation EndLoc) {
1752     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1753                                               EndLoc);
1754   }
1755 
1756   /// Build a new OpenMP 'firstprivate' clause.
1757   ///
1758   /// By default, performs semantic analysis to build the new OpenMP clause.
1759   /// Subclasses may override this routine to provide different behavior.
1760   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1761                                           SourceLocation StartLoc,
1762                                           SourceLocation LParenLoc,
1763                                           SourceLocation EndLoc) {
1764     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1765                                                    EndLoc);
1766   }
1767 
1768   /// Build a new OpenMP 'lastprivate' clause.
1769   ///
1770   /// By default, performs semantic analysis to build the new OpenMP clause.
1771   /// Subclasses may override this routine to provide different behavior.
1772   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1773                                          OpenMPLastprivateModifier LPKind,
1774                                          SourceLocation LPKindLoc,
1775                                          SourceLocation ColonLoc,
1776                                          SourceLocation StartLoc,
1777                                          SourceLocation LParenLoc,
1778                                          SourceLocation EndLoc) {
1779     return getSema().ActOnOpenMPLastprivateClause(
1780         VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1781   }
1782 
1783   /// Build a new OpenMP 'shared' clause.
1784   ///
1785   /// By default, performs semantic analysis to build the new OpenMP clause.
1786   /// Subclasses may override this routine to provide different behavior.
1787   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1788                                     SourceLocation StartLoc,
1789                                     SourceLocation LParenLoc,
1790                                     SourceLocation EndLoc) {
1791     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1792                                              EndLoc);
1793   }
1794 
1795   /// Build a new OpenMP 'reduction' clause.
1796   ///
1797   /// By default, performs semantic analysis to build the new statement.
1798   /// Subclasses may override this routine to provide different behavior.
1799   OMPClause *RebuildOMPReductionClause(
1800       ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1801       SourceLocation StartLoc, SourceLocation LParenLoc,
1802       SourceLocation ModifierLoc, SourceLocation ColonLoc,
1803       SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1804       const DeclarationNameInfo &ReductionId,
1805       ArrayRef<Expr *> UnresolvedReductions) {
1806     return getSema().ActOnOpenMPReductionClause(
1807         VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1808         ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1809   }
1810 
1811   /// Build a new OpenMP 'task_reduction' clause.
1812   ///
1813   /// By default, performs semantic analysis to build the new statement.
1814   /// Subclasses may override this routine to provide different behavior.
1815   OMPClause *RebuildOMPTaskReductionClause(
1816       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1817       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1818       CXXScopeSpec &ReductionIdScopeSpec,
1819       const DeclarationNameInfo &ReductionId,
1820       ArrayRef<Expr *> UnresolvedReductions) {
1821     return getSema().ActOnOpenMPTaskReductionClause(
1822         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1823         ReductionId, UnresolvedReductions);
1824   }
1825 
1826   /// Build a new OpenMP 'in_reduction' clause.
1827   ///
1828   /// By default, performs semantic analysis to build the new statement.
1829   /// Subclasses may override this routine to provide different behavior.
1830   OMPClause *
1831   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1832                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1833                               SourceLocation EndLoc,
1834                               CXXScopeSpec &ReductionIdScopeSpec,
1835                               const DeclarationNameInfo &ReductionId,
1836                               ArrayRef<Expr *> UnresolvedReductions) {
1837     return getSema().ActOnOpenMPInReductionClause(
1838         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1839         ReductionId, UnresolvedReductions);
1840   }
1841 
1842   /// Build a new OpenMP 'linear' clause.
1843   ///
1844   /// By default, performs semantic analysis to build the new OpenMP clause.
1845   /// Subclasses may override this routine to provide different behavior.
1846   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1847                                     SourceLocation StartLoc,
1848                                     SourceLocation LParenLoc,
1849                                     OpenMPLinearClauseKind Modifier,
1850                                     SourceLocation ModifierLoc,
1851                                     SourceLocation ColonLoc,
1852                                     SourceLocation EndLoc) {
1853     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1854                                              Modifier, ModifierLoc, ColonLoc,
1855                                              EndLoc);
1856   }
1857 
1858   /// Build a new OpenMP 'aligned' clause.
1859   ///
1860   /// By default, performs semantic analysis to build the new OpenMP clause.
1861   /// Subclasses may override this routine to provide different behavior.
1862   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1863                                      SourceLocation StartLoc,
1864                                      SourceLocation LParenLoc,
1865                                      SourceLocation ColonLoc,
1866                                      SourceLocation EndLoc) {
1867     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1868                                               LParenLoc, ColonLoc, EndLoc);
1869   }
1870 
1871   /// Build a new OpenMP 'copyin' clause.
1872   ///
1873   /// By default, performs semantic analysis to build the new OpenMP clause.
1874   /// Subclasses may override this routine to provide different behavior.
1875   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1876                                     SourceLocation StartLoc,
1877                                     SourceLocation LParenLoc,
1878                                     SourceLocation EndLoc) {
1879     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1880                                              EndLoc);
1881   }
1882 
1883   /// Build a new OpenMP 'copyprivate' clause.
1884   ///
1885   /// By default, performs semantic analysis to build the new OpenMP clause.
1886   /// Subclasses may override this routine to provide different behavior.
1887   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1888                                          SourceLocation StartLoc,
1889                                          SourceLocation LParenLoc,
1890                                          SourceLocation EndLoc) {
1891     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1892                                                   EndLoc);
1893   }
1894 
1895   /// Build a new OpenMP 'flush' pseudo clause.
1896   ///
1897   /// By default, performs semantic analysis to build the new OpenMP clause.
1898   /// Subclasses may override this routine to provide different behavior.
1899   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1900                                    SourceLocation StartLoc,
1901                                    SourceLocation LParenLoc,
1902                                    SourceLocation EndLoc) {
1903     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1904                                             EndLoc);
1905   }
1906 
1907   /// Build a new OpenMP 'depobj' pseudo clause.
1908   ///
1909   /// By default, performs semantic analysis to build the new OpenMP clause.
1910   /// Subclasses may override this routine to provide different behavior.
1911   OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1912                                     SourceLocation LParenLoc,
1913                                     SourceLocation EndLoc) {
1914     return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1915                                              EndLoc);
1916   }
1917 
1918   /// Build a new OpenMP 'depend' pseudo clause.
1919   ///
1920   /// By default, performs semantic analysis to build the new OpenMP clause.
1921   /// Subclasses may override this routine to provide different behavior.
1922   OMPClause *RebuildOMPDependClause(OMPDependClause::DependDataTy Data,
1923                                     Expr *DepModifier, ArrayRef<Expr *> VarList,
1924                                     SourceLocation StartLoc,
1925                                     SourceLocation LParenLoc,
1926                                     SourceLocation EndLoc) {
1927     return getSema().ActOnOpenMPDependClause(Data, DepModifier, VarList,
1928                                              StartLoc, LParenLoc, EndLoc);
1929   }
1930 
1931   /// Build a new OpenMP 'device' clause.
1932   ///
1933   /// By default, performs semantic analysis to build the new statement.
1934   /// Subclasses may override this routine to provide different behavior.
1935   OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1936                                     Expr *Device, SourceLocation StartLoc,
1937                                     SourceLocation LParenLoc,
1938                                     SourceLocation ModifierLoc,
1939                                     SourceLocation EndLoc) {
1940     return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
1941                                              LParenLoc, ModifierLoc, EndLoc);
1942   }
1943 
1944   /// Build a new OpenMP 'map' clause.
1945   ///
1946   /// By default, performs semantic analysis to build the new OpenMP clause.
1947   /// Subclasses may override this routine to provide different behavior.
1948   OMPClause *RebuildOMPMapClause(
1949       ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1950       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1951       CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
1952       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1953       SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1954       const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
1955     return getSema().ActOnOpenMPMapClause(
1956         MapTypeModifiers, MapTypeModifiersLoc, MapperIdScopeSpec, MapperId,
1957         MapType, IsMapTypeImplicit, MapLoc, ColonLoc, VarList, Locs,
1958         /*NoDiagnose=*/false, UnresolvedMappers);
1959   }
1960 
1961   /// Build a new OpenMP 'allocate' clause.
1962   ///
1963   /// By default, performs semantic analysis to build the new OpenMP clause.
1964   /// Subclasses may override this routine to provide different behavior.
1965   OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
1966                                       SourceLocation StartLoc,
1967                                       SourceLocation LParenLoc,
1968                                       SourceLocation ColonLoc,
1969                                       SourceLocation EndLoc) {
1970     return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
1971                                                LParenLoc, ColonLoc, EndLoc);
1972   }
1973 
1974   /// Build a new OpenMP 'num_teams' clause.
1975   ///
1976   /// By default, performs semantic analysis to build the new statement.
1977   /// Subclasses may override this routine to provide different behavior.
1978   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1979                                       SourceLocation LParenLoc,
1980                                       SourceLocation EndLoc) {
1981     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1982                                                EndLoc);
1983   }
1984 
1985   /// Build a new OpenMP 'thread_limit' clause.
1986   ///
1987   /// By default, performs semantic analysis to build the new statement.
1988   /// Subclasses may override this routine to provide different behavior.
1989   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1990                                          SourceLocation StartLoc,
1991                                          SourceLocation LParenLoc,
1992                                          SourceLocation EndLoc) {
1993     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1994                                                   LParenLoc, EndLoc);
1995   }
1996 
1997   /// Build a new OpenMP 'priority' clause.
1998   ///
1999   /// By default, performs semantic analysis to build the new statement.
2000   /// Subclasses may override this routine to provide different behavior.
2001   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
2002                                       SourceLocation LParenLoc,
2003                                       SourceLocation EndLoc) {
2004     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
2005                                                EndLoc);
2006   }
2007 
2008   /// Build a new OpenMP 'grainsize' clause.
2009   ///
2010   /// By default, performs semantic analysis to build the new statement.
2011   /// Subclasses may override this routine to provide different behavior.
2012   OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
2013                                        SourceLocation LParenLoc,
2014                                        SourceLocation EndLoc) {
2015     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
2016                                                 EndLoc);
2017   }
2018 
2019   /// Build a new OpenMP 'num_tasks' clause.
2020   ///
2021   /// By default, performs semantic analysis to build the new statement.
2022   /// Subclasses may override this routine to provide different behavior.
2023   OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
2024                                       SourceLocation LParenLoc,
2025                                       SourceLocation EndLoc) {
2026     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
2027                                                EndLoc);
2028   }
2029 
2030   /// Build a new OpenMP 'hint' clause.
2031   ///
2032   /// By default, performs semantic analysis to build the new statement.
2033   /// Subclasses may override this routine to provide different behavior.
2034   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2035                                   SourceLocation LParenLoc,
2036                                   SourceLocation EndLoc) {
2037     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2038   }
2039 
2040   /// Build a new OpenMP 'detach' clause.
2041   ///
2042   /// By default, performs semantic analysis to build the new statement.
2043   /// Subclasses may override this routine to provide different behavior.
2044   OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2045                                     SourceLocation LParenLoc,
2046                                     SourceLocation EndLoc) {
2047     return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2048   }
2049 
2050   /// Build a new OpenMP 'dist_schedule' clause.
2051   ///
2052   /// By default, performs semantic analysis to build the new OpenMP clause.
2053   /// Subclasses may override this routine to provide different behavior.
2054   OMPClause *
2055   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2056                                Expr *ChunkSize, SourceLocation StartLoc,
2057                                SourceLocation LParenLoc, SourceLocation KindLoc,
2058                                SourceLocation CommaLoc, SourceLocation EndLoc) {
2059     return getSema().ActOnOpenMPDistScheduleClause(
2060         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2061   }
2062 
2063   /// Build a new OpenMP 'to' clause.
2064   ///
2065   /// By default, performs semantic analysis to build the new statement.
2066   /// Subclasses may override this routine to provide different behavior.
2067   OMPClause *
2068   RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2069                      ArrayRef<SourceLocation> MotionModifiersLoc,
2070                      CXXScopeSpec &MapperIdScopeSpec,
2071                      DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2072                      ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2073                      ArrayRef<Expr *> UnresolvedMappers) {
2074     return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2075                                          MapperIdScopeSpec, MapperId, ColonLoc,
2076                                          VarList, Locs, UnresolvedMappers);
2077   }
2078 
2079   /// Build a new OpenMP 'from' clause.
2080   ///
2081   /// By default, performs semantic analysis to build the new statement.
2082   /// Subclasses may override this routine to provide different behavior.
2083   OMPClause *
2084   RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2085                        ArrayRef<SourceLocation> MotionModifiersLoc,
2086                        CXXScopeSpec &MapperIdScopeSpec,
2087                        DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2088                        ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2089                        ArrayRef<Expr *> UnresolvedMappers) {
2090     return getSema().ActOnOpenMPFromClause(
2091         MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2092         ColonLoc, VarList, Locs, UnresolvedMappers);
2093   }
2094 
2095   /// Build a new OpenMP 'use_device_ptr' clause.
2096   ///
2097   /// By default, performs semantic analysis to build the new OpenMP clause.
2098   /// Subclasses may override this routine to provide different behavior.
2099   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2100                                           const OMPVarListLocTy &Locs) {
2101     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2102   }
2103 
2104   /// Build a new OpenMP 'use_device_addr' clause.
2105   ///
2106   /// By default, performs semantic analysis to build the new OpenMP clause.
2107   /// Subclasses may override this routine to provide different behavior.
2108   OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2109                                            const OMPVarListLocTy &Locs) {
2110     return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2111   }
2112 
2113   /// Build a new OpenMP 'is_device_ptr' clause.
2114   ///
2115   /// By default, performs semantic analysis to build the new OpenMP clause.
2116   /// Subclasses may override this routine to provide different behavior.
2117   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2118                                          const OMPVarListLocTy &Locs) {
2119     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2120   }
2121 
2122   /// Build a new OpenMP 'has_device_addr' clause.
2123   ///
2124   /// By default, performs semantic analysis to build the new OpenMP clause.
2125   /// Subclasses may override this routine to provide different behavior.
2126   OMPClause *RebuildOMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
2127                                            const OMPVarListLocTy &Locs) {
2128     return getSema().ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
2129   }
2130 
2131   /// Build a new OpenMP 'defaultmap' clause.
2132   ///
2133   /// By default, performs semantic analysis to build the new OpenMP clause.
2134   /// Subclasses may override this routine to provide different behavior.
2135   OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2136                                         OpenMPDefaultmapClauseKind Kind,
2137                                         SourceLocation StartLoc,
2138                                         SourceLocation LParenLoc,
2139                                         SourceLocation MLoc,
2140                                         SourceLocation KindLoc,
2141                                         SourceLocation EndLoc) {
2142     return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2143                                                  MLoc, KindLoc, EndLoc);
2144   }
2145 
2146   /// Build a new OpenMP 'nontemporal' clause.
2147   ///
2148   /// By default, performs semantic analysis to build the new OpenMP clause.
2149   /// Subclasses may override this routine to provide different behavior.
2150   OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2151                                          SourceLocation StartLoc,
2152                                          SourceLocation LParenLoc,
2153                                          SourceLocation EndLoc) {
2154     return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2155                                                   EndLoc);
2156   }
2157 
2158   /// Build a new OpenMP 'inclusive' clause.
2159   ///
2160   /// By default, performs semantic analysis to build the new OpenMP clause.
2161   /// Subclasses may override this routine to provide different behavior.
2162   OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2163                                        SourceLocation StartLoc,
2164                                        SourceLocation LParenLoc,
2165                                        SourceLocation EndLoc) {
2166     return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2167                                                 EndLoc);
2168   }
2169 
2170   /// Build a new OpenMP 'exclusive' clause.
2171   ///
2172   /// By default, performs semantic analysis to build the new OpenMP clause.
2173   /// Subclasses may override this routine to provide different behavior.
2174   OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2175                                        SourceLocation StartLoc,
2176                                        SourceLocation LParenLoc,
2177                                        SourceLocation EndLoc) {
2178     return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2179                                                 EndLoc);
2180   }
2181 
2182   /// Build a new OpenMP 'uses_allocators' clause.
2183   ///
2184   /// By default, performs semantic analysis to build the new OpenMP clause.
2185   /// Subclasses may override this routine to provide different behavior.
2186   OMPClause *RebuildOMPUsesAllocatorsClause(
2187       ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2188       SourceLocation LParenLoc, SourceLocation EndLoc) {
2189     return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2190                                                     Data);
2191   }
2192 
2193   /// Build a new OpenMP 'affinity' clause.
2194   ///
2195   /// By default, performs semantic analysis to build the new OpenMP clause.
2196   /// Subclasses may override this routine to provide different behavior.
2197   OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2198                                       SourceLocation LParenLoc,
2199                                       SourceLocation ColonLoc,
2200                                       SourceLocation EndLoc, Expr *Modifier,
2201                                       ArrayRef<Expr *> Locators) {
2202     return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2203                                                EndLoc, Modifier, Locators);
2204   }
2205 
2206   /// Build a new OpenMP 'order' clause.
2207   ///
2208   /// By default, performs semantic analysis to build the new OpenMP clause.
2209   /// Subclasses may override this routine to provide different behavior.
2210   OMPClause *RebuildOMPOrderClause(OpenMPOrderClauseKind Kind,
2211                                    SourceLocation KindKwLoc,
2212                                    SourceLocation StartLoc,
2213                                    SourceLocation LParenLoc,
2214                                    SourceLocation EndLoc) {
2215     return getSema().ActOnOpenMPOrderClause(Kind, KindKwLoc, StartLoc,
2216                                             LParenLoc, EndLoc);
2217   }
2218 
2219   /// Build a new OpenMP 'init' clause.
2220   ///
2221   /// By default, performs semantic analysis to build the new OpenMP clause.
2222   /// Subclasses may override this routine to provide different behavior.
2223   OMPClause *RebuildOMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
2224                                   bool IsTarget, bool IsTargetSync,
2225                                   SourceLocation StartLoc,
2226                                   SourceLocation LParenLoc,
2227                                   SourceLocation VarLoc,
2228                                   SourceLocation EndLoc) {
2229     return getSema().ActOnOpenMPInitClause(InteropVar, PrefExprs, IsTarget,
2230                                            IsTargetSync, StartLoc, LParenLoc,
2231                                            VarLoc, EndLoc);
2232   }
2233 
2234   /// Build a new OpenMP 'use' clause.
2235   ///
2236   /// By default, performs semantic analysis to build the new OpenMP clause.
2237   /// Subclasses may override this routine to provide different behavior.
2238   OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2239                                  SourceLocation LParenLoc,
2240                                  SourceLocation VarLoc, SourceLocation EndLoc) {
2241     return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2242                                           VarLoc, EndLoc);
2243   }
2244 
2245   /// Build a new OpenMP 'destroy' clause.
2246   ///
2247   /// By default, performs semantic analysis to build the new OpenMP clause.
2248   /// Subclasses may override this routine to provide different behavior.
2249   OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2250                                      SourceLocation LParenLoc,
2251                                      SourceLocation VarLoc,
2252                                      SourceLocation EndLoc) {
2253     return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2254                                               VarLoc, EndLoc);
2255   }
2256 
2257   /// Build a new OpenMP 'novariants' clause.
2258   ///
2259   /// By default, performs semantic analysis to build the new OpenMP clause.
2260   /// Subclasses may override this routine to provide different behavior.
2261   OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2262                                         SourceLocation StartLoc,
2263                                         SourceLocation LParenLoc,
2264                                         SourceLocation EndLoc) {
2265     return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2266                                                  EndLoc);
2267   }
2268 
2269   /// Build a new OpenMP 'nocontext' clause.
2270   ///
2271   /// By default, performs semantic analysis to build the new OpenMP clause.
2272   /// Subclasses may override this routine to provide different behavior.
2273   OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2274                                        SourceLocation LParenLoc,
2275                                        SourceLocation EndLoc) {
2276     return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2277                                                 EndLoc);
2278   }
2279 
2280   /// Build a new OpenMP 'filter' clause.
2281   ///
2282   /// By default, performs semantic analysis to build the new OpenMP clause.
2283   /// Subclasses may override this routine to provide different behavior.
2284   OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2285                                     SourceLocation LParenLoc,
2286                                     SourceLocation EndLoc) {
2287     return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2288                                              EndLoc);
2289   }
2290 
2291   /// Build a new OpenMP 'bind' clause.
2292   ///
2293   /// By default, performs semantic analysis to build the new OpenMP clause.
2294   /// Subclasses may override this routine to provide different behavior.
2295   OMPClause *RebuildOMPBindClause(OpenMPBindClauseKind Kind,
2296                                   SourceLocation KindLoc,
2297                                   SourceLocation StartLoc,
2298                                   SourceLocation LParenLoc,
2299                                   SourceLocation EndLoc) {
2300     return getSema().ActOnOpenMPBindClause(Kind, KindLoc, StartLoc, LParenLoc,
2301                                            EndLoc);
2302   }
2303 
2304   /// Build a new OpenMP 'align' clause.
2305   ///
2306   /// By default, performs semantic analysis to build the new OpenMP clause.
2307   /// Subclasses may override this routine to provide different behavior.
2308   OMPClause *RebuildOMPAlignClause(Expr *A, SourceLocation StartLoc,
2309                                    SourceLocation LParenLoc,
2310                                    SourceLocation EndLoc) {
2311     return getSema().ActOnOpenMPAlignClause(A, StartLoc, LParenLoc, EndLoc);
2312   }
2313 
2314   /// Rebuild the operand to an Objective-C \@synchronized statement.
2315   ///
2316   /// By default, performs semantic analysis to build the new statement.
2317   /// Subclasses may override this routine to provide different behavior.
2318   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2319                                               Expr *object) {
2320     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2321   }
2322 
2323   /// Build a new Objective-C \@synchronized statement.
2324   ///
2325   /// By default, performs semantic analysis to build the new statement.
2326   /// Subclasses may override this routine to provide different behavior.
2327   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2328                                            Expr *Object, Stmt *Body) {
2329     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2330   }
2331 
2332   /// Build a new Objective-C \@autoreleasepool statement.
2333   ///
2334   /// By default, performs semantic analysis to build the new statement.
2335   /// Subclasses may override this routine to provide different behavior.
2336   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2337                                             Stmt *Body) {
2338     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2339   }
2340 
2341   /// Build a new Objective-C fast enumeration statement.
2342   ///
2343   /// By default, performs semantic analysis to build the new statement.
2344   /// Subclasses may override this routine to provide different behavior.
2345   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2346                                           Stmt *Element,
2347                                           Expr *Collection,
2348                                           SourceLocation RParenLoc,
2349                                           Stmt *Body) {
2350     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2351                                                 Element,
2352                                                 Collection,
2353                                                 RParenLoc);
2354     if (ForEachStmt.isInvalid())
2355       return StmtError();
2356 
2357     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2358   }
2359 
2360   /// Build a new C++ exception declaration.
2361   ///
2362   /// By default, performs semantic analysis to build the new decaration.
2363   /// Subclasses may override this routine to provide different behavior.
2364   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2365                                 TypeSourceInfo *Declarator,
2366                                 SourceLocation StartLoc,
2367                                 SourceLocation IdLoc,
2368                                 IdentifierInfo *Id) {
2369     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2370                                                        StartLoc, IdLoc, Id);
2371     if (Var)
2372       getSema().CurContext->addDecl(Var);
2373     return Var;
2374   }
2375 
2376   /// Build a new C++ catch statement.
2377   ///
2378   /// By default, performs semantic analysis to build the new statement.
2379   /// Subclasses may override this routine to provide different behavior.
2380   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2381                                  VarDecl *ExceptionDecl,
2382                                  Stmt *Handler) {
2383     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2384                                                       Handler));
2385   }
2386 
2387   /// Build a new C++ try statement.
2388   ///
2389   /// By default, performs semantic analysis to build the new statement.
2390   /// Subclasses may override this routine to provide different behavior.
2391   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2392                                ArrayRef<Stmt *> Handlers) {
2393     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2394   }
2395 
2396   /// Build a new C++0x range-based for statement.
2397   ///
2398   /// By default, performs semantic analysis to build the new statement.
2399   /// Subclasses may override this routine to provide different behavior.
2400   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2401                                     SourceLocation CoawaitLoc, Stmt *Init,
2402                                     SourceLocation ColonLoc, Stmt *Range,
2403                                     Stmt *Begin, Stmt *End, Expr *Cond,
2404                                     Expr *Inc, Stmt *LoopVar,
2405                                     SourceLocation RParenLoc) {
2406     // If we've just learned that the range is actually an Objective-C
2407     // collection, treat this as an Objective-C fast enumeration loop.
2408     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2409       if (RangeStmt->isSingleDecl()) {
2410         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2411           if (RangeVar->isInvalidDecl())
2412             return StmtError();
2413 
2414           Expr *RangeExpr = RangeVar->getInit();
2415           if (!RangeExpr->isTypeDependent() &&
2416               RangeExpr->getType()->isObjCObjectPointerType()) {
2417             // FIXME: Support init-statements in Objective-C++20 ranged for
2418             // statement.
2419             if (Init) {
2420               return SemaRef.Diag(Init->getBeginLoc(),
2421                                   diag::err_objc_for_range_init_stmt)
2422                          << Init->getSourceRange();
2423             }
2424             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2425                                                         RangeExpr, RParenLoc);
2426           }
2427         }
2428       }
2429     }
2430 
2431     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2432                                           Range, Begin, End, Cond, Inc, LoopVar,
2433                                           RParenLoc, Sema::BFRK_Rebuild);
2434   }
2435 
2436   /// Build a new C++0x range-based for statement.
2437   ///
2438   /// By default, performs semantic analysis to build the new statement.
2439   /// Subclasses may override this routine to provide different behavior.
2440   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2441                                           bool IsIfExists,
2442                                           NestedNameSpecifierLoc QualifierLoc,
2443                                           DeclarationNameInfo NameInfo,
2444                                           Stmt *Nested) {
2445     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2446                                                 QualifierLoc, NameInfo, Nested);
2447   }
2448 
2449   /// Attach body to a C++0x range-based for statement.
2450   ///
2451   /// By default, performs semantic analysis to finish the new statement.
2452   /// Subclasses may override this routine to provide different behavior.
2453   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2454     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2455   }
2456 
2457   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2458                                Stmt *TryBlock, Stmt *Handler) {
2459     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2460   }
2461 
2462   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2463                                   Stmt *Block) {
2464     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2465   }
2466 
2467   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2468     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2469   }
2470 
2471   ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2472                                              SourceLocation LParen,
2473                                              SourceLocation RParen,
2474                                              TypeSourceInfo *TSI) {
2475     return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2476   }
2477 
2478   /// Build a new predefined expression.
2479   ///
2480   /// By default, performs semantic analysis to build the new expression.
2481   /// Subclasses may override this routine to provide different behavior.
2482   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2483                                    PredefinedExpr::IdentKind IK) {
2484     return getSema().BuildPredefinedExpr(Loc, IK);
2485   }
2486 
2487   /// Build a new expression that references a declaration.
2488   ///
2489   /// By default, performs semantic analysis to build the new expression.
2490   /// Subclasses may override this routine to provide different behavior.
2491   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2492                                         LookupResult &R,
2493                                         bool RequiresADL) {
2494     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2495   }
2496 
2497 
2498   /// Build a new expression that references a declaration.
2499   ///
2500   /// By default, performs semantic analysis to build the new expression.
2501   /// Subclasses may override this routine to provide different behavior.
2502   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2503                                 ValueDecl *VD,
2504                                 const DeclarationNameInfo &NameInfo,
2505                                 NamedDecl *Found,
2506                                 TemplateArgumentListInfo *TemplateArgs) {
2507     CXXScopeSpec SS;
2508     SS.Adopt(QualifierLoc);
2509     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2510                                               TemplateArgs);
2511   }
2512 
2513   /// Build a new expression in parentheses.
2514   ///
2515   /// By default, performs semantic analysis to build the new expression.
2516   /// Subclasses may override this routine to provide different behavior.
2517   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2518                                     SourceLocation RParen) {
2519     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2520   }
2521 
2522   /// Build a new pseudo-destructor expression.
2523   ///
2524   /// By default, performs semantic analysis to build the new expression.
2525   /// Subclasses may override this routine to provide different behavior.
2526   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2527                                             SourceLocation OperatorLoc,
2528                                             bool isArrow,
2529                                             CXXScopeSpec &SS,
2530                                             TypeSourceInfo *ScopeType,
2531                                             SourceLocation CCLoc,
2532                                             SourceLocation TildeLoc,
2533                                         PseudoDestructorTypeStorage Destroyed);
2534 
2535   /// Build a new unary operator expression.
2536   ///
2537   /// By default, performs semantic analysis to build the new expression.
2538   /// Subclasses may override this routine to provide different behavior.
2539   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2540                                         UnaryOperatorKind Opc,
2541                                         Expr *SubExpr) {
2542     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2543   }
2544 
2545   /// Build a new builtin offsetof expression.
2546   ///
2547   /// By default, performs semantic analysis to build the new expression.
2548   /// Subclasses may override this routine to provide different behavior.
2549   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2550                                  TypeSourceInfo *Type,
2551                                  ArrayRef<Sema::OffsetOfComponent> Components,
2552                                  SourceLocation RParenLoc) {
2553     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2554                                           RParenLoc);
2555   }
2556 
2557   /// Build a new sizeof, alignof or vec_step expression with a
2558   /// type argument.
2559   ///
2560   /// By default, performs semantic analysis to build the new expression.
2561   /// Subclasses may override this routine to provide different behavior.
2562   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2563                                          SourceLocation OpLoc,
2564                                          UnaryExprOrTypeTrait ExprKind,
2565                                          SourceRange R) {
2566     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2567   }
2568 
2569   /// Build a new sizeof, alignof or vec step expression with an
2570   /// expression argument.
2571   ///
2572   /// By default, performs semantic analysis to build the new expression.
2573   /// Subclasses may override this routine to provide different behavior.
2574   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2575                                          UnaryExprOrTypeTrait ExprKind,
2576                                          SourceRange R) {
2577     ExprResult Result
2578       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2579     if (Result.isInvalid())
2580       return ExprError();
2581 
2582     return Result;
2583   }
2584 
2585   /// Build a new array subscript expression.
2586   ///
2587   /// By default, performs semantic analysis to build the new expression.
2588   /// Subclasses may override this routine to provide different behavior.
2589   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2590                                              SourceLocation LBracketLoc,
2591                                              Expr *RHS,
2592                                              SourceLocation RBracketLoc) {
2593     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2594                                              LBracketLoc, RHS,
2595                                              RBracketLoc);
2596   }
2597 
2598   /// Build a new matrix subscript expression.
2599   ///
2600   /// By default, performs semantic analysis to build the new expression.
2601   /// Subclasses may override this routine to provide different behavior.
2602   ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2603                                         Expr *ColumnIdx,
2604                                         SourceLocation RBracketLoc) {
2605     return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2606                                                       RBracketLoc);
2607   }
2608 
2609   /// Build a new array section expression.
2610   ///
2611   /// By default, performs semantic analysis to build the new expression.
2612   /// Subclasses may override this routine to provide different behavior.
2613   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2614                                         Expr *LowerBound,
2615                                         SourceLocation ColonLocFirst,
2616                                         SourceLocation ColonLocSecond,
2617                                         Expr *Length, Expr *Stride,
2618                                         SourceLocation RBracketLoc) {
2619     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2620                                               ColonLocFirst, ColonLocSecond,
2621                                               Length, Stride, RBracketLoc);
2622   }
2623 
2624   /// Build a new array shaping expression.
2625   ///
2626   /// By default, performs semantic analysis to build the new expression.
2627   /// Subclasses may override this routine to provide different behavior.
2628   ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2629                                         SourceLocation RParenLoc,
2630                                         ArrayRef<Expr *> Dims,
2631                                         ArrayRef<SourceRange> BracketsRanges) {
2632     return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2633                                               BracketsRanges);
2634   }
2635 
2636   /// Build a new iterator expression.
2637   ///
2638   /// By default, performs semantic analysis to build the new expression.
2639   /// Subclasses may override this routine to provide different behavior.
2640   ExprResult RebuildOMPIteratorExpr(
2641       SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2642       ArrayRef<Sema::OMPIteratorData> Data) {
2643     return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2644                                           LLoc, RLoc, Data);
2645   }
2646 
2647   /// Build a new call expression.
2648   ///
2649   /// By default, performs semantic analysis to build the new expression.
2650   /// Subclasses may override this routine to provide different behavior.
2651   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2652                                    MultiExprArg Args,
2653                                    SourceLocation RParenLoc,
2654                                    Expr *ExecConfig = nullptr) {
2655     return getSema().ActOnCallExpr(
2656         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2657   }
2658 
2659   ExprResult RebuildCxxSubscriptExpr(Expr *Callee, SourceLocation LParenLoc,
2660                                      MultiExprArg Args,
2661                                      SourceLocation RParenLoc) {
2662     return getSema().ActOnArraySubscriptExpr(
2663         /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc);
2664   }
2665 
2666   /// Build a new member access 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 RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2671                                bool isArrow,
2672                                NestedNameSpecifierLoc QualifierLoc,
2673                                SourceLocation TemplateKWLoc,
2674                                const DeclarationNameInfo &MemberNameInfo,
2675                                ValueDecl *Member,
2676                                NamedDecl *FoundDecl,
2677                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2678                                NamedDecl *FirstQualifierInScope) {
2679     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2680                                                                       isArrow);
2681     if (!Member->getDeclName()) {
2682       // We have a reference to an unnamed field.  This is always the
2683       // base of an anonymous struct/union member access, i.e. the
2684       // field is always of record type.
2685       assert(Member->getType()->isRecordType() &&
2686              "unnamed member not of record type?");
2687 
2688       BaseResult =
2689         getSema().PerformObjectMemberConversion(BaseResult.get(),
2690                                                 QualifierLoc.getNestedNameSpecifier(),
2691                                                 FoundDecl, Member);
2692       if (BaseResult.isInvalid())
2693         return ExprError();
2694       Base = BaseResult.get();
2695 
2696       CXXScopeSpec EmptySS;
2697       return getSema().BuildFieldReferenceExpr(
2698           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2699           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2700     }
2701 
2702     CXXScopeSpec SS;
2703     SS.Adopt(QualifierLoc);
2704 
2705     Base = BaseResult.get();
2706     QualType BaseType = Base->getType();
2707 
2708     if (isArrow && !BaseType->isPointerType())
2709       return ExprError();
2710 
2711     // FIXME: this involves duplicating earlier analysis in a lot of
2712     // cases; we should avoid this when possible.
2713     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2714     R.addDecl(FoundDecl);
2715     R.resolveKind();
2716 
2717     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2718                                               SS, TemplateKWLoc,
2719                                               FirstQualifierInScope,
2720                                               R, ExplicitTemplateArgs,
2721                                               /*S*/nullptr);
2722   }
2723 
2724   /// Build a new binary operator expression.
2725   ///
2726   /// By default, performs semantic analysis to build the new expression.
2727   /// Subclasses may override this routine to provide different behavior.
2728   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2729                                          BinaryOperatorKind Opc,
2730                                          Expr *LHS, Expr *RHS) {
2731     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2732   }
2733 
2734   /// Build a new rewritten operator expression.
2735   ///
2736   /// By default, performs semantic analysis to build the new expression.
2737   /// Subclasses may override this routine to provide different behavior.
2738   ExprResult RebuildCXXRewrittenBinaryOperator(
2739       SourceLocation OpLoc, BinaryOperatorKind Opcode,
2740       const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2741     return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2742                                            RHS, /*RequiresADL*/false);
2743   }
2744 
2745   /// Build a new conditional operator expression.
2746   ///
2747   /// By default, performs semantic analysis to build the new expression.
2748   /// Subclasses may override this routine to provide different behavior.
2749   ExprResult RebuildConditionalOperator(Expr *Cond,
2750                                         SourceLocation QuestionLoc,
2751                                         Expr *LHS,
2752                                         SourceLocation ColonLoc,
2753                                         Expr *RHS) {
2754     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2755                                         LHS, RHS);
2756   }
2757 
2758   /// Build a new C-style cast expression.
2759   ///
2760   /// By default, performs semantic analysis to build the new expression.
2761   /// Subclasses may override this routine to provide different behavior.
2762   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2763                                          TypeSourceInfo *TInfo,
2764                                          SourceLocation RParenLoc,
2765                                          Expr *SubExpr) {
2766     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2767                                          SubExpr);
2768   }
2769 
2770   /// Build a new compound literal expression.
2771   ///
2772   /// By default, performs semantic analysis to build the new expression.
2773   /// Subclasses may override this routine to provide different behavior.
2774   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2775                                               TypeSourceInfo *TInfo,
2776                                               SourceLocation RParenLoc,
2777                                               Expr *Init) {
2778     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2779                                               Init);
2780   }
2781 
2782   /// Build a new extended vector element access expression.
2783   ///
2784   /// By default, performs semantic analysis to build the new expression.
2785   /// Subclasses may override this routine to provide different behavior.
2786   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2787                                                SourceLocation OpLoc,
2788                                                SourceLocation AccessorLoc,
2789                                                IdentifierInfo &Accessor) {
2790 
2791     CXXScopeSpec SS;
2792     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2793     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2794                                               OpLoc, /*IsArrow*/ false,
2795                                               SS, SourceLocation(),
2796                                               /*FirstQualifierInScope*/ nullptr,
2797                                               NameInfo,
2798                                               /* TemplateArgs */ nullptr,
2799                                               /*S*/ nullptr);
2800   }
2801 
2802   /// Build a new initializer list expression.
2803   ///
2804   /// By default, performs semantic analysis to build the new expression.
2805   /// Subclasses may override this routine to provide different behavior.
2806   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2807                              MultiExprArg Inits,
2808                              SourceLocation RBraceLoc) {
2809     return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2810   }
2811 
2812   /// Build a new designated initializer expression.
2813   ///
2814   /// By default, performs semantic analysis to build the new expression.
2815   /// Subclasses may override this routine to provide different behavior.
2816   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2817                                              MultiExprArg ArrayExprs,
2818                                              SourceLocation EqualOrColonLoc,
2819                                              bool GNUSyntax,
2820                                              Expr *Init) {
2821     ExprResult Result
2822       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2823                                            Init);
2824     if (Result.isInvalid())
2825       return ExprError();
2826 
2827     return Result;
2828   }
2829 
2830   /// Build a new value-initialized expression.
2831   ///
2832   /// By default, builds the implicit value initialization without performing
2833   /// any semantic analysis. Subclasses may override this routine to provide
2834   /// different behavior.
2835   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2836     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2837   }
2838 
2839   /// Build a new \c va_arg 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 RebuildVAArgExpr(SourceLocation BuiltinLoc,
2844                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2845                                     SourceLocation RParenLoc) {
2846     return getSema().BuildVAArgExpr(BuiltinLoc,
2847                                     SubExpr, TInfo,
2848                                     RParenLoc);
2849   }
2850 
2851   /// Build a new expression list in parentheses.
2852   ///
2853   /// By default, performs semantic analysis to build the new expression.
2854   /// Subclasses may override this routine to provide different behavior.
2855   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2856                                   MultiExprArg SubExprs,
2857                                   SourceLocation RParenLoc) {
2858     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2859   }
2860 
2861   /// Build a new address-of-label expression.
2862   ///
2863   /// By default, performs semantic analysis, using the name of the label
2864   /// rather than attempting to map the label statement itself.
2865   /// Subclasses may override this routine to provide different behavior.
2866   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2867                                   SourceLocation LabelLoc, LabelDecl *Label) {
2868     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2869   }
2870 
2871   /// Build a new GNU statement expression.
2872   ///
2873   /// By default, performs semantic analysis to build the new expression.
2874   /// Subclasses may override this routine to provide different behavior.
2875   ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
2876                              SourceLocation RParenLoc, unsigned TemplateDepth) {
2877     return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
2878                                    TemplateDepth);
2879   }
2880 
2881   /// Build a new __builtin_choose_expr expression.
2882   ///
2883   /// By default, performs semantic analysis to build the new expression.
2884   /// Subclasses may override this routine to provide different behavior.
2885   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2886                                      Expr *Cond, Expr *LHS, Expr *RHS,
2887                                      SourceLocation RParenLoc) {
2888     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2889                                    Cond, LHS, RHS,
2890                                    RParenLoc);
2891   }
2892 
2893   /// Build a new generic selection expression.
2894   ///
2895   /// By default, performs semantic analysis to build the new expression.
2896   /// Subclasses may override this routine to provide different behavior.
2897   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2898                                          SourceLocation DefaultLoc,
2899                                          SourceLocation RParenLoc,
2900                                          Expr *ControllingExpr,
2901                                          ArrayRef<TypeSourceInfo *> Types,
2902                                          ArrayRef<Expr *> Exprs) {
2903     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2904                                                 ControllingExpr, Types, Exprs);
2905   }
2906 
2907   /// Build a new overloaded operator call expression.
2908   ///
2909   /// By default, performs semantic analysis to build the new expression.
2910   /// The semantic analysis provides the behavior of template instantiation,
2911   /// copying with transformations that turn what looks like an overloaded
2912   /// operator call into a use of a builtin operator, performing
2913   /// argument-dependent lookup, etc. Subclasses may override this routine to
2914   /// provide different behavior.
2915   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2916                                               SourceLocation OpLoc,
2917                                               Expr *Callee,
2918                                               Expr *First,
2919                                               Expr *Second);
2920 
2921   /// Build a new C++ "named" cast expression, such as static_cast or
2922   /// reinterpret_cast.
2923   ///
2924   /// By default, this routine dispatches to one of the more-specific routines
2925   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2926   /// Subclasses may override this routine to provide different behavior.
2927   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2928                                            Stmt::StmtClass Class,
2929                                            SourceLocation LAngleLoc,
2930                                            TypeSourceInfo *TInfo,
2931                                            SourceLocation RAngleLoc,
2932                                            SourceLocation LParenLoc,
2933                                            Expr *SubExpr,
2934                                            SourceLocation RParenLoc) {
2935     switch (Class) {
2936     case Stmt::CXXStaticCastExprClass:
2937       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2938                                                    RAngleLoc, LParenLoc,
2939                                                    SubExpr, RParenLoc);
2940 
2941     case Stmt::CXXDynamicCastExprClass:
2942       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2943                                                     RAngleLoc, LParenLoc,
2944                                                     SubExpr, RParenLoc);
2945 
2946     case Stmt::CXXReinterpretCastExprClass:
2947       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2948                                                         RAngleLoc, LParenLoc,
2949                                                         SubExpr,
2950                                                         RParenLoc);
2951 
2952     case Stmt::CXXConstCastExprClass:
2953       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2954                                                    RAngleLoc, LParenLoc,
2955                                                    SubExpr, RParenLoc);
2956 
2957     case Stmt::CXXAddrspaceCastExprClass:
2958       return getDerived().RebuildCXXAddrspaceCastExpr(
2959           OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
2960 
2961     default:
2962       llvm_unreachable("Invalid C++ named cast");
2963     }
2964   }
2965 
2966   /// Build a new C++ static_cast expression.
2967   ///
2968   /// By default, performs semantic analysis to build the new expression.
2969   /// Subclasses may override this routine to provide different behavior.
2970   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2971                                             SourceLocation LAngleLoc,
2972                                             TypeSourceInfo *TInfo,
2973                                             SourceLocation RAngleLoc,
2974                                             SourceLocation LParenLoc,
2975                                             Expr *SubExpr,
2976                                             SourceLocation RParenLoc) {
2977     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2978                                        TInfo, SubExpr,
2979                                        SourceRange(LAngleLoc, RAngleLoc),
2980                                        SourceRange(LParenLoc, RParenLoc));
2981   }
2982 
2983   /// Build a new C++ dynamic_cast expression.
2984   ///
2985   /// By default, performs semantic analysis to build the new expression.
2986   /// Subclasses may override this routine to provide different behavior.
2987   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2988                                              SourceLocation LAngleLoc,
2989                                              TypeSourceInfo *TInfo,
2990                                              SourceLocation RAngleLoc,
2991                                              SourceLocation LParenLoc,
2992                                              Expr *SubExpr,
2993                                              SourceLocation RParenLoc) {
2994     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2995                                        TInfo, SubExpr,
2996                                        SourceRange(LAngleLoc, RAngleLoc),
2997                                        SourceRange(LParenLoc, RParenLoc));
2998   }
2999 
3000   /// Build a new C++ reinterpret_cast expression.
3001   ///
3002   /// By default, performs semantic analysis to build the new expression.
3003   /// Subclasses may override this routine to provide different behavior.
3004   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
3005                                                  SourceLocation LAngleLoc,
3006                                                  TypeSourceInfo *TInfo,
3007                                                  SourceLocation RAngleLoc,
3008                                                  SourceLocation LParenLoc,
3009                                                  Expr *SubExpr,
3010                                                  SourceLocation RParenLoc) {
3011     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
3012                                        TInfo, SubExpr,
3013                                        SourceRange(LAngleLoc, RAngleLoc),
3014                                        SourceRange(LParenLoc, RParenLoc));
3015   }
3016 
3017   /// Build a new C++ const_cast expression.
3018   ///
3019   /// By default, performs semantic analysis to build the new expression.
3020   /// Subclasses may override this routine to provide different behavior.
3021   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
3022                                            SourceLocation LAngleLoc,
3023                                            TypeSourceInfo *TInfo,
3024                                            SourceLocation RAngleLoc,
3025                                            SourceLocation LParenLoc,
3026                                            Expr *SubExpr,
3027                                            SourceLocation RParenLoc) {
3028     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
3029                                        TInfo, SubExpr,
3030                                        SourceRange(LAngleLoc, RAngleLoc),
3031                                        SourceRange(LParenLoc, RParenLoc));
3032   }
3033 
3034   ExprResult
3035   RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
3036                               TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
3037                               SourceLocation LParenLoc, Expr *SubExpr,
3038                               SourceLocation RParenLoc) {
3039     return getSema().BuildCXXNamedCast(
3040         OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
3041         SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
3042   }
3043 
3044   /// Build a new C++ functional-style cast expression.
3045   ///
3046   /// By default, performs semantic analysis to build the new expression.
3047   /// Subclasses may override this routine to provide different behavior.
3048   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
3049                                           SourceLocation LParenLoc,
3050                                           Expr *Sub,
3051                                           SourceLocation RParenLoc,
3052                                           bool ListInitialization) {
3053     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
3054                                                MultiExprArg(&Sub, 1), RParenLoc,
3055                                                ListInitialization);
3056   }
3057 
3058   /// Build a new C++ __builtin_bit_cast expression.
3059   ///
3060   /// By default, performs semantic analysis to build the new expression.
3061   /// Subclasses may override this routine to provide different behavior.
3062   ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3063                                        TypeSourceInfo *TSI, Expr *Sub,
3064                                        SourceLocation RParenLoc) {
3065     return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3066   }
3067 
3068   /// Build a new C++ typeid(type) expression.
3069   ///
3070   /// By default, performs semantic analysis to build the new expression.
3071   /// Subclasses may override this routine to provide different behavior.
3072   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3073                                         SourceLocation TypeidLoc,
3074                                         TypeSourceInfo *Operand,
3075                                         SourceLocation RParenLoc) {
3076     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3077                                     RParenLoc);
3078   }
3079 
3080 
3081   /// Build a new C++ typeid(expr) expression.
3082   ///
3083   /// By default, performs semantic analysis to build the new expression.
3084   /// Subclasses may override this routine to provide different behavior.
3085   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3086                                         SourceLocation TypeidLoc,
3087                                         Expr *Operand,
3088                                         SourceLocation RParenLoc) {
3089     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3090                                     RParenLoc);
3091   }
3092 
3093   /// Build a new C++ __uuidof(type) expression.
3094   ///
3095   /// By default, performs semantic analysis to build the new expression.
3096   /// Subclasses may override this routine to provide different behavior.
3097   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3098                                   TypeSourceInfo *Operand,
3099                                   SourceLocation RParenLoc) {
3100     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3101   }
3102 
3103   /// Build a new C++ __uuidof(expr) expression.
3104   ///
3105   /// By default, performs semantic analysis to build the new expression.
3106   /// Subclasses may override this routine to provide different behavior.
3107   ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3108                                   Expr *Operand, SourceLocation RParenLoc) {
3109     return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3110   }
3111 
3112   /// Build a new C++ "this" expression.
3113   ///
3114   /// By default, builds a new "this" expression without performing any
3115   /// semantic analysis. Subclasses may override this routine to provide
3116   /// different behavior.
3117   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3118                                 QualType ThisType,
3119                                 bool isImplicit) {
3120     return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3121   }
3122 
3123   /// Build a new C++ throw expression.
3124   ///
3125   /// By default, performs semantic analysis to build the new expression.
3126   /// Subclasses may override this routine to provide different behavior.
3127   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3128                                  bool IsThrownVariableInScope) {
3129     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3130   }
3131 
3132   /// Build a new C++ default-argument expression.
3133   ///
3134   /// By default, builds a new default-argument expression, which does not
3135   /// require any semantic analysis. Subclasses may override this routine to
3136   /// provide different behavior.
3137   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param) {
3138     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3139                                      getSema().CurContext);
3140   }
3141 
3142   /// Build a new C++11 default-initialization expression.
3143   ///
3144   /// By default, builds a new default field initialization expression, which
3145   /// does not require any semantic analysis. Subclasses may override this
3146   /// routine to provide different behavior.
3147   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3148                                        FieldDecl *Field) {
3149     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field,
3150                                       getSema().CurContext);
3151   }
3152 
3153   /// Build a new C++ zero-initialization expression.
3154   ///
3155   /// By default, performs semantic analysis to build the new expression.
3156   /// Subclasses may override this routine to provide different behavior.
3157   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3158                                            SourceLocation LParenLoc,
3159                                            SourceLocation RParenLoc) {
3160     return getSema().BuildCXXTypeConstructExpr(
3161         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
3162   }
3163 
3164   /// Build a new C++ "new" expression.
3165   ///
3166   /// By default, performs semantic analysis to build the new expression.
3167   /// Subclasses may override this routine to provide different behavior.
3168   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
3169                                bool UseGlobal,
3170                                SourceLocation PlacementLParen,
3171                                MultiExprArg PlacementArgs,
3172                                SourceLocation PlacementRParen,
3173                                SourceRange TypeIdParens,
3174                                QualType AllocatedType,
3175                                TypeSourceInfo *AllocatedTypeInfo,
3176                                Optional<Expr *> ArraySize,
3177                                SourceRange DirectInitRange,
3178                                Expr *Initializer) {
3179     return getSema().BuildCXXNew(StartLoc, UseGlobal,
3180                                  PlacementLParen,
3181                                  PlacementArgs,
3182                                  PlacementRParen,
3183                                  TypeIdParens,
3184                                  AllocatedType,
3185                                  AllocatedTypeInfo,
3186                                  ArraySize,
3187                                  DirectInitRange,
3188                                  Initializer);
3189   }
3190 
3191   /// Build a new C++ "delete" expression.
3192   ///
3193   /// By default, performs semantic analysis to build the new expression.
3194   /// Subclasses may override this routine to provide different behavior.
3195   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3196                                         bool IsGlobalDelete,
3197                                         bool IsArrayForm,
3198                                         Expr *Operand) {
3199     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3200                                     Operand);
3201   }
3202 
3203   /// Build a new type trait expression.
3204   ///
3205   /// By default, performs semantic analysis to build the new expression.
3206   /// Subclasses may override this routine to provide different behavior.
3207   ExprResult RebuildTypeTrait(TypeTrait Trait,
3208                               SourceLocation StartLoc,
3209                               ArrayRef<TypeSourceInfo *> Args,
3210                               SourceLocation RParenLoc) {
3211     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3212   }
3213 
3214   /// Build a new array type trait expression.
3215   ///
3216   /// By default, performs semantic analysis to build the new expression.
3217   /// Subclasses may override this routine to provide different behavior.
3218   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3219                                    SourceLocation StartLoc,
3220                                    TypeSourceInfo *TSInfo,
3221                                    Expr *DimExpr,
3222                                    SourceLocation RParenLoc) {
3223     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3224   }
3225 
3226   /// Build a new expression trait expression.
3227   ///
3228   /// By default, performs semantic analysis to build the new expression.
3229   /// Subclasses may override this routine to provide different behavior.
3230   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3231                                    SourceLocation StartLoc,
3232                                    Expr *Queried,
3233                                    SourceLocation RParenLoc) {
3234     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3235   }
3236 
3237   /// Build a new (previously unresolved) declaration reference
3238   /// expression.
3239   ///
3240   /// By default, performs semantic analysis to build the new expression.
3241   /// Subclasses may override this routine to provide different behavior.
3242   ExprResult RebuildDependentScopeDeclRefExpr(
3243                                           NestedNameSpecifierLoc QualifierLoc,
3244                                           SourceLocation TemplateKWLoc,
3245                                        const DeclarationNameInfo &NameInfo,
3246                               const TemplateArgumentListInfo *TemplateArgs,
3247                                           bool IsAddressOfOperand,
3248                                           TypeSourceInfo **RecoveryTSI) {
3249     CXXScopeSpec SS;
3250     SS.Adopt(QualifierLoc);
3251 
3252     if (TemplateArgs || TemplateKWLoc.isValid())
3253       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3254                                                     TemplateArgs);
3255 
3256     return getSema().BuildQualifiedDeclarationNameExpr(
3257         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3258   }
3259 
3260   /// Build a new template-id expression.
3261   ///
3262   /// By default, performs semantic analysis to build the new expression.
3263   /// Subclasses may override this routine to provide different behavior.
3264   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3265                                    SourceLocation TemplateKWLoc,
3266                                    LookupResult &R,
3267                                    bool RequiresADL,
3268                               const TemplateArgumentListInfo *TemplateArgs) {
3269     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3270                                          TemplateArgs);
3271   }
3272 
3273   /// Build a new object-construction expression.
3274   ///
3275   /// By default, performs semantic analysis to build the new expression.
3276   /// Subclasses may override this routine to provide different behavior.
3277   ExprResult RebuildCXXConstructExpr(QualType T,
3278                                      SourceLocation Loc,
3279                                      CXXConstructorDecl *Constructor,
3280                                      bool IsElidable,
3281                                      MultiExprArg Args,
3282                                      bool HadMultipleCandidates,
3283                                      bool ListInitialization,
3284                                      bool StdInitListInitialization,
3285                                      bool RequiresZeroInit,
3286                              CXXConstructExpr::ConstructionKind ConstructKind,
3287                                      SourceRange ParenRange) {
3288     // Reconstruct the constructor we originally found, which might be
3289     // different if this is a call to an inherited constructor.
3290     CXXConstructorDecl *FoundCtor = Constructor;
3291     if (Constructor->isInheritingConstructor())
3292       FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3293 
3294     SmallVector<Expr *, 8> ConvertedArgs;
3295     if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3296                                           ConvertedArgs))
3297       return ExprError();
3298 
3299     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3300                                            IsElidable,
3301                                            ConvertedArgs,
3302                                            HadMultipleCandidates,
3303                                            ListInitialization,
3304                                            StdInitListInitialization,
3305                                            RequiresZeroInit, ConstructKind,
3306                                            ParenRange);
3307   }
3308 
3309   /// Build a new implicit construction via inherited constructor
3310   /// expression.
3311   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3312                                              CXXConstructorDecl *Constructor,
3313                                              bool ConstructsVBase,
3314                                              bool InheritedFromVBase) {
3315     return new (getSema().Context) CXXInheritedCtorInitExpr(
3316         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3317   }
3318 
3319   /// Build a new object-construction expression.
3320   ///
3321   /// By default, performs semantic analysis to build the new expression.
3322   /// Subclasses may override this routine to provide different behavior.
3323   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3324                                            SourceLocation LParenOrBraceLoc,
3325                                            MultiExprArg Args,
3326                                            SourceLocation RParenOrBraceLoc,
3327                                            bool ListInitialization) {
3328     return getSema().BuildCXXTypeConstructExpr(
3329         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3330   }
3331 
3332   /// Build a new object-construction expression.
3333   ///
3334   /// By default, performs semantic analysis to build the new expression.
3335   /// Subclasses may override this routine to provide different behavior.
3336   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3337                                                SourceLocation LParenLoc,
3338                                                MultiExprArg Args,
3339                                                SourceLocation RParenLoc,
3340                                                bool ListInitialization) {
3341     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3342                                                RParenLoc, ListInitialization);
3343   }
3344 
3345   /// Build a new member reference expression.
3346   ///
3347   /// By default, performs semantic analysis to build the new expression.
3348   /// Subclasses may override this routine to provide different behavior.
3349   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3350                                                 QualType BaseType,
3351                                                 bool IsArrow,
3352                                                 SourceLocation OperatorLoc,
3353                                           NestedNameSpecifierLoc QualifierLoc,
3354                                                 SourceLocation TemplateKWLoc,
3355                                             NamedDecl *FirstQualifierInScope,
3356                                    const DeclarationNameInfo &MemberNameInfo,
3357                               const TemplateArgumentListInfo *TemplateArgs) {
3358     CXXScopeSpec SS;
3359     SS.Adopt(QualifierLoc);
3360 
3361     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3362                                             OperatorLoc, IsArrow,
3363                                             SS, TemplateKWLoc,
3364                                             FirstQualifierInScope,
3365                                             MemberNameInfo,
3366                                             TemplateArgs, /*S*/nullptr);
3367   }
3368 
3369   /// Build a new member reference expression.
3370   ///
3371   /// By default, performs semantic analysis to build the new expression.
3372   /// Subclasses may override this routine to provide different behavior.
3373   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3374                                          SourceLocation OperatorLoc,
3375                                          bool IsArrow,
3376                                          NestedNameSpecifierLoc QualifierLoc,
3377                                          SourceLocation TemplateKWLoc,
3378                                          NamedDecl *FirstQualifierInScope,
3379                                          LookupResult &R,
3380                                 const TemplateArgumentListInfo *TemplateArgs) {
3381     CXXScopeSpec SS;
3382     SS.Adopt(QualifierLoc);
3383 
3384     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3385                                             OperatorLoc, IsArrow,
3386                                             SS, TemplateKWLoc,
3387                                             FirstQualifierInScope,
3388                                             R, TemplateArgs, /*S*/nullptr);
3389   }
3390 
3391   /// Build a new noexcept expression.
3392   ///
3393   /// By default, performs semantic analysis to build the new expression.
3394   /// Subclasses may override this routine to provide different behavior.
3395   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3396     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3397   }
3398 
3399   /// Build a new expression to compute the length of a parameter pack.
3400   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
3401                                    NamedDecl *Pack,
3402                                    SourceLocation PackLoc,
3403                                    SourceLocation RParenLoc,
3404                                    Optional<unsigned> Length,
3405                                    ArrayRef<TemplateArgument> PartialArgs) {
3406     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3407                                   RParenLoc, Length, PartialArgs);
3408   }
3409 
3410   /// Build a new expression representing a call to a source location
3411   ///  builtin.
3412   ///
3413   /// By default, performs semantic analysis to build the new expression.
3414   /// Subclasses may override this routine to provide different behavior.
3415   ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3416                                   QualType ResultTy, SourceLocation BuiltinLoc,
3417                                   SourceLocation RPLoc,
3418                                   DeclContext *ParentContext) {
3419     return getSema().BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc,
3420                                         ParentContext);
3421   }
3422 
3423   /// Build a new Objective-C boxed expression.
3424   ///
3425   /// By default, performs semantic analysis to build the new expression.
3426   /// Subclasses may override this routine to provide different behavior.
3427   ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3428       SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3429       NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3430       TemplateArgumentListInfo *TALI) {
3431     CXXScopeSpec SS;
3432     SS.Adopt(NNS);
3433     ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3434                                                          ConceptNameInfo,
3435                                                          FoundDecl,
3436                                                          NamedConcept, TALI);
3437     if (Result.isInvalid())
3438       return ExprError();
3439     return Result;
3440   }
3441 
3442   /// \brief Build a new requires expression.
3443   ///
3444   /// By default, performs semantic analysis to build the new expression.
3445   /// Subclasses may override this routine to provide different behavior.
3446   ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3447                                  RequiresExprBodyDecl *Body,
3448                                  ArrayRef<ParmVarDecl *> LocalParameters,
3449                                  ArrayRef<concepts::Requirement *> Requirements,
3450                                  SourceLocation ClosingBraceLoc) {
3451     return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3452                                 LocalParameters, Requirements, ClosingBraceLoc);
3453   }
3454 
3455   concepts::TypeRequirement *
3456   RebuildTypeRequirement(
3457       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3458     return SemaRef.BuildTypeRequirement(SubstDiag);
3459   }
3460 
3461   concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3462     return SemaRef.BuildTypeRequirement(T);
3463   }
3464 
3465   concepts::ExprRequirement *
3466   RebuildExprRequirement(
3467       concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3468       SourceLocation NoexceptLoc,
3469       concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3470     return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3471                                         std::move(Ret));
3472   }
3473 
3474   concepts::ExprRequirement *
3475   RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3476                          concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3477     return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3478                                         std::move(Ret));
3479   }
3480 
3481   concepts::NestedRequirement *
3482   RebuildNestedRequirement(
3483       concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3484     return SemaRef.BuildNestedRequirement(SubstDiag);
3485   }
3486 
3487   concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3488     return SemaRef.BuildNestedRequirement(Constraint);
3489   }
3490 
3491   /// \brief Build a new Objective-C boxed expression.
3492   ///
3493   /// By default, performs semantic analysis to build the new expression.
3494   /// Subclasses may override this routine to provide different behavior.
3495   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3496     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3497   }
3498 
3499   /// Build a new Objective-C array literal.
3500   ///
3501   /// By default, performs semantic analysis to build the new expression.
3502   /// Subclasses may override this routine to provide different behavior.
3503   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3504                                      Expr **Elements, unsigned NumElements) {
3505     return getSema().BuildObjCArrayLiteral(Range,
3506                                            MultiExprArg(Elements, NumElements));
3507   }
3508 
3509   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3510                                          Expr *Base, Expr *Key,
3511                                          ObjCMethodDecl *getterMethod,
3512                                          ObjCMethodDecl *setterMethod) {
3513     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3514                                                    getterMethod, setterMethod);
3515   }
3516 
3517   /// Build a new Objective-C dictionary literal.
3518   ///
3519   /// By default, performs semantic analysis to build the new expression.
3520   /// Subclasses may override this routine to provide different behavior.
3521   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3522                               MutableArrayRef<ObjCDictionaryElement> Elements) {
3523     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3524   }
3525 
3526   /// Build a new Objective-C \@encode expression.
3527   ///
3528   /// By default, performs semantic analysis to build the new expression.
3529   /// Subclasses may override this routine to provide different behavior.
3530   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3531                                          TypeSourceInfo *EncodeTypeInfo,
3532                                          SourceLocation RParenLoc) {
3533     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3534   }
3535 
3536   /// Build a new Objective-C class message.
3537   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3538                                           Selector Sel,
3539                                           ArrayRef<SourceLocation> SelectorLocs,
3540                                           ObjCMethodDecl *Method,
3541                                           SourceLocation LBracLoc,
3542                                           MultiExprArg Args,
3543                                           SourceLocation RBracLoc) {
3544     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3545                                      ReceiverTypeInfo->getType(),
3546                                      /*SuperLoc=*/SourceLocation(),
3547                                      Sel, Method, LBracLoc, SelectorLocs,
3548                                      RBracLoc, Args);
3549   }
3550 
3551   /// Build a new Objective-C instance message.
3552   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3553                                           Selector Sel,
3554                                           ArrayRef<SourceLocation> SelectorLocs,
3555                                           ObjCMethodDecl *Method,
3556                                           SourceLocation LBracLoc,
3557                                           MultiExprArg Args,
3558                                           SourceLocation RBracLoc) {
3559     return SemaRef.BuildInstanceMessage(Receiver,
3560                                         Receiver->getType(),
3561                                         /*SuperLoc=*/SourceLocation(),
3562                                         Sel, Method, LBracLoc, SelectorLocs,
3563                                         RBracLoc, Args);
3564   }
3565 
3566   /// Build a new Objective-C instance/class message to 'super'.
3567   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3568                                     Selector Sel,
3569                                     ArrayRef<SourceLocation> SelectorLocs,
3570                                     QualType SuperType,
3571                                     ObjCMethodDecl *Method,
3572                                     SourceLocation LBracLoc,
3573                                     MultiExprArg Args,
3574                                     SourceLocation RBracLoc) {
3575     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3576                                           SuperType,
3577                                           SuperLoc,
3578                                           Sel, Method, LBracLoc, SelectorLocs,
3579                                           RBracLoc, Args)
3580                                       : SemaRef.BuildClassMessage(nullptr,
3581                                           SuperType,
3582                                           SuperLoc,
3583                                           Sel, Method, LBracLoc, SelectorLocs,
3584                                           RBracLoc, Args);
3585 
3586 
3587   }
3588 
3589   /// Build a new Objective-C ivar reference expression.
3590   ///
3591   /// By default, performs semantic analysis to build the new expression.
3592   /// Subclasses may override this routine to provide different behavior.
3593   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3594                                           SourceLocation IvarLoc,
3595                                           bool IsArrow, bool IsFreeIvar) {
3596     CXXScopeSpec SS;
3597     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3598     ExprResult Result = getSema().BuildMemberReferenceExpr(
3599         BaseArg, BaseArg->getType(),
3600         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3601         /*FirstQualifierInScope=*/nullptr, NameInfo,
3602         /*TemplateArgs=*/nullptr,
3603         /*S=*/nullptr);
3604     if (IsFreeIvar && Result.isUsable())
3605       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3606     return Result;
3607   }
3608 
3609   /// Build a new Objective-C property reference expression.
3610   ///
3611   /// By default, performs semantic analysis to build the new expression.
3612   /// Subclasses may override this routine to provide different behavior.
3613   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3614                                         ObjCPropertyDecl *Property,
3615                                         SourceLocation PropertyLoc) {
3616     CXXScopeSpec SS;
3617     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3618     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3619                                               /*FIXME:*/PropertyLoc,
3620                                               /*IsArrow=*/false,
3621                                               SS, SourceLocation(),
3622                                               /*FirstQualifierInScope=*/nullptr,
3623                                               NameInfo,
3624                                               /*TemplateArgs=*/nullptr,
3625                                               /*S=*/nullptr);
3626   }
3627 
3628   /// Build a new Objective-C property reference expression.
3629   ///
3630   /// By default, performs semantic analysis to build the new expression.
3631   /// Subclasses may override this routine to provide different behavior.
3632   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3633                                         ObjCMethodDecl *Getter,
3634                                         ObjCMethodDecl *Setter,
3635                                         SourceLocation PropertyLoc) {
3636     // Since these expressions can only be value-dependent, we do not
3637     // need to perform semantic analysis again.
3638     return Owned(
3639       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3640                                                   VK_LValue, OK_ObjCProperty,
3641                                                   PropertyLoc, Base));
3642   }
3643 
3644   /// Build a new Objective-C "isa" expression.
3645   ///
3646   /// By default, performs semantic analysis to build the new expression.
3647   /// Subclasses may override this routine to provide different behavior.
3648   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3649                                 SourceLocation OpLoc, bool IsArrow) {
3650     CXXScopeSpec SS;
3651     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3652     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3653                                               OpLoc, IsArrow,
3654                                               SS, SourceLocation(),
3655                                               /*FirstQualifierInScope=*/nullptr,
3656                                               NameInfo,
3657                                               /*TemplateArgs=*/nullptr,
3658                                               /*S=*/nullptr);
3659   }
3660 
3661   /// Build a new shuffle vector expression.
3662   ///
3663   /// By default, performs semantic analysis to build the new expression.
3664   /// Subclasses may override this routine to provide different behavior.
3665   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3666                                       MultiExprArg SubExprs,
3667                                       SourceLocation RParenLoc) {
3668     // Find the declaration for __builtin_shufflevector
3669     const IdentifierInfo &Name
3670       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3671     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3672     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3673     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3674 
3675     // Build a reference to the __builtin_shufflevector builtin
3676     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3677     Expr *Callee = new (SemaRef.Context)
3678         DeclRefExpr(SemaRef.Context, Builtin, false,
3679                     SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3680     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3681     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3682                                        CK_BuiltinFnToFnPtr).get();
3683 
3684     // Build the CallExpr
3685     ExprResult TheCall = CallExpr::Create(
3686         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3687         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3688         FPOptionsOverride());
3689 
3690     // Type-check the __builtin_shufflevector expression.
3691     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3692   }
3693 
3694   /// Build a new convert vector expression.
3695   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3696                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3697                                       SourceLocation RParenLoc) {
3698     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3699                                          BuiltinLoc, RParenLoc);
3700   }
3701 
3702   /// Build a new template argument pack expansion.
3703   ///
3704   /// By default, performs semantic analysis to build a new pack expansion
3705   /// for a template argument. Subclasses may override this routine to provide
3706   /// different behavior.
3707   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3708                                            SourceLocation EllipsisLoc,
3709                                            Optional<unsigned> NumExpansions) {
3710     switch (Pattern.getArgument().getKind()) {
3711     case TemplateArgument::Expression: {
3712       ExprResult Result
3713         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3714                                        EllipsisLoc, NumExpansions);
3715       if (Result.isInvalid())
3716         return TemplateArgumentLoc();
3717 
3718       return TemplateArgumentLoc(Result.get(), Result.get());
3719     }
3720 
3721     case TemplateArgument::Template:
3722       return TemplateArgumentLoc(
3723           SemaRef.Context,
3724           TemplateArgument(Pattern.getArgument().getAsTemplate(),
3725                            NumExpansions),
3726           Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3727           EllipsisLoc);
3728 
3729     case TemplateArgument::Null:
3730     case TemplateArgument::Integral:
3731     case TemplateArgument::Declaration:
3732     case TemplateArgument::Pack:
3733     case TemplateArgument::TemplateExpansion:
3734     case TemplateArgument::NullPtr:
3735       llvm_unreachable("Pack expansion pattern has no parameter packs");
3736 
3737     case TemplateArgument::Type:
3738       if (TypeSourceInfo *Expansion
3739             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3740                                            EllipsisLoc,
3741                                            NumExpansions))
3742         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3743                                    Expansion);
3744       break;
3745     }
3746 
3747     return TemplateArgumentLoc();
3748   }
3749 
3750   /// Build a new expression pack expansion.
3751   ///
3752   /// By default, performs semantic analysis to build a new pack expansion
3753   /// for an expression. Subclasses may override this routine to provide
3754   /// different behavior.
3755   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3756                                   Optional<unsigned> NumExpansions) {
3757     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3758   }
3759 
3760   /// Build a new C++1z fold-expression.
3761   ///
3762   /// By default, performs semantic analysis in order to build a new fold
3763   /// expression.
3764   ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3765                                 SourceLocation LParenLoc, Expr *LHS,
3766                                 BinaryOperatorKind Operator,
3767                                 SourceLocation EllipsisLoc, Expr *RHS,
3768                                 SourceLocation RParenLoc,
3769                                 Optional<unsigned> NumExpansions) {
3770     return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3771                                       EllipsisLoc, RHS, RParenLoc,
3772                                       NumExpansions);
3773   }
3774 
3775   /// Build an empty C++1z fold-expression with the given operator.
3776   ///
3777   /// By default, produces the fallback value for the fold-expression, or
3778   /// produce an error if there is no fallback value.
3779   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3780                                      BinaryOperatorKind Operator) {
3781     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3782   }
3783 
3784   /// Build a new atomic operation expression.
3785   ///
3786   /// By default, performs semantic analysis to build the new expression.
3787   /// Subclasses may override this routine to provide different behavior.
3788   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3789                                AtomicExpr::AtomicOp Op,
3790                                SourceLocation RParenLoc) {
3791     // Use this for all of the locations, since we don't know the difference
3792     // between the call and the expr at this point.
3793     SourceRange Range{BuiltinLoc, RParenLoc};
3794     return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3795                                      Sema::AtomicArgumentOrder::AST);
3796   }
3797 
3798   ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3799                                  ArrayRef<Expr *> SubExprs, QualType Type) {
3800     return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3801   }
3802 
3803 private:
3804   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3805                                      QualType ObjectType,
3806                                      NamedDecl *FirstQualifierInScope,
3807                                      CXXScopeSpec &SS);
3808 
3809   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3810                                              QualType ObjectType,
3811                                              NamedDecl *FirstQualifierInScope,
3812                                              CXXScopeSpec &SS);
3813 
3814   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3815                                             NamedDecl *FirstQualifierInScope,
3816                                             CXXScopeSpec &SS);
3817 
3818   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3819                                       DependentNameTypeLoc TL,
3820                                       bool DeducibleTSTContext);
3821 };
3822 
3823 template <typename Derived>
3824 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3825   if (!S)
3826     return S;
3827 
3828   switch (S->getStmtClass()) {
3829   case Stmt::NoStmtClass: break;
3830 
3831   // Transform individual statement nodes
3832   // Pass SDK into statements that can produce a value
3833 #define STMT(Node, Parent)                                              \
3834   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3835 #define VALUESTMT(Node, Parent)                                         \
3836   case Stmt::Node##Class:                                               \
3837     return getDerived().Transform##Node(cast<Node>(S), SDK);
3838 #define ABSTRACT_STMT(Node)
3839 #define EXPR(Node, Parent)
3840 #include "clang/AST/StmtNodes.inc"
3841 
3842   // Transform expressions by calling TransformExpr.
3843 #define STMT(Node, Parent)
3844 #define ABSTRACT_STMT(Stmt)
3845 #define EXPR(Node, Parent) case Stmt::Node##Class:
3846 #include "clang/AST/StmtNodes.inc"
3847     {
3848       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3849 
3850       if (SDK == SDK_StmtExprResult)
3851         E = getSema().ActOnStmtExprResult(E);
3852       return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3853     }
3854   }
3855 
3856   return S;
3857 }
3858 
3859 template<typename Derived>
3860 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3861   if (!S)
3862     return S;
3863 
3864   switch (S->getClauseKind()) {
3865   default: break;
3866   // Transform individual clause nodes
3867 #define GEN_CLANG_CLAUSE_CLASS
3868 #define CLAUSE_CLASS(Enum, Str, Class)                                         \
3869   case Enum:                                                                   \
3870     return getDerived().Transform##Class(cast<Class>(S));
3871 #include "llvm/Frontend/OpenMP/OMP.inc"
3872   }
3873 
3874   return S;
3875 }
3876 
3877 
3878 template<typename Derived>
3879 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3880   if (!E)
3881     return E;
3882 
3883   switch (E->getStmtClass()) {
3884     case Stmt::NoStmtClass: break;
3885 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3886 #define ABSTRACT_STMT(Stmt)
3887 #define EXPR(Node, Parent)                                              \
3888     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3889 #include "clang/AST/StmtNodes.inc"
3890   }
3891 
3892   return E;
3893 }
3894 
3895 template<typename Derived>
3896 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3897                                                         bool NotCopyInit) {
3898   // Initializers are instantiated like expressions, except that various outer
3899   // layers are stripped.
3900   if (!Init)
3901     return Init;
3902 
3903   if (auto *FE = dyn_cast<FullExpr>(Init))
3904     Init = FE->getSubExpr();
3905 
3906   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init)) {
3907     OpaqueValueExpr *OVE = AIL->getCommonExpr();
3908     Init = OVE->getSourceExpr();
3909   }
3910 
3911   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3912     Init = MTE->getSubExpr();
3913 
3914   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3915     Init = Binder->getSubExpr();
3916 
3917   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3918     Init = ICE->getSubExprAsWritten();
3919 
3920   if (CXXStdInitializerListExpr *ILE =
3921           dyn_cast<CXXStdInitializerListExpr>(Init))
3922     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3923 
3924   // If this is copy-initialization, we only need to reconstruct
3925   // InitListExprs. Other forms of copy-initialization will be a no-op if
3926   // the initializer is already the right type.
3927   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3928   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3929     return getDerived().TransformExpr(Init);
3930 
3931   // Revert value-initialization back to empty parens.
3932   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3933     SourceRange Parens = VIE->getSourceRange();
3934     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3935                                              Parens.getEnd());
3936   }
3937 
3938   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3939   if (isa<ImplicitValueInitExpr>(Init))
3940     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3941                                              SourceLocation());
3942 
3943   // Revert initialization by constructor back to a parenthesized or braced list
3944   // of expressions. Any other form of initializer can just be reused directly.
3945   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3946     return getDerived().TransformExpr(Init);
3947 
3948   // If the initialization implicitly converted an initializer list to a
3949   // std::initializer_list object, unwrap the std::initializer_list too.
3950   if (Construct && Construct->isStdInitListInitialization())
3951     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3952 
3953   // Enter a list-init context if this was list initialization.
3954   EnterExpressionEvaluationContext Context(
3955       getSema(), EnterExpressionEvaluationContext::InitList,
3956       Construct->isListInitialization());
3957 
3958   SmallVector<Expr*, 8> NewArgs;
3959   bool ArgChanged = false;
3960   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3961                                   /*IsCall*/true, NewArgs, &ArgChanged))
3962     return ExprError();
3963 
3964   // If this was list initialization, revert to syntactic list form.
3965   if (Construct->isListInitialization())
3966     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3967                                         Construct->getEndLoc());
3968 
3969   // Build a ParenListExpr to represent anything else.
3970   SourceRange Parens = Construct->getParenOrBraceRange();
3971   if (Parens.isInvalid()) {
3972     // This was a variable declaration's initialization for which no initializer
3973     // was specified.
3974     assert(NewArgs.empty() &&
3975            "no parens or braces but have direct init with arguments?");
3976     return ExprEmpty();
3977   }
3978   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3979                                            Parens.getEnd());
3980 }
3981 
3982 template<typename Derived>
3983 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3984                                             unsigned NumInputs,
3985                                             bool IsCall,
3986                                       SmallVectorImpl<Expr *> &Outputs,
3987                                             bool *ArgChanged) {
3988   for (unsigned I = 0; I != NumInputs; ++I) {
3989     // If requested, drop call arguments that need to be dropped.
3990     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3991       if (ArgChanged)
3992         *ArgChanged = true;
3993 
3994       break;
3995     }
3996 
3997     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3998       Expr *Pattern = Expansion->getPattern();
3999 
4000       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4001       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4002       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4003 
4004       // Determine whether the set of unexpanded parameter packs can and should
4005       // be expanded.
4006       bool Expand = true;
4007       bool RetainExpansion = false;
4008       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
4009       Optional<unsigned> NumExpansions = OrigNumExpansions;
4010       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
4011                                                Pattern->getSourceRange(),
4012                                                Unexpanded,
4013                                                Expand, RetainExpansion,
4014                                                NumExpansions))
4015         return true;
4016 
4017       if (!Expand) {
4018         // The transform has determined that we should perform a simple
4019         // transformation on the pack expansion, producing another pack
4020         // expansion.
4021         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4022         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
4023         if (OutPattern.isInvalid())
4024           return true;
4025 
4026         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
4027                                                 Expansion->getEllipsisLoc(),
4028                                                            NumExpansions);
4029         if (Out.isInvalid())
4030           return true;
4031 
4032         if (ArgChanged)
4033           *ArgChanged = true;
4034         Outputs.push_back(Out.get());
4035         continue;
4036       }
4037 
4038       // Record right away that the argument was changed.  This needs
4039       // to happen even if the array expands to nothing.
4040       if (ArgChanged) *ArgChanged = true;
4041 
4042       // The transform has determined that we should perform an elementwise
4043       // expansion of the pattern. Do so.
4044       for (unsigned I = 0; I != *NumExpansions; ++I) {
4045         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4046         ExprResult Out = getDerived().TransformExpr(Pattern);
4047         if (Out.isInvalid())
4048           return true;
4049 
4050         if (Out.get()->containsUnexpandedParameterPack()) {
4051           Out = getDerived().RebuildPackExpansion(
4052               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4053           if (Out.isInvalid())
4054             return true;
4055         }
4056 
4057         Outputs.push_back(Out.get());
4058       }
4059 
4060       // If we're supposed to retain a pack expansion, do so by temporarily
4061       // forgetting the partially-substituted parameter pack.
4062       if (RetainExpansion) {
4063         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4064 
4065         ExprResult Out = getDerived().TransformExpr(Pattern);
4066         if (Out.isInvalid())
4067           return true;
4068 
4069         Out = getDerived().RebuildPackExpansion(
4070             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4071         if (Out.isInvalid())
4072           return true;
4073 
4074         Outputs.push_back(Out.get());
4075       }
4076 
4077       continue;
4078     }
4079 
4080     ExprResult Result =
4081       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4082              : getDerived().TransformExpr(Inputs[I]);
4083     if (Result.isInvalid())
4084       return true;
4085 
4086     if (Result.get() != Inputs[I] && ArgChanged)
4087       *ArgChanged = true;
4088 
4089     Outputs.push_back(Result.get());
4090   }
4091 
4092   return false;
4093 }
4094 
4095 template <typename Derived>
4096 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4097     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4098   if (Var) {
4099     VarDecl *ConditionVar = cast_or_null<VarDecl>(
4100         getDerived().TransformDefinition(Var->getLocation(), Var));
4101 
4102     if (!ConditionVar)
4103       return Sema::ConditionError();
4104 
4105     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4106   }
4107 
4108   if (Expr) {
4109     ExprResult CondExpr = getDerived().TransformExpr(Expr);
4110 
4111     if (CondExpr.isInvalid())
4112       return Sema::ConditionError();
4113 
4114     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind,
4115                                     /*MissingOK=*/true);
4116   }
4117 
4118   return Sema::ConditionResult();
4119 }
4120 
4121 template <typename Derived>
4122 NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4123     NestedNameSpecifierLoc NNS, QualType ObjectType,
4124     NamedDecl *FirstQualifierInScope) {
4125   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4126   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4127        Qualifier = Qualifier.getPrefix())
4128     Qualifiers.push_back(Qualifier);
4129 
4130   CXXScopeSpec SS;
4131   while (!Qualifiers.empty()) {
4132     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4133     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4134 
4135     switch (QNNS->getKind()) {
4136     case NestedNameSpecifier::Identifier: {
4137       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4138                                       Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4139                                       ObjectType);
4140       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4141                                               SS, FirstQualifierInScope, false))
4142         return NestedNameSpecifierLoc();
4143       break;
4144     }
4145 
4146     case NestedNameSpecifier::Namespace: {
4147       NamespaceDecl *NS =
4148           cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4149               Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4150       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4151       break;
4152     }
4153 
4154     case NestedNameSpecifier::NamespaceAlias: {
4155       NamespaceAliasDecl *Alias =
4156           cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4157               Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4158       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4159                 Q.getLocalEndLoc());
4160       break;
4161     }
4162 
4163     case NestedNameSpecifier::Global:
4164       // There is no meaningful transformation that one could perform on the
4165       // global scope.
4166       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4167       break;
4168 
4169     case NestedNameSpecifier::Super: {
4170       CXXRecordDecl *RD =
4171           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4172               SourceLocation(), QNNS->getAsRecordDecl()));
4173       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4174       break;
4175     }
4176 
4177     case NestedNameSpecifier::TypeSpecWithTemplate:
4178     case NestedNameSpecifier::TypeSpec: {
4179       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4180                                               FirstQualifierInScope, SS);
4181 
4182       if (!TL)
4183         return NestedNameSpecifierLoc();
4184 
4185       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
4186           (SemaRef.getLangOpts().CPlusPlus11 &&
4187            TL.getType()->isEnumeralType())) {
4188         assert(!TL.getType().hasLocalQualifiers() &&
4189                "Can't get cv-qualifiers here");
4190         if (TL.getType()->isEnumeralType())
4191           SemaRef.Diag(TL.getBeginLoc(),
4192                        diag::warn_cxx98_compat_enum_nested_name_spec);
4193         SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4194                   Q.getLocalEndLoc());
4195         break;
4196       }
4197       // If the nested-name-specifier is an invalid type def, don't emit an
4198       // error because a previous error should have already been emitted.
4199       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
4200       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4201         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4202             << TL.getType() << SS.getRange();
4203       }
4204       return NestedNameSpecifierLoc();
4205     }
4206     }
4207 
4208     // The qualifier-in-scope and object type only apply to the leftmost entity.
4209     FirstQualifierInScope = nullptr;
4210     ObjectType = QualType();
4211   }
4212 
4213   // Don't rebuild the nested-name-specifier if we don't have to.
4214   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4215       !getDerived().AlwaysRebuild())
4216     return NNS;
4217 
4218   // If we can re-use the source-location data from the original
4219   // nested-name-specifier, do so.
4220   if (SS.location_size() == NNS.getDataLength() &&
4221       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4222     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4223 
4224   // Allocate new nested-name-specifier location information.
4225   return SS.getWithLocInContext(SemaRef.Context);
4226 }
4227 
4228 template<typename Derived>
4229 DeclarationNameInfo
4230 TreeTransform<Derived>
4231 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4232   DeclarationName Name = NameInfo.getName();
4233   if (!Name)
4234     return DeclarationNameInfo();
4235 
4236   switch (Name.getNameKind()) {
4237   case DeclarationName::Identifier:
4238   case DeclarationName::ObjCZeroArgSelector:
4239   case DeclarationName::ObjCOneArgSelector:
4240   case DeclarationName::ObjCMultiArgSelector:
4241   case DeclarationName::CXXOperatorName:
4242   case DeclarationName::CXXLiteralOperatorName:
4243   case DeclarationName::CXXUsingDirective:
4244     return NameInfo;
4245 
4246   case DeclarationName::CXXDeductionGuideName: {
4247     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4248     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4249         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4250     if (!NewTemplate)
4251       return DeclarationNameInfo();
4252 
4253     DeclarationNameInfo NewNameInfo(NameInfo);
4254     NewNameInfo.setName(
4255         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4256     return NewNameInfo;
4257   }
4258 
4259   case DeclarationName::CXXConstructorName:
4260   case DeclarationName::CXXDestructorName:
4261   case DeclarationName::CXXConversionFunctionName: {
4262     TypeSourceInfo *NewTInfo;
4263     CanQualType NewCanTy;
4264     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4265       NewTInfo = getDerived().TransformType(OldTInfo);
4266       if (!NewTInfo)
4267         return DeclarationNameInfo();
4268       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4269     }
4270     else {
4271       NewTInfo = nullptr;
4272       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4273       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4274       if (NewT.isNull())
4275         return DeclarationNameInfo();
4276       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4277     }
4278 
4279     DeclarationName NewName
4280       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4281                                                            NewCanTy);
4282     DeclarationNameInfo NewNameInfo(NameInfo);
4283     NewNameInfo.setName(NewName);
4284     NewNameInfo.setNamedTypeInfo(NewTInfo);
4285     return NewNameInfo;
4286   }
4287   }
4288 
4289   llvm_unreachable("Unknown name kind.");
4290 }
4291 
4292 template<typename Derived>
4293 TemplateName
4294 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4295                                               TemplateName Name,
4296                                               SourceLocation NameLoc,
4297                                               QualType ObjectType,
4298                                               NamedDecl *FirstQualifierInScope,
4299                                               bool AllowInjectedClassName) {
4300   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4301     TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
4302     assert(Template && "qualified template name must refer to a template");
4303 
4304     TemplateDecl *TransTemplate
4305       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4306                                                               Template));
4307     if (!TransTemplate)
4308       return TemplateName();
4309 
4310     if (!getDerived().AlwaysRebuild() &&
4311         SS.getScopeRep() == QTN->getQualifier() &&
4312         TransTemplate == Template)
4313       return Name;
4314 
4315     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4316                                             TransTemplate);
4317   }
4318 
4319   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4320     if (SS.getScopeRep()) {
4321       // These apply to the scope specifier, not the template.
4322       ObjectType = QualType();
4323       FirstQualifierInScope = nullptr;
4324     }
4325 
4326     if (!getDerived().AlwaysRebuild() &&
4327         SS.getScopeRep() == DTN->getQualifier() &&
4328         ObjectType.isNull())
4329       return Name;
4330 
4331     // FIXME: Preserve the location of the "template" keyword.
4332     SourceLocation TemplateKWLoc = NameLoc;
4333 
4334     if (DTN->isIdentifier()) {
4335       return getDerived().RebuildTemplateName(SS,
4336                                               TemplateKWLoc,
4337                                               *DTN->getIdentifier(),
4338                                               NameLoc,
4339                                               ObjectType,
4340                                               FirstQualifierInScope,
4341                                               AllowInjectedClassName);
4342     }
4343 
4344     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4345                                             DTN->getOperator(), NameLoc,
4346                                             ObjectType, AllowInjectedClassName);
4347   }
4348 
4349   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4350     TemplateDecl *TransTemplate
4351       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4352                                                               Template));
4353     if (!TransTemplate)
4354       return TemplateName();
4355 
4356     if (!getDerived().AlwaysRebuild() &&
4357         TransTemplate == Template)
4358       return Name;
4359 
4360     return TemplateName(TransTemplate);
4361   }
4362 
4363   if (SubstTemplateTemplateParmPackStorage *SubstPack
4364       = Name.getAsSubstTemplateTemplateParmPack()) {
4365     TemplateTemplateParmDecl *TransParam
4366     = cast_or_null<TemplateTemplateParmDecl>(
4367             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
4368     if (!TransParam)
4369       return TemplateName();
4370 
4371     if (!getDerived().AlwaysRebuild() &&
4372         TransParam == SubstPack->getParameterPack())
4373       return Name;
4374 
4375     return getDerived().RebuildTemplateName(TransParam,
4376                                             SubstPack->getArgumentPack());
4377   }
4378 
4379   // These should be getting filtered out before they reach the AST.
4380   llvm_unreachable("overloaded function decl survived to here");
4381 }
4382 
4383 template<typename Derived>
4384 void TreeTransform<Derived>::InventTemplateArgumentLoc(
4385                                          const TemplateArgument &Arg,
4386                                          TemplateArgumentLoc &Output) {
4387   Output = getSema().getTrivialTemplateArgumentLoc(
4388       Arg, QualType(), getDerived().getBaseLocation());
4389 }
4390 
4391 template <typename Derived>
4392 bool TreeTransform<Derived>::TransformTemplateArgument(
4393     const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4394     bool Uneval) {
4395   const TemplateArgument &Arg = Input.getArgument();
4396   switch (Arg.getKind()) {
4397   case TemplateArgument::Null:
4398   case TemplateArgument::Pack:
4399     llvm_unreachable("Unexpected TemplateArgument");
4400 
4401   case TemplateArgument::Integral:
4402   case TemplateArgument::NullPtr:
4403   case TemplateArgument::Declaration: {
4404     // Transform a resolved template argument straight to a resolved template
4405     // argument. We get here when substituting into an already-substituted
4406     // template type argument during concept satisfaction checking.
4407     QualType T = Arg.getNonTypeTemplateArgumentType();
4408     QualType NewT = getDerived().TransformType(T);
4409     if (NewT.isNull())
4410       return true;
4411 
4412     ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4413                        ? Arg.getAsDecl()
4414                        : nullptr;
4415     ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4416                               getDerived().getBaseLocation(), D))
4417                         : nullptr;
4418     if (D && !NewD)
4419       return true;
4420 
4421     if (NewT == T && D == NewD)
4422       Output = Input;
4423     else if (Arg.getKind() == TemplateArgument::Integral)
4424       Output = TemplateArgumentLoc(
4425           TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4426           TemplateArgumentLocInfo());
4427     else if (Arg.getKind() == TemplateArgument::NullPtr)
4428       Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4429                                    TemplateArgumentLocInfo());
4430     else
4431       Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4432                                    TemplateArgumentLocInfo());
4433 
4434     return false;
4435   }
4436 
4437   case TemplateArgument::Type: {
4438     TypeSourceInfo *DI = Input.getTypeSourceInfo();
4439     if (!DI)
4440       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4441 
4442     DI = getDerived().TransformType(DI);
4443     if (!DI)
4444       return true;
4445 
4446     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4447     return false;
4448   }
4449 
4450   case TemplateArgument::Template: {
4451     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4452     if (QualifierLoc) {
4453       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4454       if (!QualifierLoc)
4455         return true;
4456     }
4457 
4458     CXXScopeSpec SS;
4459     SS.Adopt(QualifierLoc);
4460     TemplateName Template = getDerived().TransformTemplateName(
4461         SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4462     if (Template.isNull())
4463       return true;
4464 
4465     Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4466                                  QualifierLoc, Input.getTemplateNameLoc());
4467     return false;
4468   }
4469 
4470   case TemplateArgument::TemplateExpansion:
4471     llvm_unreachable("Caller should expand pack expansions");
4472 
4473   case TemplateArgument::Expression: {
4474     // Template argument expressions are constant expressions.
4475     EnterExpressionEvaluationContext Unevaluated(
4476         getSema(),
4477         Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4478                : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4479         /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
4480         Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4481 
4482     Expr *InputExpr = Input.getSourceExpression();
4483     if (!InputExpr)
4484       InputExpr = Input.getArgument().getAsExpr();
4485 
4486     ExprResult E = getDerived().TransformExpr(InputExpr);
4487     E = SemaRef.ActOnConstantExpression(E);
4488     if (E.isInvalid())
4489       return true;
4490     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4491     return false;
4492   }
4493   }
4494 
4495   // Work around bogus GCC warning
4496   return true;
4497 }
4498 
4499 /// Iterator adaptor that invents template argument location information
4500 /// for each of the template arguments in its underlying iterator.
4501 template<typename Derived, typename InputIterator>
4502 class TemplateArgumentLocInventIterator {
4503   TreeTransform<Derived> &Self;
4504   InputIterator Iter;
4505 
4506 public:
4507   typedef TemplateArgumentLoc value_type;
4508   typedef TemplateArgumentLoc reference;
4509   typedef typename std::iterator_traits<InputIterator>::difference_type
4510     difference_type;
4511   typedef std::input_iterator_tag iterator_category;
4512 
4513   class pointer {
4514     TemplateArgumentLoc Arg;
4515 
4516   public:
4517     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4518 
4519     const TemplateArgumentLoc *operator->() const { return &Arg; }
4520   };
4521 
4522   TemplateArgumentLocInventIterator() { }
4523 
4524   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4525                                              InputIterator Iter)
4526     : Self(Self), Iter(Iter) { }
4527 
4528   TemplateArgumentLocInventIterator &operator++() {
4529     ++Iter;
4530     return *this;
4531   }
4532 
4533   TemplateArgumentLocInventIterator operator++(int) {
4534     TemplateArgumentLocInventIterator Old(*this);
4535     ++(*this);
4536     return Old;
4537   }
4538 
4539   reference operator*() const {
4540     TemplateArgumentLoc Result;
4541     Self.InventTemplateArgumentLoc(*Iter, Result);
4542     return Result;
4543   }
4544 
4545   pointer operator->() const { return pointer(**this); }
4546 
4547   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4548                          const TemplateArgumentLocInventIterator &Y) {
4549     return X.Iter == Y.Iter;
4550   }
4551 
4552   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4553                          const TemplateArgumentLocInventIterator &Y) {
4554     return X.Iter != Y.Iter;
4555   }
4556 };
4557 
4558 template<typename Derived>
4559 template<typename InputIterator>
4560 bool TreeTransform<Derived>::TransformTemplateArguments(
4561     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4562     bool Uneval) {
4563   for (; First != Last; ++First) {
4564     TemplateArgumentLoc Out;
4565     TemplateArgumentLoc In = *First;
4566 
4567     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4568       // Unpack argument packs, which we translate them into separate
4569       // arguments.
4570       // FIXME: We could do much better if we could guarantee that the
4571       // TemplateArgumentLocInfo for the pack expansion would be usable for
4572       // all of the template arguments in the argument pack.
4573       typedef TemplateArgumentLocInventIterator<Derived,
4574                                                 TemplateArgument::pack_iterator>
4575         PackLocIterator;
4576       if (TransformTemplateArguments(PackLocIterator(*this,
4577                                                  In.getArgument().pack_begin()),
4578                                      PackLocIterator(*this,
4579                                                    In.getArgument().pack_end()),
4580                                      Outputs, Uneval))
4581         return true;
4582 
4583       continue;
4584     }
4585 
4586     if (In.getArgument().isPackExpansion()) {
4587       // We have a pack expansion, for which we will be substituting into
4588       // the pattern.
4589       SourceLocation Ellipsis;
4590       Optional<unsigned> OrigNumExpansions;
4591       TemplateArgumentLoc Pattern
4592         = getSema().getTemplateArgumentPackExpansionPattern(
4593               In, Ellipsis, OrigNumExpansions);
4594 
4595       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4596       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4597       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4598 
4599       // Determine whether the set of unexpanded parameter packs can and should
4600       // be expanded.
4601       bool Expand = true;
4602       bool RetainExpansion = false;
4603       Optional<unsigned> NumExpansions = OrigNumExpansions;
4604       if (getDerived().TryExpandParameterPacks(Ellipsis,
4605                                                Pattern.getSourceRange(),
4606                                                Unexpanded,
4607                                                Expand,
4608                                                RetainExpansion,
4609                                                NumExpansions))
4610         return true;
4611 
4612       if (!Expand) {
4613         // The transform has determined that we should perform a simple
4614         // transformation on the pack expansion, producing another pack
4615         // expansion.
4616         TemplateArgumentLoc OutPattern;
4617         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4618         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4619           return true;
4620 
4621         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4622                                                 NumExpansions);
4623         if (Out.getArgument().isNull())
4624           return true;
4625 
4626         Outputs.addArgument(Out);
4627         continue;
4628       }
4629 
4630       // The transform has determined that we should perform an elementwise
4631       // expansion of the pattern. Do so.
4632       for (unsigned I = 0; I != *NumExpansions; ++I) {
4633         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4634 
4635         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4636           return true;
4637 
4638         if (Out.getArgument().containsUnexpandedParameterPack()) {
4639           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4640                                                   OrigNumExpansions);
4641           if (Out.getArgument().isNull())
4642             return true;
4643         }
4644 
4645         Outputs.addArgument(Out);
4646       }
4647 
4648       // If we're supposed to retain a pack expansion, do so by temporarily
4649       // forgetting the partially-substituted parameter pack.
4650       if (RetainExpansion) {
4651         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4652 
4653         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4654           return true;
4655 
4656         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4657                                                 OrigNumExpansions);
4658         if (Out.getArgument().isNull())
4659           return true;
4660 
4661         Outputs.addArgument(Out);
4662       }
4663 
4664       continue;
4665     }
4666 
4667     // The simple case:
4668     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4669       return true;
4670 
4671     Outputs.addArgument(Out);
4672   }
4673 
4674   return false;
4675 
4676 }
4677 
4678 //===----------------------------------------------------------------------===//
4679 // Type transformation
4680 //===----------------------------------------------------------------------===//
4681 
4682 template<typename Derived>
4683 QualType TreeTransform<Derived>::TransformType(QualType T) {
4684   if (getDerived().AlreadyTransformed(T))
4685     return T;
4686 
4687   // Temporary workaround.  All of these transformations should
4688   // eventually turn into transformations on TypeLocs.
4689   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4690                                                 getDerived().getBaseLocation());
4691 
4692   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4693 
4694   if (!NewDI)
4695     return QualType();
4696 
4697   return NewDI->getType();
4698 }
4699 
4700 template<typename Derived>
4701 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4702   // Refine the base location to the type's location.
4703   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4704                        getDerived().getBaseEntity());
4705   if (getDerived().AlreadyTransformed(DI->getType()))
4706     return DI;
4707 
4708   TypeLocBuilder TLB;
4709 
4710   TypeLoc TL = DI->getTypeLoc();
4711   TLB.reserve(TL.getFullDataSize());
4712 
4713   QualType Result = getDerived().TransformType(TLB, TL);
4714   if (Result.isNull())
4715     return nullptr;
4716 
4717   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4718 }
4719 
4720 template<typename Derived>
4721 QualType
4722 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4723   switch (T.getTypeLocClass()) {
4724 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4725 #define TYPELOC(CLASS, PARENT)                                                 \
4726   case TypeLoc::CLASS:                                                         \
4727     return getDerived().Transform##CLASS##Type(TLB,                            \
4728                                                T.castAs<CLASS##TypeLoc>());
4729 #include "clang/AST/TypeLocNodes.def"
4730   }
4731 
4732   llvm_unreachable("unhandled type loc!");
4733 }
4734 
4735 template<typename Derived>
4736 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4737   if (!isa<DependentNameType>(T))
4738     return TransformType(T);
4739 
4740   if (getDerived().AlreadyTransformed(T))
4741     return T;
4742   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4743                                                 getDerived().getBaseLocation());
4744   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4745   return NewDI ? NewDI->getType() : QualType();
4746 }
4747 
4748 template<typename Derived>
4749 TypeSourceInfo *
4750 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4751   if (!isa<DependentNameType>(DI->getType()))
4752     return TransformType(DI);
4753 
4754   // Refine the base location to the type's location.
4755   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4756                        getDerived().getBaseEntity());
4757   if (getDerived().AlreadyTransformed(DI->getType()))
4758     return DI;
4759 
4760   TypeLocBuilder TLB;
4761 
4762   TypeLoc TL = DI->getTypeLoc();
4763   TLB.reserve(TL.getFullDataSize());
4764 
4765   auto QTL = TL.getAs<QualifiedTypeLoc>();
4766   if (QTL)
4767     TL = QTL.getUnqualifiedLoc();
4768 
4769   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4770 
4771   QualType Result = getDerived().TransformDependentNameType(
4772       TLB, DNTL, /*DeducedTSTContext*/true);
4773   if (Result.isNull())
4774     return nullptr;
4775 
4776   if (QTL) {
4777     Result = getDerived().RebuildQualifiedType(Result, QTL);
4778     if (Result.isNull())
4779       return nullptr;
4780     TLB.TypeWasModifiedSafely(Result);
4781   }
4782 
4783   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4784 }
4785 
4786 template<typename Derived>
4787 QualType
4788 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4789                                                QualifiedTypeLoc T) {
4790   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4791   if (Result.isNull())
4792     return QualType();
4793 
4794   Result = getDerived().RebuildQualifiedType(Result, T);
4795 
4796   if (Result.isNull())
4797     return QualType();
4798 
4799   // RebuildQualifiedType might have updated the type, but not in a way
4800   // that invalidates the TypeLoc. (There's no location information for
4801   // qualifiers.)
4802   TLB.TypeWasModifiedSafely(Result);
4803 
4804   return Result;
4805 }
4806 
4807 template <typename Derived>
4808 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4809                                                       QualifiedTypeLoc TL) {
4810 
4811   SourceLocation Loc = TL.getBeginLoc();
4812   Qualifiers Quals = TL.getType().getLocalQualifiers();
4813 
4814   if ((T.getAddressSpace() != LangAS::Default &&
4815        Quals.getAddressSpace() != LangAS::Default) &&
4816       T.getAddressSpace() != Quals.getAddressSpace()) {
4817     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4818         << TL.getType() << T;
4819     return QualType();
4820   }
4821 
4822   // C++ [dcl.fct]p7:
4823   //   [When] adding cv-qualifications on top of the function type [...] the
4824   //   cv-qualifiers are ignored.
4825   if (T->isFunctionType()) {
4826     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4827                                                      Quals.getAddressSpace());
4828     return T;
4829   }
4830 
4831   // C++ [dcl.ref]p1:
4832   //   when the cv-qualifiers are introduced through the use of a typedef-name
4833   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4834   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4835   // applied to a reference type.
4836   if (T->isReferenceType()) {
4837     // The only qualifier that applies to a reference type is restrict.
4838     if (!Quals.hasRestrict())
4839       return T;
4840     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4841   }
4842 
4843   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4844   // resulting type.
4845   if (Quals.hasObjCLifetime()) {
4846     if (!T->isObjCLifetimeType() && !T->isDependentType())
4847       Quals.removeObjCLifetime();
4848     else if (T.getObjCLifetime()) {
4849       // Objective-C ARC:
4850       //   A lifetime qualifier applied to a substituted template parameter
4851       //   overrides the lifetime qualifier from the template argument.
4852       const AutoType *AutoTy;
4853       if (const SubstTemplateTypeParmType *SubstTypeParam
4854                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4855         QualType Replacement = SubstTypeParam->getReplacementType();
4856         Qualifiers Qs = Replacement.getQualifiers();
4857         Qs.removeObjCLifetime();
4858         Replacement = SemaRef.Context.getQualifiedType(
4859             Replacement.getUnqualifiedType(), Qs);
4860         T = SemaRef.Context.getSubstTemplateTypeParmType(
4861             SubstTypeParam->getReplacedParameter(), Replacement);
4862       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4863         // 'auto' types behave the same way as template parameters.
4864         QualType Deduced = AutoTy->getDeducedType();
4865         Qualifiers Qs = Deduced.getQualifiers();
4866         Qs.removeObjCLifetime();
4867         Deduced =
4868             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4869         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4870                                         AutoTy->isDependentType(),
4871                                         /*isPack=*/false,
4872                                         AutoTy->getTypeConstraintConcept(),
4873                                         AutoTy->getTypeConstraintArguments());
4874       } else {
4875         // Otherwise, complain about the addition of a qualifier to an
4876         // already-qualified type.
4877         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4878         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4879         Quals.removeObjCLifetime();
4880       }
4881     }
4882   }
4883 
4884   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4885 }
4886 
4887 template<typename Derived>
4888 TypeLoc
4889 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4890                                                    QualType ObjectType,
4891                                                    NamedDecl *UnqualLookup,
4892                                                    CXXScopeSpec &SS) {
4893   if (getDerived().AlreadyTransformed(TL.getType()))
4894     return TL;
4895 
4896   TypeSourceInfo *TSI =
4897       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4898   if (TSI)
4899     return TSI->getTypeLoc();
4900   return TypeLoc();
4901 }
4902 
4903 template<typename Derived>
4904 TypeSourceInfo *
4905 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4906                                                    QualType ObjectType,
4907                                                    NamedDecl *UnqualLookup,
4908                                                    CXXScopeSpec &SS) {
4909   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4910     return TSInfo;
4911 
4912   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4913                                    UnqualLookup, SS);
4914 }
4915 
4916 template <typename Derived>
4917 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4918     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4919     CXXScopeSpec &SS) {
4920   QualType T = TL.getType();
4921   assert(!getDerived().AlreadyTransformed(T));
4922 
4923   TypeLocBuilder TLB;
4924   QualType Result;
4925 
4926   if (isa<TemplateSpecializationType>(T)) {
4927     TemplateSpecializationTypeLoc SpecTL =
4928         TL.castAs<TemplateSpecializationTypeLoc>();
4929 
4930     TemplateName Template = getDerived().TransformTemplateName(
4931         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4932         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4933     if (Template.isNull())
4934       return nullptr;
4935 
4936     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4937                                                               Template);
4938   } else if (isa<DependentTemplateSpecializationType>(T)) {
4939     DependentTemplateSpecializationTypeLoc SpecTL =
4940         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4941 
4942     TemplateName Template
4943       = getDerived().RebuildTemplateName(SS,
4944                                          SpecTL.getTemplateKeywordLoc(),
4945                                          *SpecTL.getTypePtr()->getIdentifier(),
4946                                          SpecTL.getTemplateNameLoc(),
4947                                          ObjectType, UnqualLookup,
4948                                          /*AllowInjectedClassName*/true);
4949     if (Template.isNull())
4950       return nullptr;
4951 
4952     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4953                                                                        SpecTL,
4954                                                                        Template,
4955                                                                        SS);
4956   } else {
4957     // Nothing special needs to be done for these.
4958     Result = getDerived().TransformType(TLB, TL);
4959   }
4960 
4961   if (Result.isNull())
4962     return nullptr;
4963 
4964   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4965 }
4966 
4967 template <class TyLoc> static inline
4968 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4969   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4970   NewT.setNameLoc(T.getNameLoc());
4971   return T.getType();
4972 }
4973 
4974 template<typename Derived>
4975 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4976                                                       BuiltinTypeLoc T) {
4977   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4978   NewT.setBuiltinLoc(T.getBuiltinLoc());
4979   if (T.needsExtraLocalData())
4980     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4981   return T.getType();
4982 }
4983 
4984 template<typename Derived>
4985 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4986                                                       ComplexTypeLoc T) {
4987   // FIXME: recurse?
4988   return TransformTypeSpecType(TLB, T);
4989 }
4990 
4991 template <typename Derived>
4992 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4993                                                        AdjustedTypeLoc TL) {
4994   // Adjustments applied during transformation are handled elsewhere.
4995   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4996 }
4997 
4998 template<typename Derived>
4999 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
5000                                                       DecayedTypeLoc TL) {
5001   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
5002   if (OriginalType.isNull())
5003     return QualType();
5004 
5005   QualType Result = TL.getType();
5006   if (getDerived().AlwaysRebuild() ||
5007       OriginalType != TL.getOriginalLoc().getType())
5008     Result = SemaRef.Context.getDecayedType(OriginalType);
5009   TLB.push<DecayedTypeLoc>(Result);
5010   // Nothing to set for DecayedTypeLoc.
5011   return Result;
5012 }
5013 
5014 template<typename Derived>
5015 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
5016                                                       PointerTypeLoc TL) {
5017   QualType PointeeType
5018     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5019   if (PointeeType.isNull())
5020     return QualType();
5021 
5022   QualType Result = TL.getType();
5023   if (PointeeType->getAs<ObjCObjectType>()) {
5024     // A dependent pointer type 'T *' has is being transformed such
5025     // that an Objective-C class type is being replaced for 'T'. The
5026     // resulting pointer type is an ObjCObjectPointerType, not a
5027     // PointerType.
5028     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
5029 
5030     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
5031     NewT.setStarLoc(TL.getStarLoc());
5032     return Result;
5033   }
5034 
5035   if (getDerived().AlwaysRebuild() ||
5036       PointeeType != TL.getPointeeLoc().getType()) {
5037     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
5038     if (Result.isNull())
5039       return QualType();
5040   }
5041 
5042   // Objective-C ARC can add lifetime qualifiers to the type that we're
5043   // pointing to.
5044   TLB.TypeWasModifiedSafely(Result->getPointeeType());
5045 
5046   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
5047   NewT.setSigilLoc(TL.getSigilLoc());
5048   return Result;
5049 }
5050 
5051 template<typename Derived>
5052 QualType
5053 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
5054                                                   BlockPointerTypeLoc TL) {
5055   QualType PointeeType
5056     = getDerived().TransformType(TLB, TL.getPointeeLoc());
5057   if (PointeeType.isNull())
5058     return QualType();
5059 
5060   QualType Result = TL.getType();
5061   if (getDerived().AlwaysRebuild() ||
5062       PointeeType != TL.getPointeeLoc().getType()) {
5063     Result = getDerived().RebuildBlockPointerType(PointeeType,
5064                                                   TL.getSigilLoc());
5065     if (Result.isNull())
5066       return QualType();
5067   }
5068 
5069   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5070   NewT.setSigilLoc(TL.getSigilLoc());
5071   return Result;
5072 }
5073 
5074 /// Transforms a reference type.  Note that somewhat paradoxically we
5075 /// don't care whether the type itself is an l-value type or an r-value
5076 /// type;  we only care if the type was *written* as an l-value type
5077 /// or an r-value type.
5078 template<typename Derived>
5079 QualType
5080 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5081                                                ReferenceTypeLoc TL) {
5082   const ReferenceType *T = TL.getTypePtr();
5083 
5084   // Note that this works with the pointee-as-written.
5085   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5086   if (PointeeType.isNull())
5087     return QualType();
5088 
5089   QualType Result = TL.getType();
5090   if (getDerived().AlwaysRebuild() ||
5091       PointeeType != T->getPointeeTypeAsWritten()) {
5092     Result = getDerived().RebuildReferenceType(PointeeType,
5093                                                T->isSpelledAsLValue(),
5094                                                TL.getSigilLoc());
5095     if (Result.isNull())
5096       return QualType();
5097   }
5098 
5099   // Objective-C ARC can add lifetime qualifiers to the type that we're
5100   // referring to.
5101   TLB.TypeWasModifiedSafely(
5102       Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5103 
5104   // r-value references can be rebuilt as l-value references.
5105   ReferenceTypeLoc NewTL;
5106   if (isa<LValueReferenceType>(Result))
5107     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5108   else
5109     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5110   NewTL.setSigilLoc(TL.getSigilLoc());
5111 
5112   return Result;
5113 }
5114 
5115 template<typename Derived>
5116 QualType
5117 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5118                                                  LValueReferenceTypeLoc TL) {
5119   return TransformReferenceType(TLB, TL);
5120 }
5121 
5122 template<typename Derived>
5123 QualType
5124 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5125                                                  RValueReferenceTypeLoc TL) {
5126   return TransformReferenceType(TLB, TL);
5127 }
5128 
5129 template<typename Derived>
5130 QualType
5131 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5132                                                    MemberPointerTypeLoc TL) {
5133   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5134   if (PointeeType.isNull())
5135     return QualType();
5136 
5137   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5138   TypeSourceInfo *NewClsTInfo = nullptr;
5139   if (OldClsTInfo) {
5140     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5141     if (!NewClsTInfo)
5142       return QualType();
5143   }
5144 
5145   const MemberPointerType *T = TL.getTypePtr();
5146   QualType OldClsType = QualType(T->getClass(), 0);
5147   QualType NewClsType;
5148   if (NewClsTInfo)
5149     NewClsType = NewClsTInfo->getType();
5150   else {
5151     NewClsType = getDerived().TransformType(OldClsType);
5152     if (NewClsType.isNull())
5153       return QualType();
5154   }
5155 
5156   QualType Result = TL.getType();
5157   if (getDerived().AlwaysRebuild() ||
5158       PointeeType != T->getPointeeType() ||
5159       NewClsType != OldClsType) {
5160     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5161                                                    TL.getStarLoc());
5162     if (Result.isNull())
5163       return QualType();
5164   }
5165 
5166   // If we had to adjust the pointee type when building a member pointer, make
5167   // sure to push TypeLoc info for it.
5168   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5169   if (MPT && PointeeType != MPT->getPointeeType()) {
5170     assert(isa<AdjustedType>(MPT->getPointeeType()));
5171     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5172   }
5173 
5174   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5175   NewTL.setSigilLoc(TL.getSigilLoc());
5176   NewTL.setClassTInfo(NewClsTInfo);
5177 
5178   return Result;
5179 }
5180 
5181 template<typename Derived>
5182 QualType
5183 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5184                                                    ConstantArrayTypeLoc TL) {
5185   const ConstantArrayType *T = TL.getTypePtr();
5186   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5187   if (ElementType.isNull())
5188     return QualType();
5189 
5190   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5191   Expr *OldSize = TL.getSizeExpr();
5192   if (!OldSize)
5193     OldSize = const_cast<Expr*>(T->getSizeExpr());
5194   Expr *NewSize = nullptr;
5195   if (OldSize) {
5196     EnterExpressionEvaluationContext Unevaluated(
5197         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5198     NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5199     NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5200   }
5201 
5202   QualType Result = TL.getType();
5203   if (getDerived().AlwaysRebuild() ||
5204       ElementType != T->getElementType() ||
5205       (T->getSizeExpr() && NewSize != OldSize)) {
5206     Result = getDerived().RebuildConstantArrayType(ElementType,
5207                                                    T->getSizeModifier(),
5208                                                    T->getSize(), NewSize,
5209                                              T->getIndexTypeCVRQualifiers(),
5210                                                    TL.getBracketsRange());
5211     if (Result.isNull())
5212       return QualType();
5213   }
5214 
5215   // We might have either a ConstantArrayType or a VariableArrayType now:
5216   // a ConstantArrayType is allowed to have an element type which is a
5217   // VariableArrayType if the type is dependent.  Fortunately, all array
5218   // types have the same location layout.
5219   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5220   NewTL.setLBracketLoc(TL.getLBracketLoc());
5221   NewTL.setRBracketLoc(TL.getRBracketLoc());
5222   NewTL.setSizeExpr(NewSize);
5223 
5224   return Result;
5225 }
5226 
5227 template<typename Derived>
5228 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5229                                               TypeLocBuilder &TLB,
5230                                               IncompleteArrayTypeLoc TL) {
5231   const IncompleteArrayType *T = TL.getTypePtr();
5232   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5233   if (ElementType.isNull())
5234     return QualType();
5235 
5236   QualType Result = TL.getType();
5237   if (getDerived().AlwaysRebuild() ||
5238       ElementType != T->getElementType()) {
5239     Result = getDerived().RebuildIncompleteArrayType(ElementType,
5240                                                      T->getSizeModifier(),
5241                                            T->getIndexTypeCVRQualifiers(),
5242                                                      TL.getBracketsRange());
5243     if (Result.isNull())
5244       return QualType();
5245   }
5246 
5247   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5248   NewTL.setLBracketLoc(TL.getLBracketLoc());
5249   NewTL.setRBracketLoc(TL.getRBracketLoc());
5250   NewTL.setSizeExpr(nullptr);
5251 
5252   return Result;
5253 }
5254 
5255 template<typename Derived>
5256 QualType
5257 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5258                                                    VariableArrayTypeLoc TL) {
5259   const VariableArrayType *T = TL.getTypePtr();
5260   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5261   if (ElementType.isNull())
5262     return QualType();
5263 
5264   ExprResult SizeResult;
5265   {
5266     EnterExpressionEvaluationContext Context(
5267         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5268     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5269   }
5270   if (SizeResult.isInvalid())
5271     return QualType();
5272   SizeResult =
5273       SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5274   if (SizeResult.isInvalid())
5275     return QualType();
5276 
5277   Expr *Size = SizeResult.get();
5278 
5279   QualType Result = TL.getType();
5280   if (getDerived().AlwaysRebuild() ||
5281       ElementType != T->getElementType() ||
5282       Size != T->getSizeExpr()) {
5283     Result = getDerived().RebuildVariableArrayType(ElementType,
5284                                                    T->getSizeModifier(),
5285                                                    Size,
5286                                              T->getIndexTypeCVRQualifiers(),
5287                                                    TL.getBracketsRange());
5288     if (Result.isNull())
5289       return QualType();
5290   }
5291 
5292   // We might have constant size array now, but fortunately it has the same
5293   // location layout.
5294   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5295   NewTL.setLBracketLoc(TL.getLBracketLoc());
5296   NewTL.setRBracketLoc(TL.getRBracketLoc());
5297   NewTL.setSizeExpr(Size);
5298 
5299   return Result;
5300 }
5301 
5302 template<typename Derived>
5303 QualType
5304 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5305                                              DependentSizedArrayTypeLoc TL) {
5306   const DependentSizedArrayType *T = TL.getTypePtr();
5307   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5308   if (ElementType.isNull())
5309     return QualType();
5310 
5311   // Array bounds are constant expressions.
5312   EnterExpressionEvaluationContext Unevaluated(
5313       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5314 
5315   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
5316   Expr *origSize = TL.getSizeExpr();
5317   if (!origSize) origSize = T->getSizeExpr();
5318 
5319   ExprResult sizeResult
5320     = getDerived().TransformExpr(origSize);
5321   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5322   if (sizeResult.isInvalid())
5323     return QualType();
5324 
5325   Expr *size = sizeResult.get();
5326 
5327   QualType Result = TL.getType();
5328   if (getDerived().AlwaysRebuild() ||
5329       ElementType != T->getElementType() ||
5330       size != origSize) {
5331     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5332                                                          T->getSizeModifier(),
5333                                                          size,
5334                                                 T->getIndexTypeCVRQualifiers(),
5335                                                         TL.getBracketsRange());
5336     if (Result.isNull())
5337       return QualType();
5338   }
5339 
5340   // We might have any sort of array type now, but fortunately they
5341   // all have the same location layout.
5342   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5343   NewTL.setLBracketLoc(TL.getLBracketLoc());
5344   NewTL.setRBracketLoc(TL.getRBracketLoc());
5345   NewTL.setSizeExpr(size);
5346 
5347   return Result;
5348 }
5349 
5350 template <typename Derived>
5351 QualType TreeTransform<Derived>::TransformDependentVectorType(
5352     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5353   const DependentVectorType *T = TL.getTypePtr();
5354   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5355   if (ElementType.isNull())
5356     return QualType();
5357 
5358   EnterExpressionEvaluationContext Unevaluated(
5359       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5360 
5361   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5362   Size = SemaRef.ActOnConstantExpression(Size);
5363   if (Size.isInvalid())
5364     return QualType();
5365 
5366   QualType Result = TL.getType();
5367   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5368       Size.get() != T->getSizeExpr()) {
5369     Result = getDerived().RebuildDependentVectorType(
5370         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5371     if (Result.isNull())
5372       return QualType();
5373   }
5374 
5375   // Result might be dependent or not.
5376   if (isa<DependentVectorType>(Result)) {
5377     DependentVectorTypeLoc NewTL =
5378         TLB.push<DependentVectorTypeLoc>(Result);
5379     NewTL.setNameLoc(TL.getNameLoc());
5380   } else {
5381     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5382     NewTL.setNameLoc(TL.getNameLoc());
5383   }
5384 
5385   return Result;
5386 }
5387 
5388 template<typename Derived>
5389 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5390                                       TypeLocBuilder &TLB,
5391                                       DependentSizedExtVectorTypeLoc TL) {
5392   const DependentSizedExtVectorType *T = TL.getTypePtr();
5393 
5394   // FIXME: ext vector locs should be nested
5395   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5396   if (ElementType.isNull())
5397     return QualType();
5398 
5399   // Vector sizes are constant expressions.
5400   EnterExpressionEvaluationContext Unevaluated(
5401       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5402 
5403   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5404   Size = SemaRef.ActOnConstantExpression(Size);
5405   if (Size.isInvalid())
5406     return QualType();
5407 
5408   QualType Result = TL.getType();
5409   if (getDerived().AlwaysRebuild() ||
5410       ElementType != T->getElementType() ||
5411       Size.get() != T->getSizeExpr()) {
5412     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5413                                                              Size.get(),
5414                                                          T->getAttributeLoc());
5415     if (Result.isNull())
5416       return QualType();
5417   }
5418 
5419   // Result might be dependent or not.
5420   if (isa<DependentSizedExtVectorType>(Result)) {
5421     DependentSizedExtVectorTypeLoc NewTL
5422       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5423     NewTL.setNameLoc(TL.getNameLoc());
5424   } else {
5425     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5426     NewTL.setNameLoc(TL.getNameLoc());
5427   }
5428 
5429   return Result;
5430 }
5431 
5432 template <typename Derived>
5433 QualType
5434 TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5435                                                     ConstantMatrixTypeLoc TL) {
5436   const ConstantMatrixType *T = TL.getTypePtr();
5437   QualType ElementType = getDerived().TransformType(T->getElementType());
5438   if (ElementType.isNull())
5439     return QualType();
5440 
5441   QualType Result = TL.getType();
5442   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5443     Result = getDerived().RebuildConstantMatrixType(
5444         ElementType, T->getNumRows(), T->getNumColumns());
5445     if (Result.isNull())
5446       return QualType();
5447   }
5448 
5449   ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5450   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5451   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5452   NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5453   NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5454 
5455   return Result;
5456 }
5457 
5458 template <typename Derived>
5459 QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5460     TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5461   const DependentSizedMatrixType *T = TL.getTypePtr();
5462 
5463   QualType ElementType = getDerived().TransformType(T->getElementType());
5464   if (ElementType.isNull()) {
5465     return QualType();
5466   }
5467 
5468   // Matrix dimensions are constant expressions.
5469   EnterExpressionEvaluationContext Unevaluated(
5470       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5471 
5472   Expr *origRows = TL.getAttrRowOperand();
5473   if (!origRows)
5474     origRows = T->getRowExpr();
5475   Expr *origColumns = TL.getAttrColumnOperand();
5476   if (!origColumns)
5477     origColumns = T->getColumnExpr();
5478 
5479   ExprResult rowResult = getDerived().TransformExpr(origRows);
5480   rowResult = SemaRef.ActOnConstantExpression(rowResult);
5481   if (rowResult.isInvalid())
5482     return QualType();
5483 
5484   ExprResult columnResult = getDerived().TransformExpr(origColumns);
5485   columnResult = SemaRef.ActOnConstantExpression(columnResult);
5486   if (columnResult.isInvalid())
5487     return QualType();
5488 
5489   Expr *rows = rowResult.get();
5490   Expr *columns = columnResult.get();
5491 
5492   QualType Result = TL.getType();
5493   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5494       rows != origRows || columns != origColumns) {
5495     Result = getDerived().RebuildDependentSizedMatrixType(
5496         ElementType, rows, columns, T->getAttributeLoc());
5497 
5498     if (Result.isNull())
5499       return QualType();
5500   }
5501 
5502   // We might have any sort of matrix type now, but fortunately they
5503   // all have the same location layout.
5504   MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5505   NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5506   NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5507   NewTL.setAttrRowOperand(rows);
5508   NewTL.setAttrColumnOperand(columns);
5509   return Result;
5510 }
5511 
5512 template <typename Derived>
5513 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5514     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5515   const DependentAddressSpaceType *T = TL.getTypePtr();
5516 
5517   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5518 
5519   if (pointeeType.isNull())
5520     return QualType();
5521 
5522   // Address spaces are constant expressions.
5523   EnterExpressionEvaluationContext Unevaluated(
5524       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5525 
5526   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5527   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5528   if (AddrSpace.isInvalid())
5529     return QualType();
5530 
5531   QualType Result = TL.getType();
5532   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5533       AddrSpace.get() != T->getAddrSpaceExpr()) {
5534     Result = getDerived().RebuildDependentAddressSpaceType(
5535         pointeeType, AddrSpace.get(), T->getAttributeLoc());
5536     if (Result.isNull())
5537       return QualType();
5538   }
5539 
5540   // Result might be dependent or not.
5541   if (isa<DependentAddressSpaceType>(Result)) {
5542     DependentAddressSpaceTypeLoc NewTL =
5543         TLB.push<DependentAddressSpaceTypeLoc>(Result);
5544 
5545     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5546     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5547     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5548 
5549   } else {
5550     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5551         Result, getDerived().getBaseLocation());
5552     TransformType(TLB, DI->getTypeLoc());
5553   }
5554 
5555   return Result;
5556 }
5557 
5558 template <typename Derived>
5559 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5560                                                      VectorTypeLoc TL) {
5561   const VectorType *T = TL.getTypePtr();
5562   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5563   if (ElementType.isNull())
5564     return QualType();
5565 
5566   QualType Result = TL.getType();
5567   if (getDerived().AlwaysRebuild() ||
5568       ElementType != T->getElementType()) {
5569     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5570                                             T->getVectorKind());
5571     if (Result.isNull())
5572       return QualType();
5573   }
5574 
5575   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5576   NewTL.setNameLoc(TL.getNameLoc());
5577 
5578   return Result;
5579 }
5580 
5581 template<typename Derived>
5582 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5583                                                         ExtVectorTypeLoc TL) {
5584   const VectorType *T = TL.getTypePtr();
5585   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5586   if (ElementType.isNull())
5587     return QualType();
5588 
5589   QualType Result = TL.getType();
5590   if (getDerived().AlwaysRebuild() ||
5591       ElementType != T->getElementType()) {
5592     Result = getDerived().RebuildExtVectorType(ElementType,
5593                                                T->getNumElements(),
5594                                                /*FIXME*/ SourceLocation());
5595     if (Result.isNull())
5596       return QualType();
5597   }
5598 
5599   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5600   NewTL.setNameLoc(TL.getNameLoc());
5601 
5602   return Result;
5603 }
5604 
5605 template <typename Derived>
5606 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5607     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
5608     bool ExpectParameterPack) {
5609   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5610   TypeSourceInfo *NewDI = nullptr;
5611 
5612   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5613     // If we're substituting into a pack expansion type and we know the
5614     // length we want to expand to, just substitute for the pattern.
5615     TypeLoc OldTL = OldDI->getTypeLoc();
5616     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5617 
5618     TypeLocBuilder TLB;
5619     TypeLoc NewTL = OldDI->getTypeLoc();
5620     TLB.reserve(NewTL.getFullDataSize());
5621 
5622     QualType Result = getDerived().TransformType(TLB,
5623                                                OldExpansionTL.getPatternLoc());
5624     if (Result.isNull())
5625       return nullptr;
5626 
5627     Result = RebuildPackExpansionType(Result,
5628                                 OldExpansionTL.getPatternLoc().getSourceRange(),
5629                                       OldExpansionTL.getEllipsisLoc(),
5630                                       NumExpansions);
5631     if (Result.isNull())
5632       return nullptr;
5633 
5634     PackExpansionTypeLoc NewExpansionTL
5635       = TLB.push<PackExpansionTypeLoc>(Result);
5636     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5637     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5638   } else
5639     NewDI = getDerived().TransformType(OldDI);
5640   if (!NewDI)
5641     return nullptr;
5642 
5643   if (NewDI == OldDI && indexAdjustment == 0)
5644     return OldParm;
5645 
5646   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5647                                              OldParm->getDeclContext(),
5648                                              OldParm->getInnerLocStart(),
5649                                              OldParm->getLocation(),
5650                                              OldParm->getIdentifier(),
5651                                              NewDI->getType(),
5652                                              NewDI,
5653                                              OldParm->getStorageClass(),
5654                                              /* DefArg */ nullptr);
5655   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5656                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5657   transformedLocalDecl(OldParm, {newParm});
5658   return newParm;
5659 }
5660 
5661 template <typename Derived>
5662 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5663     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5664     const QualType *ParamTypes,
5665     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5666     SmallVectorImpl<QualType> &OutParamTypes,
5667     SmallVectorImpl<ParmVarDecl *> *PVars,
5668     Sema::ExtParameterInfoBuilder &PInfos) {
5669   int indexAdjustment = 0;
5670 
5671   unsigned NumParams = Params.size();
5672   for (unsigned i = 0; i != NumParams; ++i) {
5673     if (ParmVarDecl *OldParm = Params[i]) {
5674       assert(OldParm->getFunctionScopeIndex() == i);
5675 
5676       Optional<unsigned> NumExpansions;
5677       ParmVarDecl *NewParm = nullptr;
5678       if (OldParm->isParameterPack()) {
5679         // We have a function parameter pack that may need to be expanded.
5680         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5681 
5682         // Find the parameter packs that could be expanded.
5683         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5684         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5685         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5686         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5687 
5688         // Determine whether we should expand the parameter packs.
5689         bool ShouldExpand = false;
5690         bool RetainExpansion = false;
5691         Optional<unsigned> OrigNumExpansions;
5692         if (Unexpanded.size() > 0) {
5693           OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5694           NumExpansions = OrigNumExpansions;
5695           if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5696                                                    Pattern.getSourceRange(),
5697                                                    Unexpanded,
5698                                                    ShouldExpand,
5699                                                    RetainExpansion,
5700                                                    NumExpansions)) {
5701             return true;
5702           }
5703         } else {
5704 #ifndef NDEBUG
5705           const AutoType *AT =
5706               Pattern.getType().getTypePtr()->getContainedAutoType();
5707           assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&
5708                  "Could not find parameter packs or undeduced auto type!");
5709 #endif
5710         }
5711 
5712         if (ShouldExpand) {
5713           // Expand the function parameter pack into multiple, separate
5714           // parameters.
5715           getDerived().ExpandingFunctionParameterPack(OldParm);
5716           for (unsigned I = 0; I != *NumExpansions; ++I) {
5717             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5718             ParmVarDecl *NewParm
5719               = getDerived().TransformFunctionTypeParam(OldParm,
5720                                                         indexAdjustment++,
5721                                                         OrigNumExpansions,
5722                                                 /*ExpectParameterPack=*/false);
5723             if (!NewParm)
5724               return true;
5725 
5726             if (ParamInfos)
5727               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5728             OutParamTypes.push_back(NewParm->getType());
5729             if (PVars)
5730               PVars->push_back(NewParm);
5731           }
5732 
5733           // If we're supposed to retain a pack expansion, do so by temporarily
5734           // forgetting the partially-substituted parameter pack.
5735           if (RetainExpansion) {
5736             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5737             ParmVarDecl *NewParm
5738               = getDerived().TransformFunctionTypeParam(OldParm,
5739                                                         indexAdjustment++,
5740                                                         OrigNumExpansions,
5741                                                 /*ExpectParameterPack=*/false);
5742             if (!NewParm)
5743               return true;
5744 
5745             if (ParamInfos)
5746               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5747             OutParamTypes.push_back(NewParm->getType());
5748             if (PVars)
5749               PVars->push_back(NewParm);
5750           }
5751 
5752           // The next parameter should have the same adjustment as the
5753           // last thing we pushed, but we post-incremented indexAdjustment
5754           // on every push.  Also, if we push nothing, the adjustment should
5755           // go down by one.
5756           indexAdjustment--;
5757 
5758           // We're done with the pack expansion.
5759           continue;
5760         }
5761 
5762         // We'll substitute the parameter now without expanding the pack
5763         // expansion.
5764         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5765         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5766                                                           indexAdjustment,
5767                                                           NumExpansions,
5768                                                   /*ExpectParameterPack=*/true);
5769         assert(NewParm->isParameterPack() &&
5770                "Parameter pack no longer a parameter pack after "
5771                "transformation.");
5772       } else {
5773         NewParm = getDerived().TransformFunctionTypeParam(
5774             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5775       }
5776 
5777       if (!NewParm)
5778         return true;
5779 
5780       if (ParamInfos)
5781         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5782       OutParamTypes.push_back(NewParm->getType());
5783       if (PVars)
5784         PVars->push_back(NewParm);
5785       continue;
5786     }
5787 
5788     // Deal with the possibility that we don't have a parameter
5789     // declaration for this parameter.
5790     QualType OldType = ParamTypes[i];
5791     bool IsPackExpansion = false;
5792     Optional<unsigned> NumExpansions;
5793     QualType NewType;
5794     if (const PackExpansionType *Expansion
5795                                        = dyn_cast<PackExpansionType>(OldType)) {
5796       // We have a function parameter pack that may need to be expanded.
5797       QualType Pattern = Expansion->getPattern();
5798       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5799       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5800 
5801       // Determine whether we should expand the parameter packs.
5802       bool ShouldExpand = false;
5803       bool RetainExpansion = false;
5804       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5805                                                Unexpanded,
5806                                                ShouldExpand,
5807                                                RetainExpansion,
5808                                                NumExpansions)) {
5809         return true;
5810       }
5811 
5812       if (ShouldExpand) {
5813         // Expand the function parameter pack into multiple, separate
5814         // parameters.
5815         for (unsigned I = 0; I != *NumExpansions; ++I) {
5816           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5817           QualType NewType = getDerived().TransformType(Pattern);
5818           if (NewType.isNull())
5819             return true;
5820 
5821           if (NewType->containsUnexpandedParameterPack()) {
5822             NewType =
5823                 getSema().getASTContext().getPackExpansionType(NewType, None);
5824 
5825             if (NewType.isNull())
5826               return true;
5827           }
5828 
5829           if (ParamInfos)
5830             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5831           OutParamTypes.push_back(NewType);
5832           if (PVars)
5833             PVars->push_back(nullptr);
5834         }
5835 
5836         // We're done with the pack expansion.
5837         continue;
5838       }
5839 
5840       // If we're supposed to retain a pack expansion, do so by temporarily
5841       // forgetting the partially-substituted parameter pack.
5842       if (RetainExpansion) {
5843         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5844         QualType NewType = getDerived().TransformType(Pattern);
5845         if (NewType.isNull())
5846           return true;
5847 
5848         if (ParamInfos)
5849           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5850         OutParamTypes.push_back(NewType);
5851         if (PVars)
5852           PVars->push_back(nullptr);
5853       }
5854 
5855       // We'll substitute the parameter now without expanding the pack
5856       // expansion.
5857       OldType = Expansion->getPattern();
5858       IsPackExpansion = true;
5859       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5860       NewType = getDerived().TransformType(OldType);
5861     } else {
5862       NewType = getDerived().TransformType(OldType);
5863     }
5864 
5865     if (NewType.isNull())
5866       return true;
5867 
5868     if (IsPackExpansion)
5869       NewType = getSema().Context.getPackExpansionType(NewType,
5870                                                        NumExpansions);
5871 
5872     if (ParamInfos)
5873       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5874     OutParamTypes.push_back(NewType);
5875     if (PVars)
5876       PVars->push_back(nullptr);
5877   }
5878 
5879 #ifndef NDEBUG
5880   if (PVars) {
5881     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5882       if (ParmVarDecl *parm = (*PVars)[i])
5883         assert(parm->getFunctionScopeIndex() == i);
5884   }
5885 #endif
5886 
5887   return false;
5888 }
5889 
5890 template<typename Derived>
5891 QualType
5892 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5893                                                    FunctionProtoTypeLoc TL) {
5894   SmallVector<QualType, 4> ExceptionStorage;
5895   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5896   return getDerived().TransformFunctionProtoType(
5897       TLB, TL, nullptr, Qualifiers(),
5898       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5899         return This->getDerived().TransformExceptionSpec(
5900             TL.getBeginLoc(), ESI, ExceptionStorage, Changed);
5901       });
5902 }
5903 
5904 template<typename Derived> template<typename Fn>
5905 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5906     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5907     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5908 
5909   // Transform the parameters and return type.
5910   //
5911   // We are required to instantiate the params and return type in source order.
5912   // When the function has a trailing return type, we instantiate the
5913   // parameters before the return type,  since the return type can then refer
5914   // to the parameters themselves (via decltype, sizeof, etc.).
5915   //
5916   SmallVector<QualType, 4> ParamTypes;
5917   SmallVector<ParmVarDecl*, 4> ParamDecls;
5918   Sema::ExtParameterInfoBuilder ExtParamInfos;
5919   const FunctionProtoType *T = TL.getTypePtr();
5920 
5921   QualType ResultType;
5922 
5923   if (T->hasTrailingReturn()) {
5924     if (getDerived().TransformFunctionTypeParams(
5925             TL.getBeginLoc(), TL.getParams(),
5926             TL.getTypePtr()->param_type_begin(),
5927             T->getExtParameterInfosOrNull(),
5928             ParamTypes, &ParamDecls, ExtParamInfos))
5929       return QualType();
5930 
5931     {
5932       // C++11 [expr.prim.general]p3:
5933       //   If a declaration declares a member function or member function
5934       //   template of a class X, the expression this is a prvalue of type
5935       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5936       //   and the end of the function-definition, member-declarator, or
5937       //   declarator.
5938       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5939 
5940       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5941       if (ResultType.isNull())
5942         return QualType();
5943     }
5944   }
5945   else {
5946     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5947     if (ResultType.isNull())
5948       return QualType();
5949 
5950     if (getDerived().TransformFunctionTypeParams(
5951             TL.getBeginLoc(), TL.getParams(),
5952             TL.getTypePtr()->param_type_begin(),
5953             T->getExtParameterInfosOrNull(),
5954             ParamTypes, &ParamDecls, ExtParamInfos))
5955       return QualType();
5956   }
5957 
5958   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5959 
5960   bool EPIChanged = false;
5961   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5962     return QualType();
5963 
5964   // Handle extended parameter information.
5965   if (auto NewExtParamInfos =
5966         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5967     if (!EPI.ExtParameterInfos ||
5968         llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5969           != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5970       EPIChanged = true;
5971     }
5972     EPI.ExtParameterInfos = NewExtParamInfos;
5973   } else if (EPI.ExtParameterInfos) {
5974     EPIChanged = true;
5975     EPI.ExtParameterInfos = nullptr;
5976   }
5977 
5978   QualType Result = TL.getType();
5979   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5980       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5981     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5982     if (Result.isNull())
5983       return QualType();
5984   }
5985 
5986   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5987   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5988   NewTL.setLParenLoc(TL.getLParenLoc());
5989   NewTL.setRParenLoc(TL.getRParenLoc());
5990   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5991   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5992   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5993     NewTL.setParam(i, ParamDecls[i]);
5994 
5995   return Result;
5996 }
5997 
5998 template<typename Derived>
5999 bool TreeTransform<Derived>::TransformExceptionSpec(
6000     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
6001     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
6002   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
6003 
6004   // Instantiate a dynamic noexcept expression, if any.
6005   if (isComputedNoexcept(ESI.Type)) {
6006     EnterExpressionEvaluationContext Unevaluated(
6007         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
6008     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
6009     if (NoexceptExpr.isInvalid())
6010       return true;
6011 
6012     ExceptionSpecificationType EST = ESI.Type;
6013     NoexceptExpr =
6014         getSema().ActOnNoexceptSpec(NoexceptExpr.get(), EST);
6015     if (NoexceptExpr.isInvalid())
6016       return true;
6017 
6018     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
6019       Changed = true;
6020     ESI.NoexceptExpr = NoexceptExpr.get();
6021     ESI.Type = EST;
6022   }
6023 
6024   if (ESI.Type != EST_Dynamic)
6025     return false;
6026 
6027   // Instantiate a dynamic exception specification's type.
6028   for (QualType T : ESI.Exceptions) {
6029     if (const PackExpansionType *PackExpansion =
6030             T->getAs<PackExpansionType>()) {
6031       Changed = true;
6032 
6033       // We have a pack expansion. Instantiate it.
6034       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6035       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6036                                               Unexpanded);
6037       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6038 
6039       // Determine whether the set of unexpanded parameter packs can and
6040       // should
6041       // be expanded.
6042       bool Expand = false;
6043       bool RetainExpansion = false;
6044       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6045       // FIXME: Track the location of the ellipsis (and track source location
6046       // information for the types in the exception specification in general).
6047       if (getDerived().TryExpandParameterPacks(
6048               Loc, SourceRange(), Unexpanded, Expand,
6049               RetainExpansion, NumExpansions))
6050         return true;
6051 
6052       if (!Expand) {
6053         // We can't expand this pack expansion into separate arguments yet;
6054         // just substitute into the pattern and create a new pack expansion
6055         // type.
6056         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6057         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6058         if (U.isNull())
6059           return true;
6060 
6061         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
6062         Exceptions.push_back(U);
6063         continue;
6064       }
6065 
6066       // Substitute into the pack expansion pattern for each slice of the
6067       // pack.
6068       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6069         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6070 
6071         QualType U = getDerived().TransformType(PackExpansion->getPattern());
6072         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6073           return true;
6074 
6075         Exceptions.push_back(U);
6076       }
6077     } else {
6078       QualType U = getDerived().TransformType(T);
6079       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6080         return true;
6081       if (T != U)
6082         Changed = true;
6083 
6084       Exceptions.push_back(U);
6085     }
6086   }
6087 
6088   ESI.Exceptions = Exceptions;
6089   if (ESI.Exceptions.empty())
6090     ESI.Type = EST_DynamicNone;
6091   return false;
6092 }
6093 
6094 template<typename Derived>
6095 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6096                                                  TypeLocBuilder &TLB,
6097                                                  FunctionNoProtoTypeLoc TL) {
6098   const FunctionNoProtoType *T = TL.getTypePtr();
6099   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6100   if (ResultType.isNull())
6101     return QualType();
6102 
6103   QualType Result = TL.getType();
6104   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6105     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6106 
6107   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6108   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6109   NewTL.setLParenLoc(TL.getLParenLoc());
6110   NewTL.setRParenLoc(TL.getRParenLoc());
6111   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6112 
6113   return Result;
6114 }
6115 
6116 template <typename Derived>
6117 QualType TreeTransform<Derived>::TransformUnresolvedUsingType(
6118     TypeLocBuilder &TLB, UnresolvedUsingTypeLoc TL) {
6119   const UnresolvedUsingType *T = TL.getTypePtr();
6120   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6121   if (!D)
6122     return QualType();
6123 
6124   QualType Result = TL.getType();
6125   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6126     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6127     if (Result.isNull())
6128       return QualType();
6129   }
6130 
6131   // We might get an arbitrary type spec type back.  We should at
6132   // least always get a type spec type, though.
6133   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6134   NewTL.setNameLoc(TL.getNameLoc());
6135 
6136   return Result;
6137 }
6138 
6139 template <typename Derived>
6140 QualType TreeTransform<Derived>::TransformUsingType(TypeLocBuilder &TLB,
6141                                                     UsingTypeLoc TL) {
6142   const UsingType *T = TL.getTypePtr();
6143 
6144   auto *Found = cast_or_null<UsingShadowDecl>(getDerived().TransformDecl(
6145       TL.getLocalSourceRange().getBegin(), T->getFoundDecl()));
6146   if (!Found)
6147     return QualType();
6148 
6149   QualType Underlying = getDerived().TransformType(T->desugar());
6150   if (Underlying.isNull())
6151     return QualType();
6152 
6153   QualType Result = TL.getType();
6154   if (getDerived().AlwaysRebuild() || Found != T->getFoundDecl() ||
6155       Underlying != T->getUnderlyingType()) {
6156     Result = getDerived().RebuildUsingType(Found, Underlying);
6157     if (Result.isNull())
6158       return QualType();
6159   }
6160 
6161   TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc());
6162   return Result;
6163 }
6164 
6165 template<typename Derived>
6166 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6167                                                       TypedefTypeLoc TL) {
6168   const TypedefType *T = TL.getTypePtr();
6169   TypedefNameDecl *Typedef
6170     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6171                                                                T->getDecl()));
6172   if (!Typedef)
6173     return QualType();
6174 
6175   QualType Result = TL.getType();
6176   if (getDerived().AlwaysRebuild() ||
6177       Typedef != T->getDecl()) {
6178     Result = getDerived().RebuildTypedefType(Typedef);
6179     if (Result.isNull())
6180       return QualType();
6181   }
6182 
6183   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6184   NewTL.setNameLoc(TL.getNameLoc());
6185 
6186   return Result;
6187 }
6188 
6189 template<typename Derived>
6190 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6191                                                       TypeOfExprTypeLoc TL) {
6192   // typeof expressions are not potentially evaluated contexts
6193   EnterExpressionEvaluationContext Unevaluated(
6194       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6195       Sema::ReuseLambdaContextDecl);
6196 
6197   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6198   if (E.isInvalid())
6199     return QualType();
6200 
6201   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6202   if (E.isInvalid())
6203     return QualType();
6204 
6205   QualType Result = TL.getType();
6206   if (getDerived().AlwaysRebuild() ||
6207       E.get() != TL.getUnderlyingExpr()) {
6208     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
6209     if (Result.isNull())
6210       return QualType();
6211   }
6212   else E.get();
6213 
6214   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6215   NewTL.setTypeofLoc(TL.getTypeofLoc());
6216   NewTL.setLParenLoc(TL.getLParenLoc());
6217   NewTL.setRParenLoc(TL.getRParenLoc());
6218 
6219   return Result;
6220 }
6221 
6222 template<typename Derived>
6223 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6224                                                      TypeOfTypeLoc TL) {
6225   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
6226   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6227   if (!New_Under_TI)
6228     return QualType();
6229 
6230   QualType Result = TL.getType();
6231   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6232     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
6233     if (Result.isNull())
6234       return QualType();
6235   }
6236 
6237   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6238   NewTL.setTypeofLoc(TL.getTypeofLoc());
6239   NewTL.setLParenLoc(TL.getLParenLoc());
6240   NewTL.setRParenLoc(TL.getRParenLoc());
6241   NewTL.setUnderlyingTInfo(New_Under_TI);
6242 
6243   return Result;
6244 }
6245 
6246 template<typename Derived>
6247 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6248                                                        DecltypeTypeLoc TL) {
6249   const DecltypeType *T = TL.getTypePtr();
6250 
6251   // decltype expressions are not potentially evaluated contexts
6252   EnterExpressionEvaluationContext Unevaluated(
6253       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6254       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6255 
6256   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6257   if (E.isInvalid())
6258     return QualType();
6259 
6260   E = getSema().ActOnDecltypeExpression(E.get());
6261   if (E.isInvalid())
6262     return QualType();
6263 
6264   QualType Result = TL.getType();
6265   if (getDerived().AlwaysRebuild() ||
6266       E.get() != T->getUnderlyingExpr()) {
6267     Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
6268     if (Result.isNull())
6269       return QualType();
6270   }
6271   else E.get();
6272 
6273   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6274   NewTL.setDecltypeLoc(TL.getDecltypeLoc());
6275   NewTL.setRParenLoc(TL.getRParenLoc());
6276   return Result;
6277 }
6278 
6279 template<typename Derived>
6280 QualType TreeTransform<Derived>::TransformUnaryTransformType(
6281                                                             TypeLocBuilder &TLB,
6282                                                      UnaryTransformTypeLoc TL) {
6283   QualType Result = TL.getType();
6284   if (Result->isDependentType()) {
6285     const UnaryTransformType *T = TL.getTypePtr();
6286     QualType NewBase =
6287       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6288     Result = getDerived().RebuildUnaryTransformType(NewBase,
6289                                                     T->getUTTKind(),
6290                                                     TL.getKWLoc());
6291     if (Result.isNull())
6292       return QualType();
6293   }
6294 
6295   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6296   NewTL.setKWLoc(TL.getKWLoc());
6297   NewTL.setParensRange(TL.getParensRange());
6298   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6299   return Result;
6300 }
6301 
6302 template<typename Derived>
6303 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6304     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6305   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6306 
6307   CXXScopeSpec SS;
6308   TemplateName TemplateName = getDerived().TransformTemplateName(
6309       SS, T->getTemplateName(), TL.getTemplateNameLoc());
6310   if (TemplateName.isNull())
6311     return QualType();
6312 
6313   QualType OldDeduced = T->getDeducedType();
6314   QualType NewDeduced;
6315   if (!OldDeduced.isNull()) {
6316     NewDeduced = getDerived().TransformType(OldDeduced);
6317     if (NewDeduced.isNull())
6318       return QualType();
6319   }
6320 
6321   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6322       TemplateName, NewDeduced);
6323   if (Result.isNull())
6324     return QualType();
6325 
6326   DeducedTemplateSpecializationTypeLoc NewTL =
6327       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6328   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6329 
6330   return Result;
6331 }
6332 
6333 template<typename Derived>
6334 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6335                                                      RecordTypeLoc TL) {
6336   const RecordType *T = TL.getTypePtr();
6337   RecordDecl *Record
6338     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6339                                                           T->getDecl()));
6340   if (!Record)
6341     return QualType();
6342 
6343   QualType Result = TL.getType();
6344   if (getDerived().AlwaysRebuild() ||
6345       Record != T->getDecl()) {
6346     Result = getDerived().RebuildRecordType(Record);
6347     if (Result.isNull())
6348       return QualType();
6349   }
6350 
6351   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6352   NewTL.setNameLoc(TL.getNameLoc());
6353 
6354   return Result;
6355 }
6356 
6357 template<typename Derived>
6358 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6359                                                    EnumTypeLoc TL) {
6360   const EnumType *T = TL.getTypePtr();
6361   EnumDecl *Enum
6362     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6363                                                         T->getDecl()));
6364   if (!Enum)
6365     return QualType();
6366 
6367   QualType Result = TL.getType();
6368   if (getDerived().AlwaysRebuild() ||
6369       Enum != T->getDecl()) {
6370     Result = getDerived().RebuildEnumType(Enum);
6371     if (Result.isNull())
6372       return QualType();
6373   }
6374 
6375   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6376   NewTL.setNameLoc(TL.getNameLoc());
6377 
6378   return Result;
6379 }
6380 
6381 template<typename Derived>
6382 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6383                                          TypeLocBuilder &TLB,
6384                                          InjectedClassNameTypeLoc TL) {
6385   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6386                                        TL.getTypePtr()->getDecl());
6387   if (!D) return QualType();
6388 
6389   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6390   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6391   return T;
6392 }
6393 
6394 template<typename Derived>
6395 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6396                                                 TypeLocBuilder &TLB,
6397                                                 TemplateTypeParmTypeLoc TL) {
6398   return TransformTypeSpecType(TLB, TL);
6399 }
6400 
6401 template<typename Derived>
6402 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6403                                          TypeLocBuilder &TLB,
6404                                          SubstTemplateTypeParmTypeLoc TL) {
6405   const SubstTemplateTypeParmType *T = TL.getTypePtr();
6406 
6407   // Substitute into the replacement type, which itself might involve something
6408   // that needs to be transformed. This only tends to occur with default
6409   // template arguments of template template parameters.
6410   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6411   QualType Replacement = getDerived().TransformType(T->getReplacementType());
6412   if (Replacement.isNull())
6413     return QualType();
6414 
6415   // Always canonicalize the replacement type.
6416   Replacement = SemaRef.Context.getCanonicalType(Replacement);
6417   QualType Result
6418     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
6419                                                    Replacement);
6420 
6421   // Propagate type-source information.
6422   SubstTemplateTypeParmTypeLoc NewTL
6423     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6424   NewTL.setNameLoc(TL.getNameLoc());
6425   return Result;
6426 
6427 }
6428 
6429 template<typename Derived>
6430 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6431                                           TypeLocBuilder &TLB,
6432                                           SubstTemplateTypeParmPackTypeLoc TL) {
6433   return TransformTypeSpecType(TLB, TL);
6434 }
6435 
6436 template<typename Derived>
6437 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6438                                                         TypeLocBuilder &TLB,
6439                                            TemplateSpecializationTypeLoc TL) {
6440   const TemplateSpecializationType *T = TL.getTypePtr();
6441 
6442   // The nested-name-specifier never matters in a TemplateSpecializationType,
6443   // because we can't have a dependent nested-name-specifier anyway.
6444   CXXScopeSpec SS;
6445   TemplateName Template
6446     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6447                                          TL.getTemplateNameLoc());
6448   if (Template.isNull())
6449     return QualType();
6450 
6451   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6452 }
6453 
6454 template<typename Derived>
6455 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6456                                                      AtomicTypeLoc TL) {
6457   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6458   if (ValueType.isNull())
6459     return QualType();
6460 
6461   QualType Result = TL.getType();
6462   if (getDerived().AlwaysRebuild() ||
6463       ValueType != TL.getValueLoc().getType()) {
6464     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6465     if (Result.isNull())
6466       return QualType();
6467   }
6468 
6469   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6470   NewTL.setKWLoc(TL.getKWLoc());
6471   NewTL.setLParenLoc(TL.getLParenLoc());
6472   NewTL.setRParenLoc(TL.getRParenLoc());
6473 
6474   return Result;
6475 }
6476 
6477 template <typename Derived>
6478 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6479                                                    PipeTypeLoc TL) {
6480   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6481   if (ValueType.isNull())
6482     return QualType();
6483 
6484   QualType Result = TL.getType();
6485   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6486     const PipeType *PT = Result->castAs<PipeType>();
6487     bool isReadPipe = PT->isReadOnly();
6488     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6489     if (Result.isNull())
6490       return QualType();
6491   }
6492 
6493   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6494   NewTL.setKWLoc(TL.getKWLoc());
6495 
6496   return Result;
6497 }
6498 
6499 template <typename Derived>
6500 QualType TreeTransform<Derived>::TransformBitIntType(TypeLocBuilder &TLB,
6501                                                      BitIntTypeLoc TL) {
6502   const BitIntType *EIT = TL.getTypePtr();
6503   QualType Result = TL.getType();
6504 
6505   if (getDerived().AlwaysRebuild()) {
6506     Result = getDerived().RebuildBitIntType(EIT->isUnsigned(),
6507                                             EIT->getNumBits(), TL.getNameLoc());
6508     if (Result.isNull())
6509       return QualType();
6510   }
6511 
6512   BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6513   NewTL.setNameLoc(TL.getNameLoc());
6514   return Result;
6515 }
6516 
6517 template <typename Derived>
6518 QualType TreeTransform<Derived>::TransformDependentBitIntType(
6519     TypeLocBuilder &TLB, DependentBitIntTypeLoc TL) {
6520   const DependentBitIntType *EIT = TL.getTypePtr();
6521 
6522   EnterExpressionEvaluationContext Unevaluated(
6523       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6524   ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6525   BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6526 
6527   if (BitsExpr.isInvalid())
6528     return QualType();
6529 
6530   QualType Result = TL.getType();
6531 
6532   if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6533     Result = getDerived().RebuildDependentBitIntType(
6534         EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6535 
6536     if (Result.isNull())
6537       return QualType();
6538   }
6539 
6540   if (isa<DependentBitIntType>(Result)) {
6541     DependentBitIntTypeLoc NewTL = TLB.push<DependentBitIntTypeLoc>(Result);
6542     NewTL.setNameLoc(TL.getNameLoc());
6543   } else {
6544     BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6545     NewTL.setNameLoc(TL.getNameLoc());
6546   }
6547   return Result;
6548 }
6549 
6550   /// Simple iterator that traverses the template arguments in a
6551   /// container that provides a \c getArgLoc() member function.
6552   ///
6553   /// This iterator is intended to be used with the iterator form of
6554   /// \c TreeTransform<Derived>::TransformTemplateArguments().
6555   template<typename ArgLocContainer>
6556   class TemplateArgumentLocContainerIterator {
6557     ArgLocContainer *Container;
6558     unsigned Index;
6559 
6560   public:
6561     typedef TemplateArgumentLoc value_type;
6562     typedef TemplateArgumentLoc reference;
6563     typedef int difference_type;
6564     typedef std::input_iterator_tag iterator_category;
6565 
6566     class pointer {
6567       TemplateArgumentLoc Arg;
6568 
6569     public:
6570       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6571 
6572       const TemplateArgumentLoc *operator->() const {
6573         return &Arg;
6574       }
6575     };
6576 
6577 
6578     TemplateArgumentLocContainerIterator() {}
6579 
6580     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6581                                  unsigned Index)
6582       : Container(&Container), Index(Index) { }
6583 
6584     TemplateArgumentLocContainerIterator &operator++() {
6585       ++Index;
6586       return *this;
6587     }
6588 
6589     TemplateArgumentLocContainerIterator operator++(int) {
6590       TemplateArgumentLocContainerIterator Old(*this);
6591       ++(*this);
6592       return Old;
6593     }
6594 
6595     TemplateArgumentLoc operator*() const {
6596       return Container->getArgLoc(Index);
6597     }
6598 
6599     pointer operator->() const {
6600       return pointer(Container->getArgLoc(Index));
6601     }
6602 
6603     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6604                            const TemplateArgumentLocContainerIterator &Y) {
6605       return X.Container == Y.Container && X.Index == Y.Index;
6606     }
6607 
6608     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6609                            const TemplateArgumentLocContainerIterator &Y) {
6610       return !(X == Y);
6611     }
6612   };
6613 
6614 template<typename Derived>
6615 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6616                                                    AutoTypeLoc TL) {
6617   const AutoType *T = TL.getTypePtr();
6618   QualType OldDeduced = T->getDeducedType();
6619   QualType NewDeduced;
6620   if (!OldDeduced.isNull()) {
6621     NewDeduced = getDerived().TransformType(OldDeduced);
6622     if (NewDeduced.isNull())
6623       return QualType();
6624   }
6625 
6626   ConceptDecl *NewCD = nullptr;
6627   TemplateArgumentListInfo NewTemplateArgs;
6628   NestedNameSpecifierLoc NewNestedNameSpec;
6629   if (T->isConstrained()) {
6630     NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6631         TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6632 
6633     NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6634     NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6635     typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6636     if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6637                                                 ArgIterator(TL,
6638                                                             TL.getNumArgs()),
6639                                                 NewTemplateArgs))
6640       return QualType();
6641 
6642     if (TL.getNestedNameSpecifierLoc()) {
6643       NewNestedNameSpec
6644         = getDerived().TransformNestedNameSpecifierLoc(
6645             TL.getNestedNameSpecifierLoc());
6646       if (!NewNestedNameSpec)
6647         return QualType();
6648     }
6649   }
6650 
6651   QualType Result = TL.getType();
6652   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6653       T->isDependentType() || T->isConstrained()) {
6654     // FIXME: Maybe don't rebuild if all template arguments are the same.
6655     llvm::SmallVector<TemplateArgument, 4> NewArgList;
6656     NewArgList.reserve(NewTemplateArgs.size());
6657     for (const auto &ArgLoc : NewTemplateArgs.arguments())
6658       NewArgList.push_back(ArgLoc.getArgument());
6659     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6660                                           NewArgList);
6661     if (Result.isNull())
6662       return QualType();
6663   }
6664 
6665   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6666   NewTL.setNameLoc(TL.getNameLoc());
6667   NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6668   NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6669   NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6670   NewTL.setFoundDecl(TL.getFoundDecl());
6671   NewTL.setLAngleLoc(TL.getLAngleLoc());
6672   NewTL.setRAngleLoc(TL.getRAngleLoc());
6673   NewTL.setRParenLoc(TL.getRParenLoc());
6674   for (unsigned I = 0; I < NewTL.getNumArgs(); ++I)
6675     NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6676 
6677   return Result;
6678 }
6679 
6680 template <typename Derived>
6681 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6682                                                         TypeLocBuilder &TLB,
6683                                            TemplateSpecializationTypeLoc TL,
6684                                                       TemplateName Template) {
6685   TemplateArgumentListInfo NewTemplateArgs;
6686   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6687   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6688   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6689     ArgIterator;
6690   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6691                                               ArgIterator(TL, TL.getNumArgs()),
6692                                               NewTemplateArgs))
6693     return QualType();
6694 
6695   // FIXME: maybe don't rebuild if all the template arguments are the same.
6696 
6697   QualType Result =
6698     getDerived().RebuildTemplateSpecializationType(Template,
6699                                                    TL.getTemplateNameLoc(),
6700                                                    NewTemplateArgs);
6701 
6702   if (!Result.isNull()) {
6703     // Specializations of template template parameters are represented as
6704     // TemplateSpecializationTypes, and substitution of type alias templates
6705     // within a dependent context can transform them into
6706     // DependentTemplateSpecializationTypes.
6707     if (isa<DependentTemplateSpecializationType>(Result)) {
6708       DependentTemplateSpecializationTypeLoc NewTL
6709         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6710       NewTL.setElaboratedKeywordLoc(SourceLocation());
6711       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6712       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6713       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6714       NewTL.setLAngleLoc(TL.getLAngleLoc());
6715       NewTL.setRAngleLoc(TL.getRAngleLoc());
6716       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6717         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6718       return Result;
6719     }
6720 
6721     TemplateSpecializationTypeLoc NewTL
6722       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6723     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6724     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6725     NewTL.setLAngleLoc(TL.getLAngleLoc());
6726     NewTL.setRAngleLoc(TL.getRAngleLoc());
6727     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6728       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6729   }
6730 
6731   return Result;
6732 }
6733 
6734 template <typename Derived>
6735 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6736                                      TypeLocBuilder &TLB,
6737                                      DependentTemplateSpecializationTypeLoc TL,
6738                                      TemplateName Template,
6739                                      CXXScopeSpec &SS) {
6740   TemplateArgumentListInfo NewTemplateArgs;
6741   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6742   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6743   typedef TemplateArgumentLocContainerIterator<
6744             DependentTemplateSpecializationTypeLoc> ArgIterator;
6745   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6746                                               ArgIterator(TL, TL.getNumArgs()),
6747                                               NewTemplateArgs))
6748     return QualType();
6749 
6750   // FIXME: maybe don't rebuild if all the template arguments are the same.
6751 
6752   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6753     QualType Result
6754       = getSema().Context.getDependentTemplateSpecializationType(
6755                                                 TL.getTypePtr()->getKeyword(),
6756                                                          DTN->getQualifier(),
6757                                                          DTN->getIdentifier(),
6758                                                                NewTemplateArgs);
6759 
6760     DependentTemplateSpecializationTypeLoc NewTL
6761       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6762     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6763     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6764     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6765     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6766     NewTL.setLAngleLoc(TL.getLAngleLoc());
6767     NewTL.setRAngleLoc(TL.getRAngleLoc());
6768     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6769       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6770     return Result;
6771   }
6772 
6773   QualType Result
6774     = getDerived().RebuildTemplateSpecializationType(Template,
6775                                                      TL.getTemplateNameLoc(),
6776                                                      NewTemplateArgs);
6777 
6778   if (!Result.isNull()) {
6779     /// FIXME: Wrap this in an elaborated-type-specifier?
6780     TemplateSpecializationTypeLoc NewTL
6781       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6782     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6783     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6784     NewTL.setLAngleLoc(TL.getLAngleLoc());
6785     NewTL.setRAngleLoc(TL.getRAngleLoc());
6786     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6787       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6788   }
6789 
6790   return Result;
6791 }
6792 
6793 template<typename Derived>
6794 QualType
6795 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6796                                                 ElaboratedTypeLoc TL) {
6797   const ElaboratedType *T = TL.getTypePtr();
6798 
6799   NestedNameSpecifierLoc QualifierLoc;
6800   // NOTE: the qualifier in an ElaboratedType is optional.
6801   if (TL.getQualifierLoc()) {
6802     QualifierLoc
6803       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6804     if (!QualifierLoc)
6805       return QualType();
6806   }
6807 
6808   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6809   if (NamedT.isNull())
6810     return QualType();
6811 
6812   // C++0x [dcl.type.elab]p2:
6813   //   If the identifier resolves to a typedef-name or the simple-template-id
6814   //   resolves to an alias template specialization, the
6815   //   elaborated-type-specifier is ill-formed.
6816   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6817     if (const TemplateSpecializationType *TST =
6818           NamedT->getAs<TemplateSpecializationType>()) {
6819       TemplateName Template = TST->getTemplateName();
6820       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6821               Template.getAsTemplateDecl())) {
6822         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6823                      diag::err_tag_reference_non_tag)
6824             << TAT << Sema::NTK_TypeAliasTemplate
6825             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6826         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6827       }
6828     }
6829   }
6830 
6831   QualType Result = TL.getType();
6832   if (getDerived().AlwaysRebuild() ||
6833       QualifierLoc != TL.getQualifierLoc() ||
6834       NamedT != T->getNamedType()) {
6835     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6836                                                 T->getKeyword(),
6837                                                 QualifierLoc, NamedT);
6838     if (Result.isNull())
6839       return QualType();
6840   }
6841 
6842   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6843   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6844   NewTL.setQualifierLoc(QualifierLoc);
6845   return Result;
6846 }
6847 
6848 template<typename Derived>
6849 QualType TreeTransform<Derived>::TransformAttributedType(
6850                                                 TypeLocBuilder &TLB,
6851                                                 AttributedTypeLoc TL) {
6852   const AttributedType *oldType = TL.getTypePtr();
6853   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6854   if (modifiedType.isNull())
6855     return QualType();
6856 
6857   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6858   const Attr *oldAttr = TL.getAttr();
6859   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6860   if (oldAttr && !newAttr)
6861     return QualType();
6862 
6863   QualType result = TL.getType();
6864 
6865   // FIXME: dependent operand expressions?
6866   if (getDerived().AlwaysRebuild() ||
6867       modifiedType != oldType->getModifiedType()) {
6868     // TODO: this is really lame; we should really be rebuilding the
6869     // equivalent type from first principles.
6870     QualType equivalentType
6871       = getDerived().TransformType(oldType->getEquivalentType());
6872     if (equivalentType.isNull())
6873       return QualType();
6874 
6875     // Check whether we can add nullability; it is only represented as
6876     // type sugar, and therefore cannot be diagnosed in any other way.
6877     if (auto nullability = oldType->getImmediateNullability()) {
6878       if (!modifiedType->canHaveNullability()) {
6879         SemaRef.Diag(TL.getAttr()->getLocation(),
6880                      diag::err_nullability_nonpointer)
6881             << DiagNullabilityKind(*nullability, false) << modifiedType;
6882         return QualType();
6883       }
6884     }
6885 
6886     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6887                                                modifiedType,
6888                                                equivalentType);
6889   }
6890 
6891   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6892   newTL.setAttr(newAttr);
6893   return result;
6894 }
6895 
6896 template <typename Derived>
6897 QualType TreeTransform<Derived>::TransformBTFTagAttributedType(
6898     TypeLocBuilder &TLB, BTFTagAttributedTypeLoc TL) {
6899   // The BTFTagAttributedType is available for C only.
6900   llvm_unreachable("Unexpected TreeTransform for BTFTagAttributedType");
6901 }
6902 
6903 template<typename Derived>
6904 QualType
6905 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6906                                            ParenTypeLoc TL) {
6907   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6908   if (Inner.isNull())
6909     return QualType();
6910 
6911   QualType Result = TL.getType();
6912   if (getDerived().AlwaysRebuild() ||
6913       Inner != TL.getInnerLoc().getType()) {
6914     Result = getDerived().RebuildParenType(Inner);
6915     if (Result.isNull())
6916       return QualType();
6917   }
6918 
6919   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6920   NewTL.setLParenLoc(TL.getLParenLoc());
6921   NewTL.setRParenLoc(TL.getRParenLoc());
6922   return Result;
6923 }
6924 
6925 template <typename Derived>
6926 QualType
6927 TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
6928                                                     MacroQualifiedTypeLoc TL) {
6929   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6930   if (Inner.isNull())
6931     return QualType();
6932 
6933   QualType Result = TL.getType();
6934   if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
6935     Result =
6936         getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
6937     if (Result.isNull())
6938       return QualType();
6939   }
6940 
6941   MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
6942   NewTL.setExpansionLoc(TL.getExpansionLoc());
6943   return Result;
6944 }
6945 
6946 template<typename Derived>
6947 QualType TreeTransform<Derived>::TransformDependentNameType(
6948     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6949   return TransformDependentNameType(TLB, TL, false);
6950 }
6951 
6952 template<typename Derived>
6953 QualType TreeTransform<Derived>::TransformDependentNameType(
6954     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6955   const DependentNameType *T = TL.getTypePtr();
6956 
6957   NestedNameSpecifierLoc QualifierLoc
6958     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6959   if (!QualifierLoc)
6960     return QualType();
6961 
6962   QualType Result
6963     = getDerived().RebuildDependentNameType(T->getKeyword(),
6964                                             TL.getElaboratedKeywordLoc(),
6965                                             QualifierLoc,
6966                                             T->getIdentifier(),
6967                                             TL.getNameLoc(),
6968                                             DeducedTSTContext);
6969   if (Result.isNull())
6970     return QualType();
6971 
6972   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6973     QualType NamedT = ElabT->getNamedType();
6974     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6975 
6976     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6977     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6978     NewTL.setQualifierLoc(QualifierLoc);
6979   } else {
6980     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6981     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6982     NewTL.setQualifierLoc(QualifierLoc);
6983     NewTL.setNameLoc(TL.getNameLoc());
6984   }
6985   return Result;
6986 }
6987 
6988 template<typename Derived>
6989 QualType TreeTransform<Derived>::
6990           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6991                                  DependentTemplateSpecializationTypeLoc TL) {
6992   NestedNameSpecifierLoc QualifierLoc;
6993   if (TL.getQualifierLoc()) {
6994     QualifierLoc
6995       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6996     if (!QualifierLoc)
6997       return QualType();
6998   }
6999 
7000   return getDerived()
7001            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
7002 }
7003 
7004 template<typename Derived>
7005 QualType TreeTransform<Derived>::
7006 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7007                                    DependentTemplateSpecializationTypeLoc TL,
7008                                        NestedNameSpecifierLoc QualifierLoc) {
7009   const DependentTemplateSpecializationType *T = TL.getTypePtr();
7010 
7011   TemplateArgumentListInfo NewTemplateArgs;
7012   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
7013   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
7014 
7015   typedef TemplateArgumentLocContainerIterator<
7016   DependentTemplateSpecializationTypeLoc> ArgIterator;
7017   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
7018                                               ArgIterator(TL, TL.getNumArgs()),
7019                                               NewTemplateArgs))
7020     return QualType();
7021 
7022   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
7023       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
7024       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
7025       /*AllowInjectedClassName*/ false);
7026   if (Result.isNull())
7027     return QualType();
7028 
7029   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
7030     QualType NamedT = ElabT->getNamedType();
7031 
7032     // Copy information relevant to the template specialization.
7033     TemplateSpecializationTypeLoc NamedTL
7034       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
7035     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7036     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7037     NamedTL.setLAngleLoc(TL.getLAngleLoc());
7038     NamedTL.setRAngleLoc(TL.getRAngleLoc());
7039     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7040       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7041 
7042     // Copy information relevant to the elaborated type.
7043     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7044     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7045     NewTL.setQualifierLoc(QualifierLoc);
7046   } else if (isa<DependentTemplateSpecializationType>(Result)) {
7047     DependentTemplateSpecializationTypeLoc SpecTL
7048       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
7049     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7050     SpecTL.setQualifierLoc(QualifierLoc);
7051     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7052     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7053     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7054     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7055     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7056       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7057   } else {
7058     TemplateSpecializationTypeLoc SpecTL
7059       = TLB.push<TemplateSpecializationTypeLoc>(Result);
7060     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7061     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7062     SpecTL.setLAngleLoc(TL.getLAngleLoc());
7063     SpecTL.setRAngleLoc(TL.getRAngleLoc());
7064     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7065       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7066   }
7067   return Result;
7068 }
7069 
7070 template<typename Derived>
7071 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
7072                                                       PackExpansionTypeLoc TL) {
7073   QualType Pattern
7074     = getDerived().TransformType(TLB, TL.getPatternLoc());
7075   if (Pattern.isNull())
7076     return QualType();
7077 
7078   QualType Result = TL.getType();
7079   if (getDerived().AlwaysRebuild() ||
7080       Pattern != TL.getPatternLoc().getType()) {
7081     Result = getDerived().RebuildPackExpansionType(Pattern,
7082                                            TL.getPatternLoc().getSourceRange(),
7083                                                    TL.getEllipsisLoc(),
7084                                            TL.getTypePtr()->getNumExpansions());
7085     if (Result.isNull())
7086       return QualType();
7087   }
7088 
7089   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
7090   NewT.setEllipsisLoc(TL.getEllipsisLoc());
7091   return Result;
7092 }
7093 
7094 template<typename Derived>
7095 QualType
7096 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
7097                                                    ObjCInterfaceTypeLoc TL) {
7098   // ObjCInterfaceType is never dependent.
7099   TLB.pushFullCopy(TL);
7100   return TL.getType();
7101 }
7102 
7103 template<typename Derived>
7104 QualType
7105 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7106                                                    ObjCTypeParamTypeLoc TL) {
7107   const ObjCTypeParamType *T = TL.getTypePtr();
7108   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7109       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7110   if (!OTP)
7111     return QualType();
7112 
7113   QualType Result = TL.getType();
7114   if (getDerived().AlwaysRebuild() ||
7115       OTP != T->getDecl()) {
7116     Result = getDerived().RebuildObjCTypeParamType(OTP,
7117                  TL.getProtocolLAngleLoc(),
7118                  llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
7119                                     TL.getNumProtocols()),
7120                  TL.getProtocolLocs(),
7121                  TL.getProtocolRAngleLoc());
7122     if (Result.isNull())
7123       return QualType();
7124   }
7125 
7126   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7127   if (TL.getNumProtocols()) {
7128     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7129     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7130       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7131     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7132   }
7133   return Result;
7134 }
7135 
7136 template<typename Derived>
7137 QualType
7138 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7139                                                 ObjCObjectTypeLoc TL) {
7140   // Transform base type.
7141   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7142   if (BaseType.isNull())
7143     return QualType();
7144 
7145   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7146 
7147   // Transform type arguments.
7148   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7149   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7150     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7151     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7152     QualType TypeArg = TypeArgInfo->getType();
7153     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7154       AnyChanged = true;
7155 
7156       // We have a pack expansion. Instantiate it.
7157       const auto *PackExpansion = PackExpansionLoc.getType()
7158                                     ->castAs<PackExpansionType>();
7159       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7160       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7161                                               Unexpanded);
7162       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
7163 
7164       // Determine whether the set of unexpanded parameter packs can
7165       // and should be expanded.
7166       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7167       bool Expand = false;
7168       bool RetainExpansion = false;
7169       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7170       if (getDerived().TryExpandParameterPacks(
7171             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7172             Unexpanded, Expand, RetainExpansion, NumExpansions))
7173         return QualType();
7174 
7175       if (!Expand) {
7176         // We can't expand this pack expansion into separate arguments yet;
7177         // just substitute into the pattern and create a new pack expansion
7178         // type.
7179         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7180 
7181         TypeLocBuilder TypeArgBuilder;
7182         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7183         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7184                                                              PatternLoc);
7185         if (NewPatternType.isNull())
7186           return QualType();
7187 
7188         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7189                                       NewPatternType, NumExpansions);
7190         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7191         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7192         NewTypeArgInfos.push_back(
7193           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7194         continue;
7195       }
7196 
7197       // Substitute into the pack expansion pattern for each slice of the
7198       // pack.
7199       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7200         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7201 
7202         TypeLocBuilder TypeArgBuilder;
7203         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7204 
7205         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7206                                                          PatternLoc);
7207         if (NewTypeArg.isNull())
7208           return QualType();
7209 
7210         NewTypeArgInfos.push_back(
7211           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7212       }
7213 
7214       continue;
7215     }
7216 
7217     TypeLocBuilder TypeArgBuilder;
7218     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7219     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7220     if (NewTypeArg.isNull())
7221       return QualType();
7222 
7223     // If nothing changed, just keep the old TypeSourceInfo.
7224     if (NewTypeArg == TypeArg) {
7225       NewTypeArgInfos.push_back(TypeArgInfo);
7226       continue;
7227     }
7228 
7229     NewTypeArgInfos.push_back(
7230       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7231     AnyChanged = true;
7232   }
7233 
7234   QualType Result = TL.getType();
7235   if (getDerived().AlwaysRebuild() || AnyChanged) {
7236     // Rebuild the type.
7237     Result = getDerived().RebuildObjCObjectType(
7238         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7239         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7240         llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7241         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7242 
7243     if (Result.isNull())
7244       return QualType();
7245   }
7246 
7247   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7248   NewT.setHasBaseTypeAsWritten(true);
7249   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7250   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7251     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7252   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7253   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7254   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7255     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7256   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7257   return Result;
7258 }
7259 
7260 template<typename Derived>
7261 QualType
7262 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7263                                                ObjCObjectPointerTypeLoc TL) {
7264   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7265   if (PointeeType.isNull())
7266     return QualType();
7267 
7268   QualType Result = TL.getType();
7269   if (getDerived().AlwaysRebuild() ||
7270       PointeeType != TL.getPointeeLoc().getType()) {
7271     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7272                                                        TL.getStarLoc());
7273     if (Result.isNull())
7274       return QualType();
7275   }
7276 
7277   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7278   NewT.setStarLoc(TL.getStarLoc());
7279   return Result;
7280 }
7281 
7282 //===----------------------------------------------------------------------===//
7283 // Statement transformation
7284 //===----------------------------------------------------------------------===//
7285 template<typename Derived>
7286 StmtResult
7287 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7288   return S;
7289 }
7290 
7291 template<typename Derived>
7292 StmtResult
7293 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7294   return getDerived().TransformCompoundStmt(S, false);
7295 }
7296 
7297 template<typename Derived>
7298 StmtResult
7299 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7300                                               bool IsStmtExpr) {
7301   Sema::CompoundScopeRAII CompoundScope(getSema());
7302 
7303   const Stmt *ExprResult = S->getStmtExprResult();
7304   bool SubStmtInvalid = false;
7305   bool SubStmtChanged = false;
7306   SmallVector<Stmt*, 8> Statements;
7307   for (auto *B : S->body()) {
7308     StmtResult Result = getDerived().TransformStmt(
7309         B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7310 
7311     if (Result.isInvalid()) {
7312       // Immediately fail if this was a DeclStmt, since it's very
7313       // likely that this will cause problems for future statements.
7314       if (isa<DeclStmt>(B))
7315         return StmtError();
7316 
7317       // Otherwise, just keep processing substatements and fail later.
7318       SubStmtInvalid = true;
7319       continue;
7320     }
7321 
7322     SubStmtChanged = SubStmtChanged || Result.get() != B;
7323     Statements.push_back(Result.getAs<Stmt>());
7324   }
7325 
7326   if (SubStmtInvalid)
7327     return StmtError();
7328 
7329   if (!getDerived().AlwaysRebuild() &&
7330       !SubStmtChanged)
7331     return S;
7332 
7333   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7334                                           Statements,
7335                                           S->getRBracLoc(),
7336                                           IsStmtExpr);
7337 }
7338 
7339 template<typename Derived>
7340 StmtResult
7341 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7342   ExprResult LHS, RHS;
7343   {
7344     EnterExpressionEvaluationContext Unevaluated(
7345         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7346 
7347     // Transform the left-hand case value.
7348     LHS = getDerived().TransformExpr(S->getLHS());
7349     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7350     if (LHS.isInvalid())
7351       return StmtError();
7352 
7353     // Transform the right-hand case value (for the GNU case-range extension).
7354     RHS = getDerived().TransformExpr(S->getRHS());
7355     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7356     if (RHS.isInvalid())
7357       return StmtError();
7358   }
7359 
7360   // Build the case statement.
7361   // Case statements are always rebuilt so that they will attached to their
7362   // transformed switch statement.
7363   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7364                                                        LHS.get(),
7365                                                        S->getEllipsisLoc(),
7366                                                        RHS.get(),
7367                                                        S->getColonLoc());
7368   if (Case.isInvalid())
7369     return StmtError();
7370 
7371   // Transform the statement following the case
7372   StmtResult SubStmt =
7373       getDerived().TransformStmt(S->getSubStmt());
7374   if (SubStmt.isInvalid())
7375     return StmtError();
7376 
7377   // Attach the body to the case statement
7378   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7379 }
7380 
7381 template <typename Derived>
7382 StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7383   // Transform the statement following the default case
7384   StmtResult SubStmt =
7385       getDerived().TransformStmt(S->getSubStmt());
7386   if (SubStmt.isInvalid())
7387     return StmtError();
7388 
7389   // Default statements are always rebuilt
7390   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7391                                          SubStmt.get());
7392 }
7393 
7394 template<typename Derived>
7395 StmtResult
7396 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7397   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7398   if (SubStmt.isInvalid())
7399     return StmtError();
7400 
7401   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7402                                         S->getDecl());
7403   if (!LD)
7404     return StmtError();
7405 
7406   // If we're transforming "in-place" (we're not creating new local
7407   // declarations), assume we're replacing the old label statement
7408   // and clear out the reference to it.
7409   if (LD == S->getDecl())
7410     S->getDecl()->setStmt(nullptr);
7411 
7412   // FIXME: Pass the real colon location in.
7413   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7414                                        cast<LabelDecl>(LD), SourceLocation(),
7415                                        SubStmt.get());
7416 }
7417 
7418 template <typename Derived>
7419 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7420   if (!R)
7421     return R;
7422 
7423   switch (R->getKind()) {
7424 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
7425 #define ATTR(X)
7426 #define PRAGMA_SPELLING_ATTR(X)                                                \
7427   case attr::X:                                                                \
7428     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7429 #include "clang/Basic/AttrList.inc"
7430   default:
7431     return R;
7432   }
7433 }
7434 
7435 template <typename Derived>
7436 StmtResult
7437 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7438                                                 StmtDiscardKind SDK) {
7439   bool AttrsChanged = false;
7440   SmallVector<const Attr *, 1> Attrs;
7441 
7442   // Visit attributes and keep track if any are transformed.
7443   for (const auto *I : S->getAttrs()) {
7444     const Attr *R = getDerived().TransformAttr(I);
7445     AttrsChanged |= (I != R);
7446     if (R)
7447       Attrs.push_back(R);
7448   }
7449 
7450   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7451   if (SubStmt.isInvalid())
7452     return StmtError();
7453 
7454   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7455     return S;
7456 
7457   // If transforming the attributes failed for all of the attributes in the
7458   // statement, don't make an AttributedStmt without attributes.
7459   if (Attrs.empty())
7460     return SubStmt;
7461 
7462   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7463                                             SubStmt.get());
7464 }
7465 
7466 template<typename Derived>
7467 StmtResult
7468 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7469   // Transform the initialization statement
7470   StmtResult Init = getDerived().TransformStmt(S->getInit());
7471   if (Init.isInvalid())
7472     return StmtError();
7473 
7474   Sema::ConditionResult Cond;
7475   if (!S->isConsteval()) {
7476     // Transform the condition
7477     Cond = getDerived().TransformCondition(
7478         S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7479         S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7480                          : Sema::ConditionKind::Boolean);
7481     if (Cond.isInvalid())
7482       return StmtError();
7483   }
7484 
7485   // If this is a constexpr if, determine which arm we should instantiate.
7486   llvm::Optional<bool> ConstexprConditionValue;
7487   if (S->isConstexpr())
7488     ConstexprConditionValue = Cond.getKnownValue();
7489 
7490   // Transform the "then" branch.
7491   StmtResult Then;
7492   if (!ConstexprConditionValue || *ConstexprConditionValue) {
7493     Then = getDerived().TransformStmt(S->getThen());
7494     if (Then.isInvalid())
7495       return StmtError();
7496   } else {
7497     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7498   }
7499 
7500   // Transform the "else" branch.
7501   StmtResult Else;
7502   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7503     Else = getDerived().TransformStmt(S->getElse());
7504     if (Else.isInvalid())
7505       return StmtError();
7506   }
7507 
7508   if (!getDerived().AlwaysRebuild() &&
7509       Init.get() == S->getInit() &&
7510       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7511       Then.get() == S->getThen() &&
7512       Else.get() == S->getElse())
7513     return S;
7514 
7515   return getDerived().RebuildIfStmt(
7516       S->getIfLoc(), S->getStatementKind(), S->getLParenLoc(), Cond,
7517       S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7518 }
7519 
7520 template<typename Derived>
7521 StmtResult
7522 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7523   // Transform the initialization statement
7524   StmtResult Init = getDerived().TransformStmt(S->getInit());
7525   if (Init.isInvalid())
7526     return StmtError();
7527 
7528   // Transform the condition.
7529   Sema::ConditionResult Cond = getDerived().TransformCondition(
7530       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7531       Sema::ConditionKind::Switch);
7532   if (Cond.isInvalid())
7533     return StmtError();
7534 
7535   // Rebuild the switch statement.
7536   StmtResult Switch =
7537       getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7538                                           Init.get(), Cond, S->getRParenLoc());
7539   if (Switch.isInvalid())
7540     return StmtError();
7541 
7542   // Transform the body of the switch statement.
7543   StmtResult Body = getDerived().TransformStmt(S->getBody());
7544   if (Body.isInvalid())
7545     return StmtError();
7546 
7547   // Complete the switch statement.
7548   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7549                                             Body.get());
7550 }
7551 
7552 template<typename Derived>
7553 StmtResult
7554 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7555   // Transform the condition
7556   Sema::ConditionResult Cond = getDerived().TransformCondition(
7557       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7558       Sema::ConditionKind::Boolean);
7559   if (Cond.isInvalid())
7560     return StmtError();
7561 
7562   // Transform the body
7563   StmtResult Body = getDerived().TransformStmt(S->getBody());
7564   if (Body.isInvalid())
7565     return StmtError();
7566 
7567   if (!getDerived().AlwaysRebuild() &&
7568       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7569       Body.get() == S->getBody())
7570     return Owned(S);
7571 
7572   return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7573                                        Cond, S->getRParenLoc(), Body.get());
7574 }
7575 
7576 template<typename Derived>
7577 StmtResult
7578 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7579   // Transform the body
7580   StmtResult Body = getDerived().TransformStmt(S->getBody());
7581   if (Body.isInvalid())
7582     return StmtError();
7583 
7584   // Transform the condition
7585   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7586   if (Cond.isInvalid())
7587     return StmtError();
7588 
7589   if (!getDerived().AlwaysRebuild() &&
7590       Cond.get() == S->getCond() &&
7591       Body.get() == S->getBody())
7592     return S;
7593 
7594   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7595                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
7596                                     S->getRParenLoc());
7597 }
7598 
7599 template<typename Derived>
7600 StmtResult
7601 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7602   if (getSema().getLangOpts().OpenMP)
7603     getSema().startOpenMPLoop();
7604 
7605   // Transform the initialization statement
7606   StmtResult Init = getDerived().TransformStmt(S->getInit());
7607   if (Init.isInvalid())
7608     return StmtError();
7609 
7610   // In OpenMP loop region loop control variable must be captured and be
7611   // private. Perform analysis of first part (if any).
7612   if (getSema().getLangOpts().OpenMP && Init.isUsable())
7613     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7614 
7615   // Transform the condition
7616   Sema::ConditionResult Cond = getDerived().TransformCondition(
7617       S->getForLoc(), S->getConditionVariable(), S->getCond(),
7618       Sema::ConditionKind::Boolean);
7619   if (Cond.isInvalid())
7620     return StmtError();
7621 
7622   // Transform the increment
7623   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7624   if (Inc.isInvalid())
7625     return StmtError();
7626 
7627   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7628   if (S->getInc() && !FullInc.get())
7629     return StmtError();
7630 
7631   // Transform the body
7632   StmtResult Body = getDerived().TransformStmt(S->getBody());
7633   if (Body.isInvalid())
7634     return StmtError();
7635 
7636   if (!getDerived().AlwaysRebuild() &&
7637       Init.get() == S->getInit() &&
7638       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7639       Inc.get() == S->getInc() &&
7640       Body.get() == S->getBody())
7641     return S;
7642 
7643   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7644                                      Init.get(), Cond, FullInc,
7645                                      S->getRParenLoc(), Body.get());
7646 }
7647 
7648 template<typename Derived>
7649 StmtResult
7650 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7651   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7652                                         S->getLabel());
7653   if (!LD)
7654     return StmtError();
7655 
7656   // Goto statements must always be rebuilt, to resolve the label.
7657   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7658                                       cast<LabelDecl>(LD));
7659 }
7660 
7661 template<typename Derived>
7662 StmtResult
7663 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7664   ExprResult Target = getDerived().TransformExpr(S->getTarget());
7665   if (Target.isInvalid())
7666     return StmtError();
7667   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7668 
7669   if (!getDerived().AlwaysRebuild() &&
7670       Target.get() == S->getTarget())
7671     return S;
7672 
7673   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7674                                               Target.get());
7675 }
7676 
7677 template<typename Derived>
7678 StmtResult
7679 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7680   return S;
7681 }
7682 
7683 template<typename Derived>
7684 StmtResult
7685 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7686   return S;
7687 }
7688 
7689 template<typename Derived>
7690 StmtResult
7691 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7692   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7693                                                         /*NotCopyInit*/false);
7694   if (Result.isInvalid())
7695     return StmtError();
7696 
7697   // FIXME: We always rebuild the return statement because there is no way
7698   // to tell whether the return type of the function has changed.
7699   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7700 }
7701 
7702 template<typename Derived>
7703 StmtResult
7704 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7705   bool DeclChanged = false;
7706   SmallVector<Decl *, 4> Decls;
7707   for (auto *D : S->decls()) {
7708     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7709     if (!Transformed)
7710       return StmtError();
7711 
7712     if (Transformed != D)
7713       DeclChanged = true;
7714 
7715     Decls.push_back(Transformed);
7716   }
7717 
7718   if (!getDerived().AlwaysRebuild() && !DeclChanged)
7719     return S;
7720 
7721   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7722 }
7723 
7724 template<typename Derived>
7725 StmtResult
7726 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7727 
7728   SmallVector<Expr*, 8> Constraints;
7729   SmallVector<Expr*, 8> Exprs;
7730   SmallVector<IdentifierInfo *, 4> Names;
7731 
7732   ExprResult AsmString;
7733   SmallVector<Expr*, 8> Clobbers;
7734 
7735   bool ExprsChanged = false;
7736 
7737   // Go through the outputs.
7738   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7739     Names.push_back(S->getOutputIdentifier(I));
7740 
7741     // No need to transform the constraint literal.
7742     Constraints.push_back(S->getOutputConstraintLiteral(I));
7743 
7744     // Transform the output expr.
7745     Expr *OutputExpr = S->getOutputExpr(I);
7746     ExprResult Result = getDerived().TransformExpr(OutputExpr);
7747     if (Result.isInvalid())
7748       return StmtError();
7749 
7750     ExprsChanged |= Result.get() != OutputExpr;
7751 
7752     Exprs.push_back(Result.get());
7753   }
7754 
7755   // Go through the inputs.
7756   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7757     Names.push_back(S->getInputIdentifier(I));
7758 
7759     // No need to transform the constraint literal.
7760     Constraints.push_back(S->getInputConstraintLiteral(I));
7761 
7762     // Transform the input expr.
7763     Expr *InputExpr = S->getInputExpr(I);
7764     ExprResult Result = getDerived().TransformExpr(InputExpr);
7765     if (Result.isInvalid())
7766       return StmtError();
7767 
7768     ExprsChanged |= Result.get() != InputExpr;
7769 
7770     Exprs.push_back(Result.get());
7771   }
7772 
7773   // Go through the Labels.
7774   for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7775     Names.push_back(S->getLabelIdentifier(I));
7776 
7777     ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7778     if (Result.isInvalid())
7779       return StmtError();
7780     ExprsChanged |= Result.get() != S->getLabelExpr(I);
7781     Exprs.push_back(Result.get());
7782   }
7783   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7784     return S;
7785 
7786   // Go through the clobbers.
7787   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7788     Clobbers.push_back(S->getClobberStringLiteral(I));
7789 
7790   // No need to transform the asm string literal.
7791   AsmString = S->getAsmString();
7792   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7793                                         S->isVolatile(), S->getNumOutputs(),
7794                                         S->getNumInputs(), Names.data(),
7795                                         Constraints, Exprs, AsmString.get(),
7796                                         Clobbers, S->getNumLabels(),
7797                                         S->getRParenLoc());
7798 }
7799 
7800 template<typename Derived>
7801 StmtResult
7802 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7803   ArrayRef<Token> AsmToks =
7804     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
7805 
7806   bool HadError = false, HadChange = false;
7807 
7808   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7809   SmallVector<Expr*, 8> TransformedExprs;
7810   TransformedExprs.reserve(SrcExprs.size());
7811   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7812     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7813     if (!Result.isUsable()) {
7814       HadError = true;
7815     } else {
7816       HadChange |= (Result.get() != SrcExprs[i]);
7817       TransformedExprs.push_back(Result.get());
7818     }
7819   }
7820 
7821   if (HadError) return StmtError();
7822   if (!HadChange && !getDerived().AlwaysRebuild())
7823     return Owned(S);
7824 
7825   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7826                                        AsmToks, S->getAsmString(),
7827                                        S->getNumOutputs(), S->getNumInputs(),
7828                                        S->getAllConstraints(), S->getClobbers(),
7829                                        TransformedExprs, S->getEndLoc());
7830 }
7831 
7832 // C++ Coroutines TS
7833 
7834 template<typename Derived>
7835 StmtResult
7836 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7837   auto *ScopeInfo = SemaRef.getCurFunction();
7838   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7839   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7840          ScopeInfo->NeedsCoroutineSuspends &&
7841          ScopeInfo->CoroutineSuspends.first == nullptr &&
7842          ScopeInfo->CoroutineSuspends.second == nullptr &&
7843          "expected clean scope info");
7844 
7845   // Set that we have (possibly-invalid) suspend points before we do anything
7846   // that may fail.
7847   ScopeInfo->setNeedsCoroutineSuspends(false);
7848 
7849   // We re-build the coroutine promise object (and the coroutine parameters its
7850   // type and constructor depend on) based on the types used in our current
7851   // function. We must do so, and set it on the current FunctionScopeInfo,
7852   // before attempting to transform the other parts of the coroutine body
7853   // statement, such as the implicit suspend statements (because those
7854   // statements reference the FunctionScopeInfo::CoroutinePromise).
7855   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7856     return StmtError();
7857   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7858   if (!Promise)
7859     return StmtError();
7860   getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
7861   ScopeInfo->CoroutinePromise = Promise;
7862 
7863   // Transform the implicit coroutine statements constructed using dependent
7864   // types during the previous parse: initial and final suspensions, the return
7865   // object, and others. We also transform the coroutine function's body.
7866   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7867   if (InitSuspend.isInvalid())
7868     return StmtError();
7869   StmtResult FinalSuspend =
7870       getDerived().TransformStmt(S->getFinalSuspendStmt());
7871   if (FinalSuspend.isInvalid() ||
7872       !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
7873     return StmtError();
7874   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7875   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7876 
7877   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7878   if (BodyRes.isInvalid())
7879     return StmtError();
7880 
7881   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7882   if (Builder.isInvalid())
7883     return StmtError();
7884 
7885   Expr *ReturnObject = S->getReturnValueInit();
7886   assert(ReturnObject && "the return object is expected to be valid");
7887   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7888                                                      /*NoCopyInit*/ false);
7889   if (Res.isInvalid())
7890     return StmtError();
7891   Builder.ReturnValue = Res.get();
7892 
7893   // If during the previous parse the coroutine still had a dependent promise
7894   // statement, we may need to build some implicit coroutine statements
7895   // (such as exception and fallthrough handlers) for the first time.
7896   if (S->hasDependentPromiseType()) {
7897     // We can only build these statements, however, if the current promise type
7898     // is not dependent.
7899     if (!Promise->getType()->isDependentType()) {
7900       assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7901              !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7902              "these nodes should not have been built yet");
7903       if (!Builder.buildDependentStatements())
7904         return StmtError();
7905     }
7906   } else {
7907     if (auto *OnFallthrough = S->getFallthroughHandler()) {
7908       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7909       if (Res.isInvalid())
7910         return StmtError();
7911       Builder.OnFallthrough = Res.get();
7912     }
7913 
7914     if (auto *OnException = S->getExceptionHandler()) {
7915       StmtResult Res = getDerived().TransformStmt(OnException);
7916       if (Res.isInvalid())
7917         return StmtError();
7918       Builder.OnException = Res.get();
7919     }
7920 
7921     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7922       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7923       if (Res.isInvalid())
7924         return StmtError();
7925       Builder.ReturnStmtOnAllocFailure = Res.get();
7926     }
7927 
7928     // Transform any additional statements we may have already built
7929     assert(S->getAllocate() && S->getDeallocate() &&
7930            "allocation and deallocation calls must already be built");
7931     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7932     if (AllocRes.isInvalid())
7933       return StmtError();
7934     Builder.Allocate = AllocRes.get();
7935 
7936     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7937     if (DeallocRes.isInvalid())
7938       return StmtError();
7939     Builder.Deallocate = DeallocRes.get();
7940 
7941     if (auto *ReturnStmt = S->getReturnStmt()) {
7942       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7943       if (Res.isInvalid())
7944         return StmtError();
7945       Builder.ReturnStmt = Res.get();
7946     }
7947   }
7948 
7949   return getDerived().RebuildCoroutineBodyStmt(Builder);
7950 }
7951 
7952 template<typename Derived>
7953 StmtResult
7954 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7955   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7956                                                         /*NotCopyInit*/false);
7957   if (Result.isInvalid())
7958     return StmtError();
7959 
7960   // Always rebuild; we don't know if this needs to be injected into a new
7961   // context or if the promise type has changed.
7962   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7963                                           S->isImplicit());
7964 }
7965 
7966 template <typename Derived>
7967 ExprResult TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7968   ExprResult Operand = getDerived().TransformInitializer(E->getOperand(),
7969                                                          /*NotCopyInit*/ false);
7970   if (Operand.isInvalid())
7971     return ExprError();
7972 
7973   // Rebuild the common-expr from the operand rather than transforming it
7974   // separately.
7975 
7976   // FIXME: getCurScope() should not be used during template instantiation.
7977   // We should pick up the set of unqualified lookup results for operator
7978   // co_await during the initial parse.
7979   ExprResult Lookup = getSema().BuildOperatorCoawaitLookupExpr(
7980       getSema().getCurScope(), E->getKeywordLoc());
7981 
7982   // Always rebuild; we don't know if this needs to be injected into a new
7983   // context or if the promise type has changed.
7984   return getDerived().RebuildCoawaitExpr(
7985       E->getKeywordLoc(), Operand.get(),
7986       cast<UnresolvedLookupExpr>(Lookup.get()), E->isImplicit());
7987 }
7988 
7989 template <typename Derived>
7990 ExprResult
7991 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7992   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7993                                                         /*NotCopyInit*/ false);
7994   if (OperandResult.isInvalid())
7995     return ExprError();
7996 
7997   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7998           E->getOperatorCoawaitLookup());
7999 
8000   if (LookupResult.isInvalid())
8001     return ExprError();
8002 
8003   // Always rebuild; we don't know if this needs to be injected into a new
8004   // context or if the promise type has changed.
8005   return getDerived().RebuildDependentCoawaitExpr(
8006       E->getKeywordLoc(), OperandResult.get(),
8007       cast<UnresolvedLookupExpr>(LookupResult.get()));
8008 }
8009 
8010 template<typename Derived>
8011 ExprResult
8012 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
8013   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
8014                                                         /*NotCopyInit*/false);
8015   if (Result.isInvalid())
8016     return ExprError();
8017 
8018   // Always rebuild; we don't know if this needs to be injected into a new
8019   // context or if the promise type has changed.
8020   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
8021 }
8022 
8023 // Objective-C Statements.
8024 
8025 template<typename Derived>
8026 StmtResult
8027 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
8028   // Transform the body of the @try.
8029   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
8030   if (TryBody.isInvalid())
8031     return StmtError();
8032 
8033   // Transform the @catch statements (if present).
8034   bool AnyCatchChanged = false;
8035   SmallVector<Stmt*, 8> CatchStmts;
8036   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
8037     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
8038     if (Catch.isInvalid())
8039       return StmtError();
8040     if (Catch.get() != S->getCatchStmt(I))
8041       AnyCatchChanged = true;
8042     CatchStmts.push_back(Catch.get());
8043   }
8044 
8045   // Transform the @finally statement (if present).
8046   StmtResult Finally;
8047   if (S->getFinallyStmt()) {
8048     Finally = getDerived().TransformStmt(S->getFinallyStmt());
8049     if (Finally.isInvalid())
8050       return StmtError();
8051   }
8052 
8053   // If nothing changed, just retain this statement.
8054   if (!getDerived().AlwaysRebuild() &&
8055       TryBody.get() == S->getTryBody() &&
8056       !AnyCatchChanged &&
8057       Finally.get() == S->getFinallyStmt())
8058     return S;
8059 
8060   // Build a new statement.
8061   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
8062                                            CatchStmts, Finally.get());
8063 }
8064 
8065 template<typename Derived>
8066 StmtResult
8067 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
8068   // Transform the @catch parameter, if there is one.
8069   VarDecl *Var = nullptr;
8070   if (VarDecl *FromVar = S->getCatchParamDecl()) {
8071     TypeSourceInfo *TSInfo = nullptr;
8072     if (FromVar->getTypeSourceInfo()) {
8073       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
8074       if (!TSInfo)
8075         return StmtError();
8076     }
8077 
8078     QualType T;
8079     if (TSInfo)
8080       T = TSInfo->getType();
8081     else {
8082       T = getDerived().TransformType(FromVar->getType());
8083       if (T.isNull())
8084         return StmtError();
8085     }
8086 
8087     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
8088     if (!Var)
8089       return StmtError();
8090   }
8091 
8092   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
8093   if (Body.isInvalid())
8094     return StmtError();
8095 
8096   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
8097                                              S->getRParenLoc(),
8098                                              Var, Body.get());
8099 }
8100 
8101 template<typename Derived>
8102 StmtResult
8103 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
8104   // Transform the body.
8105   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8106   if (Body.isInvalid())
8107     return StmtError();
8108 
8109   // If nothing changed, just retain this statement.
8110   if (!getDerived().AlwaysRebuild() &&
8111       Body.get() == S->getFinallyBody())
8112     return S;
8113 
8114   // Build a new statement.
8115   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8116                                                Body.get());
8117 }
8118 
8119 template<typename Derived>
8120 StmtResult
8121 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8122   ExprResult Operand;
8123   if (S->getThrowExpr()) {
8124     Operand = getDerived().TransformExpr(S->getThrowExpr());
8125     if (Operand.isInvalid())
8126       return StmtError();
8127   }
8128 
8129   if (!getDerived().AlwaysRebuild() &&
8130       Operand.get() == S->getThrowExpr())
8131     return S;
8132 
8133   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8134 }
8135 
8136 template<typename Derived>
8137 StmtResult
8138 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8139                                                   ObjCAtSynchronizedStmt *S) {
8140   // Transform the object we are locking.
8141   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8142   if (Object.isInvalid())
8143     return StmtError();
8144   Object =
8145     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8146                                                   Object.get());
8147   if (Object.isInvalid())
8148     return StmtError();
8149 
8150   // Transform the body.
8151   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8152   if (Body.isInvalid())
8153     return StmtError();
8154 
8155   // If nothing change, just retain the current statement.
8156   if (!getDerived().AlwaysRebuild() &&
8157       Object.get() == S->getSynchExpr() &&
8158       Body.get() == S->getSynchBody())
8159     return S;
8160 
8161   // Build a new statement.
8162   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8163                                                     Object.get(), Body.get());
8164 }
8165 
8166 template<typename Derived>
8167 StmtResult
8168 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8169                                               ObjCAutoreleasePoolStmt *S) {
8170   // Transform the body.
8171   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8172   if (Body.isInvalid())
8173     return StmtError();
8174 
8175   // If nothing changed, just retain this statement.
8176   if (!getDerived().AlwaysRebuild() &&
8177       Body.get() == S->getSubStmt())
8178     return S;
8179 
8180   // Build a new statement.
8181   return getDerived().RebuildObjCAutoreleasePoolStmt(
8182                         S->getAtLoc(), Body.get());
8183 }
8184 
8185 template<typename Derived>
8186 StmtResult
8187 TreeTransform<Derived>::TransformObjCForCollectionStmt(
8188                                                   ObjCForCollectionStmt *S) {
8189   // Transform the element statement.
8190   StmtResult Element =
8191       getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8192   if (Element.isInvalid())
8193     return StmtError();
8194 
8195   // Transform the collection expression.
8196   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8197   if (Collection.isInvalid())
8198     return StmtError();
8199 
8200   // Transform the body.
8201   StmtResult Body = getDerived().TransformStmt(S->getBody());
8202   if (Body.isInvalid())
8203     return StmtError();
8204 
8205   // If nothing changed, just retain this statement.
8206   if (!getDerived().AlwaysRebuild() &&
8207       Element.get() == S->getElement() &&
8208       Collection.get() == S->getCollection() &&
8209       Body.get() == S->getBody())
8210     return S;
8211 
8212   // Build a new statement.
8213   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8214                                                    Element.get(),
8215                                                    Collection.get(),
8216                                                    S->getRParenLoc(),
8217                                                    Body.get());
8218 }
8219 
8220 template <typename Derived>
8221 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8222   // Transform the exception declaration, if any.
8223   VarDecl *Var = nullptr;
8224   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8225     TypeSourceInfo *T =
8226         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8227     if (!T)
8228       return StmtError();
8229 
8230     Var = getDerived().RebuildExceptionDecl(
8231         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8232         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8233     if (!Var || Var->isInvalidDecl())
8234       return StmtError();
8235   }
8236 
8237   // Transform the actual exception handler.
8238   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8239   if (Handler.isInvalid())
8240     return StmtError();
8241 
8242   if (!getDerived().AlwaysRebuild() && !Var &&
8243       Handler.get() == S->getHandlerBlock())
8244     return S;
8245 
8246   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8247 }
8248 
8249 template <typename Derived>
8250 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8251   // Transform the try block itself.
8252   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8253   if (TryBlock.isInvalid())
8254     return StmtError();
8255 
8256   // Transform the handlers.
8257   bool HandlerChanged = false;
8258   SmallVector<Stmt *, 8> Handlers;
8259   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8260     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8261     if (Handler.isInvalid())
8262       return StmtError();
8263 
8264     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8265     Handlers.push_back(Handler.getAs<Stmt>());
8266   }
8267 
8268   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8269       !HandlerChanged)
8270     return S;
8271 
8272   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8273                                         Handlers);
8274 }
8275 
8276 template<typename Derived>
8277 StmtResult
8278 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8279   StmtResult Init =
8280       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8281   if (Init.isInvalid())
8282     return StmtError();
8283 
8284   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8285   if (Range.isInvalid())
8286     return StmtError();
8287 
8288   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8289   if (Begin.isInvalid())
8290     return StmtError();
8291   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8292   if (End.isInvalid())
8293     return StmtError();
8294 
8295   ExprResult Cond = getDerived().TransformExpr(S->getCond());
8296   if (Cond.isInvalid())
8297     return StmtError();
8298   if (Cond.get())
8299     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8300   if (Cond.isInvalid())
8301     return StmtError();
8302   if (Cond.get())
8303     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8304 
8305   ExprResult Inc = getDerived().TransformExpr(S->getInc());
8306   if (Inc.isInvalid())
8307     return StmtError();
8308   if (Inc.get())
8309     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8310 
8311   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8312   if (LoopVar.isInvalid())
8313     return StmtError();
8314 
8315   StmtResult NewStmt = S;
8316   if (getDerived().AlwaysRebuild() ||
8317       Init.get() != S->getInit() ||
8318       Range.get() != S->getRangeStmt() ||
8319       Begin.get() != S->getBeginStmt() ||
8320       End.get() != S->getEndStmt() ||
8321       Cond.get() != S->getCond() ||
8322       Inc.get() != S->getInc() ||
8323       LoopVar.get() != S->getLoopVarStmt()) {
8324     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8325                                                   S->getCoawaitLoc(), Init.get(),
8326                                                   S->getColonLoc(), Range.get(),
8327                                                   Begin.get(), End.get(),
8328                                                   Cond.get(),
8329                                                   Inc.get(), LoopVar.get(),
8330                                                   S->getRParenLoc());
8331     if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8332       // Might not have attached any initializer to the loop variable.
8333       getSema().ActOnInitializerError(
8334           cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8335       return StmtError();
8336     }
8337   }
8338 
8339   StmtResult Body = getDerived().TransformStmt(S->getBody());
8340   if (Body.isInvalid())
8341     return StmtError();
8342 
8343   // Body has changed but we didn't rebuild the for-range statement. Rebuild
8344   // it now so we have a new statement to attach the body to.
8345   if (Body.get() != S->getBody() && NewStmt.get() == S) {
8346     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8347                                                   S->getCoawaitLoc(), Init.get(),
8348                                                   S->getColonLoc(), Range.get(),
8349                                                   Begin.get(), End.get(),
8350                                                   Cond.get(),
8351                                                   Inc.get(), LoopVar.get(),
8352                                                   S->getRParenLoc());
8353     if (NewStmt.isInvalid())
8354       return StmtError();
8355   }
8356 
8357   if (NewStmt.get() == S)
8358     return S;
8359 
8360   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8361 }
8362 
8363 template<typename Derived>
8364 StmtResult
8365 TreeTransform<Derived>::TransformMSDependentExistsStmt(
8366                                                     MSDependentExistsStmt *S) {
8367   // Transform the nested-name-specifier, if any.
8368   NestedNameSpecifierLoc QualifierLoc;
8369   if (S->getQualifierLoc()) {
8370     QualifierLoc
8371       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8372     if (!QualifierLoc)
8373       return StmtError();
8374   }
8375 
8376   // Transform the declaration name.
8377   DeclarationNameInfo NameInfo = S->getNameInfo();
8378   if (NameInfo.getName()) {
8379     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8380     if (!NameInfo.getName())
8381       return StmtError();
8382   }
8383 
8384   // Check whether anything changed.
8385   if (!getDerived().AlwaysRebuild() &&
8386       QualifierLoc == S->getQualifierLoc() &&
8387       NameInfo.getName() == S->getNameInfo().getName())
8388     return S;
8389 
8390   // Determine whether this name exists, if we can.
8391   CXXScopeSpec SS;
8392   SS.Adopt(QualifierLoc);
8393   bool Dependent = false;
8394   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8395   case Sema::IER_Exists:
8396     if (S->isIfExists())
8397       break;
8398 
8399     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8400 
8401   case Sema::IER_DoesNotExist:
8402     if (S->isIfNotExists())
8403       break;
8404 
8405     return new (getSema().Context) NullStmt(S->getKeywordLoc());
8406 
8407   case Sema::IER_Dependent:
8408     Dependent = true;
8409     break;
8410 
8411   case Sema::IER_Error:
8412     return StmtError();
8413   }
8414 
8415   // We need to continue with the instantiation, so do so now.
8416   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8417   if (SubStmt.isInvalid())
8418     return StmtError();
8419 
8420   // If we have resolved the name, just transform to the substatement.
8421   if (!Dependent)
8422     return SubStmt;
8423 
8424   // The name is still dependent, so build a dependent expression again.
8425   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8426                                                    S->isIfExists(),
8427                                                    QualifierLoc,
8428                                                    NameInfo,
8429                                                    SubStmt.get());
8430 }
8431 
8432 template<typename Derived>
8433 ExprResult
8434 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8435   NestedNameSpecifierLoc QualifierLoc;
8436   if (E->getQualifierLoc()) {
8437     QualifierLoc
8438     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8439     if (!QualifierLoc)
8440       return ExprError();
8441   }
8442 
8443   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8444     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8445   if (!PD)
8446     return ExprError();
8447 
8448   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8449   if (Base.isInvalid())
8450     return ExprError();
8451 
8452   return new (SemaRef.getASTContext())
8453       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8454                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8455                         QualifierLoc, E->getMemberLoc());
8456 }
8457 
8458 template <typename Derived>
8459 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8460     MSPropertySubscriptExpr *E) {
8461   auto BaseRes = getDerived().TransformExpr(E->getBase());
8462   if (BaseRes.isInvalid())
8463     return ExprError();
8464   auto IdxRes = getDerived().TransformExpr(E->getIdx());
8465   if (IdxRes.isInvalid())
8466     return ExprError();
8467 
8468   if (!getDerived().AlwaysRebuild() &&
8469       BaseRes.get() == E->getBase() &&
8470       IdxRes.get() == E->getIdx())
8471     return E;
8472 
8473   return getDerived().RebuildArraySubscriptExpr(
8474       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8475 }
8476 
8477 template <typename Derived>
8478 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8479   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8480   if (TryBlock.isInvalid())
8481     return StmtError();
8482 
8483   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8484   if (Handler.isInvalid())
8485     return StmtError();
8486 
8487   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8488       Handler.get() == S->getHandler())
8489     return S;
8490 
8491   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8492                                         TryBlock.get(), Handler.get());
8493 }
8494 
8495 template <typename Derived>
8496 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8497   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8498   if (Block.isInvalid())
8499     return StmtError();
8500 
8501   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8502 }
8503 
8504 template <typename Derived>
8505 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8506   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8507   if (FilterExpr.isInvalid())
8508     return StmtError();
8509 
8510   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8511   if (Block.isInvalid())
8512     return StmtError();
8513 
8514   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8515                                            Block.get());
8516 }
8517 
8518 template <typename Derived>
8519 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8520   if (isa<SEHFinallyStmt>(Handler))
8521     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8522   else
8523     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8524 }
8525 
8526 template<typename Derived>
8527 StmtResult
8528 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8529   return S;
8530 }
8531 
8532 //===----------------------------------------------------------------------===//
8533 // OpenMP directive transformation
8534 //===----------------------------------------------------------------------===//
8535 
8536 template <typename Derived>
8537 StmtResult
8538 TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8539   // OMPCanonicalLoops are eliminated during transformation, since they will be
8540   // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8541   // after transformation.
8542   return getDerived().TransformStmt(L->getLoopStmt());
8543 }
8544 
8545 template <typename Derived>
8546 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8547     OMPExecutableDirective *D) {
8548 
8549   // Transform the clauses
8550   llvm::SmallVector<OMPClause *, 16> TClauses;
8551   ArrayRef<OMPClause *> Clauses = D->clauses();
8552   TClauses.reserve(Clauses.size());
8553   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8554        I != E; ++I) {
8555     if (*I) {
8556       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8557       OMPClause *Clause = getDerived().TransformOMPClause(*I);
8558       getDerived().getSema().EndOpenMPClause();
8559       if (Clause)
8560         TClauses.push_back(Clause);
8561     } else {
8562       TClauses.push_back(nullptr);
8563     }
8564   }
8565   StmtResult AssociatedStmt;
8566   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8567     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8568                                                   /*CurScope=*/nullptr);
8569     StmtResult Body;
8570     {
8571       Sema::CompoundScopeRAII CompoundScope(getSema());
8572       Stmt *CS;
8573       if (D->getDirectiveKind() == OMPD_atomic ||
8574           D->getDirectiveKind() == OMPD_critical ||
8575           D->getDirectiveKind() == OMPD_section ||
8576           D->getDirectiveKind() == OMPD_master)
8577         CS = D->getAssociatedStmt();
8578       else
8579         CS = D->getRawStmt();
8580       Body = getDerived().TransformStmt(CS);
8581       if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8582           getSema().getLangOpts().OpenMPIRBuilder)
8583         Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8584     }
8585     AssociatedStmt =
8586         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8587     if (AssociatedStmt.isInvalid()) {
8588       return StmtError();
8589     }
8590   }
8591   if (TClauses.size() != Clauses.size()) {
8592     return StmtError();
8593   }
8594 
8595   // Transform directive name for 'omp critical' directive.
8596   DeclarationNameInfo DirName;
8597   if (D->getDirectiveKind() == OMPD_critical) {
8598     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8599     DirName = getDerived().TransformDeclarationNameInfo(DirName);
8600   }
8601   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8602   if (D->getDirectiveKind() == OMPD_cancellation_point) {
8603     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8604   } else if (D->getDirectiveKind() == OMPD_cancel) {
8605     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8606   }
8607 
8608   return getDerived().RebuildOMPExecutableDirective(
8609       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8610       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8611 }
8612 
8613 template <typename Derived>
8614 StmtResult
8615 TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
8616   // TODO: Fix This
8617   SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
8618       << getOpenMPDirectiveName(D->getDirectiveKind());
8619   return StmtError();
8620 }
8621 
8622 template <typename Derived>
8623 StmtResult
8624 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8625   DeclarationNameInfo DirName;
8626   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8627                                              D->getBeginLoc());
8628   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8629   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8630   return Res;
8631 }
8632 
8633 template <typename Derived>
8634 StmtResult
8635 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8636   DeclarationNameInfo DirName;
8637   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8638                                              D->getBeginLoc());
8639   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8640   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8641   return Res;
8642 }
8643 
8644 template <typename Derived>
8645 StmtResult
8646 TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8647   DeclarationNameInfo DirName;
8648   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8649                                              nullptr, D->getBeginLoc());
8650   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8651   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8652   return Res;
8653 }
8654 
8655 template <typename Derived>
8656 StmtResult
8657 TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8658   DeclarationNameInfo DirName;
8659   getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8660                                              nullptr, D->getBeginLoc());
8661   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8662   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8663   return Res;
8664 }
8665 
8666 template <typename Derived>
8667 StmtResult
8668 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8669   DeclarationNameInfo DirName;
8670   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8671                                              D->getBeginLoc());
8672   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8673   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8674   return Res;
8675 }
8676 
8677 template <typename Derived>
8678 StmtResult
8679 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8680   DeclarationNameInfo DirName;
8681   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8682                                              D->getBeginLoc());
8683   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8684   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8685   return Res;
8686 }
8687 
8688 template <typename Derived>
8689 StmtResult
8690 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8691   DeclarationNameInfo DirName;
8692   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8693                                              D->getBeginLoc());
8694   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8695   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8696   return Res;
8697 }
8698 
8699 template <typename Derived>
8700 StmtResult
8701 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8702   DeclarationNameInfo DirName;
8703   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8704                                              D->getBeginLoc());
8705   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8706   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8707   return Res;
8708 }
8709 
8710 template <typename Derived>
8711 StmtResult
8712 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8713   DeclarationNameInfo DirName;
8714   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8715                                              D->getBeginLoc());
8716   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8717   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8718   return Res;
8719 }
8720 
8721 template <typename Derived>
8722 StmtResult
8723 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8724   DeclarationNameInfo DirName;
8725   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8726                                              D->getBeginLoc());
8727   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8728   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8729   return Res;
8730 }
8731 
8732 template <typename Derived>
8733 StmtResult
8734 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8735   getDerived().getSema().StartOpenMPDSABlock(
8736       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8737   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8738   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8739   return Res;
8740 }
8741 
8742 template <typename Derived>
8743 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8744     OMPParallelForDirective *D) {
8745   DeclarationNameInfo DirName;
8746   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8747                                              nullptr, D->getBeginLoc());
8748   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8749   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8750   return Res;
8751 }
8752 
8753 template <typename Derived>
8754 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8755     OMPParallelForSimdDirective *D) {
8756   DeclarationNameInfo DirName;
8757   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8758                                              nullptr, D->getBeginLoc());
8759   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8760   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8761   return Res;
8762 }
8763 
8764 template <typename Derived>
8765 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8766     OMPParallelMasterDirective *D) {
8767   DeclarationNameInfo DirName;
8768   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8769                                              nullptr, D->getBeginLoc());
8770   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8771   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8772   return Res;
8773 }
8774 
8775 template <typename Derived>
8776 StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedDirective(
8777     OMPParallelMaskedDirective *D) {
8778   DeclarationNameInfo DirName;
8779   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_masked, DirName,
8780                                              nullptr, D->getBeginLoc());
8781   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8782   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8783   return Res;
8784 }
8785 
8786 template <typename Derived>
8787 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8788     OMPParallelSectionsDirective *D) {
8789   DeclarationNameInfo DirName;
8790   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8791                                              nullptr, D->getBeginLoc());
8792   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8793   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8794   return Res;
8795 }
8796 
8797 template <typename Derived>
8798 StmtResult
8799 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8800   DeclarationNameInfo DirName;
8801   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8802                                              D->getBeginLoc());
8803   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8804   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8805   return Res;
8806 }
8807 
8808 template <typename Derived>
8809 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8810     OMPTaskyieldDirective *D) {
8811   DeclarationNameInfo DirName;
8812   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8813                                              D->getBeginLoc());
8814   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8815   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8816   return Res;
8817 }
8818 
8819 template <typename Derived>
8820 StmtResult
8821 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8822   DeclarationNameInfo DirName;
8823   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8824                                              D->getBeginLoc());
8825   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8826   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8827   return Res;
8828 }
8829 
8830 template <typename Derived>
8831 StmtResult
8832 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
8833   DeclarationNameInfo DirName;
8834   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
8835                                              D->getBeginLoc());
8836   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8837   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8838   return Res;
8839 }
8840 
8841 template <typename Derived>
8842 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
8843     OMPTaskgroupDirective *D) {
8844   DeclarationNameInfo DirName;
8845   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
8846                                              D->getBeginLoc());
8847   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8848   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8849   return Res;
8850 }
8851 
8852 template <typename Derived>
8853 StmtResult
8854 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
8855   DeclarationNameInfo DirName;
8856   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
8857                                              D->getBeginLoc());
8858   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8859   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8860   return Res;
8861 }
8862 
8863 template <typename Derived>
8864 StmtResult
8865 TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
8866   DeclarationNameInfo DirName;
8867   getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
8868                                              D->getBeginLoc());
8869   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8870   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8871   return Res;
8872 }
8873 
8874 template <typename Derived>
8875 StmtResult
8876 TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
8877   DeclarationNameInfo DirName;
8878   getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
8879                                              D->getBeginLoc());
8880   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8881   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8882   return Res;
8883 }
8884 
8885 template <typename Derived>
8886 StmtResult
8887 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
8888   DeclarationNameInfo DirName;
8889   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
8890                                              D->getBeginLoc());
8891   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8892   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8893   return Res;
8894 }
8895 
8896 template <typename Derived>
8897 StmtResult
8898 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
8899   DeclarationNameInfo DirName;
8900   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
8901                                              D->getBeginLoc());
8902   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8903   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8904   return Res;
8905 }
8906 
8907 template <typename Derived>
8908 StmtResult
8909 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
8910   DeclarationNameInfo DirName;
8911   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
8912                                              D->getBeginLoc());
8913   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8914   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8915   return Res;
8916 }
8917 
8918 template <typename Derived>
8919 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
8920     OMPTargetDataDirective *D) {
8921   DeclarationNameInfo DirName;
8922   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
8923                                              D->getBeginLoc());
8924   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8925   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8926   return Res;
8927 }
8928 
8929 template <typename Derived>
8930 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8931     OMPTargetEnterDataDirective *D) {
8932   DeclarationNameInfo DirName;
8933   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8934                                              nullptr, D->getBeginLoc());
8935   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8936   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8937   return Res;
8938 }
8939 
8940 template <typename Derived>
8941 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8942     OMPTargetExitDataDirective *D) {
8943   DeclarationNameInfo DirName;
8944   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8945                                              nullptr, D->getBeginLoc());
8946   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8947   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8948   return Res;
8949 }
8950 
8951 template <typename Derived>
8952 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8953     OMPTargetParallelDirective *D) {
8954   DeclarationNameInfo DirName;
8955   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8956                                              nullptr, D->getBeginLoc());
8957   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8958   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8959   return Res;
8960 }
8961 
8962 template <typename Derived>
8963 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8964     OMPTargetParallelForDirective *D) {
8965   DeclarationNameInfo DirName;
8966   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8967                                              nullptr, D->getBeginLoc());
8968   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8969   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8970   return Res;
8971 }
8972 
8973 template <typename Derived>
8974 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8975     OMPTargetUpdateDirective *D) {
8976   DeclarationNameInfo DirName;
8977   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8978                                              nullptr, D->getBeginLoc());
8979   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8980   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8981   return Res;
8982 }
8983 
8984 template <typename Derived>
8985 StmtResult
8986 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8987   DeclarationNameInfo DirName;
8988   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8989                                              D->getBeginLoc());
8990   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8991   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8992   return Res;
8993 }
8994 
8995 template <typename Derived>
8996 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8997     OMPCancellationPointDirective *D) {
8998   DeclarationNameInfo DirName;
8999   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
9000                                              nullptr, D->getBeginLoc());
9001   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9002   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9003   return Res;
9004 }
9005 
9006 template <typename Derived>
9007 StmtResult
9008 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
9009   DeclarationNameInfo DirName;
9010   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
9011                                              D->getBeginLoc());
9012   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9013   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9014   return Res;
9015 }
9016 
9017 template <typename Derived>
9018 StmtResult
9019 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
9020   DeclarationNameInfo DirName;
9021   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
9022                                              D->getBeginLoc());
9023   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9024   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9025   return Res;
9026 }
9027 
9028 template <typename Derived>
9029 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
9030     OMPTaskLoopSimdDirective *D) {
9031   DeclarationNameInfo DirName;
9032   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
9033                                              nullptr, D->getBeginLoc());
9034   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9035   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9036   return Res;
9037 }
9038 
9039 template <typename Derived>
9040 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
9041     OMPMasterTaskLoopDirective *D) {
9042   DeclarationNameInfo DirName;
9043   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
9044                                              nullptr, D->getBeginLoc());
9045   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9046   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9047   return Res;
9048 }
9049 
9050 template <typename Derived>
9051 StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopDirective(
9052     OMPMaskedTaskLoopDirective *D) {
9053   DeclarationNameInfo DirName;
9054   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop, DirName,
9055                                              nullptr, D->getBeginLoc());
9056   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9057   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9058   return Res;
9059 }
9060 
9061 template <typename Derived>
9062 StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
9063     OMPMasterTaskLoopSimdDirective *D) {
9064   DeclarationNameInfo DirName;
9065   getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
9066                                              nullptr, D->getBeginLoc());
9067   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9068   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9069   return Res;
9070 }
9071 
9072 template <typename Derived>
9073 StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopSimdDirective(
9074     OMPMaskedTaskLoopSimdDirective *D) {
9075   DeclarationNameInfo DirName;
9076   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop_simd, DirName,
9077                                              nullptr, D->getBeginLoc());
9078   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9079   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9080   return Res;
9081 }
9082 
9083 template <typename Derived>
9084 StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
9085     OMPParallelMasterTaskLoopDirective *D) {
9086   DeclarationNameInfo DirName;
9087   getDerived().getSema().StartOpenMPDSABlock(
9088       OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
9089   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9090   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9091   return Res;
9092 }
9093 
9094 template <typename Derived>
9095 StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopDirective(
9096     OMPParallelMaskedTaskLoopDirective *D) {
9097   DeclarationNameInfo DirName;
9098   getDerived().getSema().StartOpenMPDSABlock(
9099       OMPD_parallel_masked_taskloop, DirName, nullptr, D->getBeginLoc());
9100   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9101   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9102   return Res;
9103 }
9104 
9105 template <typename Derived>
9106 StmtResult
9107 TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
9108     OMPParallelMasterTaskLoopSimdDirective *D) {
9109   DeclarationNameInfo DirName;
9110   getDerived().getSema().StartOpenMPDSABlock(
9111       OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9112   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9113   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9114   return Res;
9115 }
9116 
9117 template <typename Derived>
9118 StmtResult
9119 TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopSimdDirective(
9120     OMPParallelMaskedTaskLoopSimdDirective *D) {
9121   DeclarationNameInfo DirName;
9122   getDerived().getSema().StartOpenMPDSABlock(
9123       OMPD_parallel_masked_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9124   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9125   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9126   return Res;
9127 }
9128 
9129 template <typename Derived>
9130 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
9131     OMPDistributeDirective *D) {
9132   DeclarationNameInfo DirName;
9133   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
9134                                              D->getBeginLoc());
9135   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9136   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9137   return Res;
9138 }
9139 
9140 template <typename Derived>
9141 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
9142     OMPDistributeParallelForDirective *D) {
9143   DeclarationNameInfo DirName;
9144   getDerived().getSema().StartOpenMPDSABlock(
9145       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9146   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9147   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9148   return Res;
9149 }
9150 
9151 template <typename Derived>
9152 StmtResult
9153 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
9154     OMPDistributeParallelForSimdDirective *D) {
9155   DeclarationNameInfo DirName;
9156   getDerived().getSema().StartOpenMPDSABlock(
9157       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9158   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9159   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9160   return Res;
9161 }
9162 
9163 template <typename Derived>
9164 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
9165     OMPDistributeSimdDirective *D) {
9166   DeclarationNameInfo DirName;
9167   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
9168                                              nullptr, D->getBeginLoc());
9169   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9170   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9171   return Res;
9172 }
9173 
9174 template <typename Derived>
9175 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9176     OMPTargetParallelForSimdDirective *D) {
9177   DeclarationNameInfo DirName;
9178   getDerived().getSema().StartOpenMPDSABlock(
9179       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9180   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9181   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9182   return Res;
9183 }
9184 
9185 template <typename Derived>
9186 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9187     OMPTargetSimdDirective *D) {
9188   DeclarationNameInfo DirName;
9189   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9190                                              D->getBeginLoc());
9191   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9192   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9193   return Res;
9194 }
9195 
9196 template <typename Derived>
9197 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9198     OMPTeamsDistributeDirective *D) {
9199   DeclarationNameInfo DirName;
9200   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9201                                              nullptr, D->getBeginLoc());
9202   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9203   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9204   return Res;
9205 }
9206 
9207 template <typename Derived>
9208 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9209     OMPTeamsDistributeSimdDirective *D) {
9210   DeclarationNameInfo DirName;
9211   getDerived().getSema().StartOpenMPDSABlock(
9212       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9213   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9214   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9215   return Res;
9216 }
9217 
9218 template <typename Derived>
9219 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9220     OMPTeamsDistributeParallelForSimdDirective *D) {
9221   DeclarationNameInfo DirName;
9222   getDerived().getSema().StartOpenMPDSABlock(
9223       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9224       D->getBeginLoc());
9225   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9226   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9227   return Res;
9228 }
9229 
9230 template <typename Derived>
9231 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9232     OMPTeamsDistributeParallelForDirective *D) {
9233   DeclarationNameInfo DirName;
9234   getDerived().getSema().StartOpenMPDSABlock(
9235       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9236   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9237   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9238   return Res;
9239 }
9240 
9241 template <typename Derived>
9242 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9243     OMPTargetTeamsDirective *D) {
9244   DeclarationNameInfo DirName;
9245   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9246                                              nullptr, D->getBeginLoc());
9247   auto Res = getDerived().TransformOMPExecutableDirective(D);
9248   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9249   return Res;
9250 }
9251 
9252 template <typename Derived>
9253 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9254     OMPTargetTeamsDistributeDirective *D) {
9255   DeclarationNameInfo DirName;
9256   getDerived().getSema().StartOpenMPDSABlock(
9257       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9258   auto Res = getDerived().TransformOMPExecutableDirective(D);
9259   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9260   return Res;
9261 }
9262 
9263 template <typename Derived>
9264 StmtResult
9265 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9266     OMPTargetTeamsDistributeParallelForDirective *D) {
9267   DeclarationNameInfo DirName;
9268   getDerived().getSema().StartOpenMPDSABlock(
9269       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9270       D->getBeginLoc());
9271   auto Res = getDerived().TransformOMPExecutableDirective(D);
9272   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9273   return Res;
9274 }
9275 
9276 template <typename Derived>
9277 StmtResult TreeTransform<Derived>::
9278     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9279         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9280   DeclarationNameInfo DirName;
9281   getDerived().getSema().StartOpenMPDSABlock(
9282       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9283       D->getBeginLoc());
9284   auto Res = getDerived().TransformOMPExecutableDirective(D);
9285   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9286   return Res;
9287 }
9288 
9289 template <typename Derived>
9290 StmtResult
9291 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9292     OMPTargetTeamsDistributeSimdDirective *D) {
9293   DeclarationNameInfo DirName;
9294   getDerived().getSema().StartOpenMPDSABlock(
9295       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9296   auto Res = getDerived().TransformOMPExecutableDirective(D);
9297   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9298   return Res;
9299 }
9300 
9301 template <typename Derived>
9302 StmtResult
9303 TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9304   DeclarationNameInfo DirName;
9305   getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9306                                              D->getBeginLoc());
9307   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9308   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9309   return Res;
9310 }
9311 
9312 template <typename Derived>
9313 StmtResult
9314 TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9315   DeclarationNameInfo DirName;
9316   getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9317                                              D->getBeginLoc());
9318   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9319   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9320   return Res;
9321 }
9322 
9323 template <typename Derived>
9324 StmtResult
9325 TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9326   DeclarationNameInfo DirName;
9327   getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9328                                              D->getBeginLoc());
9329   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9330   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9331   return Res;
9332 }
9333 
9334 template <typename Derived>
9335 StmtResult TreeTransform<Derived>::TransformOMPGenericLoopDirective(
9336     OMPGenericLoopDirective *D) {
9337   DeclarationNameInfo DirName;
9338   getDerived().getSema().StartOpenMPDSABlock(OMPD_loop, DirName, nullptr,
9339                                              D->getBeginLoc());
9340   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9341   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9342   return Res;
9343 }
9344 
9345 template <typename Derived>
9346 StmtResult TreeTransform<Derived>::TransformOMPTeamsGenericLoopDirective(
9347     OMPTeamsGenericLoopDirective *D) {
9348   DeclarationNameInfo DirName;
9349   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_loop, DirName, nullptr,
9350                                              D->getBeginLoc());
9351   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9352   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9353   return Res;
9354 }
9355 
9356 template <typename Derived>
9357 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsGenericLoopDirective(
9358     OMPTargetTeamsGenericLoopDirective *D) {
9359   DeclarationNameInfo DirName;
9360   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_loop, DirName,
9361                                              nullptr, D->getBeginLoc());
9362   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9363   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9364   return Res;
9365 }
9366 
9367 template <typename Derived>
9368 StmtResult TreeTransform<Derived>::TransformOMPParallelGenericLoopDirective(
9369     OMPParallelGenericLoopDirective *D) {
9370   DeclarationNameInfo DirName;
9371   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_loop, DirName,
9372                                              nullptr, D->getBeginLoc());
9373   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9374   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9375   return Res;
9376 }
9377 
9378 template <typename Derived>
9379 StmtResult
9380 TreeTransform<Derived>::TransformOMPTargetParallelGenericLoopDirective(
9381     OMPTargetParallelGenericLoopDirective *D) {
9382   DeclarationNameInfo DirName;
9383   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_loop, DirName,
9384                                              nullptr, D->getBeginLoc());
9385   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9386   getDerived().getSema().EndOpenMPDSABlock(Res.get());
9387   return Res;
9388 }
9389 
9390 //===----------------------------------------------------------------------===//
9391 // OpenMP clause transformation
9392 //===----------------------------------------------------------------------===//
9393 template <typename Derived>
9394 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9395   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9396   if (Cond.isInvalid())
9397     return nullptr;
9398   return getDerived().RebuildOMPIfClause(
9399       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9400       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9401 }
9402 
9403 template <typename Derived>
9404 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9405   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9406   if (Cond.isInvalid())
9407     return nullptr;
9408   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9409                                             C->getLParenLoc(), C->getEndLoc());
9410 }
9411 
9412 template <typename Derived>
9413 OMPClause *
9414 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9415   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9416   if (NumThreads.isInvalid())
9417     return nullptr;
9418   return getDerived().RebuildOMPNumThreadsClause(
9419       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9420 }
9421 
9422 template <typename Derived>
9423 OMPClause *
9424 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9425   ExprResult E = getDerived().TransformExpr(C->getSafelen());
9426   if (E.isInvalid())
9427     return nullptr;
9428   return getDerived().RebuildOMPSafelenClause(
9429       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9430 }
9431 
9432 template <typename Derived>
9433 OMPClause *
9434 TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9435   ExprResult E = getDerived().TransformExpr(C->getAllocator());
9436   if (E.isInvalid())
9437     return nullptr;
9438   return getDerived().RebuildOMPAllocatorClause(
9439       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9440 }
9441 
9442 template <typename Derived>
9443 OMPClause *
9444 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9445   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9446   if (E.isInvalid())
9447     return nullptr;
9448   return getDerived().RebuildOMPSimdlenClause(
9449       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9450 }
9451 
9452 template <typename Derived>
9453 OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9454   SmallVector<Expr *, 4> TransformedSizes;
9455   TransformedSizes.reserve(C->getNumSizes());
9456   bool Changed = false;
9457   for (Expr *E : C->getSizesRefs()) {
9458     if (!E) {
9459       TransformedSizes.push_back(nullptr);
9460       continue;
9461     }
9462 
9463     ExprResult T = getDerived().TransformExpr(E);
9464     if (T.isInvalid())
9465       return nullptr;
9466     if (E != T.get())
9467       Changed = true;
9468     TransformedSizes.push_back(T.get());
9469   }
9470 
9471   if (!Changed && !getDerived().AlwaysRebuild())
9472     return C;
9473   return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9474                                C->getLParenLoc(), C->getEndLoc());
9475 }
9476 
9477 template <typename Derived>
9478 OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9479   if (!getDerived().AlwaysRebuild())
9480     return C;
9481   return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9482 }
9483 
9484 template <typename Derived>
9485 OMPClause *
9486 TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9487   ExprResult T = getDerived().TransformExpr(C->getFactor());
9488   if (T.isInvalid())
9489     return nullptr;
9490   Expr *Factor = T.get();
9491   bool Changed = Factor != C->getFactor();
9492 
9493   if (!Changed && !getDerived().AlwaysRebuild())
9494     return C;
9495   return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9496                                  C->getEndLoc());
9497 }
9498 
9499 template <typename Derived>
9500 OMPClause *
9501 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9502   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9503   if (E.isInvalid())
9504     return nullptr;
9505   return getDerived().RebuildOMPCollapseClause(
9506       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9507 }
9508 
9509 template <typename Derived>
9510 OMPClause *
9511 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9512   return getDerived().RebuildOMPDefaultClause(
9513       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9514       C->getLParenLoc(), C->getEndLoc());
9515 }
9516 
9517 template <typename Derived>
9518 OMPClause *
9519 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9520   return getDerived().RebuildOMPProcBindClause(
9521       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9522       C->getLParenLoc(), C->getEndLoc());
9523 }
9524 
9525 template <typename Derived>
9526 OMPClause *
9527 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9528   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9529   if (E.isInvalid())
9530     return nullptr;
9531   return getDerived().RebuildOMPScheduleClause(
9532       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9533       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9534       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9535       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9536 }
9537 
9538 template <typename Derived>
9539 OMPClause *
9540 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9541   ExprResult E;
9542   if (auto *Num = C->getNumForLoops()) {
9543     E = getDerived().TransformExpr(Num);
9544     if (E.isInvalid())
9545       return nullptr;
9546   }
9547   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9548                                               C->getLParenLoc(), E.get());
9549 }
9550 
9551 template <typename Derived>
9552 OMPClause *
9553 TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9554   ExprResult E;
9555   if (Expr *Evt = C->getEventHandler()) {
9556     E = getDerived().TransformExpr(Evt);
9557     if (E.isInvalid())
9558       return nullptr;
9559   }
9560   return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9561                                              C->getLParenLoc(), C->getEndLoc());
9562 }
9563 
9564 template <typename Derived>
9565 OMPClause *
9566 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9567   // No need to rebuild this clause, no template-dependent parameters.
9568   return C;
9569 }
9570 
9571 template <typename Derived>
9572 OMPClause *
9573 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9574   // No need to rebuild this clause, no template-dependent parameters.
9575   return C;
9576 }
9577 
9578 template <typename Derived>
9579 OMPClause *
9580 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9581   // No need to rebuild this clause, no template-dependent parameters.
9582   return C;
9583 }
9584 
9585 template <typename Derived>
9586 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9587   // No need to rebuild this clause, no template-dependent parameters.
9588   return C;
9589 }
9590 
9591 template <typename Derived>
9592 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9593   // No need to rebuild this clause, no template-dependent parameters.
9594   return C;
9595 }
9596 
9597 template <typename Derived>
9598 OMPClause *
9599 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9600   // No need to rebuild this clause, no template-dependent parameters.
9601   return C;
9602 }
9603 
9604 template <typename Derived>
9605 OMPClause *
9606 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9607   // No need to rebuild this clause, no template-dependent parameters.
9608   return C;
9609 }
9610 
9611 template <typename Derived>
9612 OMPClause *
9613 TreeTransform<Derived>::TransformOMPCompareClause(OMPCompareClause *C) {
9614   // No need to rebuild this clause, no template-dependent parameters.
9615   return C;
9616 }
9617 
9618 template <typename Derived>
9619 OMPClause *
9620 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9621   // No need to rebuild this clause, no template-dependent parameters.
9622   return C;
9623 }
9624 
9625 template <typename Derived>
9626 OMPClause *
9627 TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9628   // No need to rebuild this clause, no template-dependent parameters.
9629   return C;
9630 }
9631 
9632 template <typename Derived>
9633 OMPClause *
9634 TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9635   // No need to rebuild this clause, no template-dependent parameters.
9636   return C;
9637 }
9638 
9639 template <typename Derived>
9640 OMPClause *
9641 TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9642   // No need to rebuild this clause, no template-dependent parameters.
9643   return C;
9644 }
9645 
9646 template <typename Derived>
9647 OMPClause *
9648 TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9649   // No need to rebuild this clause, no template-dependent parameters.
9650   return C;
9651 }
9652 
9653 template <typename Derived>
9654 OMPClause *
9655 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9656   // No need to rebuild this clause, no template-dependent parameters.
9657   return C;
9658 }
9659 
9660 template <typename Derived>
9661 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9662   // No need to rebuild this clause, no template-dependent parameters.
9663   return C;
9664 }
9665 
9666 template <typename Derived>
9667 OMPClause *
9668 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9669   // No need to rebuild this clause, no template-dependent parameters.
9670   return C;
9671 }
9672 
9673 template <typename Derived>
9674 OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9675   ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9676   if (IVR.isInvalid())
9677     return nullptr;
9678 
9679   llvm::SmallVector<Expr *, 8> PrefExprs;
9680   PrefExprs.reserve(C->varlist_size() - 1);
9681   for (Expr *E : llvm::drop_begin(C->varlists())) {
9682     ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9683     if (ER.isInvalid())
9684       return nullptr;
9685     PrefExprs.push_back(ER.get());
9686   }
9687   return getDerived().RebuildOMPInitClause(
9688       IVR.get(), PrefExprs, C->getIsTarget(), C->getIsTargetSync(),
9689       C->getBeginLoc(), C->getLParenLoc(), C->getVarLoc(), C->getEndLoc());
9690 }
9691 
9692 template <typename Derived>
9693 OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9694   ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9695   if (ER.isInvalid())
9696     return nullptr;
9697   return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9698                                           C->getLParenLoc(), C->getVarLoc(),
9699                                           C->getEndLoc());
9700 }
9701 
9702 template <typename Derived>
9703 OMPClause *
9704 TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9705   ExprResult ER;
9706   if (Expr *IV = C->getInteropVar()) {
9707     ER = getDerived().TransformExpr(IV);
9708     if (ER.isInvalid())
9709       return nullptr;
9710   }
9711   return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9712                                               C->getLParenLoc(), C->getVarLoc(),
9713                                               C->getEndLoc());
9714 }
9715 
9716 template <typename Derived>
9717 OMPClause *
9718 TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9719   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9720   if (Cond.isInvalid())
9721     return nullptr;
9722   return getDerived().RebuildOMPNovariantsClause(
9723       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9724 }
9725 
9726 template <typename Derived>
9727 OMPClause *
9728 TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
9729   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9730   if (Cond.isInvalid())
9731     return nullptr;
9732   return getDerived().RebuildOMPNocontextClause(
9733       Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9734 }
9735 
9736 template <typename Derived>
9737 OMPClause *
9738 TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
9739   ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
9740   if (ThreadID.isInvalid())
9741     return nullptr;
9742   return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
9743                                              C->getLParenLoc(), C->getEndLoc());
9744 }
9745 
9746 template <typename Derived>
9747 OMPClause *TreeTransform<Derived>::TransformOMPAlignClause(OMPAlignClause *C) {
9748   ExprResult E = getDerived().TransformExpr(C->getAlignment());
9749   if (E.isInvalid())
9750     return nullptr;
9751   return getDerived().RebuildOMPAlignClause(E.get(), C->getBeginLoc(),
9752                                             C->getLParenLoc(), C->getEndLoc());
9753 }
9754 
9755 template <typename Derived>
9756 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9757     OMPUnifiedAddressClause *C) {
9758   llvm_unreachable("unified_address clause cannot appear in dependent context");
9759 }
9760 
9761 template <typename Derived>
9762 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9763     OMPUnifiedSharedMemoryClause *C) {
9764   llvm_unreachable(
9765       "unified_shared_memory clause cannot appear in dependent context");
9766 }
9767 
9768 template <typename Derived>
9769 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9770     OMPReverseOffloadClause *C) {
9771   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
9772 }
9773 
9774 template <typename Derived>
9775 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9776     OMPDynamicAllocatorsClause *C) {
9777   llvm_unreachable(
9778       "dynamic_allocators clause cannot appear in dependent context");
9779 }
9780 
9781 template <typename Derived>
9782 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9783     OMPAtomicDefaultMemOrderClause *C) {
9784   llvm_unreachable(
9785       "atomic_default_mem_order clause cannot appear in dependent context");
9786 }
9787 
9788 template <typename Derived>
9789 OMPClause *
9790 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
9791   llvm::SmallVector<Expr *, 16> Vars;
9792   Vars.reserve(C->varlist_size());
9793   for (auto *VE : C->varlists()) {
9794     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9795     if (EVar.isInvalid())
9796       return nullptr;
9797     Vars.push_back(EVar.get());
9798   }
9799   return getDerived().RebuildOMPPrivateClause(
9800       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9801 }
9802 
9803 template <typename Derived>
9804 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
9805     OMPFirstprivateClause *C) {
9806   llvm::SmallVector<Expr *, 16> Vars;
9807   Vars.reserve(C->varlist_size());
9808   for (auto *VE : C->varlists()) {
9809     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9810     if (EVar.isInvalid())
9811       return nullptr;
9812     Vars.push_back(EVar.get());
9813   }
9814   return getDerived().RebuildOMPFirstprivateClause(
9815       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9816 }
9817 
9818 template <typename Derived>
9819 OMPClause *
9820 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
9821   llvm::SmallVector<Expr *, 16> Vars;
9822   Vars.reserve(C->varlist_size());
9823   for (auto *VE : C->varlists()) {
9824     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9825     if (EVar.isInvalid())
9826       return nullptr;
9827     Vars.push_back(EVar.get());
9828   }
9829   return getDerived().RebuildOMPLastprivateClause(
9830       Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
9831       C->getLParenLoc(), C->getEndLoc());
9832 }
9833 
9834 template <typename Derived>
9835 OMPClause *
9836 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
9837   llvm::SmallVector<Expr *, 16> Vars;
9838   Vars.reserve(C->varlist_size());
9839   for (auto *VE : C->varlists()) {
9840     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9841     if (EVar.isInvalid())
9842       return nullptr;
9843     Vars.push_back(EVar.get());
9844   }
9845   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
9846                                              C->getLParenLoc(), C->getEndLoc());
9847 }
9848 
9849 template <typename Derived>
9850 OMPClause *
9851 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
9852   llvm::SmallVector<Expr *, 16> Vars;
9853   Vars.reserve(C->varlist_size());
9854   for (auto *VE : C->varlists()) {
9855     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9856     if (EVar.isInvalid())
9857       return nullptr;
9858     Vars.push_back(EVar.get());
9859   }
9860   CXXScopeSpec ReductionIdScopeSpec;
9861   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9862 
9863   DeclarationNameInfo NameInfo = C->getNameInfo();
9864   if (NameInfo.getName()) {
9865     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9866     if (!NameInfo.getName())
9867       return nullptr;
9868   }
9869   // Build a list of all UDR decls with the same names ranged by the Scopes.
9870   // The Scope boundary is a duplication of the previous decl.
9871   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9872   for (auto *E : C->reduction_ops()) {
9873     // Transform all the decls.
9874     if (E) {
9875       auto *ULE = cast<UnresolvedLookupExpr>(E);
9876       UnresolvedSet<8> Decls;
9877       for (auto *D : ULE->decls()) {
9878         NamedDecl *InstD =
9879             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9880         Decls.addDecl(InstD, InstD->getAccess());
9881       }
9882       UnresolvedReductions.push_back(
9883        UnresolvedLookupExpr::Create(
9884           SemaRef.Context, /*NamingClass=*/nullptr,
9885           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
9886           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
9887           Decls.begin(), Decls.end()));
9888     } else
9889       UnresolvedReductions.push_back(nullptr);
9890   }
9891   return getDerived().RebuildOMPReductionClause(
9892       Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
9893       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
9894       ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9895 }
9896 
9897 template <typename Derived>
9898 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
9899     OMPTaskReductionClause *C) {
9900   llvm::SmallVector<Expr *, 16> Vars;
9901   Vars.reserve(C->varlist_size());
9902   for (auto *VE : C->varlists()) {
9903     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9904     if (EVar.isInvalid())
9905       return nullptr;
9906     Vars.push_back(EVar.get());
9907   }
9908   CXXScopeSpec ReductionIdScopeSpec;
9909   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9910 
9911   DeclarationNameInfo NameInfo = C->getNameInfo();
9912   if (NameInfo.getName()) {
9913     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9914     if (!NameInfo.getName())
9915       return nullptr;
9916   }
9917   // Build a list of all UDR decls with the same names ranged by the Scopes.
9918   // The Scope boundary is a duplication of the previous decl.
9919   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9920   for (auto *E : C->reduction_ops()) {
9921     // Transform all the decls.
9922     if (E) {
9923       auto *ULE = cast<UnresolvedLookupExpr>(E);
9924       UnresolvedSet<8> Decls;
9925       for (auto *D : ULE->decls()) {
9926         NamedDecl *InstD =
9927             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9928         Decls.addDecl(InstD, InstD->getAccess());
9929       }
9930       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9931           SemaRef.Context, /*NamingClass=*/nullptr,
9932           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9933           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9934     } else
9935       UnresolvedReductions.push_back(nullptr);
9936   }
9937   return getDerived().RebuildOMPTaskReductionClause(
9938       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9939       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9940 }
9941 
9942 template <typename Derived>
9943 OMPClause *
9944 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
9945   llvm::SmallVector<Expr *, 16> Vars;
9946   Vars.reserve(C->varlist_size());
9947   for (auto *VE : C->varlists()) {
9948     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9949     if (EVar.isInvalid())
9950       return nullptr;
9951     Vars.push_back(EVar.get());
9952   }
9953   CXXScopeSpec ReductionIdScopeSpec;
9954   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
9955 
9956   DeclarationNameInfo NameInfo = C->getNameInfo();
9957   if (NameInfo.getName()) {
9958     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
9959     if (!NameInfo.getName())
9960       return nullptr;
9961   }
9962   // Build a list of all UDR decls with the same names ranged by the Scopes.
9963   // The Scope boundary is a duplication of the previous decl.
9964   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
9965   for (auto *E : C->reduction_ops()) {
9966     // Transform all the decls.
9967     if (E) {
9968       auto *ULE = cast<UnresolvedLookupExpr>(E);
9969       UnresolvedSet<8> Decls;
9970       for (auto *D : ULE->decls()) {
9971         NamedDecl *InstD =
9972             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
9973         Decls.addDecl(InstD, InstD->getAccess());
9974       }
9975       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
9976           SemaRef.Context, /*NamingClass=*/nullptr,
9977           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
9978           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
9979     } else
9980       UnresolvedReductions.push_back(nullptr);
9981   }
9982   return getDerived().RebuildOMPInReductionClause(
9983       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
9984       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
9985 }
9986 
9987 template <typename Derived>
9988 OMPClause *
9989 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
9990   llvm::SmallVector<Expr *, 16> Vars;
9991   Vars.reserve(C->varlist_size());
9992   for (auto *VE : C->varlists()) {
9993     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
9994     if (EVar.isInvalid())
9995       return nullptr;
9996     Vars.push_back(EVar.get());
9997   }
9998   ExprResult Step = getDerived().TransformExpr(C->getStep());
9999   if (Step.isInvalid())
10000     return nullptr;
10001   return getDerived().RebuildOMPLinearClause(
10002       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
10003       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
10004 }
10005 
10006 template <typename Derived>
10007 OMPClause *
10008 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
10009   llvm::SmallVector<Expr *, 16> Vars;
10010   Vars.reserve(C->varlist_size());
10011   for (auto *VE : C->varlists()) {
10012     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10013     if (EVar.isInvalid())
10014       return nullptr;
10015     Vars.push_back(EVar.get());
10016   }
10017   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
10018   if (Alignment.isInvalid())
10019     return nullptr;
10020   return getDerived().RebuildOMPAlignedClause(
10021       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
10022       C->getColonLoc(), C->getEndLoc());
10023 }
10024 
10025 template <typename Derived>
10026 OMPClause *
10027 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
10028   llvm::SmallVector<Expr *, 16> Vars;
10029   Vars.reserve(C->varlist_size());
10030   for (auto *VE : C->varlists()) {
10031     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10032     if (EVar.isInvalid())
10033       return nullptr;
10034     Vars.push_back(EVar.get());
10035   }
10036   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
10037                                              C->getLParenLoc(), C->getEndLoc());
10038 }
10039 
10040 template <typename Derived>
10041 OMPClause *
10042 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
10043   llvm::SmallVector<Expr *, 16> Vars;
10044   Vars.reserve(C->varlist_size());
10045   for (auto *VE : C->varlists()) {
10046     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10047     if (EVar.isInvalid())
10048       return nullptr;
10049     Vars.push_back(EVar.get());
10050   }
10051   return getDerived().RebuildOMPCopyprivateClause(
10052       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10053 }
10054 
10055 template <typename Derived>
10056 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
10057   llvm::SmallVector<Expr *, 16> Vars;
10058   Vars.reserve(C->varlist_size());
10059   for (auto *VE : C->varlists()) {
10060     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10061     if (EVar.isInvalid())
10062       return nullptr;
10063     Vars.push_back(EVar.get());
10064   }
10065   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
10066                                             C->getLParenLoc(), C->getEndLoc());
10067 }
10068 
10069 template <typename Derived>
10070 OMPClause *
10071 TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
10072   ExprResult E = getDerived().TransformExpr(C->getDepobj());
10073   if (E.isInvalid())
10074     return nullptr;
10075   return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
10076                                              C->getLParenLoc(), C->getEndLoc());
10077 }
10078 
10079 template <typename Derived>
10080 OMPClause *
10081 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
10082   llvm::SmallVector<Expr *, 16> Vars;
10083   Expr *DepModifier = C->getModifier();
10084   if (DepModifier) {
10085     ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
10086     if (DepModRes.isInvalid())
10087       return nullptr;
10088     DepModifier = DepModRes.get();
10089   }
10090   Vars.reserve(C->varlist_size());
10091   for (auto *VE : C->varlists()) {
10092     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10093     if (EVar.isInvalid())
10094       return nullptr;
10095     Vars.push_back(EVar.get());
10096   }
10097   return getDerived().RebuildOMPDependClause(
10098       {C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(),
10099        C->getOmpAllMemoryLoc()},
10100       DepModifier, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10101 }
10102 
10103 template <typename Derived>
10104 OMPClause *
10105 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
10106   ExprResult E = getDerived().TransformExpr(C->getDevice());
10107   if (E.isInvalid())
10108     return nullptr;
10109   return getDerived().RebuildOMPDeviceClause(
10110       C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10111       C->getModifierLoc(), C->getEndLoc());
10112 }
10113 
10114 template <typename Derived, class T>
10115 bool transformOMPMappableExprListClause(
10116     TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
10117     llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
10118     DeclarationNameInfo &MapperIdInfo,
10119     llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
10120   // Transform expressions in the list.
10121   Vars.reserve(C->varlist_size());
10122   for (auto *VE : C->varlists()) {
10123     ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
10124     if (EVar.isInvalid())
10125       return true;
10126     Vars.push_back(EVar.get());
10127   }
10128   // Transform mapper scope specifier and identifier.
10129   NestedNameSpecifierLoc QualifierLoc;
10130   if (C->getMapperQualifierLoc()) {
10131     QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
10132         C->getMapperQualifierLoc());
10133     if (!QualifierLoc)
10134       return true;
10135   }
10136   MapperIdScopeSpec.Adopt(QualifierLoc);
10137   MapperIdInfo = C->getMapperIdInfo();
10138   if (MapperIdInfo.getName()) {
10139     MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
10140     if (!MapperIdInfo.getName())
10141       return true;
10142   }
10143   // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
10144   // the previous user-defined mapper lookup in dependent environment.
10145   for (auto *E : C->mapperlists()) {
10146     // Transform all the decls.
10147     if (E) {
10148       auto *ULE = cast<UnresolvedLookupExpr>(E);
10149       UnresolvedSet<8> Decls;
10150       for (auto *D : ULE->decls()) {
10151         NamedDecl *InstD =
10152             cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
10153         Decls.addDecl(InstD, InstD->getAccess());
10154       }
10155       UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
10156           TT.getSema().Context, /*NamingClass=*/nullptr,
10157           MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
10158           MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
10159           Decls.end()));
10160     } else {
10161       UnresolvedMappers.push_back(nullptr);
10162     }
10163   }
10164   return false;
10165 }
10166 
10167 template <typename Derived>
10168 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
10169   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10170   llvm::SmallVector<Expr *, 16> Vars;
10171   CXXScopeSpec MapperIdScopeSpec;
10172   DeclarationNameInfo MapperIdInfo;
10173   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10174   if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
10175           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10176     return nullptr;
10177   return getDerived().RebuildOMPMapClause(
10178       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), MapperIdScopeSpec,
10179       MapperIdInfo, C->getMapType(), C->isImplicitMapType(), C->getMapLoc(),
10180       C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10181 }
10182 
10183 template <typename Derived>
10184 OMPClause *
10185 TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
10186   Expr *Allocator = C->getAllocator();
10187   if (Allocator) {
10188     ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
10189     if (AllocatorRes.isInvalid())
10190       return nullptr;
10191     Allocator = AllocatorRes.get();
10192   }
10193   llvm::SmallVector<Expr *, 16> Vars;
10194   Vars.reserve(C->varlist_size());
10195   for (auto *VE : C->varlists()) {
10196     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10197     if (EVar.isInvalid())
10198       return nullptr;
10199     Vars.push_back(EVar.get());
10200   }
10201   return getDerived().RebuildOMPAllocateClause(
10202       Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10203       C->getEndLoc());
10204 }
10205 
10206 template <typename Derived>
10207 OMPClause *
10208 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
10209   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
10210   if (E.isInvalid())
10211     return nullptr;
10212   return getDerived().RebuildOMPNumTeamsClause(
10213       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10214 }
10215 
10216 template <typename Derived>
10217 OMPClause *
10218 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
10219   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
10220   if (E.isInvalid())
10221     return nullptr;
10222   return getDerived().RebuildOMPThreadLimitClause(
10223       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10224 }
10225 
10226 template <typename Derived>
10227 OMPClause *
10228 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
10229   ExprResult E = getDerived().TransformExpr(C->getPriority());
10230   if (E.isInvalid())
10231     return nullptr;
10232   return getDerived().RebuildOMPPriorityClause(
10233       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10234 }
10235 
10236 template <typename Derived>
10237 OMPClause *
10238 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
10239   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
10240   if (E.isInvalid())
10241     return nullptr;
10242   return getDerived().RebuildOMPGrainsizeClause(
10243       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10244 }
10245 
10246 template <typename Derived>
10247 OMPClause *
10248 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10249   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10250   if (E.isInvalid())
10251     return nullptr;
10252   return getDerived().RebuildOMPNumTasksClause(
10253       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10254 }
10255 
10256 template <typename Derived>
10257 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10258   ExprResult E = getDerived().TransformExpr(C->getHint());
10259   if (E.isInvalid())
10260     return nullptr;
10261   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10262                                            C->getLParenLoc(), C->getEndLoc());
10263 }
10264 
10265 template <typename Derived>
10266 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10267     OMPDistScheduleClause *C) {
10268   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10269   if (E.isInvalid())
10270     return nullptr;
10271   return getDerived().RebuildOMPDistScheduleClause(
10272       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10273       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10274 }
10275 
10276 template <typename Derived>
10277 OMPClause *
10278 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10279   // Rebuild Defaultmap Clause since we need to invoke the checking of
10280   // defaultmap(none:variable-category) after template initialization.
10281   return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10282                                                  C->getDefaultmapKind(),
10283                                                  C->getBeginLoc(),
10284                                                  C->getLParenLoc(),
10285                                                  C->getDefaultmapModifierLoc(),
10286                                                  C->getDefaultmapKindLoc(),
10287                                                  C->getEndLoc());
10288 }
10289 
10290 template <typename Derived>
10291 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10292   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10293   llvm::SmallVector<Expr *, 16> Vars;
10294   CXXScopeSpec MapperIdScopeSpec;
10295   DeclarationNameInfo MapperIdInfo;
10296   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10297   if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10298           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10299     return nullptr;
10300   return getDerived().RebuildOMPToClause(
10301       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10302       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10303 }
10304 
10305 template <typename Derived>
10306 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10307   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10308   llvm::SmallVector<Expr *, 16> Vars;
10309   CXXScopeSpec MapperIdScopeSpec;
10310   DeclarationNameInfo MapperIdInfo;
10311   llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10312   if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10313           *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10314     return nullptr;
10315   return getDerived().RebuildOMPFromClause(
10316       C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10317       MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10318 }
10319 
10320 template <typename Derived>
10321 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10322     OMPUseDevicePtrClause *C) {
10323   llvm::SmallVector<Expr *, 16> Vars;
10324   Vars.reserve(C->varlist_size());
10325   for (auto *VE : C->varlists()) {
10326     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10327     if (EVar.isInvalid())
10328       return nullptr;
10329     Vars.push_back(EVar.get());
10330   }
10331   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10332   return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10333 }
10334 
10335 template <typename Derived>
10336 OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10337     OMPUseDeviceAddrClause *C) {
10338   llvm::SmallVector<Expr *, 16> Vars;
10339   Vars.reserve(C->varlist_size());
10340   for (auto *VE : C->varlists()) {
10341     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10342     if (EVar.isInvalid())
10343       return nullptr;
10344     Vars.push_back(EVar.get());
10345   }
10346   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10347   return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10348 }
10349 
10350 template <typename Derived>
10351 OMPClause *
10352 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10353   llvm::SmallVector<Expr *, 16> Vars;
10354   Vars.reserve(C->varlist_size());
10355   for (auto *VE : C->varlists()) {
10356     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10357     if (EVar.isInvalid())
10358       return nullptr;
10359     Vars.push_back(EVar.get());
10360   }
10361   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10362   return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10363 }
10364 
10365 template <typename Derived>
10366 OMPClause *TreeTransform<Derived>::TransformOMPHasDeviceAddrClause(
10367     OMPHasDeviceAddrClause *C) {
10368   llvm::SmallVector<Expr *, 16> Vars;
10369   Vars.reserve(C->varlist_size());
10370   for (auto *VE : C->varlists()) {
10371     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10372     if (EVar.isInvalid())
10373       return nullptr;
10374     Vars.push_back(EVar.get());
10375   }
10376   OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10377   return getDerived().RebuildOMPHasDeviceAddrClause(Vars, Locs);
10378 }
10379 
10380 template <typename Derived>
10381 OMPClause *
10382 TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10383   llvm::SmallVector<Expr *, 16> Vars;
10384   Vars.reserve(C->varlist_size());
10385   for (auto *VE : C->varlists()) {
10386     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10387     if (EVar.isInvalid())
10388       return nullptr;
10389     Vars.push_back(EVar.get());
10390   }
10391   return getDerived().RebuildOMPNontemporalClause(
10392       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10393 }
10394 
10395 template <typename Derived>
10396 OMPClause *
10397 TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10398   llvm::SmallVector<Expr *, 16> Vars;
10399   Vars.reserve(C->varlist_size());
10400   for (auto *VE : C->varlists()) {
10401     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10402     if (EVar.isInvalid())
10403       return nullptr;
10404     Vars.push_back(EVar.get());
10405   }
10406   return getDerived().RebuildOMPInclusiveClause(
10407       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10408 }
10409 
10410 template <typename Derived>
10411 OMPClause *
10412 TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10413   llvm::SmallVector<Expr *, 16> Vars;
10414   Vars.reserve(C->varlist_size());
10415   for (auto *VE : C->varlists()) {
10416     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10417     if (EVar.isInvalid())
10418       return nullptr;
10419     Vars.push_back(EVar.get());
10420   }
10421   return getDerived().RebuildOMPExclusiveClause(
10422       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10423 }
10424 
10425 template <typename Derived>
10426 OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10427     OMPUsesAllocatorsClause *C) {
10428   SmallVector<Sema::UsesAllocatorsData, 16> Data;
10429   Data.reserve(C->getNumberOfAllocators());
10430   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10431     OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10432     ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10433     if (Allocator.isInvalid())
10434       continue;
10435     ExprResult AllocatorTraits;
10436     if (Expr *AT = D.AllocatorTraits) {
10437       AllocatorTraits = getDerived().TransformExpr(AT);
10438       if (AllocatorTraits.isInvalid())
10439         continue;
10440     }
10441     Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10442     NewD.Allocator = Allocator.get();
10443     NewD.AllocatorTraits = AllocatorTraits.get();
10444     NewD.LParenLoc = D.LParenLoc;
10445     NewD.RParenLoc = D.RParenLoc;
10446   }
10447   return getDerived().RebuildOMPUsesAllocatorsClause(
10448       Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10449 }
10450 
10451 template <typename Derived>
10452 OMPClause *
10453 TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10454   SmallVector<Expr *, 4> Locators;
10455   Locators.reserve(C->varlist_size());
10456   ExprResult ModifierRes;
10457   if (Expr *Modifier = C->getModifier()) {
10458     ModifierRes = getDerived().TransformExpr(Modifier);
10459     if (ModifierRes.isInvalid())
10460       return nullptr;
10461   }
10462   for (Expr *E : C->varlists()) {
10463     ExprResult Locator = getDerived().TransformExpr(E);
10464     if (Locator.isInvalid())
10465       continue;
10466     Locators.push_back(Locator.get());
10467   }
10468   return getDerived().RebuildOMPAffinityClause(
10469       C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10470       ModifierRes.get(), Locators);
10471 }
10472 
10473 template <typename Derived>
10474 OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10475   return getDerived().RebuildOMPOrderClause(C->getKind(), C->getKindKwLoc(),
10476                                             C->getBeginLoc(), C->getLParenLoc(),
10477                                             C->getEndLoc());
10478 }
10479 
10480 template <typename Derived>
10481 OMPClause *TreeTransform<Derived>::TransformOMPBindClause(OMPBindClause *C) {
10482   return getDerived().RebuildOMPBindClause(
10483       C->getBindKind(), C->getBindKindLoc(), C->getBeginLoc(),
10484       C->getLParenLoc(), C->getEndLoc());
10485 }
10486 
10487 //===----------------------------------------------------------------------===//
10488 // Expression transformation
10489 //===----------------------------------------------------------------------===//
10490 template<typename Derived>
10491 ExprResult
10492 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10493   return TransformExpr(E->getSubExpr());
10494 }
10495 
10496 template <typename Derived>
10497 ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10498     SYCLUniqueStableNameExpr *E) {
10499   if (!E->isTypeDependent())
10500     return E;
10501 
10502   TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10503 
10504   if (!NewT)
10505     return ExprError();
10506 
10507   if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10508     return E;
10509 
10510   return getDerived().RebuildSYCLUniqueStableNameExpr(
10511       E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10512 }
10513 
10514 template<typename Derived>
10515 ExprResult
10516 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10517   if (!E->isTypeDependent())
10518     return E;
10519 
10520   return getDerived().RebuildPredefinedExpr(E->getLocation(),
10521                                             E->getIdentKind());
10522 }
10523 
10524 template<typename Derived>
10525 ExprResult
10526 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10527   NestedNameSpecifierLoc QualifierLoc;
10528   if (E->getQualifierLoc()) {
10529     QualifierLoc
10530       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10531     if (!QualifierLoc)
10532       return ExprError();
10533   }
10534 
10535   ValueDecl *ND
10536     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10537                                                          E->getDecl()));
10538   if (!ND)
10539     return ExprError();
10540 
10541   NamedDecl *Found = ND;
10542   if (E->getFoundDecl() != E->getDecl()) {
10543     Found = cast_or_null<NamedDecl>(
10544         getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10545     if (!Found)
10546       return ExprError();
10547   }
10548 
10549   DeclarationNameInfo NameInfo = E->getNameInfo();
10550   if (NameInfo.getName()) {
10551     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10552     if (!NameInfo.getName())
10553       return ExprError();
10554   }
10555 
10556   if (!getDerived().AlwaysRebuild() &&
10557       QualifierLoc == E->getQualifierLoc() &&
10558       ND == E->getDecl() &&
10559       Found == E->getFoundDecl() &&
10560       NameInfo.getName() == E->getDecl()->getDeclName() &&
10561       !E->hasExplicitTemplateArgs()) {
10562 
10563     // Mark it referenced in the new context regardless.
10564     // FIXME: this is a bit instantiation-specific.
10565     SemaRef.MarkDeclRefReferenced(E);
10566 
10567     return E;
10568   }
10569 
10570   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10571   if (E->hasExplicitTemplateArgs()) {
10572     TemplateArgs = &TransArgs;
10573     TransArgs.setLAngleLoc(E->getLAngleLoc());
10574     TransArgs.setRAngleLoc(E->getRAngleLoc());
10575     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10576                                                 E->getNumTemplateArgs(),
10577                                                 TransArgs))
10578       return ExprError();
10579   }
10580 
10581   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10582                                          Found, TemplateArgs);
10583 }
10584 
10585 template<typename Derived>
10586 ExprResult
10587 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10588   return E;
10589 }
10590 
10591 template <typename Derived>
10592 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10593     FixedPointLiteral *E) {
10594   return E;
10595 }
10596 
10597 template<typename Derived>
10598 ExprResult
10599 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10600   return E;
10601 }
10602 
10603 template<typename Derived>
10604 ExprResult
10605 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10606   return E;
10607 }
10608 
10609 template<typename Derived>
10610 ExprResult
10611 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10612   return E;
10613 }
10614 
10615 template<typename Derived>
10616 ExprResult
10617 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10618   return E;
10619 }
10620 
10621 template<typename Derived>
10622 ExprResult
10623 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10624   return getDerived().TransformCallExpr(E);
10625 }
10626 
10627 template<typename Derived>
10628 ExprResult
10629 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10630   ExprResult ControllingExpr =
10631     getDerived().TransformExpr(E->getControllingExpr());
10632   if (ControllingExpr.isInvalid())
10633     return ExprError();
10634 
10635   SmallVector<Expr *, 4> AssocExprs;
10636   SmallVector<TypeSourceInfo *, 4> AssocTypes;
10637   for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10638     TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10639     if (TSI) {
10640       TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10641       if (!AssocType)
10642         return ExprError();
10643       AssocTypes.push_back(AssocType);
10644     } else {
10645       AssocTypes.push_back(nullptr);
10646     }
10647 
10648     ExprResult AssocExpr =
10649         getDerived().TransformExpr(Assoc.getAssociationExpr());
10650     if (AssocExpr.isInvalid())
10651       return ExprError();
10652     AssocExprs.push_back(AssocExpr.get());
10653   }
10654 
10655   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10656                                                   E->getDefaultLoc(),
10657                                                   E->getRParenLoc(),
10658                                                   ControllingExpr.get(),
10659                                                   AssocTypes,
10660                                                   AssocExprs);
10661 }
10662 
10663 template<typename Derived>
10664 ExprResult
10665 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10666   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10667   if (SubExpr.isInvalid())
10668     return ExprError();
10669 
10670   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10671     return E;
10672 
10673   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10674                                        E->getRParen());
10675 }
10676 
10677 /// The operand of a unary address-of operator has special rules: it's
10678 /// allowed to refer to a non-static member of a class even if there's no 'this'
10679 /// object available.
10680 template<typename Derived>
10681 ExprResult
10682 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10683   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10684     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10685   else
10686     return getDerived().TransformExpr(E);
10687 }
10688 
10689 template<typename Derived>
10690 ExprResult
10691 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10692   ExprResult SubExpr;
10693   if (E->getOpcode() == UO_AddrOf)
10694     SubExpr = TransformAddressOfOperand(E->getSubExpr());
10695   else
10696     SubExpr = TransformExpr(E->getSubExpr());
10697   if (SubExpr.isInvalid())
10698     return ExprError();
10699 
10700   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10701     return E;
10702 
10703   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10704                                            E->getOpcode(),
10705                                            SubExpr.get());
10706 }
10707 
10708 template<typename Derived>
10709 ExprResult
10710 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10711   // Transform the type.
10712   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10713   if (!Type)
10714     return ExprError();
10715 
10716   // Transform all of the components into components similar to what the
10717   // parser uses.
10718   // FIXME: It would be slightly more efficient in the non-dependent case to
10719   // just map FieldDecls, rather than requiring the rebuilder to look for
10720   // the fields again. However, __builtin_offsetof is rare enough in
10721   // template code that we don't care.
10722   bool ExprChanged = false;
10723   typedef Sema::OffsetOfComponent Component;
10724   SmallVector<Component, 4> Components;
10725   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
10726     const OffsetOfNode &ON = E->getComponent(I);
10727     Component Comp;
10728     Comp.isBrackets = true;
10729     Comp.LocStart = ON.getSourceRange().getBegin();
10730     Comp.LocEnd = ON.getSourceRange().getEnd();
10731     switch (ON.getKind()) {
10732     case OffsetOfNode::Array: {
10733       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
10734       ExprResult Index = getDerived().TransformExpr(FromIndex);
10735       if (Index.isInvalid())
10736         return ExprError();
10737 
10738       ExprChanged = ExprChanged || Index.get() != FromIndex;
10739       Comp.isBrackets = true;
10740       Comp.U.E = Index.get();
10741       break;
10742     }
10743 
10744     case OffsetOfNode::Field:
10745     case OffsetOfNode::Identifier:
10746       Comp.isBrackets = false;
10747       Comp.U.IdentInfo = ON.getFieldName();
10748       if (!Comp.U.IdentInfo)
10749         continue;
10750 
10751       break;
10752 
10753     case OffsetOfNode::Base:
10754       // Will be recomputed during the rebuild.
10755       continue;
10756     }
10757 
10758     Components.push_back(Comp);
10759   }
10760 
10761   // If nothing changed, retain the existing expression.
10762   if (!getDerived().AlwaysRebuild() &&
10763       Type == E->getTypeSourceInfo() &&
10764       !ExprChanged)
10765     return E;
10766 
10767   // Build a new offsetof expression.
10768   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
10769                                           Components, E->getRParenLoc());
10770 }
10771 
10772 template<typename Derived>
10773 ExprResult
10774 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
10775   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
10776          "opaque value expression requires transformation");
10777   return E;
10778 }
10779 
10780 template<typename Derived>
10781 ExprResult
10782 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
10783   return E;
10784 }
10785 
10786 template <typename Derived>
10787 ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
10788   llvm::SmallVector<Expr *, 8> Children;
10789   bool Changed = false;
10790   for (Expr *C : E->subExpressions()) {
10791     ExprResult NewC = getDerived().TransformExpr(C);
10792     if (NewC.isInvalid())
10793       return ExprError();
10794     Children.push_back(NewC.get());
10795 
10796     Changed |= NewC.get() != C;
10797   }
10798   if (!getDerived().AlwaysRebuild() && !Changed)
10799     return E;
10800   return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
10801                                           Children, E->getType());
10802 }
10803 
10804 template<typename Derived>
10805 ExprResult
10806 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
10807   // Rebuild the syntactic form.  The original syntactic form has
10808   // opaque-value expressions in it, so strip those away and rebuild
10809   // the result.  This is a really awful way of doing this, but the
10810   // better solution (rebuilding the semantic expressions and
10811   // rebinding OVEs as necessary) doesn't work; we'd need
10812   // TreeTransform to not strip away implicit conversions.
10813   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
10814   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
10815   if (result.isInvalid()) return ExprError();
10816 
10817   // If that gives us a pseudo-object result back, the pseudo-object
10818   // expression must have been an lvalue-to-rvalue conversion which we
10819   // should reapply.
10820   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
10821     result = SemaRef.checkPseudoObjectRValue(result.get());
10822 
10823   return result;
10824 }
10825 
10826 template<typename Derived>
10827 ExprResult
10828 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
10829                                                 UnaryExprOrTypeTraitExpr *E) {
10830   if (E->isArgumentType()) {
10831     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
10832 
10833     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
10834     if (!NewT)
10835       return ExprError();
10836 
10837     if (!getDerived().AlwaysRebuild() && OldT == NewT)
10838       return E;
10839 
10840     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
10841                                                     E->getKind(),
10842                                                     E->getSourceRange());
10843   }
10844 
10845   // C++0x [expr.sizeof]p1:
10846   //   The operand is either an expression, which is an unevaluated operand
10847   //   [...]
10848   EnterExpressionEvaluationContext Unevaluated(
10849       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10850       Sema::ReuseLambdaContextDecl);
10851 
10852   // Try to recover if we have something like sizeof(T::X) where X is a type.
10853   // Notably, there must be *exactly* one set of parens if X is a type.
10854   TypeSourceInfo *RecoveryTSI = nullptr;
10855   ExprResult SubExpr;
10856   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
10857   if (auto *DRE =
10858           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
10859     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
10860         PE, DRE, false, &RecoveryTSI);
10861   else
10862     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
10863 
10864   if (RecoveryTSI) {
10865     return getDerived().RebuildUnaryExprOrTypeTrait(
10866         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
10867   } else if (SubExpr.isInvalid())
10868     return ExprError();
10869 
10870   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
10871     return E;
10872 
10873   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
10874                                                   E->getOperatorLoc(),
10875                                                   E->getKind(),
10876                                                   E->getSourceRange());
10877 }
10878 
10879 template<typename Derived>
10880 ExprResult
10881 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
10882   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
10883   if (LHS.isInvalid())
10884     return ExprError();
10885 
10886   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
10887   if (RHS.isInvalid())
10888     return ExprError();
10889 
10890 
10891   if (!getDerived().AlwaysRebuild() &&
10892       LHS.get() == E->getLHS() &&
10893       RHS.get() == E->getRHS())
10894     return E;
10895 
10896   return getDerived().RebuildArraySubscriptExpr(
10897       LHS.get(),
10898       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
10899 }
10900 
10901 template <typename Derived>
10902 ExprResult
10903 TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
10904   ExprResult Base = getDerived().TransformExpr(E->getBase());
10905   if (Base.isInvalid())
10906     return ExprError();
10907 
10908   ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
10909   if (RowIdx.isInvalid())
10910     return ExprError();
10911 
10912   ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
10913   if (ColumnIdx.isInvalid())
10914     return ExprError();
10915 
10916   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10917       RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
10918     return E;
10919 
10920   return getDerived().RebuildMatrixSubscriptExpr(
10921       Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
10922 }
10923 
10924 template <typename Derived>
10925 ExprResult
10926 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
10927   ExprResult Base = getDerived().TransformExpr(E->getBase());
10928   if (Base.isInvalid())
10929     return ExprError();
10930 
10931   ExprResult LowerBound;
10932   if (E->getLowerBound()) {
10933     LowerBound = getDerived().TransformExpr(E->getLowerBound());
10934     if (LowerBound.isInvalid())
10935       return ExprError();
10936   }
10937 
10938   ExprResult Length;
10939   if (E->getLength()) {
10940     Length = getDerived().TransformExpr(E->getLength());
10941     if (Length.isInvalid())
10942       return ExprError();
10943   }
10944 
10945   ExprResult Stride;
10946   if (Expr *Str = E->getStride()) {
10947     Stride = getDerived().TransformExpr(Str);
10948     if (Stride.isInvalid())
10949       return ExprError();
10950   }
10951 
10952   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
10953       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
10954     return E;
10955 
10956   return getDerived().RebuildOMPArraySectionExpr(
10957       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
10958       E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
10959       E->getRBracketLoc());
10960 }
10961 
10962 template <typename Derived>
10963 ExprResult
10964 TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
10965   ExprResult Base = getDerived().TransformExpr(E->getBase());
10966   if (Base.isInvalid())
10967     return ExprError();
10968 
10969   SmallVector<Expr *, 4> Dims;
10970   bool ErrorFound = false;
10971   for (Expr *Dim : E->getDimensions()) {
10972     ExprResult DimRes = getDerived().TransformExpr(Dim);
10973     if (DimRes.isInvalid()) {
10974       ErrorFound = true;
10975       continue;
10976     }
10977     Dims.push_back(DimRes.get());
10978   }
10979 
10980   if (ErrorFound)
10981     return ExprError();
10982   return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
10983                                                  E->getRParenLoc(), Dims,
10984                                                  E->getBracketsRanges());
10985 }
10986 
10987 template <typename Derived>
10988 ExprResult
10989 TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
10990   unsigned NumIterators = E->numOfIterators();
10991   SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
10992 
10993   bool ErrorFound = false;
10994   bool NeedToRebuild = getDerived().AlwaysRebuild();
10995   for (unsigned I = 0; I < NumIterators; ++I) {
10996     auto *D = cast<VarDecl>(E->getIteratorDecl(I));
10997     Data[I].DeclIdent = D->getIdentifier();
10998     Data[I].DeclIdentLoc = D->getLocation();
10999     if (D->getLocation() == D->getBeginLoc()) {
11000       assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&
11001              "Implicit type must be int.");
11002     } else {
11003       TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
11004       QualType DeclTy = getDerived().TransformType(D->getType());
11005       Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
11006     }
11007     OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
11008     ExprResult Begin = getDerived().TransformExpr(Range.Begin);
11009     ExprResult End = getDerived().TransformExpr(Range.End);
11010     ExprResult Step = getDerived().TransformExpr(Range.Step);
11011     ErrorFound = ErrorFound ||
11012                  !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
11013                                                !Data[I].Type.get().isNull())) ||
11014                  Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
11015     if (ErrorFound)
11016       continue;
11017     Data[I].Range.Begin = Begin.get();
11018     Data[I].Range.End = End.get();
11019     Data[I].Range.Step = Step.get();
11020     Data[I].AssignLoc = E->getAssignLoc(I);
11021     Data[I].ColonLoc = E->getColonLoc(I);
11022     Data[I].SecColonLoc = E->getSecondColonLoc(I);
11023     NeedToRebuild =
11024         NeedToRebuild ||
11025         (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
11026                                        D->getType().getTypePtrOrNull()) ||
11027         Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
11028         Range.Step != Data[I].Range.Step;
11029   }
11030   if (ErrorFound)
11031     return ExprError();
11032   if (!NeedToRebuild)
11033     return E;
11034 
11035   ExprResult Res = getDerived().RebuildOMPIteratorExpr(
11036       E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
11037   if (!Res.isUsable())
11038     return Res;
11039   auto *IE = cast<OMPIteratorExpr>(Res.get());
11040   for (unsigned I = 0; I < NumIterators; ++I)
11041     getDerived().transformedLocalDecl(E->getIteratorDecl(I),
11042                                       IE->getIteratorDecl(I));
11043   return Res;
11044 }
11045 
11046 template<typename Derived>
11047 ExprResult
11048 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
11049   // Transform the callee.
11050   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11051   if (Callee.isInvalid())
11052     return ExprError();
11053 
11054   // Transform arguments.
11055   bool ArgChanged = false;
11056   SmallVector<Expr*, 8> Args;
11057   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11058                                   &ArgChanged))
11059     return ExprError();
11060 
11061   if (!getDerived().AlwaysRebuild() &&
11062       Callee.get() == E->getCallee() &&
11063       !ArgChanged)
11064     return SemaRef.MaybeBindToTemporary(E);
11065 
11066   // FIXME: Wrong source location information for the '('.
11067   SourceLocation FakeLParenLoc
11068     = ((Expr *)Callee.get())->getSourceRange().getBegin();
11069 
11070   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11071   if (E->hasStoredFPFeatures()) {
11072     FPOptionsOverride NewOverrides = E->getFPFeatures();
11073     getSema().CurFPFeatures =
11074         NewOverrides.applyOverrides(getSema().getLangOpts());
11075     getSema().FpPragmaStack.CurrentValue = NewOverrides;
11076   }
11077 
11078   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11079                                       Args,
11080                                       E->getRParenLoc());
11081 }
11082 
11083 template<typename Derived>
11084 ExprResult
11085 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
11086   ExprResult Base = getDerived().TransformExpr(E->getBase());
11087   if (Base.isInvalid())
11088     return ExprError();
11089 
11090   NestedNameSpecifierLoc QualifierLoc;
11091   if (E->hasQualifier()) {
11092     QualifierLoc
11093       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11094 
11095     if (!QualifierLoc)
11096       return ExprError();
11097   }
11098   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11099 
11100   ValueDecl *Member
11101     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
11102                                                          E->getMemberDecl()));
11103   if (!Member)
11104     return ExprError();
11105 
11106   NamedDecl *FoundDecl = E->getFoundDecl();
11107   if (FoundDecl == E->getMemberDecl()) {
11108     FoundDecl = Member;
11109   } else {
11110     FoundDecl = cast_or_null<NamedDecl>(
11111                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
11112     if (!FoundDecl)
11113       return ExprError();
11114   }
11115 
11116   if (!getDerived().AlwaysRebuild() &&
11117       Base.get() == E->getBase() &&
11118       QualifierLoc == E->getQualifierLoc() &&
11119       Member == E->getMemberDecl() &&
11120       FoundDecl == E->getFoundDecl() &&
11121       !E->hasExplicitTemplateArgs()) {
11122 
11123     // Skip for member expression of (this->f), rebuilt thisi->f is needed
11124     // for Openmp where the field need to be privatizized in the case.
11125     if (!(isa<CXXThisExpr>(E->getBase()) &&
11126           getSema().isOpenMPRebuildMemberExpr(cast<ValueDecl>(Member)))) {
11127       // Mark it referenced in the new context regardless.
11128       // FIXME: this is a bit instantiation-specific.
11129       SemaRef.MarkMemberReferenced(E);
11130       return E;
11131     }
11132   }
11133 
11134   TemplateArgumentListInfo TransArgs;
11135   if (E->hasExplicitTemplateArgs()) {
11136     TransArgs.setLAngleLoc(E->getLAngleLoc());
11137     TransArgs.setRAngleLoc(E->getRAngleLoc());
11138     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11139                                                 E->getNumTemplateArgs(),
11140                                                 TransArgs))
11141       return ExprError();
11142   }
11143 
11144   // FIXME: Bogus source location for the operator
11145   SourceLocation FakeOperatorLoc =
11146       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
11147 
11148   // FIXME: to do this check properly, we will need to preserve the
11149   // first-qualifier-in-scope here, just in case we had a dependent
11150   // base (and therefore couldn't do the check) and a
11151   // nested-name-qualifier (and therefore could do the lookup).
11152   NamedDecl *FirstQualifierInScope = nullptr;
11153   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
11154   if (MemberNameInfo.getName()) {
11155     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
11156     if (!MemberNameInfo.getName())
11157       return ExprError();
11158   }
11159 
11160   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
11161                                         E->isArrow(),
11162                                         QualifierLoc,
11163                                         TemplateKWLoc,
11164                                         MemberNameInfo,
11165                                         Member,
11166                                         FoundDecl,
11167                                         (E->hasExplicitTemplateArgs()
11168                                            ? &TransArgs : nullptr),
11169                                         FirstQualifierInScope);
11170 }
11171 
11172 template<typename Derived>
11173 ExprResult
11174 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
11175   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11176   if (LHS.isInvalid())
11177     return ExprError();
11178 
11179   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11180   if (RHS.isInvalid())
11181     return ExprError();
11182 
11183   if (!getDerived().AlwaysRebuild() &&
11184       LHS.get() == E->getLHS() &&
11185       RHS.get() == E->getRHS())
11186     return E;
11187 
11188   if (E->isCompoundAssignmentOp())
11189     // FPFeatures has already been established from trailing storage
11190     return getDerived().RebuildBinaryOperator(
11191         E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
11192   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11193   FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
11194   getSema().CurFPFeatures =
11195       NewOverrides.applyOverrides(getSema().getLangOpts());
11196   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11197   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
11198                                             LHS.get(), RHS.get());
11199 }
11200 
11201 template <typename Derived>
11202 ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
11203     CXXRewrittenBinaryOperator *E) {
11204   CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
11205 
11206   ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
11207   if (LHS.isInvalid())
11208     return ExprError();
11209 
11210   ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
11211   if (RHS.isInvalid())
11212     return ExprError();
11213 
11214   // Extract the already-resolved callee declarations so that we can restrict
11215   // ourselves to using them as the unqualified lookup results when rebuilding.
11216   UnresolvedSet<2> UnqualLookups;
11217   bool ChangedAnyLookups = false;
11218   Expr *PossibleBinOps[] = {E->getSemanticForm(),
11219                             const_cast<Expr *>(Decomp.InnerBinOp)};
11220   for (Expr *PossibleBinOp : PossibleBinOps) {
11221     auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
11222     if (!Op)
11223       continue;
11224     auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
11225     if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
11226       continue;
11227 
11228     // Transform the callee in case we built a call to a local extern
11229     // declaration.
11230     NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
11231         E->getOperatorLoc(), Callee->getFoundDecl()));
11232     if (!Found)
11233       return ExprError();
11234     if (Found != Callee->getFoundDecl())
11235       ChangedAnyLookups = true;
11236     UnqualLookups.addDecl(Found);
11237   }
11238 
11239   if (!getDerived().AlwaysRebuild() && !ChangedAnyLookups &&
11240       LHS.get() == Decomp.LHS && RHS.get() == Decomp.RHS) {
11241     // Mark all functions used in the rewrite as referenced. Note that when
11242     // a < b is rewritten to (a <=> b) < 0, both the <=> and the < might be
11243     // function calls, and/or there might be a user-defined conversion sequence
11244     // applied to the operands of the <.
11245     // FIXME: this is a bit instantiation-specific.
11246     const Expr *StopAt[] = {Decomp.LHS, Decomp.RHS};
11247     SemaRef.MarkDeclarationsReferencedInExpr(E, false, StopAt);
11248     return E;
11249   }
11250 
11251   return getDerived().RebuildCXXRewrittenBinaryOperator(
11252       E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
11253 }
11254 
11255 template<typename Derived>
11256 ExprResult
11257 TreeTransform<Derived>::TransformCompoundAssignOperator(
11258                                                       CompoundAssignOperator *E) {
11259   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11260   FPOptionsOverride NewOverrides(E->getFPFeatures(getSema().getLangOpts()));
11261   getSema().CurFPFeatures =
11262       NewOverrides.applyOverrides(getSema().getLangOpts());
11263   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11264   return getDerived().TransformBinaryOperator(E);
11265 }
11266 
11267 template<typename Derived>
11268 ExprResult TreeTransform<Derived>::
11269 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
11270   // Just rebuild the common and RHS expressions and see whether we
11271   // get any changes.
11272 
11273   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
11274   if (commonExpr.isInvalid())
11275     return ExprError();
11276 
11277   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11278   if (rhs.isInvalid())
11279     return ExprError();
11280 
11281   if (!getDerived().AlwaysRebuild() &&
11282       commonExpr.get() == e->getCommon() &&
11283       rhs.get() == e->getFalseExpr())
11284     return e;
11285 
11286   return getDerived().RebuildConditionalOperator(commonExpr.get(),
11287                                                  e->getQuestionLoc(),
11288                                                  nullptr,
11289                                                  e->getColonLoc(),
11290                                                  rhs.get());
11291 }
11292 
11293 template<typename Derived>
11294 ExprResult
11295 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11296   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11297   if (Cond.isInvalid())
11298     return ExprError();
11299 
11300   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11301   if (LHS.isInvalid())
11302     return ExprError();
11303 
11304   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11305   if (RHS.isInvalid())
11306     return ExprError();
11307 
11308   if (!getDerived().AlwaysRebuild() &&
11309       Cond.get() == E->getCond() &&
11310       LHS.get() == E->getLHS() &&
11311       RHS.get() == E->getRHS())
11312     return E;
11313 
11314   return getDerived().RebuildConditionalOperator(Cond.get(),
11315                                                  E->getQuestionLoc(),
11316                                                  LHS.get(),
11317                                                  E->getColonLoc(),
11318                                                  RHS.get());
11319 }
11320 
11321 template<typename Derived>
11322 ExprResult
11323 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11324   // Implicit casts are eliminated during transformation, since they
11325   // will be recomputed by semantic analysis after transformation.
11326   return getDerived().TransformExpr(E->getSubExprAsWritten());
11327 }
11328 
11329 template<typename Derived>
11330 ExprResult
11331 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11332   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11333   if (!Type)
11334     return ExprError();
11335 
11336   ExprResult SubExpr
11337     = getDerived().TransformExpr(E->getSubExprAsWritten());
11338   if (SubExpr.isInvalid())
11339     return ExprError();
11340 
11341   if (!getDerived().AlwaysRebuild() &&
11342       Type == E->getTypeInfoAsWritten() &&
11343       SubExpr.get() == E->getSubExpr())
11344     return E;
11345 
11346   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11347                                             Type,
11348                                             E->getRParenLoc(),
11349                                             SubExpr.get());
11350 }
11351 
11352 template<typename Derived>
11353 ExprResult
11354 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11355   TypeSourceInfo *OldT = E->getTypeSourceInfo();
11356   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11357   if (!NewT)
11358     return ExprError();
11359 
11360   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11361   if (Init.isInvalid())
11362     return ExprError();
11363 
11364   if (!getDerived().AlwaysRebuild() &&
11365       OldT == NewT &&
11366       Init.get() == E->getInitializer())
11367     return SemaRef.MaybeBindToTemporary(E);
11368 
11369   // Note: the expression type doesn't necessarily match the
11370   // type-as-written, but that's okay, because it should always be
11371   // derivable from the initializer.
11372 
11373   return getDerived().RebuildCompoundLiteralExpr(
11374       E->getLParenLoc(), NewT,
11375       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11376 }
11377 
11378 template<typename Derived>
11379 ExprResult
11380 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11381   ExprResult Base = getDerived().TransformExpr(E->getBase());
11382   if (Base.isInvalid())
11383     return ExprError();
11384 
11385   if (!getDerived().AlwaysRebuild() &&
11386       Base.get() == E->getBase())
11387     return E;
11388 
11389   // FIXME: Bad source location
11390   SourceLocation FakeOperatorLoc =
11391       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11392   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
11393                                                   E->getAccessorLoc(),
11394                                                   E->getAccessor());
11395 }
11396 
11397 template<typename Derived>
11398 ExprResult
11399 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11400   if (InitListExpr *Syntactic = E->getSyntacticForm())
11401     E = Syntactic;
11402 
11403   bool InitChanged = false;
11404 
11405   EnterExpressionEvaluationContext Context(
11406       getSema(), EnterExpressionEvaluationContext::InitList);
11407 
11408   SmallVector<Expr*, 4> Inits;
11409   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11410                                   Inits, &InitChanged))
11411     return ExprError();
11412 
11413   if (!getDerived().AlwaysRebuild() && !InitChanged) {
11414     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11415     // in some cases. We can't reuse it in general, because the syntactic and
11416     // semantic forms are linked, and we can't know that semantic form will
11417     // match even if the syntactic form does.
11418   }
11419 
11420   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11421                                       E->getRBraceLoc());
11422 }
11423 
11424 template<typename Derived>
11425 ExprResult
11426 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11427   Designation Desig;
11428 
11429   // transform the initializer value
11430   ExprResult Init = getDerived().TransformExpr(E->getInit());
11431   if (Init.isInvalid())
11432     return ExprError();
11433 
11434   // transform the designators.
11435   SmallVector<Expr*, 4> ArrayExprs;
11436   bool ExprChanged = false;
11437   for (const DesignatedInitExpr::Designator &D : E->designators()) {
11438     if (D.isFieldDesignator()) {
11439       Desig.AddDesignator(Designator::getField(D.getFieldName(),
11440                                                D.getDotLoc(),
11441                                                D.getFieldLoc()));
11442       if (D.getField()) {
11443         FieldDecl *Field = cast_or_null<FieldDecl>(
11444             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
11445         if (Field != D.getField())
11446           // Rebuild the expression when the transformed FieldDecl is
11447           // different to the already assigned FieldDecl.
11448           ExprChanged = true;
11449       } else {
11450         // Ensure that the designator expression is rebuilt when there isn't
11451         // a resolved FieldDecl in the designator as we don't want to assign
11452         // a FieldDecl to a pattern designator that will be instantiated again.
11453         ExprChanged = true;
11454       }
11455       continue;
11456     }
11457 
11458     if (D.isArrayDesignator()) {
11459       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11460       if (Index.isInvalid())
11461         return ExprError();
11462 
11463       Desig.AddDesignator(
11464           Designator::getArray(Index.get(), D.getLBracketLoc()));
11465 
11466       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11467       ArrayExprs.push_back(Index.get());
11468       continue;
11469     }
11470 
11471     assert(D.isArrayRangeDesignator() && "New kind of designator?");
11472     ExprResult Start
11473       = getDerived().TransformExpr(E->getArrayRangeStart(D));
11474     if (Start.isInvalid())
11475       return ExprError();
11476 
11477     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11478     if (End.isInvalid())
11479       return ExprError();
11480 
11481     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
11482                                                   End.get(),
11483                                                   D.getLBracketLoc(),
11484                                                   D.getEllipsisLoc()));
11485 
11486     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11487                   End.get() != E->getArrayRangeEnd(D);
11488 
11489     ArrayExprs.push_back(Start.get());
11490     ArrayExprs.push_back(End.get());
11491   }
11492 
11493   if (!getDerived().AlwaysRebuild() &&
11494       Init.get() == E->getInit() &&
11495       !ExprChanged)
11496     return E;
11497 
11498   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11499                                                 E->getEqualOrColonLoc(),
11500                                                 E->usesGNUSyntax(), Init.get());
11501 }
11502 
11503 // Seems that if TransformInitListExpr() only works on the syntactic form of an
11504 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11505 template<typename Derived>
11506 ExprResult
11507 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11508     DesignatedInitUpdateExpr *E) {
11509   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
11510                    "initializer");
11511   return ExprError();
11512 }
11513 
11514 template<typename Derived>
11515 ExprResult
11516 TreeTransform<Derived>::TransformNoInitExpr(
11517     NoInitExpr *E) {
11518   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
11519   return ExprError();
11520 }
11521 
11522 template<typename Derived>
11523 ExprResult
11524 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11525   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
11526   return ExprError();
11527 }
11528 
11529 template<typename Derived>
11530 ExprResult
11531 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11532   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
11533   return ExprError();
11534 }
11535 
11536 template<typename Derived>
11537 ExprResult
11538 TreeTransform<Derived>::TransformImplicitValueInitExpr(
11539                                                      ImplicitValueInitExpr *E) {
11540   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11541 
11542   // FIXME: Will we ever have proper type location here? Will we actually
11543   // need to transform the type?
11544   QualType T = getDerived().TransformType(E->getType());
11545   if (T.isNull())
11546     return ExprError();
11547 
11548   if (!getDerived().AlwaysRebuild() &&
11549       T == E->getType())
11550     return E;
11551 
11552   return getDerived().RebuildImplicitValueInitExpr(T);
11553 }
11554 
11555 template<typename Derived>
11556 ExprResult
11557 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11558   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11559   if (!TInfo)
11560     return ExprError();
11561 
11562   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11563   if (SubExpr.isInvalid())
11564     return ExprError();
11565 
11566   if (!getDerived().AlwaysRebuild() &&
11567       TInfo == E->getWrittenTypeInfo() &&
11568       SubExpr.get() == E->getSubExpr())
11569     return E;
11570 
11571   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11572                                        TInfo, E->getRParenLoc());
11573 }
11574 
11575 template<typename Derived>
11576 ExprResult
11577 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11578   bool ArgumentChanged = false;
11579   SmallVector<Expr*, 4> Inits;
11580   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11581                      &ArgumentChanged))
11582     return ExprError();
11583 
11584   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11585                                            Inits,
11586                                            E->getRParenLoc());
11587 }
11588 
11589 /// Transform an address-of-label expression.
11590 ///
11591 /// By default, the transformation of an address-of-label expression always
11592 /// rebuilds the expression, so that the label identifier can be resolved to
11593 /// the corresponding label statement by semantic analysis.
11594 template<typename Derived>
11595 ExprResult
11596 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11597   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11598                                         E->getLabel());
11599   if (!LD)
11600     return ExprError();
11601 
11602   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11603                                            cast<LabelDecl>(LD));
11604 }
11605 
11606 template<typename Derived>
11607 ExprResult
11608 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11609   SemaRef.ActOnStartStmtExpr();
11610   StmtResult SubStmt
11611     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11612   if (SubStmt.isInvalid()) {
11613     SemaRef.ActOnStmtExprError();
11614     return ExprError();
11615   }
11616 
11617   unsigned OldDepth = E->getTemplateDepth();
11618   unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11619 
11620   if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11621       SubStmt.get() == E->getSubStmt()) {
11622     // Calling this an 'error' is unintuitive, but it does the right thing.
11623     SemaRef.ActOnStmtExprError();
11624     return SemaRef.MaybeBindToTemporary(E);
11625   }
11626 
11627   return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11628                                       E->getRParenLoc(), NewDepth);
11629 }
11630 
11631 template<typename Derived>
11632 ExprResult
11633 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11634   ExprResult Cond = getDerived().TransformExpr(E->getCond());
11635   if (Cond.isInvalid())
11636     return ExprError();
11637 
11638   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11639   if (LHS.isInvalid())
11640     return ExprError();
11641 
11642   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11643   if (RHS.isInvalid())
11644     return ExprError();
11645 
11646   if (!getDerived().AlwaysRebuild() &&
11647       Cond.get() == E->getCond() &&
11648       LHS.get() == E->getLHS() &&
11649       RHS.get() == E->getRHS())
11650     return E;
11651 
11652   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11653                                         Cond.get(), LHS.get(), RHS.get(),
11654                                         E->getRParenLoc());
11655 }
11656 
11657 template<typename Derived>
11658 ExprResult
11659 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11660   return E;
11661 }
11662 
11663 template<typename Derived>
11664 ExprResult
11665 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11666   switch (E->getOperator()) {
11667   case OO_New:
11668   case OO_Delete:
11669   case OO_Array_New:
11670   case OO_Array_Delete:
11671     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
11672 
11673   case OO_Subscript:
11674   case OO_Call: {
11675     // This is a call to an object's operator().
11676     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
11677 
11678     // Transform the object itself.
11679     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11680     if (Object.isInvalid())
11681       return ExprError();
11682 
11683     // FIXME: Poor location information
11684     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11685         static_cast<Expr *>(Object.get())->getEndLoc());
11686 
11687     // Transform the call arguments.
11688     SmallVector<Expr*, 8> Args;
11689     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
11690                                     Args))
11691       return ExprError();
11692 
11693     if (E->getOperator() == OO_Subscript)
11694       return getDerived().RebuildCxxSubscriptExpr(Object.get(), FakeLParenLoc,
11695                                                   Args, E->getEndLoc());
11696 
11697     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11698                                         E->getEndLoc());
11699   }
11700 
11701 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
11702   case OO_##Name:                                                              \
11703     break;
11704 
11705 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11706 #include "clang/Basic/OperatorKinds.def"
11707 
11708   case OO_Conditional:
11709     llvm_unreachable("conditional operator is not actually overloadable");
11710 
11711   case OO_None:
11712   case NUM_OVERLOADED_OPERATORS:
11713     llvm_unreachable("not an overloaded operator?");
11714   }
11715 
11716   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11717   if (Callee.isInvalid())
11718     return ExprError();
11719 
11720   ExprResult First;
11721   if (E->getOperator() == OO_Amp)
11722     First = getDerived().TransformAddressOfOperand(E->getArg(0));
11723   else
11724     First = getDerived().TransformExpr(E->getArg(0));
11725   if (First.isInvalid())
11726     return ExprError();
11727 
11728   ExprResult Second;
11729   if (E->getNumArgs() == 2) {
11730     Second = getDerived().TransformExpr(E->getArg(1));
11731     if (Second.isInvalid())
11732       return ExprError();
11733   }
11734 
11735   if (!getDerived().AlwaysRebuild() &&
11736       Callee.get() == E->getCallee() &&
11737       First.get() == E->getArg(0) &&
11738       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
11739     return SemaRef.MaybeBindToTemporary(E);
11740 
11741   Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11742   FPOptionsOverride NewOverrides(E->getFPFeatures());
11743   getSema().CurFPFeatures =
11744       NewOverrides.applyOverrides(getSema().getLangOpts());
11745   getSema().FpPragmaStack.CurrentValue = NewOverrides;
11746 
11747   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
11748                                                  E->getOperatorLoc(),
11749                                                  Callee.get(),
11750                                                  First.get(),
11751                                                  Second.get());
11752 }
11753 
11754 template<typename Derived>
11755 ExprResult
11756 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
11757   return getDerived().TransformCallExpr(E);
11758 }
11759 
11760 template <typename Derived>
11761 ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
11762   bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
11763                          getSema().CurContext != E->getParentContext();
11764 
11765   if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
11766     return E;
11767 
11768   return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
11769                                            E->getBeginLoc(), E->getEndLoc(),
11770                                            getSema().CurContext);
11771 }
11772 
11773 template<typename Derived>
11774 ExprResult
11775 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
11776   // Transform the callee.
11777   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11778   if (Callee.isInvalid())
11779     return ExprError();
11780 
11781   // Transform exec config.
11782   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
11783   if (EC.isInvalid())
11784     return ExprError();
11785 
11786   // Transform arguments.
11787   bool ArgChanged = false;
11788   SmallVector<Expr*, 8> Args;
11789   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11790                                   &ArgChanged))
11791     return ExprError();
11792 
11793   if (!getDerived().AlwaysRebuild() &&
11794       Callee.get() == E->getCallee() &&
11795       !ArgChanged)
11796     return SemaRef.MaybeBindToTemporary(E);
11797 
11798   // FIXME: Wrong source location information for the '('.
11799   SourceLocation FakeLParenLoc
11800     = ((Expr *)Callee.get())->getSourceRange().getBegin();
11801   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11802                                       Args,
11803                                       E->getRParenLoc(), EC.get());
11804 }
11805 
11806 template<typename Derived>
11807 ExprResult
11808 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
11809   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11810   if (!Type)
11811     return ExprError();
11812 
11813   ExprResult SubExpr
11814     = getDerived().TransformExpr(E->getSubExprAsWritten());
11815   if (SubExpr.isInvalid())
11816     return ExprError();
11817 
11818   if (!getDerived().AlwaysRebuild() &&
11819       Type == E->getTypeInfoAsWritten() &&
11820       SubExpr.get() == E->getSubExpr())
11821     return E;
11822   return getDerived().RebuildCXXNamedCastExpr(
11823       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
11824       Type, E->getAngleBrackets().getEnd(),
11825       // FIXME. this should be '(' location
11826       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
11827 }
11828 
11829 template<typename Derived>
11830 ExprResult
11831 TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
11832   TypeSourceInfo *TSI =
11833       getDerived().TransformType(BCE->getTypeInfoAsWritten());
11834   if (!TSI)
11835     return ExprError();
11836 
11837   ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
11838   if (Sub.isInvalid())
11839     return ExprError();
11840 
11841   return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
11842                                                 Sub.get(), BCE->getEndLoc());
11843 }
11844 
11845 template<typename Derived>
11846 ExprResult
11847 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
11848   return getDerived().TransformCXXNamedCastExpr(E);
11849 }
11850 
11851 template<typename Derived>
11852 ExprResult
11853 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
11854   return getDerived().TransformCXXNamedCastExpr(E);
11855 }
11856 
11857 template<typename Derived>
11858 ExprResult
11859 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
11860                                                       CXXReinterpretCastExpr *E) {
11861   return getDerived().TransformCXXNamedCastExpr(E);
11862 }
11863 
11864 template<typename Derived>
11865 ExprResult
11866 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
11867   return getDerived().TransformCXXNamedCastExpr(E);
11868 }
11869 
11870 template<typename Derived>
11871 ExprResult
11872 TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
11873   return getDerived().TransformCXXNamedCastExpr(E);
11874 }
11875 
11876 template<typename Derived>
11877 ExprResult
11878 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
11879                                                      CXXFunctionalCastExpr *E) {
11880   TypeSourceInfo *Type =
11881       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
11882   if (!Type)
11883     return ExprError();
11884 
11885   ExprResult SubExpr
11886     = getDerived().TransformExpr(E->getSubExprAsWritten());
11887   if (SubExpr.isInvalid())
11888     return ExprError();
11889 
11890   if (!getDerived().AlwaysRebuild() &&
11891       Type == E->getTypeInfoAsWritten() &&
11892       SubExpr.get() == E->getSubExpr())
11893     return E;
11894 
11895   return getDerived().RebuildCXXFunctionalCastExpr(Type,
11896                                                    E->getLParenLoc(),
11897                                                    SubExpr.get(),
11898                                                    E->getRParenLoc(),
11899                                                    E->isListInitialization());
11900 }
11901 
11902 template<typename Derived>
11903 ExprResult
11904 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
11905   if (E->isTypeOperand()) {
11906     TypeSourceInfo *TInfo
11907       = getDerived().TransformType(E->getTypeOperandSourceInfo());
11908     if (!TInfo)
11909       return ExprError();
11910 
11911     if (!getDerived().AlwaysRebuild() &&
11912         TInfo == E->getTypeOperandSourceInfo())
11913       return E;
11914 
11915     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11916                                              TInfo, E->getEndLoc());
11917   }
11918 
11919   // Typeid's operand is an unevaluated context, unless it's a polymorphic
11920   // type.  We must not unilaterally enter unevaluated context here, as then
11921   // semantic processing can re-transform an already transformed operand.
11922   Expr *Op = E->getExprOperand();
11923   auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
11924   if (E->isGLValue())
11925     if (auto *RecordT = Op->getType()->getAs<RecordType>())
11926       if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
11927         EvalCtx = SemaRef.ExprEvalContexts.back().Context;
11928 
11929   EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
11930                                                Sema::ReuseLambdaContextDecl);
11931 
11932   ExprResult SubExpr = getDerived().TransformExpr(Op);
11933   if (SubExpr.isInvalid())
11934     return ExprError();
11935 
11936   if (!getDerived().AlwaysRebuild() &&
11937       SubExpr.get() == E->getExprOperand())
11938     return E;
11939 
11940   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
11941                                            SubExpr.get(), E->getEndLoc());
11942 }
11943 
11944 template<typename Derived>
11945 ExprResult
11946 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
11947   if (E->isTypeOperand()) {
11948     TypeSourceInfo *TInfo
11949       = getDerived().TransformType(E->getTypeOperandSourceInfo());
11950     if (!TInfo)
11951       return ExprError();
11952 
11953     if (!getDerived().AlwaysRebuild() &&
11954         TInfo == E->getTypeOperandSourceInfo())
11955       return E;
11956 
11957     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11958                                              TInfo, E->getEndLoc());
11959   }
11960 
11961   EnterExpressionEvaluationContext Unevaluated(
11962       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11963 
11964   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
11965   if (SubExpr.isInvalid())
11966     return ExprError();
11967 
11968   if (!getDerived().AlwaysRebuild() &&
11969       SubExpr.get() == E->getExprOperand())
11970     return E;
11971 
11972   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
11973                                            SubExpr.get(), E->getEndLoc());
11974 }
11975 
11976 template<typename Derived>
11977 ExprResult
11978 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
11979   return E;
11980 }
11981 
11982 template<typename Derived>
11983 ExprResult
11984 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
11985                                                      CXXNullPtrLiteralExpr *E) {
11986   return E;
11987 }
11988 
11989 template<typename Derived>
11990 ExprResult
11991 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
11992   QualType T = getSema().getCurrentThisType();
11993 
11994   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
11995     // Mark it referenced in the new context regardless.
11996     // FIXME: this is a bit instantiation-specific.
11997     getSema().MarkThisReferenced(E);
11998     return E;
11999   }
12000 
12001   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
12002 }
12003 
12004 template<typename Derived>
12005 ExprResult
12006 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
12007   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12008   if (SubExpr.isInvalid())
12009     return ExprError();
12010 
12011   if (!getDerived().AlwaysRebuild() &&
12012       SubExpr.get() == E->getSubExpr())
12013     return E;
12014 
12015   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
12016                                           E->isThrownVariableInScope());
12017 }
12018 
12019 template<typename Derived>
12020 ExprResult
12021 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12022   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
12023       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
12024   if (!Param)
12025     return ExprError();
12026 
12027   if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
12028       E->getUsedContext() == SemaRef.CurContext)
12029     return E;
12030 
12031   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
12032 }
12033 
12034 template<typename Derived>
12035 ExprResult
12036 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
12037   FieldDecl *Field = cast_or_null<FieldDecl>(
12038       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
12039   if (!Field)
12040     return ExprError();
12041 
12042   if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
12043       E->getUsedContext() == SemaRef.CurContext)
12044     return E;
12045 
12046   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
12047 }
12048 
12049 template<typename Derived>
12050 ExprResult
12051 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
12052                                                     CXXScalarValueInitExpr *E) {
12053   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
12054   if (!T)
12055     return ExprError();
12056 
12057   if (!getDerived().AlwaysRebuild() &&
12058       T == E->getTypeSourceInfo())
12059     return E;
12060 
12061   return getDerived().RebuildCXXScalarValueInitExpr(T,
12062                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
12063                                                     E->getRParenLoc());
12064 }
12065 
12066 template<typename Derived>
12067 ExprResult
12068 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
12069   // Transform the type that we're allocating
12070   TypeSourceInfo *AllocTypeInfo =
12071       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
12072   if (!AllocTypeInfo)
12073     return ExprError();
12074 
12075   // Transform the size of the array we're allocating (if any).
12076   Optional<Expr *> ArraySize;
12077   if (E->isArray()) {
12078     ExprResult NewArraySize;
12079     if (Optional<Expr *> OldArraySize = E->getArraySize()) {
12080       NewArraySize = getDerived().TransformExpr(*OldArraySize);
12081       if (NewArraySize.isInvalid())
12082         return ExprError();
12083     }
12084     ArraySize = NewArraySize.get();
12085   }
12086 
12087   // Transform the placement arguments (if any).
12088   bool ArgumentChanged = false;
12089   SmallVector<Expr*, 8> PlacementArgs;
12090   if (getDerived().TransformExprs(E->getPlacementArgs(),
12091                                   E->getNumPlacementArgs(), true,
12092                                   PlacementArgs, &ArgumentChanged))
12093     return ExprError();
12094 
12095   // Transform the initializer (if any).
12096   Expr *OldInit = E->getInitializer();
12097   ExprResult NewInit;
12098   if (OldInit)
12099     NewInit = getDerived().TransformInitializer(OldInit, true);
12100   if (NewInit.isInvalid())
12101     return ExprError();
12102 
12103   // Transform new operator and delete operator.
12104   FunctionDecl *OperatorNew = nullptr;
12105   if (E->getOperatorNew()) {
12106     OperatorNew = cast_or_null<FunctionDecl>(
12107         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
12108     if (!OperatorNew)
12109       return ExprError();
12110   }
12111 
12112   FunctionDecl *OperatorDelete = nullptr;
12113   if (E->getOperatorDelete()) {
12114     OperatorDelete = cast_or_null<FunctionDecl>(
12115         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12116     if (!OperatorDelete)
12117       return ExprError();
12118   }
12119 
12120   if (!getDerived().AlwaysRebuild() &&
12121       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
12122       ArraySize == E->getArraySize() &&
12123       NewInit.get() == OldInit &&
12124       OperatorNew == E->getOperatorNew() &&
12125       OperatorDelete == E->getOperatorDelete() &&
12126       !ArgumentChanged) {
12127     // Mark any declarations we need as referenced.
12128     // FIXME: instantiation-specific.
12129     if (OperatorNew)
12130       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
12131     if (OperatorDelete)
12132       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12133 
12134     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
12135       QualType ElementType
12136         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
12137       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
12138         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
12139         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
12140           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
12141         }
12142       }
12143     }
12144 
12145     return E;
12146   }
12147 
12148   QualType AllocType = AllocTypeInfo->getType();
12149   if (!ArraySize) {
12150     // If no array size was specified, but the new expression was
12151     // instantiated with an array type (e.g., "new T" where T is
12152     // instantiated with "int[4]"), extract the outer bound from the
12153     // array type as our array size. We do this with constant and
12154     // dependently-sized array types.
12155     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
12156     if (!ArrayT) {
12157       // Do nothing
12158     } else if (const ConstantArrayType *ConsArrayT
12159                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
12160       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
12161                                          SemaRef.Context.getSizeType(),
12162                                          /*FIXME:*/ E->getBeginLoc());
12163       AllocType = ConsArrayT->getElementType();
12164     } else if (const DependentSizedArrayType *DepArrayT
12165                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
12166       if (DepArrayT->getSizeExpr()) {
12167         ArraySize = DepArrayT->getSizeExpr();
12168         AllocType = DepArrayT->getElementType();
12169       }
12170     }
12171   }
12172 
12173   return getDerived().RebuildCXXNewExpr(
12174       E->getBeginLoc(), E->isGlobalNew(),
12175       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
12176       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
12177       AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
12178 }
12179 
12180 template<typename Derived>
12181 ExprResult
12182 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
12183   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
12184   if (Operand.isInvalid())
12185     return ExprError();
12186 
12187   // Transform the delete operator, if known.
12188   FunctionDecl *OperatorDelete = nullptr;
12189   if (E->getOperatorDelete()) {
12190     OperatorDelete = cast_or_null<FunctionDecl>(
12191         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12192     if (!OperatorDelete)
12193       return ExprError();
12194   }
12195 
12196   if (!getDerived().AlwaysRebuild() &&
12197       Operand.get() == E->getArgument() &&
12198       OperatorDelete == E->getOperatorDelete()) {
12199     // Mark any declarations we need as referenced.
12200     // FIXME: instantiation-specific.
12201     if (OperatorDelete)
12202       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12203 
12204     if (!E->getArgument()->isTypeDependent()) {
12205       QualType Destroyed = SemaRef.Context.getBaseElementType(
12206                                                          E->getDestroyedType());
12207       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12208         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12209         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12210                                        SemaRef.LookupDestructor(Record));
12211       }
12212     }
12213 
12214     return E;
12215   }
12216 
12217   return getDerived().RebuildCXXDeleteExpr(
12218       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
12219 }
12220 
12221 template<typename Derived>
12222 ExprResult
12223 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
12224                                                      CXXPseudoDestructorExpr *E) {
12225   ExprResult Base = getDerived().TransformExpr(E->getBase());
12226   if (Base.isInvalid())
12227     return ExprError();
12228 
12229   ParsedType ObjectTypePtr;
12230   bool MayBePseudoDestructor = false;
12231   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12232                                               E->getOperatorLoc(),
12233                                         E->isArrow()? tok::arrow : tok::period,
12234                                               ObjectTypePtr,
12235                                               MayBePseudoDestructor);
12236   if (Base.isInvalid())
12237     return ExprError();
12238 
12239   QualType ObjectType = ObjectTypePtr.get();
12240   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
12241   if (QualifierLoc) {
12242     QualifierLoc
12243       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
12244     if (!QualifierLoc)
12245       return ExprError();
12246   }
12247   CXXScopeSpec SS;
12248   SS.Adopt(QualifierLoc);
12249 
12250   PseudoDestructorTypeStorage Destroyed;
12251   if (E->getDestroyedTypeInfo()) {
12252     TypeSourceInfo *DestroyedTypeInfo
12253       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
12254                                                 ObjectType, nullptr, SS);
12255     if (!DestroyedTypeInfo)
12256       return ExprError();
12257     Destroyed = DestroyedTypeInfo;
12258   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
12259     // We aren't likely to be able to resolve the identifier down to a type
12260     // now anyway, so just retain the identifier.
12261     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
12262                                             E->getDestroyedTypeLoc());
12263   } else {
12264     // Look for a destructor known with the given name.
12265     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
12266                                               *E->getDestroyedTypeIdentifier(),
12267                                                 E->getDestroyedTypeLoc(),
12268                                                 /*Scope=*/nullptr,
12269                                                 SS, ObjectTypePtr,
12270                                                 false);
12271     if (!T)
12272       return ExprError();
12273 
12274     Destroyed
12275       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
12276                                                  E->getDestroyedTypeLoc());
12277   }
12278 
12279   TypeSourceInfo *ScopeTypeInfo = nullptr;
12280   if (E->getScopeTypeInfo()) {
12281     CXXScopeSpec EmptySS;
12282     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12283                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12284     if (!ScopeTypeInfo)
12285       return ExprError();
12286   }
12287 
12288   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12289                                                      E->getOperatorLoc(),
12290                                                      E->isArrow(),
12291                                                      SS,
12292                                                      ScopeTypeInfo,
12293                                                      E->getColonColonLoc(),
12294                                                      E->getTildeLoc(),
12295                                                      Destroyed);
12296 }
12297 
12298 template <typename Derived>
12299 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12300                                                         bool RequiresADL,
12301                                                         LookupResult &R) {
12302   // Transform all the decls.
12303   bool AllEmptyPacks = true;
12304   for (auto *OldD : Old->decls()) {
12305     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12306     if (!InstD) {
12307       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12308       // This can happen because of dependent hiding.
12309       if (isa<UsingShadowDecl>(OldD))
12310         continue;
12311       else {
12312         R.clear();
12313         return true;
12314       }
12315     }
12316 
12317     // Expand using pack declarations.
12318     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12319     ArrayRef<NamedDecl*> Decls = SingleDecl;
12320     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12321       Decls = UPD->expansions();
12322 
12323     // Expand using declarations.
12324     for (auto *D : Decls) {
12325       if (auto *UD = dyn_cast<UsingDecl>(D)) {
12326         for (auto *SD : UD->shadows())
12327           R.addDecl(SD);
12328       } else {
12329         R.addDecl(D);
12330       }
12331     }
12332 
12333     AllEmptyPacks &= Decls.empty();
12334   };
12335 
12336   // C++ [temp.res]/8.4.2:
12337   //   The program is ill-formed, no diagnostic required, if [...] lookup for
12338   //   a name in the template definition found a using-declaration, but the
12339   //   lookup in the corresponding scope in the instantiation odoes not find
12340   //   any declarations because the using-declaration was a pack expansion and
12341   //   the corresponding pack is empty
12342   if (AllEmptyPacks && !RequiresADL) {
12343     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12344         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12345     return true;
12346   }
12347 
12348   // Resolve a kind, but don't do any further analysis.  If it's
12349   // ambiguous, the callee needs to deal with it.
12350   R.resolveKind();
12351   return false;
12352 }
12353 
12354 template<typename Derived>
12355 ExprResult
12356 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12357                                                   UnresolvedLookupExpr *Old) {
12358   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12359                  Sema::LookupOrdinaryName);
12360 
12361   // Transform the declaration set.
12362   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12363     return ExprError();
12364 
12365   // Rebuild the nested-name qualifier, if present.
12366   CXXScopeSpec SS;
12367   if (Old->getQualifierLoc()) {
12368     NestedNameSpecifierLoc QualifierLoc
12369       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12370     if (!QualifierLoc)
12371       return ExprError();
12372 
12373     SS.Adopt(QualifierLoc);
12374   }
12375 
12376   if (Old->getNamingClass()) {
12377     CXXRecordDecl *NamingClass
12378       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12379                                                             Old->getNameLoc(),
12380                                                         Old->getNamingClass()));
12381     if (!NamingClass) {
12382       R.clear();
12383       return ExprError();
12384     }
12385 
12386     R.setNamingClass(NamingClass);
12387   }
12388 
12389   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12390 
12391   // If we have neither explicit template arguments, nor the template keyword,
12392   // it's a normal declaration name or member reference.
12393   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12394     NamedDecl *D = R.getAsSingle<NamedDecl>();
12395     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12396     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12397     // give a good diagnostic.
12398     if (D && D->isCXXInstanceMember()) {
12399       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12400                                                      /*TemplateArgs=*/nullptr,
12401                                                      /*Scope=*/nullptr);
12402     }
12403 
12404     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12405   }
12406 
12407   // If we have template arguments, rebuild them, then rebuild the
12408   // templateid expression.
12409   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12410   if (Old->hasExplicitTemplateArgs() &&
12411       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12412                                               Old->getNumTemplateArgs(),
12413                                               TransArgs)) {
12414     R.clear();
12415     return ExprError();
12416   }
12417 
12418   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12419                                             Old->requiresADL(), &TransArgs);
12420 }
12421 
12422 template<typename Derived>
12423 ExprResult
12424 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12425   bool ArgChanged = false;
12426   SmallVector<TypeSourceInfo *, 4> Args;
12427   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12428     TypeSourceInfo *From = E->getArg(I);
12429     TypeLoc FromTL = From->getTypeLoc();
12430     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12431       TypeLocBuilder TLB;
12432       TLB.reserve(FromTL.getFullDataSize());
12433       QualType To = getDerived().TransformType(TLB, FromTL);
12434       if (To.isNull())
12435         return ExprError();
12436 
12437       if (To == From->getType())
12438         Args.push_back(From);
12439       else {
12440         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12441         ArgChanged = true;
12442       }
12443       continue;
12444     }
12445 
12446     ArgChanged = true;
12447 
12448     // We have a pack expansion. Instantiate it.
12449     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12450     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12451     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12452     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12453 
12454     // Determine whether the set of unexpanded parameter packs can and should
12455     // be expanded.
12456     bool Expand = true;
12457     bool RetainExpansion = false;
12458     Optional<unsigned> OrigNumExpansions =
12459         ExpansionTL.getTypePtr()->getNumExpansions();
12460     Optional<unsigned> NumExpansions = OrigNumExpansions;
12461     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12462                                              PatternTL.getSourceRange(),
12463                                              Unexpanded,
12464                                              Expand, RetainExpansion,
12465                                              NumExpansions))
12466       return ExprError();
12467 
12468     if (!Expand) {
12469       // The transform has determined that we should perform a simple
12470       // transformation on the pack expansion, producing another pack
12471       // expansion.
12472       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12473 
12474       TypeLocBuilder TLB;
12475       TLB.reserve(From->getTypeLoc().getFullDataSize());
12476 
12477       QualType To = getDerived().TransformType(TLB, PatternTL);
12478       if (To.isNull())
12479         return ExprError();
12480 
12481       To = getDerived().RebuildPackExpansionType(To,
12482                                                  PatternTL.getSourceRange(),
12483                                                  ExpansionTL.getEllipsisLoc(),
12484                                                  NumExpansions);
12485       if (To.isNull())
12486         return ExprError();
12487 
12488       PackExpansionTypeLoc ToExpansionTL
12489         = TLB.push<PackExpansionTypeLoc>(To);
12490       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12491       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12492       continue;
12493     }
12494 
12495     // Expand the pack expansion by substituting for each argument in the
12496     // pack(s).
12497     for (unsigned I = 0; I != *NumExpansions; ++I) {
12498       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12499       TypeLocBuilder TLB;
12500       TLB.reserve(PatternTL.getFullDataSize());
12501       QualType To = getDerived().TransformType(TLB, PatternTL);
12502       if (To.isNull())
12503         return ExprError();
12504 
12505       if (To->containsUnexpandedParameterPack()) {
12506         To = getDerived().RebuildPackExpansionType(To,
12507                                                    PatternTL.getSourceRange(),
12508                                                    ExpansionTL.getEllipsisLoc(),
12509                                                    NumExpansions);
12510         if (To.isNull())
12511           return ExprError();
12512 
12513         PackExpansionTypeLoc ToExpansionTL
12514           = TLB.push<PackExpansionTypeLoc>(To);
12515         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12516       }
12517 
12518       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12519     }
12520 
12521     if (!RetainExpansion)
12522       continue;
12523 
12524     // If we're supposed to retain a pack expansion, do so by temporarily
12525     // forgetting the partially-substituted parameter pack.
12526     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12527 
12528     TypeLocBuilder TLB;
12529     TLB.reserve(From->getTypeLoc().getFullDataSize());
12530 
12531     QualType To = getDerived().TransformType(TLB, PatternTL);
12532     if (To.isNull())
12533       return ExprError();
12534 
12535     To = getDerived().RebuildPackExpansionType(To,
12536                                                PatternTL.getSourceRange(),
12537                                                ExpansionTL.getEllipsisLoc(),
12538                                                NumExpansions);
12539     if (To.isNull())
12540       return ExprError();
12541 
12542     PackExpansionTypeLoc ToExpansionTL
12543       = TLB.push<PackExpansionTypeLoc>(To);
12544     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12545     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12546   }
12547 
12548   if (!getDerived().AlwaysRebuild() && !ArgChanged)
12549     return E;
12550 
12551   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12552                                        E->getEndLoc());
12553 }
12554 
12555 template<typename Derived>
12556 ExprResult
12557 TreeTransform<Derived>::TransformConceptSpecializationExpr(
12558                                                  ConceptSpecializationExpr *E) {
12559   const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12560   TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12561   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12562                                               Old->NumTemplateArgs, TransArgs))
12563     return ExprError();
12564 
12565   return getDerived().RebuildConceptSpecializationExpr(
12566       E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12567       E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12568       &TransArgs);
12569 }
12570 
12571 template<typename Derived>
12572 ExprResult
12573 TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12574   SmallVector<ParmVarDecl*, 4> TransParams;
12575   SmallVector<QualType, 4> TransParamTypes;
12576   Sema::ExtParameterInfoBuilder ExtParamInfos;
12577 
12578   // C++2a [expr.prim.req]p2
12579   // Expressions appearing within a requirement-body are unevaluated operands.
12580   EnterExpressionEvaluationContext Ctx(
12581       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12582 
12583   RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12584       getSema().Context, getSema().CurContext,
12585       E->getBody()->getBeginLoc());
12586 
12587   Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12588 
12589   if (getDerived().TransformFunctionTypeParams(E->getRequiresKWLoc(),
12590                                                E->getLocalParameters(),
12591                                                /*ParamTypes=*/nullptr,
12592                                                /*ParamInfos=*/nullptr,
12593                                                TransParamTypes, &TransParams,
12594                                                ExtParamInfos))
12595     return ExprError();
12596 
12597   for (ParmVarDecl *Param : TransParams)
12598     Param->setDeclContext(Body);
12599 
12600   SmallVector<concepts::Requirement *, 4> TransReqs;
12601   if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12602                                                      TransReqs))
12603     return ExprError();
12604 
12605   for (concepts::Requirement *Req : TransReqs) {
12606     if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12607       if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12608         ER->getReturnTypeRequirement()
12609                 .getTypeConstraintTemplateParameterList()->getParam(0)
12610                 ->setDeclContext(Body);
12611       }
12612     }
12613   }
12614 
12615   return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
12616                                           TransParams, TransReqs,
12617                                           E->getRBraceLoc());
12618 }
12619 
12620 template<typename Derived>
12621 bool TreeTransform<Derived>::TransformRequiresExprRequirements(
12622     ArrayRef<concepts::Requirement *> Reqs,
12623     SmallVectorImpl<concepts::Requirement *> &Transformed) {
12624   for (concepts::Requirement *Req : Reqs) {
12625     concepts::Requirement *TransReq = nullptr;
12626     if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
12627       TransReq = getDerived().TransformTypeRequirement(TypeReq);
12628     else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
12629       TransReq = getDerived().TransformExprRequirement(ExprReq);
12630     else
12631       TransReq = getDerived().TransformNestedRequirement(
12632                      cast<concepts::NestedRequirement>(Req));
12633     if (!TransReq)
12634       return true;
12635     Transformed.push_back(TransReq);
12636   }
12637   return false;
12638 }
12639 
12640 template<typename Derived>
12641 concepts::TypeRequirement *
12642 TreeTransform<Derived>::TransformTypeRequirement(
12643     concepts::TypeRequirement *Req) {
12644   if (Req->isSubstitutionFailure()) {
12645     if (getDerived().AlwaysRebuild())
12646       return getDerived().RebuildTypeRequirement(
12647               Req->getSubstitutionDiagnostic());
12648     return Req;
12649   }
12650   TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12651   if (!TransType)
12652     return nullptr;
12653   return getDerived().RebuildTypeRequirement(TransType);
12654 }
12655 
12656 template<typename Derived>
12657 concepts::ExprRequirement *
12658 TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12659   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12660   if (Req->isExprSubstitutionFailure())
12661     TransExpr = Req->getExprSubstitutionDiagnostic();
12662   else {
12663     ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12664     if (TransExprRes.isUsable() && TransExprRes.get()->hasPlaceholderType())
12665       TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
12666     if (TransExprRes.isInvalid())
12667       return nullptr;
12668     TransExpr = TransExprRes.get();
12669   }
12670 
12671   llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12672   const auto &RetReq = Req->getReturnTypeRequirement();
12673   if (RetReq.isEmpty())
12674     TransRetReq.emplace();
12675   else if (RetReq.isSubstitutionFailure())
12676     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12677   else if (RetReq.isTypeConstraint()) {
12678     TemplateParameterList *OrigTPL =
12679         RetReq.getTypeConstraintTemplateParameterList();
12680     TemplateParameterList *TPL =
12681         getDerived().TransformTemplateParameterList(OrigTPL);
12682     if (!TPL)
12683       return nullptr;
12684     TransRetReq.emplace(TPL);
12685   }
12686   assert(TransRetReq && "All code paths leading here must set TransRetReq");
12687   if (Expr *E = TransExpr.dyn_cast<Expr *>())
12688     return getDerived().RebuildExprRequirement(E, Req->isSimple(),
12689                                                Req->getNoexceptLoc(),
12690                                                std::move(*TransRetReq));
12691   return getDerived().RebuildExprRequirement(
12692       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
12693       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
12694 }
12695 
12696 template<typename Derived>
12697 concepts::NestedRequirement *
12698 TreeTransform<Derived>::TransformNestedRequirement(
12699     concepts::NestedRequirement *Req) {
12700   if (Req->isSubstitutionFailure()) {
12701     if (getDerived().AlwaysRebuild())
12702       return getDerived().RebuildNestedRequirement(
12703           Req->getSubstitutionDiagnostic());
12704     return Req;
12705   }
12706   ExprResult TransConstraint =
12707       getDerived().TransformExpr(Req->getConstraintExpr());
12708   if (TransConstraint.isInvalid())
12709     return nullptr;
12710   return getDerived().RebuildNestedRequirement(TransConstraint.get());
12711 }
12712 
12713 template<typename Derived>
12714 ExprResult
12715 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
12716   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
12717   if (!T)
12718     return ExprError();
12719 
12720   if (!getDerived().AlwaysRebuild() &&
12721       T == E->getQueriedTypeSourceInfo())
12722     return E;
12723 
12724   ExprResult SubExpr;
12725   {
12726     EnterExpressionEvaluationContext Unevaluated(
12727         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12728     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
12729     if (SubExpr.isInvalid())
12730       return ExprError();
12731 
12732     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
12733       return E;
12734   }
12735 
12736   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
12737                                             SubExpr.get(), E->getEndLoc());
12738 }
12739 
12740 template<typename Derived>
12741 ExprResult
12742 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
12743   ExprResult SubExpr;
12744   {
12745     EnterExpressionEvaluationContext Unevaluated(
12746         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12747     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
12748     if (SubExpr.isInvalid())
12749       return ExprError();
12750 
12751     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
12752       return E;
12753   }
12754 
12755   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
12756                                              SubExpr.get(), E->getEndLoc());
12757 }
12758 
12759 template <typename Derived>
12760 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
12761     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
12762     TypeSourceInfo **RecoveryTSI) {
12763   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
12764       DRE, AddrTaken, RecoveryTSI);
12765 
12766   // Propagate both errors and recovered types, which return ExprEmpty.
12767   if (!NewDRE.isUsable())
12768     return NewDRE;
12769 
12770   // We got an expr, wrap it up in parens.
12771   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
12772     return PE;
12773   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
12774                                        PE->getRParen());
12775 }
12776 
12777 template <typename Derived>
12778 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12779     DependentScopeDeclRefExpr *E) {
12780   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
12781                                             nullptr);
12782 }
12783 
12784 template <typename Derived>
12785 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
12786     DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
12787     TypeSourceInfo **RecoveryTSI) {
12788   assert(E->getQualifierLoc());
12789   NestedNameSpecifierLoc QualifierLoc =
12790       getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
12791   if (!QualifierLoc)
12792     return ExprError();
12793   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
12794 
12795   // TODO: If this is a conversion-function-id, verify that the
12796   // destination type name (if present) resolves the same way after
12797   // instantiation as it did in the local scope.
12798 
12799   DeclarationNameInfo NameInfo =
12800       getDerived().TransformDeclarationNameInfo(E->getNameInfo());
12801   if (!NameInfo.getName())
12802     return ExprError();
12803 
12804   if (!E->hasExplicitTemplateArgs()) {
12805     if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
12806         // Note: it is sufficient to compare the Name component of NameInfo:
12807         // if name has not changed, DNLoc has not changed either.
12808         NameInfo.getName() == E->getDeclName())
12809       return E;
12810 
12811     return getDerived().RebuildDependentScopeDeclRefExpr(
12812         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
12813         IsAddressOfOperand, RecoveryTSI);
12814   }
12815 
12816   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
12817   if (getDerived().TransformTemplateArguments(
12818           E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
12819     return ExprError();
12820 
12821   return getDerived().RebuildDependentScopeDeclRefExpr(
12822       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
12823       RecoveryTSI);
12824 }
12825 
12826 template<typename Derived>
12827 ExprResult
12828 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
12829   // CXXConstructExprs other than for list-initialization and
12830   // CXXTemporaryObjectExpr are always implicit, so when we have
12831   // a 1-argument construction we just transform that argument.
12832   if (getDerived().AllowSkippingCXXConstructExpr() &&
12833       ((E->getNumArgs() == 1 ||
12834         (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
12835        (!getDerived().DropCallArgument(E->getArg(0))) &&
12836        !E->isListInitialization()))
12837     return getDerived().TransformInitializer(E->getArg(0),
12838                                              /*DirectInit*/ false);
12839 
12840   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
12841 
12842   QualType T = getDerived().TransformType(E->getType());
12843   if (T.isNull())
12844     return ExprError();
12845 
12846   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12847       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12848   if (!Constructor)
12849     return ExprError();
12850 
12851   bool ArgumentChanged = false;
12852   SmallVector<Expr*, 8> Args;
12853   {
12854     EnterExpressionEvaluationContext Context(
12855         getSema(), EnterExpressionEvaluationContext::InitList,
12856         E->isListInitialization());
12857     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12858                                     &ArgumentChanged))
12859       return ExprError();
12860   }
12861 
12862   if (!getDerived().AlwaysRebuild() &&
12863       T == E->getType() &&
12864       Constructor == E->getConstructor() &&
12865       !ArgumentChanged) {
12866     // Mark the constructor as referenced.
12867     // FIXME: Instantiation-specific
12868     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12869     return E;
12870   }
12871 
12872   return getDerived().RebuildCXXConstructExpr(
12873       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
12874       E->hadMultipleCandidates(), E->isListInitialization(),
12875       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
12876       E->getConstructionKind(), E->getParenOrBraceRange());
12877 }
12878 
12879 template<typename Derived>
12880 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
12881     CXXInheritedCtorInitExpr *E) {
12882   QualType T = getDerived().TransformType(E->getType());
12883   if (T.isNull())
12884     return ExprError();
12885 
12886   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12887       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12888   if (!Constructor)
12889     return ExprError();
12890 
12891   if (!getDerived().AlwaysRebuild() &&
12892       T == E->getType() &&
12893       Constructor == E->getConstructor()) {
12894     // Mark the constructor as referenced.
12895     // FIXME: Instantiation-specific
12896     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12897     return E;
12898   }
12899 
12900   return getDerived().RebuildCXXInheritedCtorInitExpr(
12901       T, E->getLocation(), Constructor,
12902       E->constructsVBase(), E->inheritedFromVBase());
12903 }
12904 
12905 /// Transform a C++ temporary-binding expression.
12906 ///
12907 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
12908 /// transform the subexpression and return that.
12909 template<typename Derived>
12910 ExprResult
12911 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12912   if (auto *Dtor = E->getTemporary()->getDestructor())
12913     SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12914                                    const_cast<CXXDestructorDecl *>(Dtor));
12915   return getDerived().TransformExpr(E->getSubExpr());
12916 }
12917 
12918 /// Transform a C++ expression that contains cleanups that should
12919 /// be run after the expression is evaluated.
12920 ///
12921 /// Since ExprWithCleanups nodes are implicitly generated, we
12922 /// just transform the subexpression and return that.
12923 template<typename Derived>
12924 ExprResult
12925 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
12926   return getDerived().TransformExpr(E->getSubExpr());
12927 }
12928 
12929 template<typename Derived>
12930 ExprResult
12931 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
12932                                                     CXXTemporaryObjectExpr *E) {
12933   TypeSourceInfo *T =
12934       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
12935   if (!T)
12936     return ExprError();
12937 
12938   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
12939       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
12940   if (!Constructor)
12941     return ExprError();
12942 
12943   bool ArgumentChanged = false;
12944   SmallVector<Expr*, 8> Args;
12945   Args.reserve(E->getNumArgs());
12946   {
12947     EnterExpressionEvaluationContext Context(
12948         getSema(), EnterExpressionEvaluationContext::InitList,
12949         E->isListInitialization());
12950     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12951                        &ArgumentChanged))
12952       return ExprError();
12953   }
12954 
12955   if (!getDerived().AlwaysRebuild() &&
12956       T == E->getTypeSourceInfo() &&
12957       Constructor == E->getConstructor() &&
12958       !ArgumentChanged) {
12959     // FIXME: Instantiation-specific
12960     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
12961     return SemaRef.MaybeBindToTemporary(E);
12962   }
12963 
12964   // FIXME: We should just pass E->isListInitialization(), but we're not
12965   // prepared to handle list-initialization without a child InitListExpr.
12966   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
12967   return getDerived().RebuildCXXTemporaryObjectExpr(
12968       T, LParenLoc, Args, E->getEndLoc(),
12969       /*ListInitialization=*/LParenLoc.isInvalid());
12970 }
12971 
12972 template<typename Derived>
12973 ExprResult
12974 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
12975   // Transform any init-capture expressions before entering the scope of the
12976   // lambda body, because they are not semantically within that scope.
12977   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
12978   struct TransformedInitCapture {
12979     // The location of the ... if the result is retaining a pack expansion.
12980     SourceLocation EllipsisLoc;
12981     // Zero or more expansions of the init-capture.
12982     SmallVector<InitCaptureInfoTy, 4> Expansions;
12983   };
12984   SmallVector<TransformedInitCapture, 4> InitCaptures;
12985   InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
12986   for (LambdaExpr::capture_iterator C = E->capture_begin(),
12987                                     CEnd = E->capture_end();
12988        C != CEnd; ++C) {
12989     if (!E->isInitCapture(C))
12990       continue;
12991 
12992     TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
12993     VarDecl *OldVD = C->getCapturedVar();
12994 
12995     auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
12996                                 Optional<unsigned> NumExpansions) {
12997       ExprResult NewExprInitResult = getDerived().TransformInitializer(
12998           OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
12999 
13000       if (NewExprInitResult.isInvalid()) {
13001         Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
13002         return;
13003       }
13004       Expr *NewExprInit = NewExprInitResult.get();
13005 
13006       QualType NewInitCaptureType =
13007           getSema().buildLambdaInitCaptureInitialization(
13008               C->getLocation(), OldVD->getType()->isReferenceType(),
13009               EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
13010               C->getCapturedVar()->getInitStyle() != VarDecl::CInit,
13011               NewExprInit);
13012       Result.Expansions.push_back(
13013           InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
13014     };
13015 
13016     // If this is an init-capture pack, consider expanding the pack now.
13017     if (OldVD->isParameterPack()) {
13018       PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
13019                                              ->getTypeLoc()
13020                                              .castAs<PackExpansionTypeLoc>();
13021       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13022       SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
13023 
13024       // Determine whether the set of unexpanded parameter packs can and should
13025       // be expanded.
13026       bool Expand = true;
13027       bool RetainExpansion = false;
13028       Optional<unsigned> OrigNumExpansions =
13029           ExpansionTL.getTypePtr()->getNumExpansions();
13030       Optional<unsigned> NumExpansions = OrigNumExpansions;
13031       if (getDerived().TryExpandParameterPacks(
13032               ExpansionTL.getEllipsisLoc(),
13033               OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
13034               RetainExpansion, NumExpansions))
13035         return ExprError();
13036       if (Expand) {
13037         for (unsigned I = 0; I != *NumExpansions; ++I) {
13038           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13039           SubstInitCapture(SourceLocation(), None);
13040         }
13041       }
13042       if (!Expand || RetainExpansion) {
13043         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13044         SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
13045         Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
13046       }
13047     } else {
13048       SubstInitCapture(SourceLocation(), None);
13049     }
13050   }
13051 
13052   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
13053   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
13054 
13055   // Transform the template parameters, and add them to the current
13056   // instantiation scope. The null case is handled correctly.
13057   auto TPL = getDerived().TransformTemplateParameterList(
13058       E->getTemplateParameterList());
13059   LSI->GLTemplateParameterList = TPL;
13060 
13061   // Transform the type of the original lambda's call operator.
13062   // The transformation MUST be done in the CurrentInstantiationScope since
13063   // it introduces a mapping of the original to the newly created
13064   // transformed parameters.
13065   TypeSourceInfo *NewCallOpTSI = nullptr;
13066   {
13067     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
13068     FunctionProtoTypeLoc OldCallOpFPTL =
13069         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
13070 
13071     TypeLocBuilder NewCallOpTLBuilder;
13072     SmallVector<QualType, 4> ExceptionStorage;
13073     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
13074     QualType NewCallOpType = TransformFunctionProtoType(
13075         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
13076         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
13077           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
13078                                               ExceptionStorage, Changed);
13079         });
13080     if (NewCallOpType.isNull())
13081       return ExprError();
13082     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
13083                                                         NewCallOpType);
13084   }
13085 
13086   // Transform the trailing requires clause
13087   ExprResult NewTrailingRequiresClause;
13088   if (Expr *TRC = E->getCallOperator()->getTrailingRequiresClause())
13089     // FIXME: Concepts: Substitution into requires clause should only happen
13090     //                  when checking satisfaction.
13091     NewTrailingRequiresClause = getDerived().TransformExpr(TRC);
13092 
13093   // Create the local class that will describe the lambda.
13094 
13095   // FIXME: DependencyKind below is wrong when substituting inside a templated
13096   // context that isn't a DeclContext (such as a variable template), or when
13097   // substituting an unevaluated lambda inside of a function's parameter's type
13098   // - as parameter types are not instantiated from within a function's DC. We
13099   // use isUnevaluatedContext() to distinguish the function parameter case.
13100   CXXRecordDecl::LambdaDependencyKind DependencyKind =
13101       CXXRecordDecl::LDK_Unknown;
13102   if (getSema().isUnevaluatedContext() &&
13103       (getSema().CurContext->isFileContext() ||
13104        !getSema().CurContext->getParent()->isDependentContext()))
13105     DependencyKind = CXXRecordDecl::LDK_NeverDependent;
13106 
13107   CXXRecordDecl *OldClass = E->getLambdaClass();
13108   CXXRecordDecl *Class =
13109       getSema().createLambdaClosureType(E->getIntroducerRange(), NewCallOpTSI,
13110                                         DependencyKind, E->getCaptureDefault());
13111 
13112   getDerived().transformedLocalDecl(OldClass, {Class});
13113 
13114   Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling;
13115   if (getDerived().ReplacingOriginal())
13116     Mangling = std::make_tuple(OldClass->hasKnownLambdaInternalLinkage(),
13117                                OldClass->getLambdaManglingNumber(),
13118                                OldClass->getDeviceLambdaManglingNumber(),
13119                                OldClass->getLambdaContextDecl());
13120 
13121   // Build the call operator.
13122   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
13123       Class, E->getIntroducerRange(), NewCallOpTSI,
13124       E->getCallOperator()->getEndLoc(),
13125       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
13126       E->getCallOperator()->getConstexprKind(),
13127       NewTrailingRequiresClause.get());
13128 
13129   LSI->CallOperator = NewCallOperator;
13130 
13131   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
13132   getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
13133 
13134   // Number the lambda for linkage purposes if necessary.
13135   getSema().handleLambdaNumbering(Class, NewCallOperator, Mangling);
13136 
13137   // Introduce the context of the call operator.
13138   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
13139                                  /*NewThisContext*/false);
13140 
13141   // Enter the scope of the lambda.
13142   getSema().buildLambdaScope(LSI, NewCallOperator,
13143                              E->getIntroducerRange(),
13144                              E->getCaptureDefault(),
13145                              E->getCaptureDefaultLoc(),
13146                              E->hasExplicitParameters(),
13147                              E->hasExplicitResultType(),
13148                              E->isMutable());
13149 
13150   bool Invalid = false;
13151 
13152   // Transform captures.
13153   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13154                                  CEnd = E->capture_end();
13155        C != CEnd; ++C) {
13156     // When we hit the first implicit capture, tell Sema that we've finished
13157     // the list of explicit captures.
13158     if (C->isImplicit())
13159       break;
13160 
13161     // Capturing 'this' is trivial.
13162     if (C->capturesThis()) {
13163       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13164                                     /*BuildAndDiagnose*/ true, nullptr,
13165                                     C->getCaptureKind() == LCK_StarThis);
13166       continue;
13167     }
13168     // Captured expression will be recaptured during captured variables
13169     // rebuilding.
13170     if (C->capturesVLAType())
13171       continue;
13172 
13173     // Rebuild init-captures, including the implied field declaration.
13174     if (E->isInitCapture(C)) {
13175       TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
13176 
13177       VarDecl *OldVD = C->getCapturedVar();
13178       llvm::SmallVector<Decl*, 4> NewVDs;
13179 
13180       for (InitCaptureInfoTy &Info : NewC.Expansions) {
13181         ExprResult Init = Info.first;
13182         QualType InitQualType = Info.second;
13183         if (Init.isInvalid() || InitQualType.isNull()) {
13184           Invalid = true;
13185           break;
13186         }
13187         VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
13188             OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
13189             OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get());
13190         if (!NewVD) {
13191           Invalid = true;
13192           break;
13193         }
13194         NewVDs.push_back(NewVD);
13195         getSema().addInitCapture(LSI, NewVD);
13196       }
13197 
13198       if (Invalid)
13199         break;
13200 
13201       getDerived().transformedLocalDecl(OldVD, NewVDs);
13202       continue;
13203     }
13204 
13205     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13206 
13207     // Determine the capture kind for Sema.
13208     Sema::TryCaptureKind Kind
13209       = C->isImplicit()? Sema::TryCapture_Implicit
13210                        : C->getCaptureKind() == LCK_ByCopy
13211                            ? Sema::TryCapture_ExplicitByVal
13212                            : Sema::TryCapture_ExplicitByRef;
13213     SourceLocation EllipsisLoc;
13214     if (C->isPackExpansion()) {
13215       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
13216       bool ShouldExpand = false;
13217       bool RetainExpansion = false;
13218       Optional<unsigned> NumExpansions;
13219       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
13220                                                C->getLocation(),
13221                                                Unexpanded,
13222                                                ShouldExpand, RetainExpansion,
13223                                                NumExpansions)) {
13224         Invalid = true;
13225         continue;
13226       }
13227 
13228       if (ShouldExpand) {
13229         // The transform has determined that we should perform an expansion;
13230         // transform and capture each of the arguments.
13231         // expansion of the pattern. Do so.
13232         VarDecl *Pack = C->getCapturedVar();
13233         for (unsigned I = 0; I != *NumExpansions; ++I) {
13234           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13235           VarDecl *CapturedVar
13236             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13237                                                                Pack));
13238           if (!CapturedVar) {
13239             Invalid = true;
13240             continue;
13241           }
13242 
13243           // Capture the transformed variable.
13244           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
13245         }
13246 
13247         // FIXME: Retain a pack expansion if RetainExpansion is true.
13248 
13249         continue;
13250       }
13251 
13252       EllipsisLoc = C->getEllipsisLoc();
13253     }
13254 
13255     // Transform the captured variable.
13256     VarDecl *CapturedVar
13257       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13258                                                          C->getCapturedVar()));
13259     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
13260       Invalid = true;
13261       continue;
13262     }
13263 
13264     // Capture the transformed variable.
13265     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
13266                                  EllipsisLoc);
13267   }
13268   getSema().finishLambdaExplicitCaptures(LSI);
13269 
13270   // FIXME: Sema's lambda-building mechanism expects us to push an expression
13271   // evaluation context even if we're not transforming the function body.
13272   getSema().PushExpressionEvaluationContext(
13273       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13274 
13275   // Instantiate the body of the lambda expression.
13276   StmtResult Body =
13277       Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
13278 
13279   // ActOnLambda* will pop the function scope for us.
13280   FuncScopeCleanup.disable();
13281 
13282   if (Body.isInvalid()) {
13283     SavedContext.pop();
13284     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
13285                                /*IsInstantiation=*/true);
13286     return ExprError();
13287   }
13288 
13289   // Copy the LSI before ActOnFinishFunctionBody removes it.
13290   // FIXME: This is dumb. Store the lambda information somewhere that outlives
13291   // the call operator.
13292   auto LSICopy = *LSI;
13293   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
13294                                     /*IsInstantiation*/ true);
13295   SavedContext.pop();
13296 
13297   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13298                                    &LSICopy);
13299 }
13300 
13301 template<typename Derived>
13302 StmtResult
13303 TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13304   return TransformStmt(S);
13305 }
13306 
13307 template<typename Derived>
13308 StmtResult
13309 TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13310   // Transform captures.
13311   for (LambdaExpr::capture_iterator C = E->capture_begin(),
13312                                  CEnd = E->capture_end();
13313        C != CEnd; ++C) {
13314     // When we hit the first implicit capture, tell Sema that we've finished
13315     // the list of explicit captures.
13316     if (!C->isImplicit())
13317       continue;
13318 
13319     // Capturing 'this' is trivial.
13320     if (C->capturesThis()) {
13321       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13322                                     /*BuildAndDiagnose*/ true, nullptr,
13323                                     C->getCaptureKind() == LCK_StarThis);
13324       continue;
13325     }
13326     // Captured expression will be recaptured during captured variables
13327     // rebuilding.
13328     if (C->capturesVLAType())
13329       continue;
13330 
13331     assert(C->capturesVariable() && "unexpected kind of lambda capture");
13332     assert(!E->isInitCapture(C) && "implicit init-capture?");
13333 
13334     // Transform the captured variable.
13335     VarDecl *CapturedVar = cast_or_null<VarDecl>(
13336         getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13337     if (!CapturedVar || CapturedVar->isInvalidDecl())
13338       return StmtError();
13339 
13340     // Capture the transformed variable.
13341     getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13342   }
13343 
13344   return S;
13345 }
13346 
13347 template<typename Derived>
13348 ExprResult
13349 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13350                                                   CXXUnresolvedConstructExpr *E) {
13351   TypeSourceInfo *T =
13352       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13353   if (!T)
13354     return ExprError();
13355 
13356   bool ArgumentChanged = false;
13357   SmallVector<Expr*, 8> Args;
13358   Args.reserve(E->getNumArgs());
13359   {
13360     EnterExpressionEvaluationContext Context(
13361         getSema(), EnterExpressionEvaluationContext::InitList,
13362         E->isListInitialization());
13363     if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13364                                     &ArgumentChanged))
13365       return ExprError();
13366   }
13367 
13368   if (!getDerived().AlwaysRebuild() &&
13369       T == E->getTypeSourceInfo() &&
13370       !ArgumentChanged)
13371     return E;
13372 
13373   // FIXME: we're faking the locations of the commas
13374   return getDerived().RebuildCXXUnresolvedConstructExpr(
13375       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13376 }
13377 
13378 template<typename Derived>
13379 ExprResult
13380 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13381                                              CXXDependentScopeMemberExpr *E) {
13382   // Transform the base of the expression.
13383   ExprResult Base((Expr*) nullptr);
13384   Expr *OldBase;
13385   QualType BaseType;
13386   QualType ObjectType;
13387   if (!E->isImplicitAccess()) {
13388     OldBase = E->getBase();
13389     Base = getDerived().TransformExpr(OldBase);
13390     if (Base.isInvalid())
13391       return ExprError();
13392 
13393     // Start the member reference and compute the object's type.
13394     ParsedType ObjectTy;
13395     bool MayBePseudoDestructor = false;
13396     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13397                                                 E->getOperatorLoc(),
13398                                       E->isArrow()? tok::arrow : tok::period,
13399                                                 ObjectTy,
13400                                                 MayBePseudoDestructor);
13401     if (Base.isInvalid())
13402       return ExprError();
13403 
13404     ObjectType = ObjectTy.get();
13405     BaseType = ((Expr*) Base.get())->getType();
13406   } else {
13407     OldBase = nullptr;
13408     BaseType = getDerived().TransformType(E->getBaseType());
13409     ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13410   }
13411 
13412   // Transform the first part of the nested-name-specifier that qualifies
13413   // the member name.
13414   NamedDecl *FirstQualifierInScope
13415     = getDerived().TransformFirstQualifierInScope(
13416                                             E->getFirstQualifierFoundInScope(),
13417                                             E->getQualifierLoc().getBeginLoc());
13418 
13419   NestedNameSpecifierLoc QualifierLoc;
13420   if (E->getQualifier()) {
13421     QualifierLoc
13422       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13423                                                      ObjectType,
13424                                                      FirstQualifierInScope);
13425     if (!QualifierLoc)
13426       return ExprError();
13427   }
13428 
13429   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13430 
13431   // TODO: If this is a conversion-function-id, verify that the
13432   // destination type name (if present) resolves the same way after
13433   // instantiation as it did in the local scope.
13434 
13435   DeclarationNameInfo NameInfo
13436     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13437   if (!NameInfo.getName())
13438     return ExprError();
13439 
13440   if (!E->hasExplicitTemplateArgs()) {
13441     // This is a reference to a member without an explicitly-specified
13442     // template argument list. Optimize for this common case.
13443     if (!getDerived().AlwaysRebuild() &&
13444         Base.get() == OldBase &&
13445         BaseType == E->getBaseType() &&
13446         QualifierLoc == E->getQualifierLoc() &&
13447         NameInfo.getName() == E->getMember() &&
13448         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13449       return E;
13450 
13451     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13452                                                        BaseType,
13453                                                        E->isArrow(),
13454                                                        E->getOperatorLoc(),
13455                                                        QualifierLoc,
13456                                                        TemplateKWLoc,
13457                                                        FirstQualifierInScope,
13458                                                        NameInfo,
13459                                                        /*TemplateArgs*/nullptr);
13460   }
13461 
13462   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13463   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13464                                               E->getNumTemplateArgs(),
13465                                               TransArgs))
13466     return ExprError();
13467 
13468   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13469                                                      BaseType,
13470                                                      E->isArrow(),
13471                                                      E->getOperatorLoc(),
13472                                                      QualifierLoc,
13473                                                      TemplateKWLoc,
13474                                                      FirstQualifierInScope,
13475                                                      NameInfo,
13476                                                      &TransArgs);
13477 }
13478 
13479 template <typename Derived>
13480 ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13481     UnresolvedMemberExpr *Old) {
13482   // Transform the base of the expression.
13483   ExprResult Base((Expr *)nullptr);
13484   QualType BaseType;
13485   if (!Old->isImplicitAccess()) {
13486     Base = getDerived().TransformExpr(Old->getBase());
13487     if (Base.isInvalid())
13488       return ExprError();
13489     Base =
13490         getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13491     if (Base.isInvalid())
13492       return ExprError();
13493     BaseType = Base.get()->getType();
13494   } else {
13495     BaseType = getDerived().TransformType(Old->getBaseType());
13496   }
13497 
13498   NestedNameSpecifierLoc QualifierLoc;
13499   if (Old->getQualifierLoc()) {
13500     QualifierLoc =
13501         getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13502     if (!QualifierLoc)
13503       return ExprError();
13504   }
13505 
13506   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13507 
13508   LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13509 
13510   // Transform the declaration set.
13511   if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13512     return ExprError();
13513 
13514   // Determine the naming class.
13515   if (Old->getNamingClass()) {
13516     CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13517         getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13518     if (!NamingClass)
13519       return ExprError();
13520 
13521     R.setNamingClass(NamingClass);
13522   }
13523 
13524   TemplateArgumentListInfo TransArgs;
13525   if (Old->hasExplicitTemplateArgs()) {
13526     TransArgs.setLAngleLoc(Old->getLAngleLoc());
13527     TransArgs.setRAngleLoc(Old->getRAngleLoc());
13528     if (getDerived().TransformTemplateArguments(
13529             Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13530       return ExprError();
13531   }
13532 
13533   // FIXME: to do this check properly, we will need to preserve the
13534   // first-qualifier-in-scope here, just in case we had a dependent
13535   // base (and therefore couldn't do the check) and a
13536   // nested-name-qualifier (and therefore could do the lookup).
13537   NamedDecl *FirstQualifierInScope = nullptr;
13538 
13539   return getDerived().RebuildUnresolvedMemberExpr(
13540       Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13541       TemplateKWLoc, FirstQualifierInScope, R,
13542       (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13543 }
13544 
13545 template<typename Derived>
13546 ExprResult
13547 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13548   EnterExpressionEvaluationContext Unevaluated(
13549       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13550   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13551   if (SubExpr.isInvalid())
13552     return ExprError();
13553 
13554   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13555     return E;
13556 
13557   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13558 }
13559 
13560 template<typename Derived>
13561 ExprResult
13562 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13563   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13564   if (Pattern.isInvalid())
13565     return ExprError();
13566 
13567   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13568     return E;
13569 
13570   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13571                                            E->getNumExpansions());
13572 }
13573 
13574 template<typename Derived>
13575 ExprResult
13576 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13577   // If E is not value-dependent, then nothing will change when we transform it.
13578   // Note: This is an instantiation-centric view.
13579   if (!E->isValueDependent())
13580     return E;
13581 
13582   EnterExpressionEvaluationContext Unevaluated(
13583       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
13584 
13585   ArrayRef<TemplateArgument> PackArgs;
13586   TemplateArgument ArgStorage;
13587 
13588   // Find the argument list to transform.
13589   if (E->isPartiallySubstituted()) {
13590     PackArgs = E->getPartialArguments();
13591   } else if (E->isValueDependent()) {
13592     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
13593     bool ShouldExpand = false;
13594     bool RetainExpansion = false;
13595     Optional<unsigned> NumExpansions;
13596     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
13597                                              Unexpanded,
13598                                              ShouldExpand, RetainExpansion,
13599                                              NumExpansions))
13600       return ExprError();
13601 
13602     // If we need to expand the pack, build a template argument from it and
13603     // expand that.
13604     if (ShouldExpand) {
13605       auto *Pack = E->getPack();
13606       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
13607         ArgStorage = getSema().Context.getPackExpansionType(
13608             getSema().Context.getTypeDeclType(TTPD), None);
13609       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
13610         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
13611       } else {
13612         auto *VD = cast<ValueDecl>(Pack);
13613         ExprResult DRE = getSema().BuildDeclRefExpr(
13614             VD, VD->getType().getNonLValueExprType(getSema().Context),
13615             VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
13616             E->getPackLoc());
13617         if (DRE.isInvalid())
13618           return ExprError();
13619         ArgStorage = new (getSema().Context) PackExpansionExpr(
13620             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
13621       }
13622       PackArgs = ArgStorage;
13623     }
13624   }
13625 
13626   // If we're not expanding the pack, just transform the decl.
13627   if (!PackArgs.size()) {
13628     auto *Pack = cast_or_null<NamedDecl>(
13629         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
13630     if (!Pack)
13631       return ExprError();
13632     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
13633                                               E->getPackLoc(),
13634                                               E->getRParenLoc(), None, None);
13635   }
13636 
13637   // Try to compute the result without performing a partial substitution.
13638   Optional<unsigned> Result = 0;
13639   for (const TemplateArgument &Arg : PackArgs) {
13640     if (!Arg.isPackExpansion()) {
13641       Result = *Result + 1;
13642       continue;
13643     }
13644 
13645     TemplateArgumentLoc ArgLoc;
13646     InventTemplateArgumentLoc(Arg, ArgLoc);
13647 
13648     // Find the pattern of the pack expansion.
13649     SourceLocation Ellipsis;
13650     Optional<unsigned> OrigNumExpansions;
13651     TemplateArgumentLoc Pattern =
13652         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13653                                                           OrigNumExpansions);
13654 
13655     // Substitute under the pack expansion. Do not expand the pack (yet).
13656     TemplateArgumentLoc OutPattern;
13657     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13658     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13659                                                /*Uneval*/ true))
13660       return true;
13661 
13662     // See if we can determine the number of arguments from the result.
13663     Optional<unsigned> NumExpansions =
13664         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13665     if (!NumExpansions) {
13666       // No: we must be in an alias template expansion, and we're going to need
13667       // to actually expand the packs.
13668       Result = None;
13669       break;
13670     }
13671 
13672     Result = *Result + *NumExpansions;
13673   }
13674 
13675   // Common case: we could determine the number of expansions without
13676   // substituting.
13677   if (Result)
13678     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13679                                               E->getPackLoc(),
13680                                               E->getRParenLoc(), *Result, None);
13681 
13682   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13683                                                E->getPackLoc());
13684   {
13685     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
13686     typedef TemplateArgumentLocInventIterator<
13687         Derived, const TemplateArgument*> PackLocIterator;
13688     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
13689                                    PackLocIterator(*this, PackArgs.end()),
13690                                    TransformedPackArgs, /*Uneval*/true))
13691       return ExprError();
13692   }
13693 
13694   // Check whether we managed to fully-expand the pack.
13695   // FIXME: Is it possible for us to do so and not hit the early exit path?
13696   SmallVector<TemplateArgument, 8> Args;
13697   bool PartialSubstitution = false;
13698   for (auto &Loc : TransformedPackArgs.arguments()) {
13699     Args.push_back(Loc.getArgument());
13700     if (Loc.getArgument().isPackExpansion())
13701       PartialSubstitution = true;
13702   }
13703 
13704   if (PartialSubstitution)
13705     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13706                                               E->getPackLoc(),
13707                                               E->getRParenLoc(), None, Args);
13708 
13709   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13710                                             E->getPackLoc(), E->getRParenLoc(),
13711                                             Args.size(), None);
13712 }
13713 
13714 template<typename Derived>
13715 ExprResult
13716 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
13717                                           SubstNonTypeTemplateParmPackExpr *E) {
13718   // Default behavior is to do nothing with this transformation.
13719   return E;
13720 }
13721 
13722 template<typename Derived>
13723 ExprResult
13724 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
13725                                           SubstNonTypeTemplateParmExpr *E) {
13726   // Default behavior is to do nothing with this transformation.
13727   return E;
13728 }
13729 
13730 template<typename Derived>
13731 ExprResult
13732 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
13733   // Default behavior is to do nothing with this transformation.
13734   return E;
13735 }
13736 
13737 template<typename Derived>
13738 ExprResult
13739 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
13740                                                   MaterializeTemporaryExpr *E) {
13741   return getDerived().TransformExpr(E->getSubExpr());
13742 }
13743 
13744 template<typename Derived>
13745 ExprResult
13746 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
13747   UnresolvedLookupExpr *Callee = nullptr;
13748   if (Expr *OldCallee = E->getCallee()) {
13749     ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
13750     if (CalleeResult.isInvalid())
13751       return ExprError();
13752     Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
13753   }
13754 
13755   Expr *Pattern = E->getPattern();
13756 
13757   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13758   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
13759   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
13760 
13761   // Determine whether the set of unexpanded parameter packs can and should
13762   // be expanded.
13763   bool Expand = true;
13764   bool RetainExpansion = false;
13765   Optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
13766                      NumExpansions = OrigNumExpansions;
13767   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
13768                                            Pattern->getSourceRange(),
13769                                            Unexpanded,
13770                                            Expand, RetainExpansion,
13771                                            NumExpansions))
13772     return true;
13773 
13774   if (!Expand) {
13775     // Do not expand any packs here, just transform and rebuild a fold
13776     // expression.
13777     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13778 
13779     ExprResult LHS =
13780         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
13781     if (LHS.isInvalid())
13782       return true;
13783 
13784     ExprResult RHS =
13785         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
13786     if (RHS.isInvalid())
13787       return true;
13788 
13789     if (!getDerived().AlwaysRebuild() &&
13790         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
13791       return E;
13792 
13793     return getDerived().RebuildCXXFoldExpr(
13794         Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
13795         E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
13796   }
13797 
13798   // Formally a fold expression expands to nested parenthesized expressions.
13799   // Enforce this limit to avoid creating trees so deep we can't safely traverse
13800   // them.
13801   if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
13802     SemaRef.Diag(E->getEllipsisLoc(),
13803                  clang::diag::err_fold_expression_limit_exceeded)
13804         << *NumExpansions << SemaRef.getLangOpts().BracketDepth
13805         << E->getSourceRange();
13806     SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
13807     return ExprError();
13808   }
13809 
13810   // The transform has determined that we should perform an elementwise
13811   // expansion of the pattern. Do so.
13812   ExprResult Result = getDerived().TransformExpr(E->getInit());
13813   if (Result.isInvalid())
13814     return true;
13815   bool LeftFold = E->isLeftFold();
13816 
13817   // If we're retaining an expansion for a right fold, it is the innermost
13818   // component and takes the init (if any).
13819   if (!LeftFold && RetainExpansion) {
13820     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13821 
13822     ExprResult Out = getDerived().TransformExpr(Pattern);
13823     if (Out.isInvalid())
13824       return true;
13825 
13826     Result = getDerived().RebuildCXXFoldExpr(
13827         Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
13828         E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
13829     if (Result.isInvalid())
13830       return true;
13831   }
13832 
13833   for (unsigned I = 0; I != *NumExpansions; ++I) {
13834     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
13835         getSema(), LeftFold ? I : *NumExpansions - I - 1);
13836     ExprResult Out = getDerived().TransformExpr(Pattern);
13837     if (Out.isInvalid())
13838       return true;
13839 
13840     if (Out.get()->containsUnexpandedParameterPack()) {
13841       // We still have a pack; retain a pack expansion for this slice.
13842       Result = getDerived().RebuildCXXFoldExpr(
13843           Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
13844           E->getOperator(), E->getEllipsisLoc(),
13845           LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
13846           OrigNumExpansions);
13847     } else if (Result.isUsable()) {
13848       // We've got down to a single element; build a binary operator.
13849       Expr *LHS = LeftFold ? Result.get() : Out.get();
13850       Expr *RHS = LeftFold ? Out.get() : Result.get();
13851       if (Callee)
13852         Result = getDerived().RebuildCXXOperatorCallExpr(
13853             BinaryOperator::getOverloadedOperator(E->getOperator()),
13854             E->getEllipsisLoc(), Callee, LHS, RHS);
13855       else
13856         Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
13857                                                     E->getOperator(), LHS, RHS);
13858     } else
13859       Result = Out;
13860 
13861     if (Result.isInvalid())
13862       return true;
13863   }
13864 
13865   // If we're retaining an expansion for a left fold, it is the outermost
13866   // component and takes the complete expansion so far as its init (if any).
13867   if (LeftFold && RetainExpansion) {
13868     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13869 
13870     ExprResult Out = getDerived().TransformExpr(Pattern);
13871     if (Out.isInvalid())
13872       return true;
13873 
13874     Result = getDerived().RebuildCXXFoldExpr(
13875         Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
13876         E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
13877     if (Result.isInvalid())
13878       return true;
13879   }
13880 
13881   // If we had no init and an empty pack, and we're not retaining an expansion,
13882   // then produce a fallback value or error.
13883   if (Result.isUnset())
13884     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
13885                                                 E->getOperator());
13886 
13887   return Result;
13888 }
13889 
13890 template<typename Derived>
13891 ExprResult
13892 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
13893     CXXStdInitializerListExpr *E) {
13894   return getDerived().TransformExpr(E->getSubExpr());
13895 }
13896 
13897 template<typename Derived>
13898 ExprResult
13899 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
13900   return SemaRef.MaybeBindToTemporary(E);
13901 }
13902 
13903 template<typename Derived>
13904 ExprResult
13905 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
13906   return E;
13907 }
13908 
13909 template<typename Derived>
13910 ExprResult
13911 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
13912   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
13913   if (SubExpr.isInvalid())
13914     return ExprError();
13915 
13916   if (!getDerived().AlwaysRebuild() &&
13917       SubExpr.get() == E->getSubExpr())
13918     return E;
13919 
13920   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
13921 }
13922 
13923 template<typename Derived>
13924 ExprResult
13925 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
13926   // Transform each of the elements.
13927   SmallVector<Expr *, 8> Elements;
13928   bool ArgChanged = false;
13929   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
13930                                   /*IsCall=*/false, Elements, &ArgChanged))
13931     return ExprError();
13932 
13933   if (!getDerived().AlwaysRebuild() && !ArgChanged)
13934     return SemaRef.MaybeBindToTemporary(E);
13935 
13936   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
13937                                               Elements.data(),
13938                                               Elements.size());
13939 }
13940 
13941 template<typename Derived>
13942 ExprResult
13943 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
13944                                                     ObjCDictionaryLiteral *E) {
13945   // Transform each of the elements.
13946   SmallVector<ObjCDictionaryElement, 8> Elements;
13947   bool ArgChanged = false;
13948   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
13949     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
13950 
13951     if (OrigElement.isPackExpansion()) {
13952       // This key/value element is a pack expansion.
13953       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13954       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
13955       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
13956       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
13957 
13958       // Determine whether the set of unexpanded parameter packs can
13959       // and should be expanded.
13960       bool Expand = true;
13961       bool RetainExpansion = false;
13962       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
13963       Optional<unsigned> NumExpansions = OrigNumExpansions;
13964       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
13965                                OrigElement.Value->getEndLoc());
13966       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
13967                                                PatternRange, Unexpanded, Expand,
13968                                                RetainExpansion, NumExpansions))
13969         return ExprError();
13970 
13971       if (!Expand) {
13972         // The transform has determined that we should perform a simple
13973         // transformation on the pack expansion, producing another pack
13974         // expansion.
13975         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13976         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
13977         if (Key.isInvalid())
13978           return ExprError();
13979 
13980         if (Key.get() != OrigElement.Key)
13981           ArgChanged = true;
13982 
13983         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
13984         if (Value.isInvalid())
13985           return ExprError();
13986 
13987         if (Value.get() != OrigElement.Value)
13988           ArgChanged = true;
13989 
13990         ObjCDictionaryElement Expansion = {
13991           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
13992         };
13993         Elements.push_back(Expansion);
13994         continue;
13995       }
13996 
13997       // Record right away that the argument was changed.  This needs
13998       // to happen even if the array expands to nothing.
13999       ArgChanged = true;
14000 
14001       // The transform has determined that we should perform an elementwise
14002       // expansion of the pattern. Do so.
14003       for (unsigned I = 0; I != *NumExpansions; ++I) {
14004         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
14005         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14006         if (Key.isInvalid())
14007           return ExprError();
14008 
14009         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14010         if (Value.isInvalid())
14011           return ExprError();
14012 
14013         ObjCDictionaryElement Element = {
14014           Key.get(), Value.get(), SourceLocation(), NumExpansions
14015         };
14016 
14017         // If any unexpanded parameter packs remain, we still have a
14018         // pack expansion.
14019         // FIXME: Can this really happen?
14020         if (Key.get()->containsUnexpandedParameterPack() ||
14021             Value.get()->containsUnexpandedParameterPack())
14022           Element.EllipsisLoc = OrigElement.EllipsisLoc;
14023 
14024         Elements.push_back(Element);
14025       }
14026 
14027       // FIXME: Retain a pack expansion if RetainExpansion is true.
14028 
14029       // We've finished with this pack expansion.
14030       continue;
14031     }
14032 
14033     // Transform and check key.
14034     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14035     if (Key.isInvalid())
14036       return ExprError();
14037 
14038     if (Key.get() != OrigElement.Key)
14039       ArgChanged = true;
14040 
14041     // Transform and check value.
14042     ExprResult Value
14043       = getDerived().TransformExpr(OrigElement.Value);
14044     if (Value.isInvalid())
14045       return ExprError();
14046 
14047     if (Value.get() != OrigElement.Value)
14048       ArgChanged = true;
14049 
14050     ObjCDictionaryElement Element = {
14051       Key.get(), Value.get(), SourceLocation(), None
14052     };
14053     Elements.push_back(Element);
14054   }
14055 
14056   if (!getDerived().AlwaysRebuild() && !ArgChanged)
14057     return SemaRef.MaybeBindToTemporary(E);
14058 
14059   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
14060                                                    Elements);
14061 }
14062 
14063 template<typename Derived>
14064 ExprResult
14065 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
14066   TypeSourceInfo *EncodedTypeInfo
14067     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
14068   if (!EncodedTypeInfo)
14069     return ExprError();
14070 
14071   if (!getDerived().AlwaysRebuild() &&
14072       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
14073     return E;
14074 
14075   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
14076                                             EncodedTypeInfo,
14077                                             E->getRParenLoc());
14078 }
14079 
14080 template<typename Derived>
14081 ExprResult TreeTransform<Derived>::
14082 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
14083   // This is a kind of implicit conversion, and it needs to get dropped
14084   // and recomputed for the same general reasons that ImplicitCastExprs
14085   // do, as well a more specific one: this expression is only valid when
14086   // it appears *immediately* as an argument expression.
14087   return getDerived().TransformExpr(E->getSubExpr());
14088 }
14089 
14090 template<typename Derived>
14091 ExprResult TreeTransform<Derived>::
14092 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
14093   TypeSourceInfo *TSInfo
14094     = getDerived().TransformType(E->getTypeInfoAsWritten());
14095   if (!TSInfo)
14096     return ExprError();
14097 
14098   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
14099   if (Result.isInvalid())
14100     return ExprError();
14101 
14102   if (!getDerived().AlwaysRebuild() &&
14103       TSInfo == E->getTypeInfoAsWritten() &&
14104       Result.get() == E->getSubExpr())
14105     return E;
14106 
14107   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
14108                                       E->getBridgeKeywordLoc(), TSInfo,
14109                                       Result.get());
14110 }
14111 
14112 template <typename Derived>
14113 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
14114     ObjCAvailabilityCheckExpr *E) {
14115   return E;
14116 }
14117 
14118 template<typename Derived>
14119 ExprResult
14120 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
14121   // Transform arguments.
14122   bool ArgChanged = false;
14123   SmallVector<Expr*, 8> Args;
14124   Args.reserve(E->getNumArgs());
14125   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
14126                                   &ArgChanged))
14127     return ExprError();
14128 
14129   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
14130     // Class message: transform the receiver type.
14131     TypeSourceInfo *ReceiverTypeInfo
14132       = getDerived().TransformType(E->getClassReceiverTypeInfo());
14133     if (!ReceiverTypeInfo)
14134       return ExprError();
14135 
14136     // If nothing changed, just retain the existing message send.
14137     if (!getDerived().AlwaysRebuild() &&
14138         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
14139       return SemaRef.MaybeBindToTemporary(E);
14140 
14141     // Build a new class message send.
14142     SmallVector<SourceLocation, 16> SelLocs;
14143     E->getSelectorLocs(SelLocs);
14144     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
14145                                                E->getSelector(),
14146                                                SelLocs,
14147                                                E->getMethodDecl(),
14148                                                E->getLeftLoc(),
14149                                                Args,
14150                                                E->getRightLoc());
14151   }
14152   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
14153            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14154     if (!E->getMethodDecl())
14155       return ExprError();
14156 
14157     // Build a new class message send to 'super'.
14158     SmallVector<SourceLocation, 16> SelLocs;
14159     E->getSelectorLocs(SelLocs);
14160     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
14161                                                E->getSelector(),
14162                                                SelLocs,
14163                                                E->getReceiverType(),
14164                                                E->getMethodDecl(),
14165                                                E->getLeftLoc(),
14166                                                Args,
14167                                                E->getRightLoc());
14168   }
14169 
14170   // Instance message: transform the receiver
14171   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
14172          "Only class and instance messages may be instantiated");
14173   ExprResult Receiver
14174     = getDerived().TransformExpr(E->getInstanceReceiver());
14175   if (Receiver.isInvalid())
14176     return ExprError();
14177 
14178   // If nothing changed, just retain the existing message send.
14179   if (!getDerived().AlwaysRebuild() &&
14180       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
14181     return SemaRef.MaybeBindToTemporary(E);
14182 
14183   // Build a new instance message send.
14184   SmallVector<SourceLocation, 16> SelLocs;
14185   E->getSelectorLocs(SelLocs);
14186   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
14187                                              E->getSelector(),
14188                                              SelLocs,
14189                                              E->getMethodDecl(),
14190                                              E->getLeftLoc(),
14191                                              Args,
14192                                              E->getRightLoc());
14193 }
14194 
14195 template<typename Derived>
14196 ExprResult
14197 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
14198   return E;
14199 }
14200 
14201 template<typename Derived>
14202 ExprResult
14203 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
14204   return E;
14205 }
14206 
14207 template<typename Derived>
14208 ExprResult
14209 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
14210   // Transform the base expression.
14211   ExprResult Base = getDerived().TransformExpr(E->getBase());
14212   if (Base.isInvalid())
14213     return ExprError();
14214 
14215   // We don't need to transform the ivar; it will never change.
14216 
14217   // If nothing changed, just retain the existing expression.
14218   if (!getDerived().AlwaysRebuild() &&
14219       Base.get() == E->getBase())
14220     return E;
14221 
14222   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
14223                                              E->getLocation(),
14224                                              E->isArrow(), E->isFreeIvar());
14225 }
14226 
14227 template<typename Derived>
14228 ExprResult
14229 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
14230   // 'super' and types never change. Property never changes. Just
14231   // retain the existing expression.
14232   if (!E->isObjectReceiver())
14233     return E;
14234 
14235   // Transform the base expression.
14236   ExprResult Base = getDerived().TransformExpr(E->getBase());
14237   if (Base.isInvalid())
14238     return ExprError();
14239 
14240   // We don't need to transform the property; it will never change.
14241 
14242   // If nothing changed, just retain the existing expression.
14243   if (!getDerived().AlwaysRebuild() &&
14244       Base.get() == E->getBase())
14245     return E;
14246 
14247   if (E->isExplicitProperty())
14248     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14249                                                    E->getExplicitProperty(),
14250                                                    E->getLocation());
14251 
14252   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14253                                                  SemaRef.Context.PseudoObjectTy,
14254                                                  E->getImplicitPropertyGetter(),
14255                                                  E->getImplicitPropertySetter(),
14256                                                  E->getLocation());
14257 }
14258 
14259 template<typename Derived>
14260 ExprResult
14261 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
14262   // Transform the base expression.
14263   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
14264   if (Base.isInvalid())
14265     return ExprError();
14266 
14267   // Transform the key expression.
14268   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
14269   if (Key.isInvalid())
14270     return ExprError();
14271 
14272   // If nothing changed, just retain the existing expression.
14273   if (!getDerived().AlwaysRebuild() &&
14274       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
14275     return E;
14276 
14277   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
14278                                                   Base.get(), Key.get(),
14279                                                   E->getAtIndexMethodDecl(),
14280                                                   E->setAtIndexMethodDecl());
14281 }
14282 
14283 template<typename Derived>
14284 ExprResult
14285 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
14286   // Transform the base expression.
14287   ExprResult Base = getDerived().TransformExpr(E->getBase());
14288   if (Base.isInvalid())
14289     return ExprError();
14290 
14291   // If nothing changed, just retain the existing expression.
14292   if (!getDerived().AlwaysRebuild() &&
14293       Base.get() == E->getBase())
14294     return E;
14295 
14296   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14297                                          E->getOpLoc(),
14298                                          E->isArrow());
14299 }
14300 
14301 template<typename Derived>
14302 ExprResult
14303 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14304   bool ArgumentChanged = false;
14305   SmallVector<Expr*, 8> SubExprs;
14306   SubExprs.reserve(E->getNumSubExprs());
14307   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14308                                   SubExprs, &ArgumentChanged))
14309     return ExprError();
14310 
14311   if (!getDerived().AlwaysRebuild() &&
14312       !ArgumentChanged)
14313     return E;
14314 
14315   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14316                                                SubExprs,
14317                                                E->getRParenLoc());
14318 }
14319 
14320 template<typename Derived>
14321 ExprResult
14322 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14323   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14324   if (SrcExpr.isInvalid())
14325     return ExprError();
14326 
14327   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14328   if (!Type)
14329     return ExprError();
14330 
14331   if (!getDerived().AlwaysRebuild() &&
14332       Type == E->getTypeSourceInfo() &&
14333       SrcExpr.get() == E->getSrcExpr())
14334     return E;
14335 
14336   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14337                                                SrcExpr.get(), Type,
14338                                                E->getRParenLoc());
14339 }
14340 
14341 template<typename Derived>
14342 ExprResult
14343 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14344   BlockDecl *oldBlock = E->getBlockDecl();
14345 
14346   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14347   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14348 
14349   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14350   blockScope->TheDecl->setBlockMissingReturnType(
14351                          oldBlock->blockMissingReturnType());
14352 
14353   SmallVector<ParmVarDecl*, 4> params;
14354   SmallVector<QualType, 4> paramTypes;
14355 
14356   const FunctionProtoType *exprFunctionType = E->getFunctionType();
14357 
14358   // Parameter substitution.
14359   Sema::ExtParameterInfoBuilder extParamInfos;
14360   if (getDerived().TransformFunctionTypeParams(
14361           E->getCaretLocation(), oldBlock->parameters(), nullptr,
14362           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14363           extParamInfos)) {
14364     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14365     return ExprError();
14366   }
14367 
14368   QualType exprResultType =
14369       getDerived().TransformType(exprFunctionType->getReturnType());
14370 
14371   auto epi = exprFunctionType->getExtProtoInfo();
14372   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14373 
14374   QualType functionType =
14375     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14376   blockScope->FunctionType = functionType;
14377 
14378   // Set the parameters on the block decl.
14379   if (!params.empty())
14380     blockScope->TheDecl->setParams(params);
14381 
14382   if (!oldBlock->blockMissingReturnType()) {
14383     blockScope->HasImplicitReturnType = false;
14384     blockScope->ReturnType = exprResultType;
14385   }
14386 
14387   // Transform the body
14388   StmtResult body = getDerived().TransformStmt(E->getBody());
14389   if (body.isInvalid()) {
14390     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14391     return ExprError();
14392   }
14393 
14394 #ifndef NDEBUG
14395   // In builds with assertions, make sure that we captured everything we
14396   // captured before.
14397   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14398     for (const auto &I : oldBlock->captures()) {
14399       VarDecl *oldCapture = I.getVariable();
14400 
14401       // Ignore parameter packs.
14402       if (oldCapture->isParameterPack())
14403         continue;
14404 
14405       VarDecl *newCapture =
14406         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14407                                                  oldCapture));
14408       assert(blockScope->CaptureMap.count(newCapture));
14409     }
14410     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
14411   }
14412 #endif
14413 
14414   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14415                                     /*Scope=*/nullptr);
14416 }
14417 
14418 template<typename Derived>
14419 ExprResult
14420 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14421   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14422   if (SrcExpr.isInvalid())
14423     return ExprError();
14424 
14425   QualType Type = getDerived().TransformType(E->getType());
14426 
14427   return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14428                                  E->getRParenLoc());
14429 }
14430 
14431 template<typename Derived>
14432 ExprResult
14433 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14434   bool ArgumentChanged = false;
14435   SmallVector<Expr*, 8> SubExprs;
14436   SubExprs.reserve(E->getNumSubExprs());
14437   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14438                                   SubExprs, &ArgumentChanged))
14439     return ExprError();
14440 
14441   if (!getDerived().AlwaysRebuild() &&
14442       !ArgumentChanged)
14443     return E;
14444 
14445   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14446                                         E->getOp(), E->getRParenLoc());
14447 }
14448 
14449 //===----------------------------------------------------------------------===//
14450 // Type reconstruction
14451 //===----------------------------------------------------------------------===//
14452 
14453 template<typename Derived>
14454 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14455                                                     SourceLocation Star) {
14456   return SemaRef.BuildPointerType(PointeeType, Star,
14457                                   getDerived().getBaseEntity());
14458 }
14459 
14460 template<typename Derived>
14461 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14462                                                          SourceLocation Star) {
14463   return SemaRef.BuildBlockPointerType(PointeeType, Star,
14464                                        getDerived().getBaseEntity());
14465 }
14466 
14467 template<typename Derived>
14468 QualType
14469 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14470                                              bool WrittenAsLValue,
14471                                              SourceLocation Sigil) {
14472   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14473                                     Sigil, getDerived().getBaseEntity());
14474 }
14475 
14476 template<typename Derived>
14477 QualType
14478 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14479                                                  QualType ClassType,
14480                                                  SourceLocation Sigil) {
14481   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14482                                         getDerived().getBaseEntity());
14483 }
14484 
14485 template<typename Derived>
14486 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14487            const ObjCTypeParamDecl *Decl,
14488            SourceLocation ProtocolLAngleLoc,
14489            ArrayRef<ObjCProtocolDecl *> Protocols,
14490            ArrayRef<SourceLocation> ProtocolLocs,
14491            SourceLocation ProtocolRAngleLoc) {
14492   return SemaRef.BuildObjCTypeParamType(Decl,
14493                                         ProtocolLAngleLoc, Protocols,
14494                                         ProtocolLocs, ProtocolRAngleLoc,
14495                                         /*FailOnError=*/true);
14496 }
14497 
14498 template<typename Derived>
14499 QualType TreeTransform<Derived>::RebuildObjCObjectType(
14500            QualType BaseType,
14501            SourceLocation Loc,
14502            SourceLocation TypeArgsLAngleLoc,
14503            ArrayRef<TypeSourceInfo *> TypeArgs,
14504            SourceLocation TypeArgsRAngleLoc,
14505            SourceLocation ProtocolLAngleLoc,
14506            ArrayRef<ObjCProtocolDecl *> Protocols,
14507            ArrayRef<SourceLocation> ProtocolLocs,
14508            SourceLocation ProtocolRAngleLoc) {
14509   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
14510                                      TypeArgs, TypeArgsRAngleLoc,
14511                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
14512                                      ProtocolRAngleLoc,
14513                                      /*FailOnError=*/true);
14514 }
14515 
14516 template<typename Derived>
14517 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14518            QualType PointeeType,
14519            SourceLocation Star) {
14520   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14521 }
14522 
14523 template<typename Derived>
14524 QualType
14525 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
14526                                          ArrayType::ArraySizeModifier SizeMod,
14527                                          const llvm::APInt *Size,
14528                                          Expr *SizeExpr,
14529                                          unsigned IndexTypeQuals,
14530                                          SourceRange BracketsRange) {
14531   if (SizeExpr || !Size)
14532     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14533                                   IndexTypeQuals, BracketsRange,
14534                                   getDerived().getBaseEntity());
14535 
14536   QualType Types[] = {
14537     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14538     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14539     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14540   };
14541   const unsigned NumTypes = llvm::array_lengthof(Types);
14542   QualType SizeType;
14543   for (unsigned I = 0; I != NumTypes; ++I)
14544     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
14545       SizeType = Types[I];
14546       break;
14547     }
14548 
14549   // Note that we can return a VariableArrayType here in the case where
14550   // the element type was a dependent VariableArrayType.
14551   IntegerLiteral *ArraySize
14552       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14553                                /*FIXME*/BracketsRange.getBegin());
14554   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14555                                 IndexTypeQuals, BracketsRange,
14556                                 getDerived().getBaseEntity());
14557 }
14558 
14559 template<typename Derived>
14560 QualType
14561 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
14562                                                  ArrayType::ArraySizeModifier SizeMod,
14563                                                  const llvm::APInt &Size,
14564                                                  Expr *SizeExpr,
14565                                                  unsigned IndexTypeQuals,
14566                                                  SourceRange BracketsRange) {
14567   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
14568                                         IndexTypeQuals, BracketsRange);
14569 }
14570 
14571 template<typename Derived>
14572 QualType
14573 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
14574                                           ArrayType::ArraySizeModifier SizeMod,
14575                                                  unsigned IndexTypeQuals,
14576                                                    SourceRange BracketsRange) {
14577   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
14578                                        IndexTypeQuals, BracketsRange);
14579 }
14580 
14581 template<typename Derived>
14582 QualType
14583 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
14584                                           ArrayType::ArraySizeModifier SizeMod,
14585                                                  Expr *SizeExpr,
14586                                                  unsigned IndexTypeQuals,
14587                                                  SourceRange BracketsRange) {
14588   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14589                                        SizeExpr,
14590                                        IndexTypeQuals, BracketsRange);
14591 }
14592 
14593 template<typename Derived>
14594 QualType
14595 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
14596                                           ArrayType::ArraySizeModifier SizeMod,
14597                                                        Expr *SizeExpr,
14598                                                        unsigned IndexTypeQuals,
14599                                                    SourceRange BracketsRange) {
14600   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14601                                        SizeExpr,
14602                                        IndexTypeQuals, BracketsRange);
14603 }
14604 
14605 template <typename Derived>
14606 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
14607     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
14608   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
14609                                           AttributeLoc);
14610 }
14611 
14612 template <typename Derived>
14613 QualType
14614 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
14615                                           unsigned NumElements,
14616                                           VectorType::VectorKind VecKind) {
14617   // FIXME: semantic checking!
14618   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
14619 }
14620 
14621 template <typename Derived>
14622 QualType TreeTransform<Derived>::RebuildDependentVectorType(
14623     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
14624     VectorType::VectorKind VecKind) {
14625   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
14626 }
14627 
14628 template<typename Derived>
14629 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
14630                                                       unsigned NumElements,
14631                                                  SourceLocation AttributeLoc) {
14632   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14633                           NumElements, true);
14634   IntegerLiteral *VectorSize
14635     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
14636                              AttributeLoc);
14637   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
14638 }
14639 
14640 template<typename Derived>
14641 QualType
14642 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
14643                                                            Expr *SizeExpr,
14644                                                   SourceLocation AttributeLoc) {
14645   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
14646 }
14647 
14648 template <typename Derived>
14649 QualType TreeTransform<Derived>::RebuildConstantMatrixType(
14650     QualType ElementType, unsigned NumRows, unsigned NumColumns) {
14651   return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
14652                                                NumColumns);
14653 }
14654 
14655 template <typename Derived>
14656 QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
14657     QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
14658     SourceLocation AttributeLoc) {
14659   return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
14660                                  AttributeLoc);
14661 }
14662 
14663 template<typename Derived>
14664 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
14665     QualType T,
14666     MutableArrayRef<QualType> ParamTypes,
14667     const FunctionProtoType::ExtProtoInfo &EPI) {
14668   return SemaRef.BuildFunctionType(T, ParamTypes,
14669                                    getDerived().getBaseLocation(),
14670                                    getDerived().getBaseEntity(),
14671                                    EPI);
14672 }
14673 
14674 template<typename Derived>
14675 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
14676   return SemaRef.Context.getFunctionNoProtoType(T);
14677 }
14678 
14679 template<typename Derived>
14680 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
14681                                                             Decl *D) {
14682   assert(D && "no decl found");
14683   if (D->isInvalidDecl()) return QualType();
14684 
14685   // FIXME: Doesn't account for ObjCInterfaceDecl!
14686   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
14687     // A valid resolved using typename pack expansion decl can have multiple
14688     // UsingDecls, but they must each have exactly one type, and it must be
14689     // the same type in every case. But we must have at least one expansion!
14690     if (UPD->expansions().empty()) {
14691       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
14692           << UPD->isCXXClassMember() << UPD;
14693       return QualType();
14694     }
14695 
14696     // We might still have some unresolved types. Try to pick a resolved type
14697     // if we can. The final instantiation will check that the remaining
14698     // unresolved types instantiate to the type we pick.
14699     QualType FallbackT;
14700     QualType T;
14701     for (auto *E : UPD->expansions()) {
14702       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
14703       if (ThisT.isNull())
14704         continue;
14705       else if (ThisT->getAs<UnresolvedUsingType>())
14706         FallbackT = ThisT;
14707       else if (T.isNull())
14708         T = ThisT;
14709       else
14710         assert(getSema().Context.hasSameType(ThisT, T) &&
14711                "mismatched resolved types in using pack expansion");
14712     }
14713     return T.isNull() ? FallbackT : T;
14714   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
14715     assert(Using->hasTypename() &&
14716            "UnresolvedUsingTypenameDecl transformed to non-typename using");
14717 
14718     // A valid resolved using typename decl points to exactly one type decl.
14719     assert(++Using->shadow_begin() == Using->shadow_end());
14720 
14721     UsingShadowDecl *Shadow = *Using->shadow_begin();
14722     if (SemaRef.DiagnoseUseOfDecl(Shadow->getTargetDecl(), Loc))
14723       return QualType();
14724     return SemaRef.Context.getUsingType(
14725         Shadow, SemaRef.Context.getTypeDeclType(
14726                     cast<TypeDecl>(Shadow->getTargetDecl())));
14727   } else {
14728     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
14729            "UnresolvedUsingTypenameDecl transformed to non-using decl");
14730     return SemaRef.Context.getTypeDeclType(
14731         cast<UnresolvedUsingTypenameDecl>(D));
14732   }
14733 }
14734 
14735 template <typename Derived>
14736 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
14737                                                        SourceLocation) {
14738   return SemaRef.BuildTypeofExprType(E);
14739 }
14740 
14741 template<typename Derived>
14742 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
14743   return SemaRef.Context.getTypeOfType(Underlying);
14744 }
14745 
14746 template <typename Derived>
14747 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E, SourceLocation) {
14748   return SemaRef.BuildDecltypeType(E);
14749 }
14750 
14751 template<typename Derived>
14752 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
14753                                             UnaryTransformType::UTTKind UKind,
14754                                             SourceLocation Loc) {
14755   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
14756 }
14757 
14758 template<typename Derived>
14759 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
14760                                                       TemplateName Template,
14761                                              SourceLocation TemplateNameLoc,
14762                                      TemplateArgumentListInfo &TemplateArgs) {
14763   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
14764 }
14765 
14766 template<typename Derived>
14767 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
14768                                                    SourceLocation KWLoc) {
14769   return SemaRef.BuildAtomicType(ValueType, KWLoc);
14770 }
14771 
14772 template<typename Derived>
14773 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
14774                                                  SourceLocation KWLoc,
14775                                                  bool isReadPipe) {
14776   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
14777                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
14778 }
14779 
14780 template <typename Derived>
14781 QualType TreeTransform<Derived>::RebuildBitIntType(bool IsUnsigned,
14782                                                    unsigned NumBits,
14783                                                    SourceLocation Loc) {
14784   llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14785                         NumBits, true);
14786   IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
14787                                                 SemaRef.Context.IntTy, Loc);
14788   return SemaRef.BuildBitIntType(IsUnsigned, Bits, Loc);
14789 }
14790 
14791 template <typename Derived>
14792 QualType TreeTransform<Derived>::RebuildDependentBitIntType(
14793     bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
14794   return SemaRef.BuildBitIntType(IsUnsigned, NumBitsExpr, Loc);
14795 }
14796 
14797 template<typename Derived>
14798 TemplateName
14799 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14800                                             bool TemplateKW,
14801                                             TemplateDecl *Template) {
14802   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
14803                                                   TemplateName(Template));
14804 }
14805 
14806 template<typename Derived>
14807 TemplateName
14808 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14809                                             SourceLocation TemplateKWLoc,
14810                                             const IdentifierInfo &Name,
14811                                             SourceLocation NameLoc,
14812                                             QualType ObjectType,
14813                                             NamedDecl *FirstQualifierInScope,
14814                                             bool AllowInjectedClassName) {
14815   UnqualifiedId TemplateName;
14816   TemplateName.setIdentifier(&Name, NameLoc);
14817   Sema::TemplateTy Template;
14818   getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
14819                               TemplateName, ParsedType::make(ObjectType),
14820                               /*EnteringContext=*/false, Template,
14821                               AllowInjectedClassName);
14822   return Template.get();
14823 }
14824 
14825 template<typename Derived>
14826 TemplateName
14827 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
14828                                             SourceLocation TemplateKWLoc,
14829                                             OverloadedOperatorKind Operator,
14830                                             SourceLocation NameLoc,
14831                                             QualType ObjectType,
14832                                             bool AllowInjectedClassName) {
14833   UnqualifiedId Name;
14834   // FIXME: Bogus location information.
14835   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
14836   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
14837   Sema::TemplateTy Template;
14838   getSema().ActOnTemplateName(
14839       /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
14840       /*EnteringContext=*/false, Template, AllowInjectedClassName);
14841   return Template.get();
14842 }
14843 
14844 template<typename Derived>
14845 ExprResult
14846 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
14847                                                    SourceLocation OpLoc,
14848                                                    Expr *OrigCallee,
14849                                                    Expr *First,
14850                                                    Expr *Second) {
14851   Expr *Callee = OrigCallee->IgnoreParenCasts();
14852   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
14853 
14854   if (First->getObjectKind() == OK_ObjCProperty) {
14855     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14856     if (BinaryOperator::isAssignmentOp(Opc))
14857       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
14858                                                  First, Second);
14859     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
14860     if (Result.isInvalid())
14861       return ExprError();
14862     First = Result.get();
14863   }
14864 
14865   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
14866     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
14867     if (Result.isInvalid())
14868       return ExprError();
14869     Second = Result.get();
14870   }
14871 
14872   // Determine whether this should be a builtin operation.
14873   if (Op == OO_Subscript) {
14874     if (!First->getType()->isOverloadableType() &&
14875         !Second->getType()->isOverloadableType())
14876       return getSema().CreateBuiltinArraySubscriptExpr(
14877           First, Callee->getBeginLoc(), Second, OpLoc);
14878   } else if (Op == OO_Arrow) {
14879     // It is possible that the type refers to a RecoveryExpr created earlier
14880     // in the tree transformation.
14881     if (First->getType()->isDependentType())
14882       return ExprError();
14883     // -> is never a builtin operation.
14884     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
14885   } else if (Second == nullptr || isPostIncDec) {
14886     if (!First->getType()->isOverloadableType() ||
14887         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
14888       // The argument is not of overloadable type, or this is an expression
14889       // of the form &Class::member, so try to create a built-in unary
14890       // operation.
14891       UnaryOperatorKind Opc
14892         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14893 
14894       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
14895     }
14896   } else {
14897     if (!First->getType()->isOverloadableType() &&
14898         !Second->getType()->isOverloadableType()) {
14899       // Neither of the arguments is an overloadable type, so try to
14900       // create a built-in binary operation.
14901       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14902       ExprResult Result
14903         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
14904       if (Result.isInvalid())
14905         return ExprError();
14906 
14907       return Result;
14908     }
14909   }
14910 
14911   // Compute the transformed set of functions (and function templates) to be
14912   // used during overload resolution.
14913   UnresolvedSet<16> Functions;
14914   bool RequiresADL;
14915 
14916   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
14917     Functions.append(ULE->decls_begin(), ULE->decls_end());
14918     // If the overload could not be resolved in the template definition
14919     // (because we had a dependent argument), ADL is performed as part of
14920     // template instantiation.
14921     RequiresADL = ULE->requiresADL();
14922   } else {
14923     // If we've resolved this to a particular non-member function, just call
14924     // that function. If we resolved it to a member function,
14925     // CreateOverloaded* will find that function for us.
14926     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
14927     if (!isa<CXXMethodDecl>(ND))
14928       Functions.addDecl(ND);
14929     RequiresADL = false;
14930   }
14931 
14932   // Add any functions found via argument-dependent lookup.
14933   Expr *Args[2] = { First, Second };
14934   unsigned NumArgs = 1 + (Second != nullptr);
14935 
14936   // Create the overloaded operator invocation for unary operators.
14937   if (NumArgs == 1 || isPostIncDec) {
14938     UnaryOperatorKind Opc
14939       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
14940     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
14941                                            RequiresADL);
14942   }
14943 
14944   if (Op == OO_Subscript) {
14945     SourceLocation LBrace;
14946     SourceLocation RBrace;
14947 
14948     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
14949       DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
14950       LBrace = NameLoc.getCXXOperatorNameBeginLoc();
14951       RBrace = NameLoc.getCXXOperatorNameEndLoc();
14952     } else {
14953       LBrace = Callee->getBeginLoc();
14954       RBrace = OpLoc;
14955     }
14956 
14957     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
14958                                                       First, Second);
14959   }
14960 
14961   // Create the overloaded operator invocation for binary operators.
14962   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
14963   ExprResult Result = SemaRef.CreateOverloadedBinOp(
14964       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
14965   if (Result.isInvalid())
14966     return ExprError();
14967 
14968   return Result;
14969 }
14970 
14971 template<typename Derived>
14972 ExprResult
14973 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
14974                                                      SourceLocation OperatorLoc,
14975                                                        bool isArrow,
14976                                                        CXXScopeSpec &SS,
14977                                                      TypeSourceInfo *ScopeType,
14978                                                        SourceLocation CCLoc,
14979                                                        SourceLocation TildeLoc,
14980                                         PseudoDestructorTypeStorage Destroyed) {
14981   QualType BaseType = Base->getType();
14982   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
14983       (!isArrow && !BaseType->getAs<RecordType>()) ||
14984       (isArrow && BaseType->getAs<PointerType>() &&
14985        !BaseType->castAs<PointerType>()->getPointeeType()
14986                                               ->template getAs<RecordType>())){
14987     // This pseudo-destructor expression is still a pseudo-destructor.
14988     return SemaRef.BuildPseudoDestructorExpr(
14989         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
14990         CCLoc, TildeLoc, Destroyed);
14991   }
14992 
14993   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
14994   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
14995                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
14996   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
14997   NameInfo.setNamedTypeInfo(DestroyedType);
14998 
14999   // The scope type is now known to be a valid nested name specifier
15000   // component. Tack it on to the end of the nested name specifier.
15001   if (ScopeType) {
15002     if (!ScopeType->getType()->getAs<TagType>()) {
15003       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
15004                      diag::err_expected_class_or_namespace)
15005           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
15006       return ExprError();
15007     }
15008     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
15009               CCLoc);
15010   }
15011 
15012   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
15013   return getSema().BuildMemberReferenceExpr(Base, BaseType,
15014                                             OperatorLoc, isArrow,
15015                                             SS, TemplateKWLoc,
15016                                             /*FIXME: FirstQualifier*/ nullptr,
15017                                             NameInfo,
15018                                             /*TemplateArgs*/ nullptr,
15019                                             /*S*/nullptr);
15020 }
15021 
15022 template<typename Derived>
15023 StmtResult
15024 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
15025   SourceLocation Loc = S->getBeginLoc();
15026   CapturedDecl *CD = S->getCapturedDecl();
15027   unsigned NumParams = CD->getNumParams();
15028   unsigned ContextParamPos = CD->getContextParamPosition();
15029   SmallVector<Sema::CapturedParamNameType, 4> Params;
15030   for (unsigned I = 0; I < NumParams; ++I) {
15031     if (I != ContextParamPos) {
15032       Params.push_back(
15033              std::make_pair(
15034                   CD->getParam(I)->getName(),
15035                   getDerived().TransformType(CD->getParam(I)->getType())));
15036     } else {
15037       Params.push_back(std::make_pair(StringRef(), QualType()));
15038     }
15039   }
15040   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
15041                                      S->getCapturedRegionKind(), Params);
15042   StmtResult Body;
15043   {
15044     Sema::CompoundScopeRAII CompoundScope(getSema());
15045     Body = getDerived().TransformStmt(S->getCapturedStmt());
15046   }
15047 
15048   if (Body.isInvalid()) {
15049     getSema().ActOnCapturedRegionError();
15050     return StmtError();
15051   }
15052 
15053   return getSema().ActOnCapturedRegionEnd(Body.get());
15054 }
15055 
15056 } // end namespace clang
15057 
15058 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15059