1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements a semantic tree transformation that takes a given
10 //  AST and rebuilds it, possibly transforming some nodes in the process.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15 #define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
16 
17 #include "CoroutineStmtBuilder.h"
18 #include "TypeLocBuilder.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/StmtObjC.h"
29 #include "clang/AST/StmtOpenMP.h"
30 #include "clang/Sema/Designator.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Ownership.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaDiagnostic.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include <algorithm>
40 
41 namespace clang {
42 using namespace sema;
43 
44 /// A semantic tree transformation that allows one to transform one
45 /// abstract syntax tree into another.
46 ///
47 /// A new tree transformation is defined by creating a new subclass \c X of
48 /// \c TreeTransform<X> and then overriding certain operations to provide
49 /// behavior specific to that transformation. For example, template
50 /// instantiation is implemented as a tree transformation where the
51 /// transformation of TemplateTypeParmType nodes involves substituting the
52 /// template arguments for their corresponding template parameters; a similar
53 /// transformation is performed for non-type template parameters and
54 /// template template parameters.
55 ///
56 /// This tree-transformation template uses static polymorphism to allow
57 /// subclasses to customize any of its operations. Thus, a subclass can
58 /// override any of the transformation or rebuild operators by providing an
59 /// operation with the same signature as the default implementation. The
60 /// overriding function should not be virtual.
61 ///
62 /// Semantic tree transformations are split into two stages, either of which
63 /// can be replaced by a subclass. The "transform" step transforms an AST node
64 /// or the parts of an AST node using the various transformation functions,
65 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
66 /// node of the appropriate kind from the pieces. The default transformation
67 /// routines recursively transform the operands to composite AST nodes (e.g.,
68 /// the pointee type of a PointerType node) and, if any of those operand nodes
69 /// were changed by the transformation, invokes the rebuild operation to create
70 /// a new AST node.
71 ///
72 /// Subclasses can customize the transformation at various levels. The
73 /// most coarse-grained transformations involve replacing TransformType(),
74 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
75 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
76 /// new implementations.
77 ///
78 /// For more fine-grained transformations, subclasses can replace any of the
79 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
80 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
81 /// replacing TransformTemplateTypeParmType() allows template instantiation
82 /// to substitute template arguments for their corresponding template
83 /// parameters. Additionally, subclasses can override the \c RebuildXXX
84 /// functions to control how AST nodes are rebuilt when their operands change.
85 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
86 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
87 /// be able to use more efficient rebuild steps.
88 ///
89 /// There are a handful of other functions that can be overridden, allowing one
90 /// to avoid traversing nodes that don't need any transformation
91 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
92 /// operands have not changed (\c AlwaysRebuild()), and customize the
93 /// default locations and entity names used for type-checking
94 /// (\c getBaseLocation(), \c getBaseEntity()).
95 template<typename Derived>
96 class TreeTransform {
97   /// Private RAII object that helps us forget and then re-remember
98   /// the template argument corresponding to a partially-substituted parameter
99   /// pack.
100   class ForgetPartiallySubstitutedPackRAII {
101     Derived &Self;
102     TemplateArgument Old;
103 
104   public:
ForgetPartiallySubstitutedPackRAII(Derived & Self)105     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
106       Old = Self.ForgetPartiallySubstitutedPack();
107     }
108 
~ForgetPartiallySubstitutedPackRAII()109     ~ForgetPartiallySubstitutedPackRAII() {
110       Self.RememberPartiallySubstitutedPack(Old);
111     }
112   };
113 
114 protected:
115   Sema &SemaRef;
116 
117   /// The set of local declarations that have been transformed, for
118   /// cases where we are forced to build new declarations within the transformer
119   /// rather than in the subclass (e.g., lambda closure types).
120   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
121 
122 public:
123   /// Initializes a new tree transformer.
TreeTransform(Sema & SemaRef)124   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
125 
126   /// Retrieves a reference to the derived class.
getDerived()127   Derived &getDerived() { return static_cast<Derived&>(*this); }
128 
129   /// Retrieves a reference to the derived class.
getDerived()130   const Derived &getDerived() const {
131     return static_cast<const Derived&>(*this);
132   }
133 
Owned(Expr * E)134   static inline ExprResult Owned(Expr *E) { return E; }
Owned(Stmt * S)135   static inline StmtResult Owned(Stmt *S) { return S; }
136 
137   /// Retrieves a reference to the semantic analysis object used for
138   /// this tree transform.
getSema()139   Sema &getSema() const { return SemaRef; }
140 
141   /// Whether the transformation should always rebuild AST nodes, even
142   /// if none of the children have changed.
143   ///
144   /// Subclasses may override this function to specify when the transformation
145   /// should rebuild all AST nodes.
146   ///
147   /// We must always rebuild all AST nodes when performing variadic template
148   /// pack expansion, in order to avoid violating the AST invariant that each
149   /// statement node appears at most once in its containing declaration.
AlwaysRebuild()150   bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
151 
152   /// Returns the location of the entity being transformed, if that
153   /// information was not available elsewhere in the AST.
154   ///
155   /// By default, returns no source-location information. Subclasses can
156   /// provide an alternative implementation that provides better location
157   /// information.
getBaseLocation()158   SourceLocation getBaseLocation() { return SourceLocation(); }
159 
160   /// Returns the name of the entity being transformed, if that
161   /// information was not available elsewhere in the AST.
162   ///
163   /// By default, returns an empty name. Subclasses can provide an alternative
164   /// implementation with a more precise name.
getBaseEntity()165   DeclarationName getBaseEntity() { return DeclarationName(); }
166 
167   /// Sets the "base" location and entity when that
168   /// information is known based on another transformation.
169   ///
170   /// By default, the source location and entity are ignored. Subclasses can
171   /// override this function to provide a customized implementation.
setBase(SourceLocation Loc,DeclarationName Entity)172   void setBase(SourceLocation Loc, DeclarationName Entity) { }
173 
174   /// RAII object that temporarily sets the base location and entity
175   /// used for reporting diagnostics in types.
176   class TemporaryBase {
177     TreeTransform &Self;
178     SourceLocation OldLocation;
179     DeclarationName OldEntity;
180 
181   public:
TemporaryBase(TreeTransform & Self,SourceLocation Location,DeclarationName Entity)182     TemporaryBase(TreeTransform &Self, SourceLocation Location,
183                   DeclarationName Entity) : Self(Self) {
184       OldLocation = Self.getDerived().getBaseLocation();
185       OldEntity = Self.getDerived().getBaseEntity();
186 
187       if (Location.isValid())
188         Self.getDerived().setBase(Location, Entity);
189     }
190 
~TemporaryBase()191     ~TemporaryBase() {
192       Self.getDerived().setBase(OldLocation, OldEntity);
193     }
194   };
195 
196   /// Determine whether the given type \p T has already been
197   /// transformed.
198   ///
199   /// Subclasses can provide an alternative implementation of this routine
200   /// to short-circuit evaluation when it is known that a given type will
201   /// not change. For example, template instantiation need not traverse
202   /// non-dependent types.
AlreadyTransformed(QualType T)203   bool AlreadyTransformed(QualType T) {
204     return T.isNull();
205   }
206 
207   /// Determine whether the given call argument should be dropped, e.g.,
208   /// because it is a default argument.
209   ///
210   /// Subclasses can provide an alternative implementation of this routine to
211   /// determine which kinds of call arguments get dropped. By default,
212   /// CXXDefaultArgument nodes are dropped (prior to transformation).
DropCallArgument(Expr * E)213   bool DropCallArgument(Expr *E) {
214     return E->isDefaultArgument();
215   }
216 
217   /// Determine whether we should expand a pack expansion with the
218   /// given set of parameter packs into separate arguments by repeatedly
219   /// transforming the pattern.
220   ///
221   /// By default, the transformer never tries to expand pack expansions.
222   /// Subclasses can override this routine to provide different behavior.
223   ///
224   /// \param EllipsisLoc The location of the ellipsis that identifies the
225   /// pack expansion.
226   ///
227   /// \param PatternRange The source range that covers the entire pattern of
228   /// the pack expansion.
229   ///
230   /// \param Unexpanded The set of unexpanded parameter packs within the
231   /// pattern.
232   ///
233   /// \param ShouldExpand Will be set to \c true if the transformer should
234   /// expand the corresponding pack expansions into separate arguments. When
235   /// set, \c NumExpansions must also be set.
236   ///
237   /// \param RetainExpansion Whether the caller should add an unexpanded
238   /// pack expansion after all of the expanded arguments. This is used
239   /// when extending explicitly-specified template argument packs per
240   /// C++0x [temp.arg.explicit]p9.
241   ///
242   /// \param NumExpansions The number of separate arguments that will be in
243   /// the expanded form of the corresponding pack expansion. This is both an
244   /// input and an output parameter, which can be set by the caller if the
245   /// number of expansions is known a priori (e.g., due to a prior substitution)
246   /// and will be set by the callee when the number of expansions is known.
247   /// The callee must set this value when \c ShouldExpand is \c true; it may
248   /// set this value in other cases.
249   ///
250   /// \returns true if an error occurred (e.g., because the parameter packs
251   /// are to be instantiated with arguments of different lengths), false
252   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
253   /// must be set.
TryExpandParameterPacks(SourceLocation EllipsisLoc,SourceRange PatternRange,ArrayRef<UnexpandedParameterPack> Unexpanded,bool & ShouldExpand,bool & RetainExpansion,Optional<unsigned> & NumExpansions)254   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
255                                SourceRange PatternRange,
256                                ArrayRef<UnexpandedParameterPack> Unexpanded,
257                                bool &ShouldExpand,
258                                bool &RetainExpansion,
259                                Optional<unsigned> &NumExpansions) {
260     ShouldExpand = false;
261     return false;
262   }
263 
264   /// "Forget" about the partially-substituted pack template argument,
265   /// when performing an instantiation that must preserve the parameter pack
266   /// use.
267   ///
268   /// This routine is meant to be overridden by the template instantiator.
ForgetPartiallySubstitutedPack()269   TemplateArgument ForgetPartiallySubstitutedPack() {
270     return TemplateArgument();
271   }
272 
273   /// "Remember" the partially-substituted pack template argument
274   /// after performing an instantiation that must preserve the parameter pack
275   /// use.
276   ///
277   /// This routine is meant to be overridden by the template instantiator.
RememberPartiallySubstitutedPack(TemplateArgument Arg)278   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
279 
280   /// Note to the derived class when a function parameter pack is
281   /// being expanded.
ExpandingFunctionParameterPack(ParmVarDecl * Pack)282   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
283 
284   /// Transforms the given type into another type.
285   ///
286   /// By default, this routine transforms a type by creating a
287   /// TypeSourceInfo for it and delegating to the appropriate
288   /// function.  This is expensive, but we don't mind, because
289   /// this method is deprecated anyway;  all users should be
290   /// switched to storing TypeSourceInfos.
291   ///
292   /// \returns the transformed type.
293   QualType TransformType(QualType T);
294 
295   /// Transforms the given type-with-location into a new
296   /// type-with-location.
297   ///
298   /// By default, this routine transforms a type by delegating to the
299   /// appropriate TransformXXXType to build a new type.  Subclasses
300   /// may override this function (to take over all type
301   /// transformations) or some set of the TransformXXXType functions
302   /// to alter the transformation.
303   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
304 
305   /// Transform the given type-with-location into a new
306   /// type, collecting location information in the given builder
307   /// as necessary.
308   ///
309   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
310 
311   /// Transform a type that is permitted to produce a
312   /// DeducedTemplateSpecializationType.
313   ///
314   /// This is used in the (relatively rare) contexts where it is acceptable
315   /// for transformation to produce a class template type with deduced
316   /// template arguments.
317   /// @{
318   QualType TransformTypeWithDeducedTST(QualType T);
319   TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
320   /// @}
321 
322   /// Transform the given statement.
323   ///
324   /// By default, this routine transforms a statement by delegating to the
325   /// appropriate TransformXXXStmt function to transform a specific kind of
326   /// statement or the TransformExpr() function to transform an expression.
327   /// Subclasses may override this function to transform statements using some
328   /// other mechanism.
329   ///
330   /// \returns the transformed statement.
331   StmtResult TransformStmt(Stmt *S);
332 
333   /// Transform the given statement.
334   ///
335   /// By default, this routine transforms a statement by delegating to the
336   /// appropriate TransformOMPXXXClause function to transform a specific kind
337   /// of clause. Subclasses may override this function to transform statements
338   /// using some other mechanism.
339   ///
340   /// \returns the transformed OpenMP clause.
341   OMPClause *TransformOMPClause(OMPClause *S);
342 
343   /// Transform the given attribute.
344   ///
345   /// By default, this routine transforms a statement by delegating to the
346   /// appropriate TransformXXXAttr function to transform a specific kind
347   /// of attribute. Subclasses may override this function to transform
348   /// attributed statements using some other mechanism.
349   ///
350   /// \returns the transformed attribute
351   const Attr *TransformAttr(const Attr *S);
352 
353 /// Transform the specified attribute.
354 ///
355 /// Subclasses should override the transformation of attributes with a pragma
356 /// spelling to transform expressions stored within the attribute.
357 ///
358 /// \returns the transformed attribute.
359 #define ATTR(X)
360 #define PRAGMA_SPELLING_ATTR(X)                                                \
361   const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
362 #include "clang/Basic/AttrList.inc"
363 
364   /// Transform the given expression.
365   ///
366   /// By default, this routine transforms an expression by delegating to the
367   /// appropriate TransformXXXExpr function to build a new expression.
368   /// Subclasses may override this function to transform expressions using some
369   /// other mechanism.
370   ///
371   /// \returns the transformed expression.
372   ExprResult TransformExpr(Expr *E);
373 
374   /// Transform the given initializer.
375   ///
376   /// By default, this routine transforms an initializer by stripping off the
377   /// semantic nodes added by initialization, then passing the result to
378   /// TransformExpr or TransformExprs.
379   ///
380   /// \returns the transformed initializer.
381   ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
382 
383   /// Transform the given list of expressions.
384   ///
385   /// This routine transforms a list of expressions by invoking
386   /// \c TransformExpr() for each subexpression. However, it also provides
387   /// support for variadic templates by expanding any pack expansions (if the
388   /// derived class permits such expansion) along the way. When pack expansions
389   /// are present, the number of outputs may not equal the number of inputs.
390   ///
391   /// \param Inputs The set of expressions to be transformed.
392   ///
393   /// \param NumInputs The number of expressions in \c Inputs.
394   ///
395   /// \param IsCall If \c true, then this transform is being performed on
396   /// function-call arguments, and any arguments that should be dropped, will
397   /// be.
398   ///
399   /// \param Outputs The transformed input expressions will be added to this
400   /// vector.
401   ///
402   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
403   /// due to transformation.
404   ///
405   /// \returns true if an error occurred, false otherwise.
406   bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
407                       SmallVectorImpl<Expr *> &Outputs,
408                       bool *ArgChanged = nullptr);
409 
410   /// Transform the given declaration, which is referenced from a type
411   /// or expression.
412   ///
413   /// By default, acts as the identity function on declarations, unless the
414   /// transformer has had to transform the declaration itself. Subclasses
415   /// may override this function to provide alternate behavior.
TransformDecl(SourceLocation Loc,Decl * D)416   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
417     llvm::DenseMap<Decl *, Decl *>::iterator Known
418       = TransformedLocalDecls.find(D);
419     if (Known != TransformedLocalDecls.end())
420       return Known->second;
421 
422     return D;
423   }
424 
425   /// Transform the specified condition.
426   ///
427   /// By default, this transforms the variable and expression and rebuilds
428   /// the condition.
429   Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
430                                            Expr *Expr,
431                                            Sema::ConditionKind Kind);
432 
433   /// Transform the attributes associated with the given declaration and
434   /// place them on the new declaration.
435   ///
436   /// By default, this operation does nothing. Subclasses may override this
437   /// behavior to transform attributes.
transformAttrs(Decl * Old,Decl * New)438   void transformAttrs(Decl *Old, Decl *New) { }
439 
440   /// Note that a local declaration has been transformed by this
441   /// transformer.
442   ///
443   /// Local declarations are typically transformed via a call to
444   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
445   /// the transformer itself has to transform the declarations. This routine
446   /// can be overridden by a subclass that keeps track of such mappings.
transformedLocalDecl(Decl * Old,Decl * New)447   void transformedLocalDecl(Decl *Old, Decl *New) {
448     TransformedLocalDecls[Old] = New;
449   }
450 
451   /// Transform the definition of the given declaration.
452   ///
453   /// By default, invokes TransformDecl() to transform the declaration.
454   /// Subclasses may override this function to provide alternate behavior.
TransformDefinition(SourceLocation Loc,Decl * D)455   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
456     return getDerived().TransformDecl(Loc, D);
457   }
458 
459   /// Transform the given declaration, which was the first part of a
460   /// nested-name-specifier in a member access expression.
461   ///
462   /// This specific declaration transformation only applies to the first
463   /// identifier in a nested-name-specifier of a member access expression, e.g.,
464   /// the \c T in \c x->T::member
465   ///
466   /// By default, invokes TransformDecl() to transform the declaration.
467   /// Subclasses may override this function to provide alternate behavior.
TransformFirstQualifierInScope(NamedDecl * D,SourceLocation Loc)468   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
469     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
470   }
471 
472   /// Transform the set of declarations in an OverloadExpr.
473   bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
474                                   LookupResult &R);
475 
476   /// Transform the given nested-name-specifier with source-location
477   /// information.
478   ///
479   /// By default, transforms all of the types and declarations within the
480   /// nested-name-specifier. Subclasses may override this function to provide
481   /// alternate behavior.
482   NestedNameSpecifierLoc
483   TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
484                                   QualType ObjectType = QualType(),
485                                   NamedDecl *FirstQualifierInScope = nullptr);
486 
487   /// Transform the given declaration name.
488   ///
489   /// By default, transforms the types of conversion function, constructor,
490   /// and destructor names and then (if needed) rebuilds the declaration name.
491   /// Identifiers and selectors are returned unmodified. Sublcasses may
492   /// override this function to provide alternate behavior.
493   DeclarationNameInfo
494   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
495 
496   /// Transform the given template name.
497   ///
498   /// \param SS The nested-name-specifier that qualifies the template
499   /// name. This nested-name-specifier must already have been transformed.
500   ///
501   /// \param Name The template name to transform.
502   ///
503   /// \param NameLoc The source location of the template name.
504   ///
505   /// \param ObjectType If we're translating a template name within a member
506   /// access expression, this is the type of the object whose member template
507   /// is being referenced.
508   ///
509   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
510   /// also refers to a name within the current (lexical) scope, this is the
511   /// declaration it refers to.
512   ///
513   /// By default, transforms the template name by transforming the declarations
514   /// and nested-name-specifiers that occur within the template name.
515   /// Subclasses may override this function to provide alternate behavior.
516   TemplateName
517   TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
518                         SourceLocation NameLoc,
519                         QualType ObjectType = QualType(),
520                         NamedDecl *FirstQualifierInScope = nullptr,
521                         bool AllowInjectedClassName = false);
522 
523   /// Transform the given template argument.
524   ///
525   /// By default, this operation transforms the type, expression, or
526   /// declaration stored within the template argument and constructs a
527   /// new template argument from the transformed result. Subclasses may
528   /// override this function to provide alternate behavior.
529   ///
530   /// Returns true if there was an error.
531   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
532                                  TemplateArgumentLoc &Output,
533                                  bool Uneval = false);
534 
535   /// Transform the given set of template arguments.
536   ///
537   /// By default, this operation transforms all of the template arguments
538   /// in the input set using \c TransformTemplateArgument(), and appends
539   /// the transformed arguments to the output list.
540   ///
541   /// Note that this overload of \c TransformTemplateArguments() is merely
542   /// a convenience function. Subclasses that wish to override this behavior
543   /// should override the iterator-based member template version.
544   ///
545   /// \param Inputs The set of template arguments to be transformed.
546   ///
547   /// \param NumInputs The number of template arguments in \p Inputs.
548   ///
549   /// \param Outputs The set of transformed template arguments output by this
550   /// routine.
551   ///
552   /// Returns true if an error occurred.
553   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
554                                   unsigned NumInputs,
555                                   TemplateArgumentListInfo &Outputs,
556                                   bool Uneval = false) {
557     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
558                                       Uneval);
559   }
560 
561   /// Transform the given set of template arguments.
562   ///
563   /// By default, this operation transforms all of the template arguments
564   /// in the input set using \c TransformTemplateArgument(), and appends
565   /// the transformed arguments to the output list.
566   ///
567   /// \param First An iterator to the first template argument.
568   ///
569   /// \param Last An iterator one step past the last template argument.
570   ///
571   /// \param Outputs The set of transformed template arguments output by this
572   /// routine.
573   ///
574   /// Returns true if an error occurred.
575   template<typename InputIterator>
576   bool TransformTemplateArguments(InputIterator First,
577                                   InputIterator Last,
578                                   TemplateArgumentListInfo &Outputs,
579                                   bool Uneval = false);
580 
581   /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
582   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
583                                  TemplateArgumentLoc &ArgLoc);
584 
585   /// Fakes up a TypeSourceInfo for a type.
InventTypeSourceInfo(QualType T)586   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
587     return SemaRef.Context.getTrivialTypeSourceInfo(T,
588                        getDerived().getBaseLocation());
589   }
590 
591 #define ABSTRACT_TYPELOC(CLASS, PARENT)
592 #define TYPELOC(CLASS, PARENT)                                   \
593   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
594 #include "clang/AST/TypeLocNodes.def"
595 
596   template<typename Fn>
597   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
598                                       FunctionProtoTypeLoc TL,
599                                       CXXRecordDecl *ThisContext,
600                                       Qualifiers ThisTypeQuals,
601                                       Fn TransformExceptionSpec);
602 
603   bool TransformExceptionSpec(SourceLocation Loc,
604                               FunctionProtoType::ExceptionSpecInfo &ESI,
605                               SmallVectorImpl<QualType> &Exceptions,
606                               bool &Changed);
607 
608   StmtResult TransformSEHHandler(Stmt *Handler);
609 
610   QualType
611   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
612                                       TemplateSpecializationTypeLoc TL,
613                                       TemplateName Template);
614 
615   QualType
616   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
617                                       DependentTemplateSpecializationTypeLoc TL,
618                                                TemplateName Template,
619                                                CXXScopeSpec &SS);
620 
621   QualType TransformDependentTemplateSpecializationType(
622       TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
623       NestedNameSpecifierLoc QualifierLoc);
624 
625   /// Transforms the parameters of a function type into the
626   /// given vectors.
627   ///
628   /// The result vectors should be kept in sync; null entries in the
629   /// variables vector are acceptable.
630   ///
631   /// Return true on error.
632   bool TransformFunctionTypeParams(
633       SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
634       const QualType *ParamTypes,
635       const FunctionProtoType::ExtParameterInfo *ParamInfos,
636       SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
637       Sema::ExtParameterInfoBuilder &PInfos);
638 
639   /// Transforms a single function-type parameter.  Return null
640   /// on error.
641   ///
642   /// \param indexAdjustment - A number to add to the parameter's
643   ///   scope index;  can be negative
644   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
645                                           int indexAdjustment,
646                                           Optional<unsigned> NumExpansions,
647                                           bool ExpectParameterPack);
648 
649   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
650 
651   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
652   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
653 
TransformTemplateParameterList(TemplateParameterList * TPL)654   TemplateParameterList *TransformTemplateParameterList(
655         TemplateParameterList *TPL) {
656     return TPL;
657   }
658 
659   ExprResult TransformAddressOfOperand(Expr *E);
660 
661   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
662                                                 bool IsAddressOfOperand,
663                                                 TypeSourceInfo **RecoveryTSI);
664 
665   ExprResult TransformParenDependentScopeDeclRefExpr(
666       ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
667       TypeSourceInfo **RecoveryTSI);
668 
669   StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
670 
671 // FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
672 // amount of stack usage with clang.
673 #define STMT(Node, Parent)                        \
674   LLVM_ATTRIBUTE_NOINLINE \
675   StmtResult Transform##Node(Node *S);
676 #define EXPR(Node, Parent)                        \
677   LLVM_ATTRIBUTE_NOINLINE \
678   ExprResult Transform##Node(Node *E);
679 #define ABSTRACT_STMT(Stmt)
680 #include "clang/AST/StmtNodes.inc"
681 
682 #define OPENMP_CLAUSE(Name, Class)                        \
683   LLVM_ATTRIBUTE_NOINLINE \
684   OMPClause *Transform ## Class(Class *S);
685 #include "clang/Basic/OpenMPKinds.def"
686 
687   /// Build a new qualified type given its unqualified type and type location.
688   ///
689   /// By default, this routine adds type qualifiers only to types that can
690   /// have qualifiers, and silently suppresses those qualifiers that are not
691   /// permitted. Subclasses may override this routine to provide different
692   /// behavior.
693   QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
694 
695   /// Build a new pointer type given its pointee type.
696   ///
697   /// By default, performs semantic analysis when building the pointer type.
698   /// Subclasses may override this routine to provide different behavior.
699   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
700 
701   /// Build a new block pointer type given its pointee type.
702   ///
703   /// By default, performs semantic analysis when building the block pointer
704   /// type. Subclasses may override this routine to provide different behavior.
705   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
706 
707   /// Build a new reference type given the type it references.
708   ///
709   /// By default, performs semantic analysis when building the
710   /// reference type. Subclasses may override this routine to provide
711   /// different behavior.
712   ///
713   /// \param LValue whether the type was written with an lvalue sigil
714   /// or an rvalue sigil.
715   QualType RebuildReferenceType(QualType ReferentType,
716                                 bool LValue,
717                                 SourceLocation Sigil);
718 
719   /// Build a new member pointer type given the pointee type and the
720   /// class type it refers into.
721   ///
722   /// By default, performs semantic analysis when building the member pointer
723   /// type. Subclasses may override this routine to provide different behavior.
724   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
725                                     SourceLocation Sigil);
726 
727   QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
728                                     SourceLocation ProtocolLAngleLoc,
729                                     ArrayRef<ObjCProtocolDecl *> Protocols,
730                                     ArrayRef<SourceLocation> ProtocolLocs,
731                                     SourceLocation ProtocolRAngleLoc);
732 
733   /// Build an Objective-C object type.
734   ///
735   /// By default, performs semantic analysis when building the object type.
736   /// Subclasses may override this routine to provide different behavior.
737   QualType RebuildObjCObjectType(QualType BaseType,
738                                  SourceLocation Loc,
739                                  SourceLocation TypeArgsLAngleLoc,
740                                  ArrayRef<TypeSourceInfo *> TypeArgs,
741                                  SourceLocation TypeArgsRAngleLoc,
742                                  SourceLocation ProtocolLAngleLoc,
743                                  ArrayRef<ObjCProtocolDecl *> Protocols,
744                                  ArrayRef<SourceLocation> ProtocolLocs,
745                                  SourceLocation ProtocolRAngleLoc);
746 
747   /// Build a new Objective-C object pointer type given the pointee type.
748   ///
749   /// By default, directly builds the pointer type, with no additional semantic
750   /// analysis.
751   QualType RebuildObjCObjectPointerType(QualType PointeeType,
752                                         SourceLocation Star);
753 
754   /// Build a new array type given the element type, size
755   /// modifier, size of the array (if known), size expression, and index type
756   /// qualifiers.
757   ///
758   /// By default, performs semantic analysis when building the array type.
759   /// Subclasses may override this routine to provide different behavior.
760   /// Also by default, all of the other Rebuild*Array
761   QualType RebuildArrayType(QualType ElementType,
762                             ArrayType::ArraySizeModifier SizeMod,
763                             const llvm::APInt *Size,
764                             Expr *SizeExpr,
765                             unsigned IndexTypeQuals,
766                             SourceRange BracketsRange);
767 
768   /// Build a new constant array type given the element type, size
769   /// modifier, (known) size of the array, and index type qualifiers.
770   ///
771   /// By default, performs semantic analysis when building the array type.
772   /// Subclasses may override this routine to provide different behavior.
773   QualType RebuildConstantArrayType(QualType ElementType,
774                                     ArrayType::ArraySizeModifier SizeMod,
775                                     const llvm::APInt &Size,
776                                     unsigned IndexTypeQuals,
777                                     SourceRange BracketsRange);
778 
779   /// Build a new incomplete array type given the element type, size
780   /// modifier, and index type qualifiers.
781   ///
782   /// By default, performs semantic analysis when building the array type.
783   /// Subclasses may override this routine to provide different behavior.
784   QualType RebuildIncompleteArrayType(QualType ElementType,
785                                       ArrayType::ArraySizeModifier SizeMod,
786                                       unsigned IndexTypeQuals,
787                                       SourceRange BracketsRange);
788 
789   /// Build a new variable-length array type given the element type,
790   /// size modifier, size expression, and index type qualifiers.
791   ///
792   /// By default, performs semantic analysis when building the array type.
793   /// Subclasses may override this routine to provide different behavior.
794   QualType RebuildVariableArrayType(QualType ElementType,
795                                     ArrayType::ArraySizeModifier SizeMod,
796                                     Expr *SizeExpr,
797                                     unsigned IndexTypeQuals,
798                                     SourceRange BracketsRange);
799 
800   /// Build a new dependent-sized array type given the element type,
801   /// size modifier, size expression, and index type qualifiers.
802   ///
803   /// By default, performs semantic analysis when building the array type.
804   /// Subclasses may override this routine to provide different behavior.
805   QualType RebuildDependentSizedArrayType(QualType ElementType,
806                                           ArrayType::ArraySizeModifier SizeMod,
807                                           Expr *SizeExpr,
808                                           unsigned IndexTypeQuals,
809                                           SourceRange BracketsRange);
810 
811   /// Build a new vector type given the element type and
812   /// number of elements.
813   ///
814   /// By default, performs semantic analysis when building the vector type.
815   /// Subclasses may override this routine to provide different behavior.
816   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
817                              VectorType::VectorKind VecKind);
818 
819   /// Build a new potentially dependently-sized extended vector type
820   /// given the element type and number of elements.
821   ///
822   /// By default, performs semantic analysis when building the vector type.
823   /// Subclasses may override this routine to provide different behavior.
824   QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
825                                            SourceLocation AttributeLoc,
826                                            VectorType::VectorKind);
827 
828   /// Build a new extended vector type given the element type and
829   /// number of elements.
830   ///
831   /// By default, performs semantic analysis when building the vector type.
832   /// Subclasses may override this routine to provide different behavior.
833   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
834                                 SourceLocation AttributeLoc);
835 
836   /// Build a new potentially dependently-sized extended vector type
837   /// given the element type and number of elements.
838   ///
839   /// By default, performs semantic analysis when building the vector type.
840   /// Subclasses may override this routine to provide different behavior.
841   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
842                                               Expr *SizeExpr,
843                                               SourceLocation AttributeLoc);
844 
845   /// Build a new DependentAddressSpaceType or return the pointee
846   /// type variable with the correct address space (retrieved from
847   /// AddrSpaceExpr) applied to it. The former will be returned in cases
848   /// where the address space remains dependent.
849   ///
850   /// By default, performs semantic analysis when building the type with address
851   /// space applied. Subclasses may override this routine to provide different
852   /// behavior.
853   QualType RebuildDependentAddressSpaceType(QualType PointeeType,
854                                             Expr *AddrSpaceExpr,
855                                             SourceLocation AttributeLoc);
856 
857   /// Build a new function type.
858   ///
859   /// By default, performs semantic analysis when building the function type.
860   /// Subclasses may override this routine to provide different behavior.
861   QualType RebuildFunctionProtoType(QualType T,
862                                     MutableArrayRef<QualType> ParamTypes,
863                                     const FunctionProtoType::ExtProtoInfo &EPI);
864 
865   /// Build a new unprototyped function type.
866   QualType RebuildFunctionNoProtoType(QualType ResultType);
867 
868   /// Rebuild an unresolved typename type, given the decl that
869   /// the UnresolvedUsingTypenameDecl was transformed to.
870   QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
871 
872   /// Build a new typedef type.
RebuildTypedefType(TypedefNameDecl * Typedef)873   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
874     return SemaRef.Context.getTypeDeclType(Typedef);
875   }
876 
877   /// Build a new class/struct/union type.
RebuildRecordType(RecordDecl * Record)878   QualType RebuildRecordType(RecordDecl *Record) {
879     return SemaRef.Context.getTypeDeclType(Record);
880   }
881 
882   /// Build a new Enum type.
RebuildEnumType(EnumDecl * Enum)883   QualType RebuildEnumType(EnumDecl *Enum) {
884     return SemaRef.Context.getTypeDeclType(Enum);
885   }
886 
887   /// Build a new typeof(expr) type.
888   ///
889   /// By default, performs semantic analysis when building the typeof type.
890   /// Subclasses may override this routine to provide different behavior.
891   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
892 
893   /// Build a new typeof(type) type.
894   ///
895   /// By default, builds a new TypeOfType with the given underlying type.
896   QualType RebuildTypeOfType(QualType Underlying);
897 
898   /// Build a new unary transform type.
899   QualType RebuildUnaryTransformType(QualType BaseType,
900                                      UnaryTransformType::UTTKind UKind,
901                                      SourceLocation Loc);
902 
903   /// Build a new C++11 decltype type.
904   ///
905   /// By default, performs semantic analysis when building the decltype type.
906   /// Subclasses may override this routine to provide different behavior.
907   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
908 
909   /// Build a new C++11 auto type.
910   ///
911   /// By default, builds a new AutoType with the given deduced type.
RebuildAutoType(QualType Deduced,AutoTypeKeyword Keyword)912   QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword) {
913     // Note, IsDependent is always false here: we implicitly convert an 'auto'
914     // which has been deduced to a dependent type into an undeduced 'auto', so
915     // that we'll retry deduction after the transformation.
916     return SemaRef.Context.getAutoType(Deduced, Keyword,
917                                        /*IsDependent*/ false);
918   }
919 
920   /// By default, builds a new DeducedTemplateSpecializationType with the given
921   /// deduced type.
RebuildDeducedTemplateSpecializationType(TemplateName Template,QualType Deduced)922   QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
923       QualType Deduced) {
924     return SemaRef.Context.getDeducedTemplateSpecializationType(
925         Template, Deduced, /*IsDependent*/ false);
926   }
927 
928   /// Build a new template specialization type.
929   ///
930   /// By default, performs semantic analysis when building the template
931   /// specialization type. Subclasses may override this routine to provide
932   /// different behavior.
933   QualType RebuildTemplateSpecializationType(TemplateName Template,
934                                              SourceLocation TemplateLoc,
935                                              TemplateArgumentListInfo &Args);
936 
937   /// Build a new parenthesized type.
938   ///
939   /// By default, builds a new ParenType type from the inner type.
940   /// Subclasses may override this routine to provide different behavior.
RebuildParenType(QualType InnerType)941   QualType RebuildParenType(QualType InnerType) {
942     return SemaRef.BuildParenType(InnerType);
943   }
944 
945   /// Build a new qualified name type.
946   ///
947   /// By default, builds a new ElaboratedType type from the keyword,
948   /// the nested-name-specifier and the named type.
949   /// Subclasses may override this routine to provide different behavior.
RebuildElaboratedType(SourceLocation KeywordLoc,ElaboratedTypeKeyword Keyword,NestedNameSpecifierLoc QualifierLoc,QualType Named)950   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
951                                  ElaboratedTypeKeyword Keyword,
952                                  NestedNameSpecifierLoc QualifierLoc,
953                                  QualType Named) {
954     return SemaRef.Context.getElaboratedType(Keyword,
955                                          QualifierLoc.getNestedNameSpecifier(),
956                                              Named);
957   }
958 
959   /// Build a new typename type that refers to a template-id.
960   ///
961   /// By default, builds a new DependentNameType type from the
962   /// nested-name-specifier and the given type. Subclasses may override
963   /// this routine to provide different behavior.
RebuildDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,const IdentifierInfo * Name,SourceLocation NameLoc,TemplateArgumentListInfo & Args,bool AllowInjectedClassName)964   QualType RebuildDependentTemplateSpecializationType(
965                                           ElaboratedTypeKeyword Keyword,
966                                           NestedNameSpecifierLoc QualifierLoc,
967                                           SourceLocation TemplateKWLoc,
968                                           const IdentifierInfo *Name,
969                                           SourceLocation NameLoc,
970                                           TemplateArgumentListInfo &Args,
971                                           bool AllowInjectedClassName) {
972     // Rebuild the template name.
973     // TODO: avoid TemplateName abstraction
974     CXXScopeSpec SS;
975     SS.Adopt(QualifierLoc);
976     TemplateName InstName = getDerived().RebuildTemplateName(
977         SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
978         AllowInjectedClassName);
979 
980     if (InstName.isNull())
981       return QualType();
982 
983     // If it's still dependent, make a dependent specialization.
984     if (InstName.getAsDependentTemplateName())
985       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
986                                           QualifierLoc.getNestedNameSpecifier(),
987                                                                     Name,
988                                                                     Args);
989 
990     // Otherwise, make an elaborated type wrapping a non-dependent
991     // specialization.
992     QualType T =
993     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
994     if (T.isNull()) return QualType();
995 
996     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == nullptr)
997       return T;
998 
999     return SemaRef.Context.getElaboratedType(Keyword,
1000                                        QualifierLoc.getNestedNameSpecifier(),
1001                                              T);
1002   }
1003 
1004   /// Build a new typename type that refers to an identifier.
1005   ///
1006   /// By default, performs semantic analysis when building the typename type
1007   /// (or elaborated type). Subclasses may override this routine to provide
1008   /// different behavior.
RebuildDependentNameType(ElaboratedTypeKeyword Keyword,SourceLocation KeywordLoc,NestedNameSpecifierLoc QualifierLoc,const IdentifierInfo * Id,SourceLocation IdLoc,bool DeducedTSTContext)1009   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1010                                     SourceLocation KeywordLoc,
1011                                     NestedNameSpecifierLoc QualifierLoc,
1012                                     const IdentifierInfo *Id,
1013                                     SourceLocation IdLoc,
1014                                     bool DeducedTSTContext) {
1015     CXXScopeSpec SS;
1016     SS.Adopt(QualifierLoc);
1017 
1018     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1019       // If the name is still dependent, just build a new dependent name type.
1020       if (!SemaRef.computeDeclContext(SS))
1021         return SemaRef.Context.getDependentNameType(Keyword,
1022                                           QualifierLoc.getNestedNameSpecifier(),
1023                                                     Id);
1024     }
1025 
1026     if (Keyword == ETK_None || Keyword == ETK_Typename) {
1027       QualType T = SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1028                                              *Id, IdLoc);
1029       // If a dependent name resolves to a deduced template specialization type,
1030       // check that we're in one of the syntactic contexts permitting it.
1031       if (!DeducedTSTContext) {
1032         if (auto *Deduced = dyn_cast_or_null<DeducedTemplateSpecializationType>(
1033                 T.isNull() ? nullptr : T->getContainedDeducedType())) {
1034           SemaRef.Diag(IdLoc, diag::err_dependent_deduced_tst)
1035             << (int)SemaRef.getTemplateNameKindForDiagnostics(
1036                    Deduced->getTemplateName())
1037             << QualType(QualifierLoc.getNestedNameSpecifier()->getAsType(), 0);
1038           if (auto *TD = Deduced->getTemplateName().getAsTemplateDecl())
1039             SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
1040           return QualType();
1041         }
1042       }
1043       return T;
1044     }
1045 
1046     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1047 
1048     // We had a dependent elaborated-type-specifier that has been transformed
1049     // into a non-dependent elaborated-type-specifier. Find the tag we're
1050     // referring to.
1051     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1052     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1053     if (!DC)
1054       return QualType();
1055 
1056     if (SemaRef.RequireCompleteDeclContext(SS, DC))
1057       return QualType();
1058 
1059     TagDecl *Tag = nullptr;
1060     SemaRef.LookupQualifiedName(Result, DC);
1061     switch (Result.getResultKind()) {
1062       case LookupResult::NotFound:
1063       case LookupResult::NotFoundInCurrentInstantiation:
1064         break;
1065 
1066       case LookupResult::Found:
1067         Tag = Result.getAsSingle<TagDecl>();
1068         break;
1069 
1070       case LookupResult::FoundOverloaded:
1071       case LookupResult::FoundUnresolvedValue:
1072         llvm_unreachable("Tag lookup cannot find non-tags");
1073 
1074       case LookupResult::Ambiguous:
1075         // Let the LookupResult structure handle ambiguities.
1076         return QualType();
1077     }
1078 
1079     if (!Tag) {
1080       // Check where the name exists but isn't a tag type and use that to emit
1081       // better diagnostics.
1082       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1083       SemaRef.LookupQualifiedName(Result, DC);
1084       switch (Result.getResultKind()) {
1085         case LookupResult::Found:
1086         case LookupResult::FoundOverloaded:
1087         case LookupResult::FoundUnresolvedValue: {
1088           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1089           Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1090           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1091                                                                << NTK << Kind;
1092           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1093           break;
1094         }
1095         default:
1096           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1097               << Kind << Id << DC << QualifierLoc.getSourceRange();
1098           break;
1099       }
1100       return QualType();
1101     }
1102 
1103     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1104                                               IdLoc, Id)) {
1105       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1106       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1107       return QualType();
1108     }
1109 
1110     // Build the elaborated-type-specifier type.
1111     QualType T = SemaRef.Context.getTypeDeclType(Tag);
1112     return SemaRef.Context.getElaboratedType(Keyword,
1113                                          QualifierLoc.getNestedNameSpecifier(),
1114                                              T);
1115   }
1116 
1117   /// Build a new pack expansion type.
1118   ///
1119   /// By default, builds a new PackExpansionType type from the given pattern.
1120   /// Subclasses may override this routine to provide different behavior.
RebuildPackExpansionType(QualType Pattern,SourceRange PatternRange,SourceLocation EllipsisLoc,Optional<unsigned> NumExpansions)1121   QualType RebuildPackExpansionType(QualType Pattern,
1122                                     SourceRange PatternRange,
1123                                     SourceLocation EllipsisLoc,
1124                                     Optional<unsigned> NumExpansions) {
1125     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1126                                         NumExpansions);
1127   }
1128 
1129   /// Build a new atomic type given its value type.
1130   ///
1131   /// By default, performs semantic analysis when building the atomic type.
1132   /// Subclasses may override this routine to provide different behavior.
1133   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1134 
1135   /// Build a new pipe type given its value type.
1136   QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1137                            bool isReadPipe);
1138 
1139   /// Build a new template name given a nested name specifier, a flag
1140   /// indicating whether the "template" keyword was provided, and the template
1141   /// that the template name refers to.
1142   ///
1143   /// By default, builds the new template name directly. Subclasses may override
1144   /// this routine to provide different behavior.
1145   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1146                                    bool TemplateKW,
1147                                    TemplateDecl *Template);
1148 
1149   /// Build a new template name given a nested name specifier and the
1150   /// name that is referred to as a template.
1151   ///
1152   /// By default, performs semantic analysis to determine whether the name can
1153   /// be resolved to a specific template, then builds the appropriate kind of
1154   /// template name. Subclasses may override this routine to provide different
1155   /// behavior.
1156   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1157                                    SourceLocation TemplateKWLoc,
1158                                    const IdentifierInfo &Name,
1159                                    SourceLocation NameLoc, QualType ObjectType,
1160                                    NamedDecl *FirstQualifierInScope,
1161                                    bool AllowInjectedClassName);
1162 
1163   /// Build a new template name given a nested name specifier and the
1164   /// overloaded operator name that is referred to as a template.
1165   ///
1166   /// By default, performs semantic analysis to determine whether the name can
1167   /// be resolved to a specific template, then builds the appropriate kind of
1168   /// template name. Subclasses may override this routine to provide different
1169   /// behavior.
1170   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1171                                    SourceLocation TemplateKWLoc,
1172                                    OverloadedOperatorKind Operator,
1173                                    SourceLocation NameLoc, QualType ObjectType,
1174                                    bool AllowInjectedClassName);
1175 
1176   /// Build a new template name given a template template parameter pack
1177   /// and the
1178   ///
1179   /// By default, performs semantic analysis to determine whether the name can
1180   /// be resolved to a specific template, then builds the appropriate kind of
1181   /// template name. Subclasses may override this routine to provide different
1182   /// behavior.
RebuildTemplateName(TemplateTemplateParmDecl * Param,const TemplateArgument & ArgPack)1183   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1184                                    const TemplateArgument &ArgPack) {
1185     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1186   }
1187 
1188   /// Build a new compound statement.
1189   ///
1190   /// By default, performs semantic analysis to build the new statement.
1191   /// Subclasses may override this routine to provide different behavior.
RebuildCompoundStmt(SourceLocation LBraceLoc,MultiStmtArg Statements,SourceLocation RBraceLoc,bool IsStmtExpr)1192   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1193                                        MultiStmtArg Statements,
1194                                        SourceLocation RBraceLoc,
1195                                        bool IsStmtExpr) {
1196     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1197                                        IsStmtExpr);
1198   }
1199 
1200   /// Build a new case statement.
1201   ///
1202   /// By default, performs semantic analysis to build the new statement.
1203   /// Subclasses may override this routine to provide different behavior.
RebuildCaseStmt(SourceLocation CaseLoc,Expr * LHS,SourceLocation EllipsisLoc,Expr * RHS,SourceLocation ColonLoc)1204   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1205                                    Expr *LHS,
1206                                    SourceLocation EllipsisLoc,
1207                                    Expr *RHS,
1208                                    SourceLocation ColonLoc) {
1209     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1210                                    ColonLoc);
1211   }
1212 
1213   /// Attach the body to a new case statement.
1214   ///
1215   /// By default, performs semantic analysis to build the new statement.
1216   /// Subclasses may override this routine to provide different behavior.
RebuildCaseStmtBody(Stmt * S,Stmt * Body)1217   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1218     getSema().ActOnCaseStmtBody(S, Body);
1219     return S;
1220   }
1221 
1222   /// Build a new default statement.
1223   ///
1224   /// By default, performs semantic analysis to build the new statement.
1225   /// Subclasses may override this routine to provide different behavior.
RebuildDefaultStmt(SourceLocation DefaultLoc,SourceLocation ColonLoc,Stmt * SubStmt)1226   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1227                                       SourceLocation ColonLoc,
1228                                       Stmt *SubStmt) {
1229     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1230                                       /*CurScope=*/nullptr);
1231   }
1232 
1233   /// Build a new label statement.
1234   ///
1235   /// By default, performs semantic analysis to build the new statement.
1236   /// Subclasses may override this routine to provide different behavior.
RebuildLabelStmt(SourceLocation IdentLoc,LabelDecl * L,SourceLocation ColonLoc,Stmt * SubStmt)1237   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1238                               SourceLocation ColonLoc, Stmt *SubStmt) {
1239     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1240   }
1241 
1242   /// Build a new label statement.
1243   ///
1244   /// By default, performs semantic analysis to build the new statement.
1245   /// Subclasses may override this routine to provide different behavior.
RebuildAttributedStmt(SourceLocation AttrLoc,ArrayRef<const Attr * > Attrs,Stmt * SubStmt)1246   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1247                                    ArrayRef<const Attr*> Attrs,
1248                                    Stmt *SubStmt) {
1249     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1250   }
1251 
1252   /// Build a new "if" statement.
1253   ///
1254   /// By default, performs semantic analysis to build the new statement.
1255   /// Subclasses may override this routine to provide different behavior.
RebuildIfStmt(SourceLocation IfLoc,bool IsConstexpr,Sema::ConditionResult Cond,Stmt * Init,Stmt * Then,SourceLocation ElseLoc,Stmt * Else)1256   StmtResult RebuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
1257                            Sema::ConditionResult Cond, Stmt *Init, Stmt *Then,
1258                            SourceLocation ElseLoc, Stmt *Else) {
1259     return getSema().ActOnIfStmt(IfLoc, IsConstexpr, Init, Cond, Then,
1260                                  ElseLoc, Else);
1261   }
1262 
1263   /// Start building a new switch statement.
1264   ///
1265   /// By default, performs semantic analysis to build the new statement.
1266   /// Subclasses may override this routine to provide different behavior.
RebuildSwitchStmtStart(SourceLocation SwitchLoc,Stmt * Init,Sema::ConditionResult Cond)1267   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc, Stmt *Init,
1268                                     Sema::ConditionResult Cond) {
1269     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Init, Cond);
1270   }
1271 
1272   /// Attach the body to the switch statement.
1273   ///
1274   /// By default, performs semantic analysis to build the new statement.
1275   /// Subclasses may override this routine to provide different behavior.
RebuildSwitchStmtBody(SourceLocation SwitchLoc,Stmt * Switch,Stmt * Body)1276   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1277                                    Stmt *Switch, Stmt *Body) {
1278     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1279   }
1280 
1281   /// Build a new while statement.
1282   ///
1283   /// By default, performs semantic analysis to build the new statement.
1284   /// Subclasses may override this routine to provide different behavior.
RebuildWhileStmt(SourceLocation WhileLoc,Sema::ConditionResult Cond,Stmt * Body)1285   StmtResult RebuildWhileStmt(SourceLocation WhileLoc,
1286                               Sema::ConditionResult Cond, Stmt *Body) {
1287     return getSema().ActOnWhileStmt(WhileLoc, Cond, Body);
1288   }
1289 
1290   /// Build a new do-while statement.
1291   ///
1292   /// By default, performs semantic analysis to build the new statement.
1293   /// Subclasses may override this routine to provide different behavior.
RebuildDoStmt(SourceLocation DoLoc,Stmt * Body,SourceLocation WhileLoc,SourceLocation LParenLoc,Expr * Cond,SourceLocation RParenLoc)1294   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1295                            SourceLocation WhileLoc, SourceLocation LParenLoc,
1296                            Expr *Cond, SourceLocation RParenLoc) {
1297     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1298                                  Cond, RParenLoc);
1299   }
1300 
1301   /// Build a new for statement.
1302   ///
1303   /// By default, performs semantic analysis to build the new statement.
1304   /// Subclasses may override this routine to provide different behavior.
RebuildForStmt(SourceLocation ForLoc,SourceLocation LParenLoc,Stmt * Init,Sema::ConditionResult Cond,Sema::FullExprArg Inc,SourceLocation RParenLoc,Stmt * Body)1305   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1306                             Stmt *Init, Sema::ConditionResult Cond,
1307                             Sema::FullExprArg Inc, SourceLocation RParenLoc,
1308                             Stmt *Body) {
1309     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1310                                   Inc, RParenLoc, Body);
1311   }
1312 
1313   /// Build a new goto statement.
1314   ///
1315   /// By default, performs semantic analysis to build the new statement.
1316   /// Subclasses may override this routine to provide different behavior.
RebuildGotoStmt(SourceLocation GotoLoc,SourceLocation LabelLoc,LabelDecl * Label)1317   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1318                              LabelDecl *Label) {
1319     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1320   }
1321 
1322   /// Build a new indirect goto statement.
1323   ///
1324   /// By default, performs semantic analysis to build the new statement.
1325   /// Subclasses may override this routine to provide different behavior.
RebuildIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc,Expr * Target)1326   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1327                                      SourceLocation StarLoc,
1328                                      Expr *Target) {
1329     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1330   }
1331 
1332   /// Build a new return statement.
1333   ///
1334   /// By default, performs semantic analysis to build the new statement.
1335   /// Subclasses may override this routine to provide different behavior.
RebuildReturnStmt(SourceLocation ReturnLoc,Expr * Result)1336   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1337     return getSema().BuildReturnStmt(ReturnLoc, Result);
1338   }
1339 
1340   /// Build a new declaration statement.
1341   ///
1342   /// By default, performs semantic analysis to build the new statement.
1343   /// Subclasses may override this routine to provide different behavior.
RebuildDeclStmt(MutableArrayRef<Decl * > Decls,SourceLocation StartLoc,SourceLocation EndLoc)1344   StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1345                              SourceLocation StartLoc, SourceLocation EndLoc) {
1346     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1347     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1348   }
1349 
1350   /// Build a new inline asm statement.
1351   ///
1352   /// By default, performs semantic analysis to build the new statement.
1353   /// Subclasses may override this routine to provide different behavior.
RebuildGCCAsmStmt(SourceLocation AsmLoc,bool IsSimple,bool IsVolatile,unsigned NumOutputs,unsigned NumInputs,IdentifierInfo ** Names,MultiExprArg Constraints,MultiExprArg Exprs,Expr * AsmString,MultiExprArg Clobbers,SourceLocation RParenLoc)1354   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1355                                bool IsVolatile, unsigned NumOutputs,
1356                                unsigned NumInputs, IdentifierInfo **Names,
1357                                MultiExprArg Constraints, MultiExprArg Exprs,
1358                                Expr *AsmString, MultiExprArg Clobbers,
1359                                SourceLocation RParenLoc) {
1360     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1361                                      NumInputs, Names, Constraints, Exprs,
1362                                      AsmString, Clobbers, RParenLoc);
1363   }
1364 
1365   /// Build a new MS style inline asm statement.
1366   ///
1367   /// By default, performs semantic analysis to build the new statement.
1368   /// Subclasses may override this routine to provide different behavior.
RebuildMSAsmStmt(SourceLocation AsmLoc,SourceLocation LBraceLoc,ArrayRef<Token> AsmToks,StringRef AsmString,unsigned NumOutputs,unsigned NumInputs,ArrayRef<StringRef> Constraints,ArrayRef<StringRef> Clobbers,ArrayRef<Expr * > Exprs,SourceLocation EndLoc)1369   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1370                               ArrayRef<Token> AsmToks,
1371                               StringRef AsmString,
1372                               unsigned NumOutputs, unsigned NumInputs,
1373                               ArrayRef<StringRef> Constraints,
1374                               ArrayRef<StringRef> Clobbers,
1375                               ArrayRef<Expr*> Exprs,
1376                               SourceLocation EndLoc) {
1377     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1378                                     NumOutputs, NumInputs,
1379                                     Constraints, Clobbers, Exprs, EndLoc);
1380   }
1381 
1382   /// Build a new co_return statement.
1383   ///
1384   /// By default, performs semantic analysis to build the new statement.
1385   /// Subclasses may override this routine to provide different behavior.
RebuildCoreturnStmt(SourceLocation CoreturnLoc,Expr * Result,bool IsImplicit)1386   StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1387                                  bool IsImplicit) {
1388     return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1389   }
1390 
1391   /// Build a new co_await expression.
1392   ///
1393   /// By default, performs semantic analysis to build the new expression.
1394   /// Subclasses may override this routine to provide different behavior.
RebuildCoawaitExpr(SourceLocation CoawaitLoc,Expr * Result,bool IsImplicit)1395   ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Result,
1396                                 bool IsImplicit) {
1397     return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Result, IsImplicit);
1398   }
1399 
1400   /// Build a new co_await expression.
1401   ///
1402   /// By default, performs semantic analysis to build the new expression.
1403   /// Subclasses may override this routine to provide different behavior.
RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,Expr * Result,UnresolvedLookupExpr * Lookup)1404   ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1405                                          Expr *Result,
1406                                          UnresolvedLookupExpr *Lookup) {
1407     return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1408   }
1409 
1410   /// Build a new co_yield expression.
1411   ///
1412   /// By default, performs semantic analysis to build the new expression.
1413   /// Subclasses may override this routine to provide different behavior.
RebuildCoyieldExpr(SourceLocation CoyieldLoc,Expr * Result)1414   ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1415     return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1416   }
1417 
RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args)1418   StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1419     return getSema().BuildCoroutineBodyStmt(Args);
1420   }
1421 
1422   /// Build a new Objective-C \@try statement.
1423   ///
1424   /// By default, performs semantic analysis to build the new statement.
1425   /// Subclasses may override this routine to provide different behavior.
RebuildObjCAtTryStmt(SourceLocation AtLoc,Stmt * TryBody,MultiStmtArg CatchStmts,Stmt * Finally)1426   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1427                                         Stmt *TryBody,
1428                                         MultiStmtArg CatchStmts,
1429                                         Stmt *Finally) {
1430     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1431                                         Finally);
1432   }
1433 
1434   /// Rebuild an Objective-C exception declaration.
1435   ///
1436   /// By default, performs semantic analysis to build the new declaration.
1437   /// Subclasses may override this routine to provide different behavior.
RebuildObjCExceptionDecl(VarDecl * ExceptionDecl,TypeSourceInfo * TInfo,QualType T)1438   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1439                                     TypeSourceInfo *TInfo, QualType T) {
1440     return getSema().BuildObjCExceptionDecl(TInfo, T,
1441                                             ExceptionDecl->getInnerLocStart(),
1442                                             ExceptionDecl->getLocation(),
1443                                             ExceptionDecl->getIdentifier());
1444   }
1445 
1446   /// Build a new Objective-C \@catch statement.
1447   ///
1448   /// By default, performs semantic analysis to build the new statement.
1449   /// Subclasses may override this routine to provide different behavior.
RebuildObjCAtCatchStmt(SourceLocation AtLoc,SourceLocation RParenLoc,VarDecl * Var,Stmt * Body)1450   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1451                                           SourceLocation RParenLoc,
1452                                           VarDecl *Var,
1453                                           Stmt *Body) {
1454     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1455                                           Var, Body);
1456   }
1457 
1458   /// Build a new Objective-C \@finally statement.
1459   ///
1460   /// By default, performs semantic analysis to build the new statement.
1461   /// Subclasses may override this routine to provide different behavior.
RebuildObjCAtFinallyStmt(SourceLocation AtLoc,Stmt * Body)1462   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1463                                             Stmt *Body) {
1464     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1465   }
1466 
1467   /// Build a new Objective-C \@throw statement.
1468   ///
1469   /// By default, performs semantic analysis to build the new statement.
1470   /// Subclasses may override this routine to provide different behavior.
RebuildObjCAtThrowStmt(SourceLocation AtLoc,Expr * Operand)1471   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1472                                           Expr *Operand) {
1473     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1474   }
1475 
1476   /// Build a new OpenMP executable directive.
1477   ///
1478   /// By default, performs semantic analysis to build the new statement.
1479   /// Subclasses may override this routine to provide different behavior.
RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,DeclarationNameInfo DirName,OpenMPDirectiveKind CancelRegion,ArrayRef<OMPClause * > Clauses,Stmt * AStmt,SourceLocation StartLoc,SourceLocation EndLoc)1480   StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1481                                            DeclarationNameInfo DirName,
1482                                            OpenMPDirectiveKind CancelRegion,
1483                                            ArrayRef<OMPClause *> Clauses,
1484                                            Stmt *AStmt, SourceLocation StartLoc,
1485                                            SourceLocation EndLoc) {
1486     return getSema().ActOnOpenMPExecutableDirective(
1487         Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1488   }
1489 
1490   /// Build a new OpenMP 'if' clause.
1491   ///
1492   /// By default, performs semantic analysis to build the new OpenMP clause.
1493   /// Subclasses may override this routine to provide different behavior.
RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,Expr * Condition,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation NameModifierLoc,SourceLocation ColonLoc,SourceLocation EndLoc)1494   OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1495                                 Expr *Condition, SourceLocation StartLoc,
1496                                 SourceLocation LParenLoc,
1497                                 SourceLocation NameModifierLoc,
1498                                 SourceLocation ColonLoc,
1499                                 SourceLocation EndLoc) {
1500     return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1501                                          LParenLoc, NameModifierLoc, ColonLoc,
1502                                          EndLoc);
1503   }
1504 
1505   /// Build a new OpenMP 'final' clause.
1506   ///
1507   /// By default, performs semantic analysis to build the new OpenMP clause.
1508   /// Subclasses may override this routine to provide different behavior.
RebuildOMPFinalClause(Expr * Condition,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1509   OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1510                                    SourceLocation LParenLoc,
1511                                    SourceLocation EndLoc) {
1512     return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1513                                             EndLoc);
1514   }
1515 
1516   /// Build a new OpenMP 'num_threads' clause.
1517   ///
1518   /// By default, performs semantic analysis to build the new OpenMP clause.
1519   /// Subclasses may override this routine to provide different behavior.
RebuildOMPNumThreadsClause(Expr * NumThreads,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1520   OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1521                                         SourceLocation StartLoc,
1522                                         SourceLocation LParenLoc,
1523                                         SourceLocation EndLoc) {
1524     return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1525                                                  LParenLoc, EndLoc);
1526   }
1527 
1528   /// Build a new OpenMP 'safelen' clause.
1529   ///
1530   /// By default, performs semantic analysis to build the new OpenMP clause.
1531   /// Subclasses may override this routine to provide different behavior.
RebuildOMPSafelenClause(Expr * Len,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1532   OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1533                                      SourceLocation LParenLoc,
1534                                      SourceLocation EndLoc) {
1535     return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1536   }
1537 
1538   /// Build a new OpenMP 'simdlen' clause.
1539   ///
1540   /// By default, performs semantic analysis to build the new OpenMP clause.
1541   /// Subclasses may override this routine to provide different behavior.
RebuildOMPSimdlenClause(Expr * Len,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1542   OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1543                                      SourceLocation LParenLoc,
1544                                      SourceLocation EndLoc) {
1545     return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1546   }
1547 
1548   /// Build a new OpenMP 'collapse' clause.
1549   ///
1550   /// By default, performs semantic analysis to build the new OpenMP clause.
1551   /// Subclasses may override this routine to provide different behavior.
RebuildOMPCollapseClause(Expr * Num,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1552   OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1553                                       SourceLocation LParenLoc,
1554                                       SourceLocation EndLoc) {
1555     return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1556                                                EndLoc);
1557   }
1558 
1559   /// Build a new OpenMP 'default' clause.
1560   ///
1561   /// By default, performs semantic analysis to build the new OpenMP clause.
1562   /// Subclasses may override this routine to provide different behavior.
RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,SourceLocation KindKwLoc,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1563   OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
1564                                      SourceLocation KindKwLoc,
1565                                      SourceLocation StartLoc,
1566                                      SourceLocation LParenLoc,
1567                                      SourceLocation EndLoc) {
1568     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1569                                               StartLoc, LParenLoc, EndLoc);
1570   }
1571 
1572   /// Build a new OpenMP 'proc_bind' clause.
1573   ///
1574   /// By default, performs semantic analysis to build the new OpenMP clause.
1575   /// Subclasses may override this routine to provide different behavior.
RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,SourceLocation KindKwLoc,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1576   OMPClause *RebuildOMPProcBindClause(OpenMPProcBindClauseKind Kind,
1577                                       SourceLocation KindKwLoc,
1578                                       SourceLocation StartLoc,
1579                                       SourceLocation LParenLoc,
1580                                       SourceLocation EndLoc) {
1581     return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1582                                                StartLoc, LParenLoc, EndLoc);
1583   }
1584 
1585   /// Build a new OpenMP 'schedule' clause.
1586   ///
1587   /// By default, performs semantic analysis to build the new OpenMP clause.
1588   /// Subclasses may override this routine to provide different behavior.
RebuildOMPScheduleClause(OpenMPScheduleClauseModifier M1,OpenMPScheduleClauseModifier M2,OpenMPScheduleClauseKind Kind,Expr * ChunkSize,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation M1Loc,SourceLocation M2Loc,SourceLocation KindLoc,SourceLocation CommaLoc,SourceLocation EndLoc)1589   OMPClause *RebuildOMPScheduleClause(
1590       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1591       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1592       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1593       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1594     return getSema().ActOnOpenMPScheduleClause(
1595         M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1596         CommaLoc, EndLoc);
1597   }
1598 
1599   /// Build a new OpenMP 'ordered' clause.
1600   ///
1601   /// By default, performs semantic analysis to build the new OpenMP clause.
1602   /// Subclasses may override this routine to provide different behavior.
RebuildOMPOrderedClause(SourceLocation StartLoc,SourceLocation EndLoc,SourceLocation LParenLoc,Expr * Num)1603   OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1604                                      SourceLocation EndLoc,
1605                                      SourceLocation LParenLoc, Expr *Num) {
1606     return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1607   }
1608 
1609   /// Build a new OpenMP 'private' clause.
1610   ///
1611   /// By default, performs semantic analysis to build the new OpenMP clause.
1612   /// Subclasses may override this routine to provide different behavior.
RebuildOMPPrivateClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1613   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1614                                      SourceLocation StartLoc,
1615                                      SourceLocation LParenLoc,
1616                                      SourceLocation EndLoc) {
1617     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1618                                               EndLoc);
1619   }
1620 
1621   /// Build a new OpenMP 'firstprivate' clause.
1622   ///
1623   /// By default, performs semantic analysis to build the new OpenMP clause.
1624   /// Subclasses may override this routine to provide different behavior.
RebuildOMPFirstprivateClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1625   OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1626                                           SourceLocation StartLoc,
1627                                           SourceLocation LParenLoc,
1628                                           SourceLocation EndLoc) {
1629     return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1630                                                    EndLoc);
1631   }
1632 
1633   /// Build a new OpenMP 'lastprivate' clause.
1634   ///
1635   /// By default, performs semantic analysis to build the new OpenMP clause.
1636   /// Subclasses may override this routine to provide different behavior.
RebuildOMPLastprivateClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1637   OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1638                                          SourceLocation StartLoc,
1639                                          SourceLocation LParenLoc,
1640                                          SourceLocation EndLoc) {
1641     return getSema().ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc,
1642                                                   EndLoc);
1643   }
1644 
1645   /// Build a new OpenMP 'shared' clause.
1646   ///
1647   /// By default, performs semantic analysis to build the new OpenMP clause.
1648   /// Subclasses may override this routine to provide different behavior.
RebuildOMPSharedClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1649   OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1650                                     SourceLocation StartLoc,
1651                                     SourceLocation LParenLoc,
1652                                     SourceLocation EndLoc) {
1653     return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1654                                              EndLoc);
1655   }
1656 
1657   /// Build a new OpenMP 'reduction' clause.
1658   ///
1659   /// By default, performs semantic analysis to build the new statement.
1660   /// Subclasses may override this routine to provide different behavior.
RebuildOMPReductionClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation ColonLoc,SourceLocation EndLoc,CXXScopeSpec & ReductionIdScopeSpec,const DeclarationNameInfo & ReductionId,ArrayRef<Expr * > UnresolvedReductions)1661   OMPClause *RebuildOMPReductionClause(ArrayRef<Expr *> VarList,
1662                                        SourceLocation StartLoc,
1663                                        SourceLocation LParenLoc,
1664                                        SourceLocation ColonLoc,
1665                                        SourceLocation EndLoc,
1666                                        CXXScopeSpec &ReductionIdScopeSpec,
1667                                        const DeclarationNameInfo &ReductionId,
1668                                        ArrayRef<Expr *> UnresolvedReductions) {
1669     return getSema().ActOnOpenMPReductionClause(
1670         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1671         ReductionId, UnresolvedReductions);
1672   }
1673 
1674   /// Build a new OpenMP 'task_reduction' clause.
1675   ///
1676   /// By default, performs semantic analysis to build the new statement.
1677   /// Subclasses may override this routine to provide different behavior.
RebuildOMPTaskReductionClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation ColonLoc,SourceLocation EndLoc,CXXScopeSpec & ReductionIdScopeSpec,const DeclarationNameInfo & ReductionId,ArrayRef<Expr * > UnresolvedReductions)1678   OMPClause *RebuildOMPTaskReductionClause(
1679       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1680       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1681       CXXScopeSpec &ReductionIdScopeSpec,
1682       const DeclarationNameInfo &ReductionId,
1683       ArrayRef<Expr *> UnresolvedReductions) {
1684     return getSema().ActOnOpenMPTaskReductionClause(
1685         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1686         ReductionId, UnresolvedReductions);
1687   }
1688 
1689   /// Build a new OpenMP 'in_reduction' clause.
1690   ///
1691   /// By default, performs semantic analysis to build the new statement.
1692   /// Subclasses may override this routine to provide different behavior.
1693   OMPClause *
RebuildOMPInReductionClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation ColonLoc,SourceLocation EndLoc,CXXScopeSpec & ReductionIdScopeSpec,const DeclarationNameInfo & ReductionId,ArrayRef<Expr * > UnresolvedReductions)1694   RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1695                               SourceLocation LParenLoc, SourceLocation ColonLoc,
1696                               SourceLocation EndLoc,
1697                               CXXScopeSpec &ReductionIdScopeSpec,
1698                               const DeclarationNameInfo &ReductionId,
1699                               ArrayRef<Expr *> UnresolvedReductions) {
1700     return getSema().ActOnOpenMPInReductionClause(
1701         VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1702         ReductionId, UnresolvedReductions);
1703   }
1704 
1705   /// Build a new OpenMP 'linear' clause.
1706   ///
1707   /// By default, performs semantic analysis to build the new OpenMP clause.
1708   /// Subclasses may override this routine to provide different behavior.
RebuildOMPLinearClause(ArrayRef<Expr * > VarList,Expr * Step,SourceLocation StartLoc,SourceLocation LParenLoc,OpenMPLinearClauseKind Modifier,SourceLocation ModifierLoc,SourceLocation ColonLoc,SourceLocation EndLoc)1709   OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1710                                     SourceLocation StartLoc,
1711                                     SourceLocation LParenLoc,
1712                                     OpenMPLinearClauseKind Modifier,
1713                                     SourceLocation ModifierLoc,
1714                                     SourceLocation ColonLoc,
1715                                     SourceLocation EndLoc) {
1716     return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1717                                              Modifier, ModifierLoc, ColonLoc,
1718                                              EndLoc);
1719   }
1720 
1721   /// Build a new OpenMP 'aligned' clause.
1722   ///
1723   /// By default, performs semantic analysis to build the new OpenMP clause.
1724   /// Subclasses may override this routine to provide different behavior.
RebuildOMPAlignedClause(ArrayRef<Expr * > VarList,Expr * Alignment,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation ColonLoc,SourceLocation EndLoc)1725   OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1726                                      SourceLocation StartLoc,
1727                                      SourceLocation LParenLoc,
1728                                      SourceLocation ColonLoc,
1729                                      SourceLocation EndLoc) {
1730     return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1731                                               LParenLoc, ColonLoc, EndLoc);
1732   }
1733 
1734   /// Build a new OpenMP 'copyin' clause.
1735   ///
1736   /// By default, performs semantic analysis to build the new OpenMP clause.
1737   /// Subclasses may override this routine to provide different behavior.
RebuildOMPCopyinClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1738   OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1739                                     SourceLocation StartLoc,
1740                                     SourceLocation LParenLoc,
1741                                     SourceLocation EndLoc) {
1742     return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1743                                              EndLoc);
1744   }
1745 
1746   /// Build a new OpenMP 'copyprivate' clause.
1747   ///
1748   /// By default, performs semantic analysis to build the new OpenMP clause.
1749   /// Subclasses may override this routine to provide different behavior.
RebuildOMPCopyprivateClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1750   OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1751                                          SourceLocation StartLoc,
1752                                          SourceLocation LParenLoc,
1753                                          SourceLocation EndLoc) {
1754     return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1755                                                   EndLoc);
1756   }
1757 
1758   /// Build a new OpenMP 'flush' pseudo clause.
1759   ///
1760   /// By default, performs semantic analysis to build the new OpenMP clause.
1761   /// Subclasses may override this routine to provide different behavior.
RebuildOMPFlushClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1762   OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1763                                    SourceLocation StartLoc,
1764                                    SourceLocation LParenLoc,
1765                                    SourceLocation EndLoc) {
1766     return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1767                                             EndLoc);
1768   }
1769 
1770   /// Build a new OpenMP 'depend' pseudo clause.
1771   ///
1772   /// By default, performs semantic analysis to build the new OpenMP clause.
1773   /// Subclasses may override this routine to provide different behavior.
1774   OMPClause *
RebuildOMPDependClause(OpenMPDependClauseKind DepKind,SourceLocation DepLoc,SourceLocation ColonLoc,ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1775   RebuildOMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
1776                          SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
1777                          SourceLocation StartLoc, SourceLocation LParenLoc,
1778                          SourceLocation EndLoc) {
1779     return getSema().ActOnOpenMPDependClause(DepKind, DepLoc, ColonLoc, VarList,
1780                                              StartLoc, LParenLoc, EndLoc);
1781   }
1782 
1783   /// Build a new OpenMP 'device' clause.
1784   ///
1785   /// By default, performs semantic analysis to build the new statement.
1786   /// Subclasses may override this routine to provide different behavior.
RebuildOMPDeviceClause(Expr * Device,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1787   OMPClause *RebuildOMPDeviceClause(Expr *Device, SourceLocation StartLoc,
1788                                     SourceLocation LParenLoc,
1789                                     SourceLocation EndLoc) {
1790     return getSema().ActOnOpenMPDeviceClause(Device, StartLoc, LParenLoc,
1791                                              EndLoc);
1792   }
1793 
1794   /// Build a new OpenMP 'map' clause.
1795   ///
1796   /// By default, performs semantic analysis to build the new OpenMP clause.
1797   /// Subclasses may override this routine to provide different behavior.
1798   OMPClause *
RebuildOMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,ArrayRef<SourceLocation> MapTypeModifiersLoc,OpenMPMapClauseKind MapType,bool IsMapTypeImplicit,SourceLocation MapLoc,SourceLocation ColonLoc,ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1799   RebuildOMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
1800                       ArrayRef<SourceLocation> MapTypeModifiersLoc,
1801                       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
1802                       SourceLocation MapLoc, SourceLocation ColonLoc,
1803                       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1804                       SourceLocation LParenLoc, SourceLocation EndLoc) {
1805     return getSema().ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
1806                                           MapType, IsMapTypeImplicit, MapLoc,
1807                                           ColonLoc, VarList, StartLoc,
1808                                           LParenLoc, EndLoc);
1809   }
1810 
1811   /// Build a new OpenMP 'num_teams' clause.
1812   ///
1813   /// By default, performs semantic analysis to build the new statement.
1814   /// Subclasses may override this routine to provide different behavior.
RebuildOMPNumTeamsClause(Expr * NumTeams,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1815   OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
1816                                       SourceLocation LParenLoc,
1817                                       SourceLocation EndLoc) {
1818     return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
1819                                                EndLoc);
1820   }
1821 
1822   /// Build a new OpenMP 'thread_limit' clause.
1823   ///
1824   /// By default, performs semantic analysis to build the new statement.
1825   /// Subclasses may override this routine to provide different behavior.
RebuildOMPThreadLimitClause(Expr * ThreadLimit,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1826   OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
1827                                          SourceLocation StartLoc,
1828                                          SourceLocation LParenLoc,
1829                                          SourceLocation EndLoc) {
1830     return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
1831                                                   LParenLoc, EndLoc);
1832   }
1833 
1834   /// Build a new OpenMP 'priority' clause.
1835   ///
1836   /// By default, performs semantic analysis to build the new statement.
1837   /// Subclasses may override this routine to provide different behavior.
RebuildOMPPriorityClause(Expr * Priority,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1838   OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
1839                                       SourceLocation LParenLoc,
1840                                       SourceLocation EndLoc) {
1841     return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
1842                                                EndLoc);
1843   }
1844 
1845   /// Build a new OpenMP 'grainsize' clause.
1846   ///
1847   /// By default, performs semantic analysis to build the new statement.
1848   /// Subclasses may override this routine to provide different behavior.
RebuildOMPGrainsizeClause(Expr * Grainsize,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1849   OMPClause *RebuildOMPGrainsizeClause(Expr *Grainsize, SourceLocation StartLoc,
1850                                        SourceLocation LParenLoc,
1851                                        SourceLocation EndLoc) {
1852     return getSema().ActOnOpenMPGrainsizeClause(Grainsize, StartLoc, LParenLoc,
1853                                                 EndLoc);
1854   }
1855 
1856   /// Build a new OpenMP 'num_tasks' clause.
1857   ///
1858   /// By default, performs semantic analysis to build the new statement.
1859   /// Subclasses may override this routine to provide different behavior.
RebuildOMPNumTasksClause(Expr * NumTasks,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1860   OMPClause *RebuildOMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
1861                                       SourceLocation LParenLoc,
1862                                       SourceLocation EndLoc) {
1863     return getSema().ActOnOpenMPNumTasksClause(NumTasks, StartLoc, LParenLoc,
1864                                                EndLoc);
1865   }
1866 
1867   /// Build a new OpenMP 'hint' clause.
1868   ///
1869   /// By default, performs semantic analysis to build the new statement.
1870   /// Subclasses may override this routine to provide different behavior.
RebuildOMPHintClause(Expr * Hint,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1871   OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
1872                                   SourceLocation LParenLoc,
1873                                   SourceLocation EndLoc) {
1874     return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
1875   }
1876 
1877   /// Build a new OpenMP 'dist_schedule' clause.
1878   ///
1879   /// By default, performs semantic analysis to build the new OpenMP clause.
1880   /// Subclasses may override this routine to provide different behavior.
1881   OMPClause *
RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,Expr * ChunkSize,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation KindLoc,SourceLocation CommaLoc,SourceLocation EndLoc)1882   RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
1883                                Expr *ChunkSize, SourceLocation StartLoc,
1884                                SourceLocation LParenLoc, SourceLocation KindLoc,
1885                                SourceLocation CommaLoc, SourceLocation EndLoc) {
1886     return getSema().ActOnOpenMPDistScheduleClause(
1887         Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
1888   }
1889 
1890   /// Build a new OpenMP 'to' clause.
1891   ///
1892   /// By default, performs semantic analysis to build the new statement.
1893   /// Subclasses may override this routine to provide different behavior.
RebuildOMPToClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1894   OMPClause *RebuildOMPToClause(ArrayRef<Expr *> VarList,
1895                                 SourceLocation StartLoc,
1896                                 SourceLocation LParenLoc,
1897                                 SourceLocation EndLoc) {
1898     return getSema().ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
1899   }
1900 
1901   /// Build a new OpenMP 'from' clause.
1902   ///
1903   /// By default, performs semantic analysis to build the new statement.
1904   /// Subclasses may override this routine to provide different behavior.
RebuildOMPFromClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1905   OMPClause *RebuildOMPFromClause(ArrayRef<Expr *> VarList,
1906                                   SourceLocation StartLoc,
1907                                   SourceLocation LParenLoc,
1908                                   SourceLocation EndLoc) {
1909     return getSema().ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc,
1910                                            EndLoc);
1911   }
1912 
1913   /// Build a new OpenMP 'use_device_ptr' clause.
1914   ///
1915   /// By default, performs semantic analysis to build the new OpenMP clause.
1916   /// Subclasses may override this routine to provide different behavior.
RebuildOMPUseDevicePtrClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1917   OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
1918                                           SourceLocation StartLoc,
1919                                           SourceLocation LParenLoc,
1920                                           SourceLocation EndLoc) {
1921     return getSema().ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc,
1922                                                    EndLoc);
1923   }
1924 
1925   /// Build a new OpenMP 'is_device_ptr' clause.
1926   ///
1927   /// By default, performs semantic analysis to build the new OpenMP clause.
1928   /// Subclasses may override this routine to provide different behavior.
RebuildOMPIsDevicePtrClause(ArrayRef<Expr * > VarList,SourceLocation StartLoc,SourceLocation LParenLoc,SourceLocation EndLoc)1929   OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
1930                                          SourceLocation StartLoc,
1931                                          SourceLocation LParenLoc,
1932                                          SourceLocation EndLoc) {
1933     return getSema().ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc,
1934                                                   EndLoc);
1935   }
1936 
1937   /// Rebuild the operand to an Objective-C \@synchronized statement.
1938   ///
1939   /// By default, performs semantic analysis to build the new statement.
1940   /// Subclasses may override this routine to provide different behavior.
RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,Expr * object)1941   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1942                                               Expr *object) {
1943     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1944   }
1945 
1946   /// Build a new Objective-C \@synchronized statement.
1947   ///
1948   /// By default, performs semantic analysis to build the new statement.
1949   /// Subclasses may override this routine to provide different behavior.
RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,Expr * Object,Stmt * Body)1950   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1951                                            Expr *Object, Stmt *Body) {
1952     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
1953   }
1954 
1955   /// Build a new Objective-C \@autoreleasepool statement.
1956   ///
1957   /// By default, performs semantic analysis to build the new statement.
1958   /// Subclasses may override this routine to provide different behavior.
RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,Stmt * Body)1959   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
1960                                             Stmt *Body) {
1961     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
1962   }
1963 
1964   /// Build a new Objective-C fast enumeration statement.
1965   ///
1966   /// By default, performs semantic analysis to build the new statement.
1967   /// Subclasses may override this routine to provide different behavior.
RebuildObjCForCollectionStmt(SourceLocation ForLoc,Stmt * Element,Expr * Collection,SourceLocation RParenLoc,Stmt * Body)1968   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1969                                           Stmt *Element,
1970                                           Expr *Collection,
1971                                           SourceLocation RParenLoc,
1972                                           Stmt *Body) {
1973     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
1974                                                 Element,
1975                                                 Collection,
1976                                                 RParenLoc);
1977     if (ForEachStmt.isInvalid())
1978       return StmtError();
1979 
1980     return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
1981   }
1982 
1983   /// Build a new C++ exception declaration.
1984   ///
1985   /// By default, performs semantic analysis to build the new decaration.
1986   /// Subclasses may override this routine to provide different behavior.
RebuildExceptionDecl(VarDecl * ExceptionDecl,TypeSourceInfo * Declarator,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id)1987   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1988                                 TypeSourceInfo *Declarator,
1989                                 SourceLocation StartLoc,
1990                                 SourceLocation IdLoc,
1991                                 IdentifierInfo *Id) {
1992     VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
1993                                                        StartLoc, IdLoc, Id);
1994     if (Var)
1995       getSema().CurContext->addDecl(Var);
1996     return Var;
1997   }
1998 
1999   /// Build a new C++ catch statement.
2000   ///
2001   /// By default, performs semantic analysis to build the new statement.
2002   /// Subclasses may override this routine to provide different behavior.
RebuildCXXCatchStmt(SourceLocation CatchLoc,VarDecl * ExceptionDecl,Stmt * Handler)2003   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2004                                  VarDecl *ExceptionDecl,
2005                                  Stmt *Handler) {
2006     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2007                                                       Handler));
2008   }
2009 
2010   /// Build a new C++ try statement.
2011   ///
2012   /// By default, performs semantic analysis to build the new statement.
2013   /// Subclasses may override this routine to provide different behavior.
RebuildCXXTryStmt(SourceLocation TryLoc,Stmt * TryBlock,ArrayRef<Stmt * > Handlers)2014   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2015                                ArrayRef<Stmt *> Handlers) {
2016     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2017   }
2018 
2019   /// Build a new C++0x range-based for statement.
2020   ///
2021   /// By default, performs semantic analysis to build the new statement.
2022   /// Subclasses may override this routine to provide different behavior.
RebuildCXXForRangeStmt(SourceLocation ForLoc,SourceLocation CoawaitLoc,Stmt * Init,SourceLocation ColonLoc,Stmt * Range,Stmt * Begin,Stmt * End,Expr * Cond,Expr * Inc,Stmt * LoopVar,SourceLocation RParenLoc)2023   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2024                                     SourceLocation CoawaitLoc, Stmt *Init,
2025                                     SourceLocation ColonLoc, Stmt *Range,
2026                                     Stmt *Begin, Stmt *End, Expr *Cond,
2027                                     Expr *Inc, Stmt *LoopVar,
2028                                     SourceLocation RParenLoc) {
2029     // If we've just learned that the range is actually an Objective-C
2030     // collection, treat this as an Objective-C fast enumeration loop.
2031     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2032       if (RangeStmt->isSingleDecl()) {
2033         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2034           if (RangeVar->isInvalidDecl())
2035             return StmtError();
2036 
2037           Expr *RangeExpr = RangeVar->getInit();
2038           if (!RangeExpr->isTypeDependent() &&
2039               RangeExpr->getType()->isObjCObjectPointerType()) {
2040             // FIXME: Support init-statements in Objective-C++20 ranged for
2041             // statement.
2042             if (Init) {
2043               return SemaRef.Diag(Init->getBeginLoc(),
2044                                   diag::err_objc_for_range_init_stmt)
2045                          << Init->getSourceRange();
2046             }
2047             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2048                                                         RangeExpr, RParenLoc);
2049           }
2050         }
2051       }
2052     }
2053 
2054     return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2055                                           Range, Begin, End, Cond, Inc, LoopVar,
2056                                           RParenLoc, Sema::BFRK_Rebuild);
2057   }
2058 
2059   /// Build a new C++0x range-based for statement.
2060   ///
2061   /// By default, performs semantic analysis to build the new statement.
2062   /// Subclasses may override this routine to provide different behavior.
RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,bool IsIfExists,NestedNameSpecifierLoc QualifierLoc,DeclarationNameInfo NameInfo,Stmt * Nested)2063   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2064                                           bool IsIfExists,
2065                                           NestedNameSpecifierLoc QualifierLoc,
2066                                           DeclarationNameInfo NameInfo,
2067                                           Stmt *Nested) {
2068     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2069                                                 QualifierLoc, NameInfo, Nested);
2070   }
2071 
2072   /// Attach body to a C++0x range-based for statement.
2073   ///
2074   /// By default, performs semantic analysis to finish the new statement.
2075   /// Subclasses may override this routine to provide different behavior.
FinishCXXForRangeStmt(Stmt * ForRange,Stmt * Body)2076   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2077     return getSema().FinishCXXForRangeStmt(ForRange, Body);
2078   }
2079 
RebuildSEHTryStmt(bool IsCXXTry,SourceLocation TryLoc,Stmt * TryBlock,Stmt * Handler)2080   StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2081                                Stmt *TryBlock, Stmt *Handler) {
2082     return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2083   }
2084 
RebuildSEHExceptStmt(SourceLocation Loc,Expr * FilterExpr,Stmt * Block)2085   StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2086                                   Stmt *Block) {
2087     return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2088   }
2089 
RebuildSEHFinallyStmt(SourceLocation Loc,Stmt * Block)2090   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2091     return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2092   }
2093 
2094   /// Build a new predefined expression.
2095   ///
2096   /// By default, performs semantic analysis to build the new expression.
2097   /// Subclasses may override this routine to provide different behavior.
RebuildPredefinedExpr(SourceLocation Loc,PredefinedExpr::IdentKind IK)2098   ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2099                                    PredefinedExpr::IdentKind IK) {
2100     return getSema().BuildPredefinedExpr(Loc, IK);
2101   }
2102 
2103   /// Build a new expression that references a declaration.
2104   ///
2105   /// By default, performs semantic analysis to build the new expression.
2106   /// Subclasses may override this routine to provide different behavior.
RebuildDeclarationNameExpr(const CXXScopeSpec & SS,LookupResult & R,bool RequiresADL)2107   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2108                                         LookupResult &R,
2109                                         bool RequiresADL) {
2110     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2111   }
2112 
2113 
2114   /// Build a new expression that references a declaration.
2115   ///
2116   /// By default, performs semantic analysis to build the new expression.
2117   /// Subclasses may override this routine to provide different behavior.
RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,ValueDecl * VD,const DeclarationNameInfo & NameInfo,TemplateArgumentListInfo * TemplateArgs)2118   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2119                                 ValueDecl *VD,
2120                                 const DeclarationNameInfo &NameInfo,
2121                                 TemplateArgumentListInfo *TemplateArgs) {
2122     CXXScopeSpec SS;
2123     SS.Adopt(QualifierLoc);
2124 
2125     // FIXME: loses template args.
2126 
2127     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
2128   }
2129 
2130   /// Build a new expression in parentheses.
2131   ///
2132   /// By default, performs semantic analysis to build the new expression.
2133   /// Subclasses may override this routine to provide different behavior.
RebuildParenExpr(Expr * SubExpr,SourceLocation LParen,SourceLocation RParen)2134   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2135                                     SourceLocation RParen) {
2136     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2137   }
2138 
2139   /// Build a new pseudo-destructor expression.
2140   ///
2141   /// By default, performs semantic analysis to build the new expression.
2142   /// Subclasses may override this routine to provide different behavior.
2143   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2144                                             SourceLocation OperatorLoc,
2145                                             bool isArrow,
2146                                             CXXScopeSpec &SS,
2147                                             TypeSourceInfo *ScopeType,
2148                                             SourceLocation CCLoc,
2149                                             SourceLocation TildeLoc,
2150                                         PseudoDestructorTypeStorage Destroyed);
2151 
2152   /// Build a new unary operator expression.
2153   ///
2154   /// By default, performs semantic analysis to build the new expression.
2155   /// Subclasses may override this routine to provide different behavior.
RebuildUnaryOperator(SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * SubExpr)2156   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2157                                         UnaryOperatorKind Opc,
2158                                         Expr *SubExpr) {
2159     return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2160   }
2161 
2162   /// Build a new builtin offsetof expression.
2163   ///
2164   /// By default, performs semantic analysis to build the new expression.
2165   /// Subclasses may override this routine to provide different behavior.
RebuildOffsetOfExpr(SourceLocation OperatorLoc,TypeSourceInfo * Type,ArrayRef<Sema::OffsetOfComponent> Components,SourceLocation RParenLoc)2166   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2167                                  TypeSourceInfo *Type,
2168                                  ArrayRef<Sema::OffsetOfComponent> Components,
2169                                  SourceLocation RParenLoc) {
2170     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2171                                           RParenLoc);
2172   }
2173 
2174   /// Build a new sizeof, alignof or vec_step expression with a
2175   /// type argument.
2176   ///
2177   /// By default, performs semantic analysis to build the new expression.
2178   /// Subclasses may override this routine to provide different behavior.
RebuildUnaryExprOrTypeTrait(TypeSourceInfo * TInfo,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)2179   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2180                                          SourceLocation OpLoc,
2181                                          UnaryExprOrTypeTrait ExprKind,
2182                                          SourceRange R) {
2183     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2184   }
2185 
2186   /// Build a new sizeof, alignof or vec step expression with an
2187   /// expression argument.
2188   ///
2189   /// By default, performs semantic analysis to build the new expression.
2190   /// Subclasses may override this routine to provide different behavior.
RebuildUnaryExprOrTypeTrait(Expr * SubExpr,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)2191   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2192                                          UnaryExprOrTypeTrait ExprKind,
2193                                          SourceRange R) {
2194     ExprResult Result
2195       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2196     if (Result.isInvalid())
2197       return ExprError();
2198 
2199     return Result;
2200   }
2201 
2202   /// Build a new array subscript expression.
2203   ///
2204   /// By default, performs semantic analysis to build the new expression.
2205   /// Subclasses may override this routine to provide different behavior.
RebuildArraySubscriptExpr(Expr * LHS,SourceLocation LBracketLoc,Expr * RHS,SourceLocation RBracketLoc)2206   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2207                                              SourceLocation LBracketLoc,
2208                                              Expr *RHS,
2209                                              SourceLocation RBracketLoc) {
2210     return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2211                                              LBracketLoc, RHS,
2212                                              RBracketLoc);
2213   }
2214 
2215   /// Build a new array section expression.
2216   ///
2217   /// By default, performs semantic analysis to build the new expression.
2218   /// Subclasses may override this routine to provide different behavior.
RebuildOMPArraySectionExpr(Expr * Base,SourceLocation LBracketLoc,Expr * LowerBound,SourceLocation ColonLoc,Expr * Length,SourceLocation RBracketLoc)2219   ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2220                                         Expr *LowerBound,
2221                                         SourceLocation ColonLoc, Expr *Length,
2222                                         SourceLocation RBracketLoc) {
2223     return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2224                                               ColonLoc, Length, RBracketLoc);
2225   }
2226 
2227   /// Build a new call expression.
2228   ///
2229   /// By default, performs semantic analysis to build the new expression.
2230   /// Subclasses may override this routine to provide different behavior.
2231   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2232                                    MultiExprArg Args,
2233                                    SourceLocation RParenLoc,
2234                                    Expr *ExecConfig = nullptr) {
2235     return getSema().ActOnCallExpr(/*Scope=*/nullptr, Callee, LParenLoc,
2236                                    Args, RParenLoc, ExecConfig);
2237   }
2238 
2239   /// Build a new member access expression.
2240   ///
2241   /// By default, performs semantic analysis to build the new expression.
2242   /// Subclasses may override this routine to provide different behavior.
RebuildMemberExpr(Expr * Base,SourceLocation OpLoc,bool isArrow,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,const DeclarationNameInfo & MemberNameInfo,ValueDecl * Member,NamedDecl * FoundDecl,const TemplateArgumentListInfo * ExplicitTemplateArgs,NamedDecl * FirstQualifierInScope)2243   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2244                                bool isArrow,
2245                                NestedNameSpecifierLoc QualifierLoc,
2246                                SourceLocation TemplateKWLoc,
2247                                const DeclarationNameInfo &MemberNameInfo,
2248                                ValueDecl *Member,
2249                                NamedDecl *FoundDecl,
2250                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
2251                                NamedDecl *FirstQualifierInScope) {
2252     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2253                                                                       isArrow);
2254     if (!Member->getDeclName()) {
2255       // We have a reference to an unnamed field.  This is always the
2256       // base of an anonymous struct/union member access, i.e. the
2257       // field is always of record type.
2258       assert(Member->getType()->isRecordType() &&
2259              "unnamed member not of record type?");
2260 
2261       BaseResult =
2262         getSema().PerformObjectMemberConversion(BaseResult.get(),
2263                                                 QualifierLoc.getNestedNameSpecifier(),
2264                                                 FoundDecl, Member);
2265       if (BaseResult.isInvalid())
2266         return ExprError();
2267       Base = BaseResult.get();
2268 
2269       CXXScopeSpec EmptySS;
2270       return getSema().BuildFieldReferenceExpr(
2271           Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2272           DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2273     }
2274 
2275     CXXScopeSpec SS;
2276     SS.Adopt(QualifierLoc);
2277 
2278     Base = BaseResult.get();
2279     QualType BaseType = Base->getType();
2280 
2281     if (isArrow && !BaseType->isPointerType())
2282       return ExprError();
2283 
2284     // FIXME: this involves duplicating earlier analysis in a lot of
2285     // cases; we should avoid this when possible.
2286     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2287     R.addDecl(FoundDecl);
2288     R.resolveKind();
2289 
2290     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2291                                               SS, TemplateKWLoc,
2292                                               FirstQualifierInScope,
2293                                               R, ExplicitTemplateArgs,
2294                                               /*S*/nullptr);
2295   }
2296 
2297   /// Build a new binary operator expression.
2298   ///
2299   /// By default, performs semantic analysis to build the new expression.
2300   /// Subclasses may override this routine to provide different behavior.
RebuildBinaryOperator(SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHS,Expr * RHS)2301   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2302                                          BinaryOperatorKind Opc,
2303                                          Expr *LHS, Expr *RHS) {
2304     return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2305   }
2306 
2307   /// Build a new conditional operator expression.
2308   ///
2309   /// By default, performs semantic analysis to build the new expression.
2310   /// Subclasses may override this routine to provide different behavior.
RebuildConditionalOperator(Expr * Cond,SourceLocation QuestionLoc,Expr * LHS,SourceLocation ColonLoc,Expr * RHS)2311   ExprResult RebuildConditionalOperator(Expr *Cond,
2312                                         SourceLocation QuestionLoc,
2313                                         Expr *LHS,
2314                                         SourceLocation ColonLoc,
2315                                         Expr *RHS) {
2316     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2317                                         LHS, RHS);
2318   }
2319 
2320   /// Build a new C-style cast expression.
2321   ///
2322   /// By default, performs semantic analysis to build the new expression.
2323   /// Subclasses may override this routine to provide different behavior.
RebuildCStyleCastExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * SubExpr)2324   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2325                                          TypeSourceInfo *TInfo,
2326                                          SourceLocation RParenLoc,
2327                                          Expr *SubExpr) {
2328     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2329                                          SubExpr);
2330   }
2331 
2332   /// Build a new compound literal expression.
2333   ///
2334   /// By default, performs semantic analysis to build the new expression.
2335   /// Subclasses may override this routine to provide different behavior.
RebuildCompoundLiteralExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * Init)2336   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2337                                               TypeSourceInfo *TInfo,
2338                                               SourceLocation RParenLoc,
2339                                               Expr *Init) {
2340     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2341                                               Init);
2342   }
2343 
2344   /// Build a new extended vector element access expression.
2345   ///
2346   /// By default, performs semantic analysis to build the new expression.
2347   /// Subclasses may override this routine to provide different behavior.
RebuildExtVectorElementExpr(Expr * Base,SourceLocation OpLoc,SourceLocation AccessorLoc,IdentifierInfo & Accessor)2348   ExprResult RebuildExtVectorElementExpr(Expr *Base,
2349                                                SourceLocation OpLoc,
2350                                                SourceLocation AccessorLoc,
2351                                                IdentifierInfo &Accessor) {
2352 
2353     CXXScopeSpec SS;
2354     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2355     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
2356                                               OpLoc, /*IsArrow*/ false,
2357                                               SS, SourceLocation(),
2358                                               /*FirstQualifierInScope*/ nullptr,
2359                                               NameInfo,
2360                                               /* TemplateArgs */ nullptr,
2361                                               /*S*/ nullptr);
2362   }
2363 
2364   /// Build a new initializer list expression.
2365   ///
2366   /// By default, performs semantic analysis to build the new expression.
2367   /// Subclasses may override this routine to provide different behavior.
RebuildInitList(SourceLocation LBraceLoc,MultiExprArg Inits,SourceLocation RBraceLoc)2368   ExprResult RebuildInitList(SourceLocation LBraceLoc,
2369                              MultiExprArg Inits,
2370                              SourceLocation RBraceLoc) {
2371     return SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
2372   }
2373 
2374   /// Build a new designated initializer expression.
2375   ///
2376   /// By default, performs semantic analysis to build the new expression.
2377   /// Subclasses may override this routine to provide different behavior.
RebuildDesignatedInitExpr(Designation & Desig,MultiExprArg ArrayExprs,SourceLocation EqualOrColonLoc,bool GNUSyntax,Expr * Init)2378   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2379                                              MultiExprArg ArrayExprs,
2380                                              SourceLocation EqualOrColonLoc,
2381                                              bool GNUSyntax,
2382                                              Expr *Init) {
2383     ExprResult Result
2384       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2385                                            Init);
2386     if (Result.isInvalid())
2387       return ExprError();
2388 
2389     return Result;
2390   }
2391 
2392   /// Build a new value-initialized expression.
2393   ///
2394   /// By default, builds the implicit value initialization without performing
2395   /// any semantic analysis. Subclasses may override this routine to provide
2396   /// different behavior.
RebuildImplicitValueInitExpr(QualType T)2397   ExprResult RebuildImplicitValueInitExpr(QualType T) {
2398     return new (SemaRef.Context) ImplicitValueInitExpr(T);
2399   }
2400 
2401   /// Build a new \c va_arg expression.
2402   ///
2403   /// By default, performs semantic analysis to build the new expression.
2404   /// Subclasses may override this routine to provide different behavior.
RebuildVAArgExpr(SourceLocation BuiltinLoc,Expr * SubExpr,TypeSourceInfo * TInfo,SourceLocation RParenLoc)2405   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2406                                     Expr *SubExpr, TypeSourceInfo *TInfo,
2407                                     SourceLocation RParenLoc) {
2408     return getSema().BuildVAArgExpr(BuiltinLoc,
2409                                     SubExpr, TInfo,
2410                                     RParenLoc);
2411   }
2412 
2413   /// Build a new expression list in parentheses.
2414   ///
2415   /// By default, performs semantic analysis to build the new expression.
2416   /// Subclasses may override this routine to provide different behavior.
RebuildParenListExpr(SourceLocation LParenLoc,MultiExprArg SubExprs,SourceLocation RParenLoc)2417   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2418                                   MultiExprArg SubExprs,
2419                                   SourceLocation RParenLoc) {
2420     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2421   }
2422 
2423   /// Build a new address-of-label expression.
2424   ///
2425   /// By default, performs semantic analysis, using the name of the label
2426   /// rather than attempting to map the label statement itself.
2427   /// Subclasses may override this routine to provide different behavior.
RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,SourceLocation LabelLoc,LabelDecl * Label)2428   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2429                                   SourceLocation LabelLoc, LabelDecl *Label) {
2430     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2431   }
2432 
2433   /// Build a new GNU statement expression.
2434   ///
2435   /// By default, performs semantic analysis to build the new expression.
2436   /// Subclasses may override this routine to provide different behavior.
RebuildStmtExpr(SourceLocation LParenLoc,Stmt * SubStmt,SourceLocation RParenLoc)2437   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
2438                                    Stmt *SubStmt,
2439                                    SourceLocation RParenLoc) {
2440     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
2441   }
2442 
2443   /// Build a new __builtin_choose_expr expression.
2444   ///
2445   /// By default, performs semantic analysis to build the new expression.
2446   /// Subclasses may override this routine to provide different behavior.
RebuildChooseExpr(SourceLocation BuiltinLoc,Expr * Cond,Expr * LHS,Expr * RHS,SourceLocation RParenLoc)2447   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
2448                                      Expr *Cond, Expr *LHS, Expr *RHS,
2449                                      SourceLocation RParenLoc) {
2450     return SemaRef.ActOnChooseExpr(BuiltinLoc,
2451                                    Cond, LHS, RHS,
2452                                    RParenLoc);
2453   }
2454 
2455   /// Build a new generic selection expression.
2456   ///
2457   /// By default, performs semantic analysis to build the new expression.
2458   /// Subclasses may override this routine to provide different behavior.
RebuildGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > Types,ArrayRef<Expr * > Exprs)2459   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
2460                                          SourceLocation DefaultLoc,
2461                                          SourceLocation RParenLoc,
2462                                          Expr *ControllingExpr,
2463                                          ArrayRef<TypeSourceInfo *> Types,
2464                                          ArrayRef<Expr *> Exprs) {
2465     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
2466                                                 ControllingExpr, Types, Exprs);
2467   }
2468 
2469   /// Build a new overloaded operator call expression.
2470   ///
2471   /// By default, performs semantic analysis to build the new expression.
2472   /// The semantic analysis provides the behavior of template instantiation,
2473   /// copying with transformations that turn what looks like an overloaded
2474   /// operator call into a use of a builtin operator, performing
2475   /// argument-dependent lookup, etc. Subclasses may override this routine to
2476   /// provide different behavior.
2477   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
2478                                               SourceLocation OpLoc,
2479                                               Expr *Callee,
2480                                               Expr *First,
2481                                               Expr *Second);
2482 
2483   /// Build a new C++ "named" cast expression, such as static_cast or
2484   /// reinterpret_cast.
2485   ///
2486   /// By default, this routine dispatches to one of the more-specific routines
2487   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
2488   /// Subclasses may override this routine to provide different behavior.
RebuildCXXNamedCastExpr(SourceLocation OpLoc,Stmt::StmtClass Class,SourceLocation LAngleLoc,TypeSourceInfo * TInfo,SourceLocation RAngleLoc,SourceLocation LParenLoc,Expr * SubExpr,SourceLocation RParenLoc)2489   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
2490                                            Stmt::StmtClass Class,
2491                                            SourceLocation LAngleLoc,
2492                                            TypeSourceInfo *TInfo,
2493                                            SourceLocation RAngleLoc,
2494                                            SourceLocation LParenLoc,
2495                                            Expr *SubExpr,
2496                                            SourceLocation RParenLoc) {
2497     switch (Class) {
2498     case Stmt::CXXStaticCastExprClass:
2499       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
2500                                                    RAngleLoc, LParenLoc,
2501                                                    SubExpr, RParenLoc);
2502 
2503     case Stmt::CXXDynamicCastExprClass:
2504       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
2505                                                     RAngleLoc, LParenLoc,
2506                                                     SubExpr, RParenLoc);
2507 
2508     case Stmt::CXXReinterpretCastExprClass:
2509       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
2510                                                         RAngleLoc, LParenLoc,
2511                                                         SubExpr,
2512                                                         RParenLoc);
2513 
2514     case Stmt::CXXConstCastExprClass:
2515       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
2516                                                    RAngleLoc, LParenLoc,
2517                                                    SubExpr, RParenLoc);
2518 
2519     default:
2520       llvm_unreachable("Invalid C++ named cast");
2521     }
2522   }
2523 
2524   /// Build a new C++ static_cast expression.
2525   ///
2526   /// By default, performs semantic analysis to build the new expression.
2527   /// Subclasses may override this routine to provide different behavior.
RebuildCXXStaticCastExpr(SourceLocation OpLoc,SourceLocation LAngleLoc,TypeSourceInfo * TInfo,SourceLocation RAngleLoc,SourceLocation LParenLoc,Expr * SubExpr,SourceLocation RParenLoc)2528   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
2529                                             SourceLocation LAngleLoc,
2530                                             TypeSourceInfo *TInfo,
2531                                             SourceLocation RAngleLoc,
2532                                             SourceLocation LParenLoc,
2533                                             Expr *SubExpr,
2534                                             SourceLocation RParenLoc) {
2535     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
2536                                        TInfo, SubExpr,
2537                                        SourceRange(LAngleLoc, RAngleLoc),
2538                                        SourceRange(LParenLoc, RParenLoc));
2539   }
2540 
2541   /// Build a new C++ dynamic_cast expression.
2542   ///
2543   /// By default, performs semantic analysis to build the new expression.
2544   /// Subclasses may override this routine to provide different behavior.
RebuildCXXDynamicCastExpr(SourceLocation OpLoc,SourceLocation LAngleLoc,TypeSourceInfo * TInfo,SourceLocation RAngleLoc,SourceLocation LParenLoc,Expr * SubExpr,SourceLocation RParenLoc)2545   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
2546                                              SourceLocation LAngleLoc,
2547                                              TypeSourceInfo *TInfo,
2548                                              SourceLocation RAngleLoc,
2549                                              SourceLocation LParenLoc,
2550                                              Expr *SubExpr,
2551                                              SourceLocation RParenLoc) {
2552     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
2553                                        TInfo, SubExpr,
2554                                        SourceRange(LAngleLoc, RAngleLoc),
2555                                        SourceRange(LParenLoc, RParenLoc));
2556   }
2557 
2558   /// Build a new C++ reinterpret_cast expression.
2559   ///
2560   /// By default, performs semantic analysis to build the new expression.
2561   /// Subclasses may override this routine to provide different behavior.
RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,SourceLocation LAngleLoc,TypeSourceInfo * TInfo,SourceLocation RAngleLoc,SourceLocation LParenLoc,Expr * SubExpr,SourceLocation RParenLoc)2562   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
2563                                                  SourceLocation LAngleLoc,
2564                                                  TypeSourceInfo *TInfo,
2565                                                  SourceLocation RAngleLoc,
2566                                                  SourceLocation LParenLoc,
2567                                                  Expr *SubExpr,
2568                                                  SourceLocation RParenLoc) {
2569     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
2570                                        TInfo, SubExpr,
2571                                        SourceRange(LAngleLoc, RAngleLoc),
2572                                        SourceRange(LParenLoc, RParenLoc));
2573   }
2574 
2575   /// Build a new C++ const_cast expression.
2576   ///
2577   /// By default, performs semantic analysis to build the new expression.
2578   /// Subclasses may override this routine to provide different behavior.
RebuildCXXConstCastExpr(SourceLocation OpLoc,SourceLocation LAngleLoc,TypeSourceInfo * TInfo,SourceLocation RAngleLoc,SourceLocation LParenLoc,Expr * SubExpr,SourceLocation RParenLoc)2579   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
2580                                            SourceLocation LAngleLoc,
2581                                            TypeSourceInfo *TInfo,
2582                                            SourceLocation RAngleLoc,
2583                                            SourceLocation LParenLoc,
2584                                            Expr *SubExpr,
2585                                            SourceLocation RParenLoc) {
2586     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
2587                                        TInfo, SubExpr,
2588                                        SourceRange(LAngleLoc, RAngleLoc),
2589                                        SourceRange(LParenLoc, RParenLoc));
2590   }
2591 
2592   /// Build a new C++ functional-style cast expression.
2593   ///
2594   /// By default, performs semantic analysis to build the new expression.
2595   /// Subclasses may override this routine to provide different behavior.
RebuildCXXFunctionalCastExpr(TypeSourceInfo * TInfo,SourceLocation LParenLoc,Expr * Sub,SourceLocation RParenLoc,bool ListInitialization)2596   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
2597                                           SourceLocation LParenLoc,
2598                                           Expr *Sub,
2599                                           SourceLocation RParenLoc,
2600                                           bool ListInitialization) {
2601     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
2602                                                MultiExprArg(&Sub, 1), RParenLoc,
2603                                                ListInitialization);
2604   }
2605 
2606   /// Build a new C++ typeid(type) expression.
2607   ///
2608   /// By default, performs semantic analysis to build the new expression.
2609   /// Subclasses may override this routine to provide different behavior.
RebuildCXXTypeidExpr(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)2610   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2611                                         SourceLocation TypeidLoc,
2612                                         TypeSourceInfo *Operand,
2613                                         SourceLocation RParenLoc) {
2614     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2615                                     RParenLoc);
2616   }
2617 
2618 
2619   /// Build a new C++ typeid(expr) expression.
2620   ///
2621   /// By default, performs semantic analysis to build the new expression.
2622   /// Subclasses may override this routine to provide different behavior.
RebuildCXXTypeidExpr(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * Operand,SourceLocation RParenLoc)2623   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
2624                                         SourceLocation TypeidLoc,
2625                                         Expr *Operand,
2626                                         SourceLocation RParenLoc) {
2627     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
2628                                     RParenLoc);
2629   }
2630 
2631   /// Build a new C++ __uuidof(type) expression.
2632   ///
2633   /// By default, performs semantic analysis to build the new expression.
2634   /// Subclasses may override this routine to provide different behavior.
RebuildCXXUuidofExpr(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)2635   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2636                                         SourceLocation TypeidLoc,
2637                                         TypeSourceInfo *Operand,
2638                                         SourceLocation RParenLoc) {
2639     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2640                                     RParenLoc);
2641   }
2642 
2643   /// Build a new C++ __uuidof(expr) expression.
2644   ///
2645   /// By default, performs semantic analysis to build the new expression.
2646   /// Subclasses may override this routine to provide different behavior.
RebuildCXXUuidofExpr(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * Operand,SourceLocation RParenLoc)2647   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
2648                                         SourceLocation TypeidLoc,
2649                                         Expr *Operand,
2650                                         SourceLocation RParenLoc) {
2651     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
2652                                     RParenLoc);
2653   }
2654 
2655   /// Build a new C++ "this" expression.
2656   ///
2657   /// By default, builds a new "this" expression without performing any
2658   /// semantic analysis. Subclasses may override this routine to provide
2659   /// different behavior.
RebuildCXXThisExpr(SourceLocation ThisLoc,QualType ThisType,bool isImplicit)2660   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
2661                                 QualType ThisType,
2662                                 bool isImplicit) {
2663     getSema().CheckCXXThisCapture(ThisLoc);
2664     return new (getSema().Context) CXXThisExpr(ThisLoc, ThisType, isImplicit);
2665   }
2666 
2667   /// Build a new C++ throw expression.
2668   ///
2669   /// By default, performs semantic analysis to build the new expression.
2670   /// Subclasses may override this routine to provide different behavior.
RebuildCXXThrowExpr(SourceLocation ThrowLoc,Expr * Sub,bool IsThrownVariableInScope)2671   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
2672                                  bool IsThrownVariableInScope) {
2673     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
2674   }
2675 
2676   /// Build a new C++ default-argument expression.
2677   ///
2678   /// By default, builds a new default-argument expression, which does not
2679   /// require any semantic analysis. Subclasses may override this routine to
2680   /// provide different behavior.
RebuildCXXDefaultArgExpr(SourceLocation Loc,ParmVarDecl * Param)2681   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
2682                                             ParmVarDecl *Param) {
2683     return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param);
2684   }
2685 
2686   /// Build a new C++11 default-initialization expression.
2687   ///
2688   /// By default, builds a new default field initialization expression, which
2689   /// does not require any semantic analysis. Subclasses may override this
2690   /// routine to provide different behavior.
RebuildCXXDefaultInitExpr(SourceLocation Loc,FieldDecl * Field)2691   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2692                                        FieldDecl *Field) {
2693     return CXXDefaultInitExpr::Create(getSema().Context, Loc, Field);
2694   }
2695 
2696   /// Build a new C++ zero-initialization expression.
2697   ///
2698   /// By default, performs semantic analysis to build the new expression.
2699   /// Subclasses may override this routine to provide different behavior.
RebuildCXXScalarValueInitExpr(TypeSourceInfo * TSInfo,SourceLocation LParenLoc,SourceLocation RParenLoc)2700   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2701                                            SourceLocation LParenLoc,
2702                                            SourceLocation RParenLoc) {
2703     return getSema().BuildCXXTypeConstructExpr(
2704         TSInfo, LParenLoc, None, RParenLoc, /*ListInitialization=*/false);
2705   }
2706 
2707   /// Build a new C++ "new" expression.
2708   ///
2709   /// By default, performs semantic analysis to build the new expression.
2710   /// Subclasses may override this routine to provide different behavior.
RebuildCXXNewExpr(SourceLocation StartLoc,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,QualType AllocatedType,TypeSourceInfo * AllocatedTypeInfo,Expr * ArraySize,SourceRange DirectInitRange,Expr * Initializer)2711   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2712                                bool UseGlobal,
2713                                SourceLocation PlacementLParen,
2714                                MultiExprArg PlacementArgs,
2715                                SourceLocation PlacementRParen,
2716                                SourceRange TypeIdParens,
2717                                QualType AllocatedType,
2718                                TypeSourceInfo *AllocatedTypeInfo,
2719                                Expr *ArraySize,
2720                                SourceRange DirectInitRange,
2721                                Expr *Initializer) {
2722     return getSema().BuildCXXNew(StartLoc, UseGlobal,
2723                                  PlacementLParen,
2724                                  PlacementArgs,
2725                                  PlacementRParen,
2726                                  TypeIdParens,
2727                                  AllocatedType,
2728                                  AllocatedTypeInfo,
2729                                  ArraySize,
2730                                  DirectInitRange,
2731                                  Initializer);
2732   }
2733 
2734   /// Build a new C++ "delete" expression.
2735   ///
2736   /// By default, performs semantic analysis to build the new expression.
2737   /// Subclasses may override this routine to provide different behavior.
RebuildCXXDeleteExpr(SourceLocation StartLoc,bool IsGlobalDelete,bool IsArrayForm,Expr * Operand)2738   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2739                                         bool IsGlobalDelete,
2740                                         bool IsArrayForm,
2741                                         Expr *Operand) {
2742     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2743                                     Operand);
2744   }
2745 
2746   /// Build a new type trait expression.
2747   ///
2748   /// By default, performs semantic analysis to build the new expression.
2749   /// Subclasses may override this routine to provide different behavior.
RebuildTypeTrait(TypeTrait Trait,SourceLocation StartLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)2750   ExprResult RebuildTypeTrait(TypeTrait Trait,
2751                               SourceLocation StartLoc,
2752                               ArrayRef<TypeSourceInfo *> Args,
2753                               SourceLocation RParenLoc) {
2754     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2755   }
2756 
2757   /// Build a new array type trait expression.
2758   ///
2759   /// By default, performs semantic analysis to build the new expression.
2760   /// Subclasses may override this routine to provide different behavior.
RebuildArrayTypeTrait(ArrayTypeTrait Trait,SourceLocation StartLoc,TypeSourceInfo * TSInfo,Expr * DimExpr,SourceLocation RParenLoc)2761   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2762                                    SourceLocation StartLoc,
2763                                    TypeSourceInfo *TSInfo,
2764                                    Expr *DimExpr,
2765                                    SourceLocation RParenLoc) {
2766     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2767   }
2768 
2769   /// Build a new expression trait expression.
2770   ///
2771   /// By default, performs semantic analysis to build the new expression.
2772   /// Subclasses may override this routine to provide different behavior.
RebuildExpressionTrait(ExpressionTrait Trait,SourceLocation StartLoc,Expr * Queried,SourceLocation RParenLoc)2773   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2774                                    SourceLocation StartLoc,
2775                                    Expr *Queried,
2776                                    SourceLocation RParenLoc) {
2777     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2778   }
2779 
2780   /// Build a new (previously unresolved) declaration reference
2781   /// expression.
2782   ///
2783   /// By default, performs semantic analysis to build the new expression.
2784   /// Subclasses may override this routine to provide different behavior.
RebuildDependentScopeDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs,bool IsAddressOfOperand,TypeSourceInfo ** RecoveryTSI)2785   ExprResult RebuildDependentScopeDeclRefExpr(
2786                                           NestedNameSpecifierLoc QualifierLoc,
2787                                           SourceLocation TemplateKWLoc,
2788                                        const DeclarationNameInfo &NameInfo,
2789                               const TemplateArgumentListInfo *TemplateArgs,
2790                                           bool IsAddressOfOperand,
2791                                           TypeSourceInfo **RecoveryTSI) {
2792     CXXScopeSpec SS;
2793     SS.Adopt(QualifierLoc);
2794 
2795     if (TemplateArgs || TemplateKWLoc.isValid())
2796       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
2797                                                     TemplateArgs);
2798 
2799     return getSema().BuildQualifiedDeclarationNameExpr(
2800         SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
2801   }
2802 
2803   /// Build a new template-id expression.
2804   ///
2805   /// By default, performs semantic analysis to build the new expression.
2806   /// Subclasses may override this routine to provide different behavior.
RebuildTemplateIdExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,LookupResult & R,bool RequiresADL,const TemplateArgumentListInfo * TemplateArgs)2807   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2808                                    SourceLocation TemplateKWLoc,
2809                                    LookupResult &R,
2810                                    bool RequiresADL,
2811                               const TemplateArgumentListInfo *TemplateArgs) {
2812     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2813                                          TemplateArgs);
2814   }
2815 
2816   /// Build a new object-construction expression.
2817   ///
2818   /// By default, performs semantic analysis to build the new expression.
2819   /// Subclasses may override this routine to provide different behavior.
RebuildCXXConstructExpr(QualType T,SourceLocation Loc,CXXConstructorDecl * Constructor,bool IsElidable,MultiExprArg Args,bool HadMultipleCandidates,bool ListInitialization,bool StdInitListInitialization,bool RequiresZeroInit,CXXConstructExpr::ConstructionKind ConstructKind,SourceRange ParenRange)2820   ExprResult RebuildCXXConstructExpr(QualType T,
2821                                      SourceLocation Loc,
2822                                      CXXConstructorDecl *Constructor,
2823                                      bool IsElidable,
2824                                      MultiExprArg Args,
2825                                      bool HadMultipleCandidates,
2826                                      bool ListInitialization,
2827                                      bool StdInitListInitialization,
2828                                      bool RequiresZeroInit,
2829                              CXXConstructExpr::ConstructionKind ConstructKind,
2830                                      SourceRange ParenRange) {
2831     SmallVector<Expr*, 8> ConvertedArgs;
2832     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2833                                           ConvertedArgs))
2834       return ExprError();
2835 
2836     return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
2837                                            IsElidable,
2838                                            ConvertedArgs,
2839                                            HadMultipleCandidates,
2840                                            ListInitialization,
2841                                            StdInitListInitialization,
2842                                            RequiresZeroInit, ConstructKind,
2843                                            ParenRange);
2844   }
2845 
2846   /// Build a new implicit construction via inherited constructor
2847   /// expression.
RebuildCXXInheritedCtorInitExpr(QualType T,SourceLocation Loc,CXXConstructorDecl * Constructor,bool ConstructsVBase,bool InheritedFromVBase)2848   ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
2849                                              CXXConstructorDecl *Constructor,
2850                                              bool ConstructsVBase,
2851                                              bool InheritedFromVBase) {
2852     return new (getSema().Context) CXXInheritedCtorInitExpr(
2853         Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
2854   }
2855 
2856   /// Build a new object-construction expression.
2857   ///
2858   /// By default, performs semantic analysis to build the new expression.
2859   /// Subclasses may override this routine to provide different behavior.
RebuildCXXTemporaryObjectExpr(TypeSourceInfo * TSInfo,SourceLocation LParenOrBraceLoc,MultiExprArg Args,SourceLocation RParenOrBraceLoc,bool ListInitialization)2860   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2861                                            SourceLocation LParenOrBraceLoc,
2862                                            MultiExprArg Args,
2863                                            SourceLocation RParenOrBraceLoc,
2864                                            bool ListInitialization) {
2865     return getSema().BuildCXXTypeConstructExpr(
2866         TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
2867   }
2868 
2869   /// Build a new object-construction expression.
2870   ///
2871   /// By default, performs semantic analysis to build the new expression.
2872   /// Subclasses may override this routine to provide different behavior.
RebuildCXXUnresolvedConstructExpr(TypeSourceInfo * TSInfo,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,bool ListInitialization)2873   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2874                                                SourceLocation LParenLoc,
2875                                                MultiExprArg Args,
2876                                                SourceLocation RParenLoc,
2877                                                bool ListInitialization) {
2878     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
2879                                                RParenLoc, ListInitialization);
2880   }
2881 
2882   /// Build a new member reference expression.
2883   ///
2884   /// By default, performs semantic analysis to build the new expression.
2885   /// Subclasses may override this routine to provide different behavior.
RebuildCXXDependentScopeMemberExpr(Expr * BaseE,QualType BaseType,bool IsArrow,SourceLocation OperatorLoc,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,NamedDecl * FirstQualifierInScope,const DeclarationNameInfo & MemberNameInfo,const TemplateArgumentListInfo * TemplateArgs)2886   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2887                                                 QualType BaseType,
2888                                                 bool IsArrow,
2889                                                 SourceLocation OperatorLoc,
2890                                           NestedNameSpecifierLoc QualifierLoc,
2891                                                 SourceLocation TemplateKWLoc,
2892                                             NamedDecl *FirstQualifierInScope,
2893                                    const DeclarationNameInfo &MemberNameInfo,
2894                               const TemplateArgumentListInfo *TemplateArgs) {
2895     CXXScopeSpec SS;
2896     SS.Adopt(QualifierLoc);
2897 
2898     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2899                                             OperatorLoc, IsArrow,
2900                                             SS, TemplateKWLoc,
2901                                             FirstQualifierInScope,
2902                                             MemberNameInfo,
2903                                             TemplateArgs, /*S*/nullptr);
2904   }
2905 
2906   /// Build a new member reference expression.
2907   ///
2908   /// By default, performs semantic analysis to build the new expression.
2909   /// Subclasses may override this routine to provide different behavior.
RebuildUnresolvedMemberExpr(Expr * BaseE,QualType BaseType,SourceLocation OperatorLoc,bool IsArrow,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,NamedDecl * FirstQualifierInScope,LookupResult & R,const TemplateArgumentListInfo * TemplateArgs)2910   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2911                                          SourceLocation OperatorLoc,
2912                                          bool IsArrow,
2913                                          NestedNameSpecifierLoc QualifierLoc,
2914                                          SourceLocation TemplateKWLoc,
2915                                          NamedDecl *FirstQualifierInScope,
2916                                          LookupResult &R,
2917                                 const TemplateArgumentListInfo *TemplateArgs) {
2918     CXXScopeSpec SS;
2919     SS.Adopt(QualifierLoc);
2920 
2921     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2922                                             OperatorLoc, IsArrow,
2923                                             SS, TemplateKWLoc,
2924                                             FirstQualifierInScope,
2925                                             R, TemplateArgs, /*S*/nullptr);
2926   }
2927 
2928   /// Build a new noexcept expression.
2929   ///
2930   /// By default, performs semantic analysis to build the new expression.
2931   /// Subclasses may override this routine to provide different behavior.
RebuildCXXNoexceptExpr(SourceRange Range,Expr * Arg)2932   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2933     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2934   }
2935 
2936   /// Build a new expression to compute the length of a parameter pack.
RebuildSizeOfPackExpr(SourceLocation OperatorLoc,NamedDecl * Pack,SourceLocation PackLoc,SourceLocation RParenLoc,Optional<unsigned> Length,ArrayRef<TemplateArgument> PartialArgs)2937   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc,
2938                                    NamedDecl *Pack,
2939                                    SourceLocation PackLoc,
2940                                    SourceLocation RParenLoc,
2941                                    Optional<unsigned> Length,
2942                                    ArrayRef<TemplateArgument> PartialArgs) {
2943     return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
2944                                   RParenLoc, Length, PartialArgs);
2945   }
2946 
2947   /// Build a new Objective-C boxed expression.
2948   ///
2949   /// By default, performs semantic analysis to build the new expression.
2950   /// Subclasses may override this routine to provide different behavior.
RebuildObjCBoxedExpr(SourceRange SR,Expr * ValueExpr)2951   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
2952     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
2953   }
2954 
2955   /// Build a new Objective-C array literal.
2956   ///
2957   /// By default, performs semantic analysis to build the new expression.
2958   /// Subclasses may override this routine to provide different behavior.
RebuildObjCArrayLiteral(SourceRange Range,Expr ** Elements,unsigned NumElements)2959   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
2960                                      Expr **Elements, unsigned NumElements) {
2961     return getSema().BuildObjCArrayLiteral(Range,
2962                                            MultiExprArg(Elements, NumElements));
2963   }
2964 
RebuildObjCSubscriptRefExpr(SourceLocation RB,Expr * Base,Expr * Key,ObjCMethodDecl * getterMethod,ObjCMethodDecl * setterMethod)2965   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
2966                                          Expr *Base, Expr *Key,
2967                                          ObjCMethodDecl *getterMethod,
2968                                          ObjCMethodDecl *setterMethod) {
2969     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
2970                                                    getterMethod, setterMethod);
2971   }
2972 
2973   /// Build a new Objective-C dictionary literal.
2974   ///
2975   /// By default, performs semantic analysis to build the new expression.
2976   /// Subclasses may override this routine to provide different behavior.
RebuildObjCDictionaryLiteral(SourceRange Range,MutableArrayRef<ObjCDictionaryElement> Elements)2977   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
2978                               MutableArrayRef<ObjCDictionaryElement> Elements) {
2979     return getSema().BuildObjCDictionaryLiteral(Range, Elements);
2980   }
2981 
2982   /// Build a new Objective-C \@encode expression.
2983   ///
2984   /// By default, performs semantic analysis to build the new expression.
2985   /// Subclasses may override this routine to provide different behavior.
RebuildObjCEncodeExpr(SourceLocation AtLoc,TypeSourceInfo * EncodeTypeInfo,SourceLocation RParenLoc)2986   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
2987                                          TypeSourceInfo *EncodeTypeInfo,
2988                                          SourceLocation RParenLoc) {
2989     return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
2990   }
2991 
2992   /// Build a new Objective-C class message.
RebuildObjCMessageExpr(TypeSourceInfo * ReceiverTypeInfo,Selector Sel,ArrayRef<SourceLocation> SelectorLocs,ObjCMethodDecl * Method,SourceLocation LBracLoc,MultiExprArg Args,SourceLocation RBracLoc)2993   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
2994                                           Selector Sel,
2995                                           ArrayRef<SourceLocation> SelectorLocs,
2996                                           ObjCMethodDecl *Method,
2997                                           SourceLocation LBracLoc,
2998                                           MultiExprArg Args,
2999                                           SourceLocation RBracLoc) {
3000     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3001                                      ReceiverTypeInfo->getType(),
3002                                      /*SuperLoc=*/SourceLocation(),
3003                                      Sel, Method, LBracLoc, SelectorLocs,
3004                                      RBracLoc, Args);
3005   }
3006 
3007   /// Build a new Objective-C instance message.
RebuildObjCMessageExpr(Expr * Receiver,Selector Sel,ArrayRef<SourceLocation> SelectorLocs,ObjCMethodDecl * Method,SourceLocation LBracLoc,MultiExprArg Args,SourceLocation RBracLoc)3008   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3009                                           Selector Sel,
3010                                           ArrayRef<SourceLocation> SelectorLocs,
3011                                           ObjCMethodDecl *Method,
3012                                           SourceLocation LBracLoc,
3013                                           MultiExprArg Args,
3014                                           SourceLocation RBracLoc) {
3015     return SemaRef.BuildInstanceMessage(Receiver,
3016                                         Receiver->getType(),
3017                                         /*SuperLoc=*/SourceLocation(),
3018                                         Sel, Method, LBracLoc, SelectorLocs,
3019                                         RBracLoc, Args);
3020   }
3021 
3022   /// Build a new Objective-C instance/class message to 'super'.
RebuildObjCMessageExpr(SourceLocation SuperLoc,Selector Sel,ArrayRef<SourceLocation> SelectorLocs,QualType SuperType,ObjCMethodDecl * Method,SourceLocation LBracLoc,MultiExprArg Args,SourceLocation RBracLoc)3023   ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3024                                     Selector Sel,
3025                                     ArrayRef<SourceLocation> SelectorLocs,
3026                                     QualType SuperType,
3027                                     ObjCMethodDecl *Method,
3028                                     SourceLocation LBracLoc,
3029                                     MultiExprArg Args,
3030                                     SourceLocation RBracLoc) {
3031     return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3032                                           SuperType,
3033                                           SuperLoc,
3034                                           Sel, Method, LBracLoc, SelectorLocs,
3035                                           RBracLoc, Args)
3036                                       : SemaRef.BuildClassMessage(nullptr,
3037                                           SuperType,
3038                                           SuperLoc,
3039                                           Sel, Method, LBracLoc, SelectorLocs,
3040                                           RBracLoc, Args);
3041 
3042 
3043   }
3044 
3045   /// Build a new Objective-C ivar reference expression.
3046   ///
3047   /// By default, performs semantic analysis to build the new expression.
3048   /// Subclasses may override this routine to provide different behavior.
RebuildObjCIvarRefExpr(Expr * BaseArg,ObjCIvarDecl * Ivar,SourceLocation IvarLoc,bool IsArrow,bool IsFreeIvar)3049   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3050                                           SourceLocation IvarLoc,
3051                                           bool IsArrow, bool IsFreeIvar) {
3052     CXXScopeSpec SS;
3053     DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3054     ExprResult Result = getSema().BuildMemberReferenceExpr(
3055         BaseArg, BaseArg->getType(),
3056         /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3057         /*FirstQualifierInScope=*/nullptr, NameInfo,
3058         /*TemplateArgs=*/nullptr,
3059         /*S=*/nullptr);
3060     if (IsFreeIvar && Result.isUsable())
3061       cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3062     return Result;
3063   }
3064 
3065   /// Build a new Objective-C property reference expression.
3066   ///
3067   /// By default, performs semantic analysis to build the new expression.
3068   /// Subclasses may override this routine to provide different behavior.
RebuildObjCPropertyRefExpr(Expr * BaseArg,ObjCPropertyDecl * Property,SourceLocation PropertyLoc)3069   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3070                                         ObjCPropertyDecl *Property,
3071                                         SourceLocation PropertyLoc) {
3072     CXXScopeSpec SS;
3073     DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3074     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3075                                               /*FIXME:*/PropertyLoc,
3076                                               /*IsArrow=*/false,
3077                                               SS, SourceLocation(),
3078                                               /*FirstQualifierInScope=*/nullptr,
3079                                               NameInfo,
3080                                               /*TemplateArgs=*/nullptr,
3081                                               /*S=*/nullptr);
3082   }
3083 
3084   /// Build a new Objective-C property reference expression.
3085   ///
3086   /// By default, performs semantic analysis to build the new expression.
3087   /// Subclasses may override this routine to provide different behavior.
RebuildObjCPropertyRefExpr(Expr * Base,QualType T,ObjCMethodDecl * Getter,ObjCMethodDecl * Setter,SourceLocation PropertyLoc)3088   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3089                                         ObjCMethodDecl *Getter,
3090                                         ObjCMethodDecl *Setter,
3091                                         SourceLocation PropertyLoc) {
3092     // Since these expressions can only be value-dependent, we do not
3093     // need to perform semantic analysis again.
3094     return Owned(
3095       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3096                                                   VK_LValue, OK_ObjCProperty,
3097                                                   PropertyLoc, Base));
3098   }
3099 
3100   /// Build a new Objective-C "isa" expression.
3101   ///
3102   /// By default, performs semantic analysis to build the new expression.
3103   /// Subclasses may override this routine to provide different behavior.
RebuildObjCIsaExpr(Expr * BaseArg,SourceLocation IsaLoc,SourceLocation OpLoc,bool IsArrow)3104   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3105                                 SourceLocation OpLoc, bool IsArrow) {
3106     CXXScopeSpec SS;
3107     DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3108     return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3109                                               OpLoc, IsArrow,
3110                                               SS, SourceLocation(),
3111                                               /*FirstQualifierInScope=*/nullptr,
3112                                               NameInfo,
3113                                               /*TemplateArgs=*/nullptr,
3114                                               /*S=*/nullptr);
3115   }
3116 
3117   /// Build a new shuffle vector expression.
3118   ///
3119   /// By default, performs semantic analysis to build the new expression.
3120   /// Subclasses may override this routine to provide different behavior.
RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,MultiExprArg SubExprs,SourceLocation RParenLoc)3121   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3122                                       MultiExprArg SubExprs,
3123                                       SourceLocation RParenLoc) {
3124     // Find the declaration for __builtin_shufflevector
3125     const IdentifierInfo &Name
3126       = SemaRef.Context.Idents.get("__builtin_shufflevector");
3127     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3128     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3129     assert(!Lookup.empty() && "No __builtin_shufflevector?");
3130 
3131     // Build a reference to the __builtin_shufflevector builtin
3132     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3133     Expr *Callee = new (SemaRef.Context)
3134         DeclRefExpr(SemaRef.Context, Builtin, false,
3135                     SemaRef.Context.BuiltinFnTy, VK_RValue, BuiltinLoc);
3136     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3137     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3138                                        CK_BuiltinFnToFnPtr).get();
3139 
3140     // Build the CallExpr
3141     ExprResult TheCall = CallExpr::Create(
3142         SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3143         Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc);
3144 
3145     // Type-check the __builtin_shufflevector expression.
3146     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3147   }
3148 
3149   /// Build a new convert vector expression.
RebuildConvertVectorExpr(SourceLocation BuiltinLoc,Expr * SrcExpr,TypeSourceInfo * DstTInfo,SourceLocation RParenLoc)3150   ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3151                                       Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3152                                       SourceLocation RParenLoc) {
3153     return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3154                                          BuiltinLoc, RParenLoc);
3155   }
3156 
3157   /// Build a new template argument pack expansion.
3158   ///
3159   /// By default, performs semantic analysis to build a new pack expansion
3160   /// for a template argument. Subclasses may override this routine to provide
3161   /// different behavior.
RebuildPackExpansion(TemplateArgumentLoc Pattern,SourceLocation EllipsisLoc,Optional<unsigned> NumExpansions)3162   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
3163                                            SourceLocation EllipsisLoc,
3164                                            Optional<unsigned> NumExpansions) {
3165     switch (Pattern.getArgument().getKind()) {
3166     case TemplateArgument::Expression: {
3167       ExprResult Result
3168         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3169                                        EllipsisLoc, NumExpansions);
3170       if (Result.isInvalid())
3171         return TemplateArgumentLoc();
3172 
3173       return TemplateArgumentLoc(Result.get(), Result.get());
3174     }
3175 
3176     case TemplateArgument::Template:
3177       return TemplateArgumentLoc(TemplateArgument(
3178                                           Pattern.getArgument().getAsTemplate(),
3179                                                   NumExpansions),
3180                                  Pattern.getTemplateQualifierLoc(),
3181                                  Pattern.getTemplateNameLoc(),
3182                                  EllipsisLoc);
3183 
3184     case TemplateArgument::Null:
3185     case TemplateArgument::Integral:
3186     case TemplateArgument::Declaration:
3187     case TemplateArgument::Pack:
3188     case TemplateArgument::TemplateExpansion:
3189     case TemplateArgument::NullPtr:
3190       llvm_unreachable("Pack expansion pattern has no parameter packs");
3191 
3192     case TemplateArgument::Type:
3193       if (TypeSourceInfo *Expansion
3194             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3195                                            EllipsisLoc,
3196                                            NumExpansions))
3197         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3198                                    Expansion);
3199       break;
3200     }
3201 
3202     return TemplateArgumentLoc();
3203   }
3204 
3205   /// Build a new expression pack expansion.
3206   ///
3207   /// By default, performs semantic analysis to build a new pack expansion
3208   /// for an expression. Subclasses may override this routine to provide
3209   /// different behavior.
RebuildPackExpansion(Expr * Pattern,SourceLocation EllipsisLoc,Optional<unsigned> NumExpansions)3210   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3211                                   Optional<unsigned> NumExpansions) {
3212     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3213   }
3214 
3215   /// Build a new C++1z fold-expression.
3216   ///
3217   /// By default, performs semantic analysis in order to build a new fold
3218   /// expression.
RebuildCXXFoldExpr(SourceLocation LParenLoc,Expr * LHS,BinaryOperatorKind Operator,SourceLocation EllipsisLoc,Expr * RHS,SourceLocation RParenLoc)3219   ExprResult RebuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
3220                                 BinaryOperatorKind Operator,
3221                                 SourceLocation EllipsisLoc, Expr *RHS,
3222                                 SourceLocation RParenLoc) {
3223     return getSema().BuildCXXFoldExpr(LParenLoc, LHS, Operator, EllipsisLoc,
3224                                       RHS, RParenLoc);
3225   }
3226 
3227   /// Build an empty C++1z fold-expression with the given operator.
3228   ///
3229   /// By default, produces the fallback value for the fold-expression, or
3230   /// produce an error if there is no fallback value.
RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,BinaryOperatorKind Operator)3231   ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3232                                      BinaryOperatorKind Operator) {
3233     return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3234   }
3235 
3236   /// Build a new atomic operation expression.
3237   ///
3238   /// By default, performs semantic analysis to build the new expression.
3239   /// Subclasses may override this routine to provide different behavior.
RebuildAtomicExpr(SourceLocation BuiltinLoc,MultiExprArg SubExprs,QualType RetTy,AtomicExpr::AtomicOp Op,SourceLocation RParenLoc)3240   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
3241                                MultiExprArg SubExprs,
3242                                QualType RetTy,
3243                                AtomicExpr::AtomicOp Op,
3244                                SourceLocation RParenLoc) {
3245     // Just create the expression; there is not any interesting semantic
3246     // analysis here because we can't actually build an AtomicExpr until
3247     // we are sure it is semantically sound.
3248     return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
3249                                             RParenLoc);
3250   }
3251 
3252 private:
3253   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3254                                      QualType ObjectType,
3255                                      NamedDecl *FirstQualifierInScope,
3256                                      CXXScopeSpec &SS);
3257 
3258   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3259                                              QualType ObjectType,
3260                                              NamedDecl *FirstQualifierInScope,
3261                                              CXXScopeSpec &SS);
3262 
3263   TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3264                                             NamedDecl *FirstQualifierInScope,
3265                                             CXXScopeSpec &SS);
3266 
3267   QualType TransformDependentNameType(TypeLocBuilder &TLB,
3268                                       DependentNameTypeLoc TL,
3269                                       bool DeducibleTSTContext);
3270 };
3271 
3272 template<typename Derived>
TransformStmt(Stmt * S)3273 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
3274   if (!S)
3275     return S;
3276 
3277   switch (S->getStmtClass()) {
3278   case Stmt::NoStmtClass: break;
3279 
3280   // Transform individual statement nodes
3281 #define STMT(Node, Parent)                                              \
3282   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3283 #define ABSTRACT_STMT(Node)
3284 #define EXPR(Node, Parent)
3285 #include "clang/AST/StmtNodes.inc"
3286 
3287   // Transform expressions by calling TransformExpr.
3288 #define STMT(Node, Parent)
3289 #define ABSTRACT_STMT(Stmt)
3290 #define EXPR(Node, Parent) case Stmt::Node##Class:
3291 #include "clang/AST/StmtNodes.inc"
3292     {
3293       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3294       if (E.isInvalid())
3295         return StmtError();
3296 
3297       return getSema().ActOnExprStmt(E);
3298     }
3299   }
3300 
3301   return S;
3302 }
3303 
3304 template<typename Derived>
TransformOMPClause(OMPClause * S)3305 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3306   if (!S)
3307     return S;
3308 
3309   switch (S->getClauseKind()) {
3310   default: break;
3311   // Transform individual clause nodes
3312 #define OPENMP_CLAUSE(Name, Class)                                             \
3313   case OMPC_ ## Name :                                                         \
3314     return getDerived().Transform ## Class(cast<Class>(S));
3315 #include "clang/Basic/OpenMPKinds.def"
3316   }
3317 
3318   return S;
3319 }
3320 
3321 
3322 template<typename Derived>
TransformExpr(Expr * E)3323 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
3324   if (!E)
3325     return E;
3326 
3327   switch (E->getStmtClass()) {
3328     case Stmt::NoStmtClass: break;
3329 #define STMT(Node, Parent) case Stmt::Node##Class: break;
3330 #define ABSTRACT_STMT(Stmt)
3331 #define EXPR(Node, Parent)                                              \
3332     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
3333 #include "clang/AST/StmtNodes.inc"
3334   }
3335 
3336   return E;
3337 }
3338 
3339 template<typename Derived>
TransformInitializer(Expr * Init,bool NotCopyInit)3340 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
3341                                                         bool NotCopyInit) {
3342   // Initializers are instantiated like expressions, except that various outer
3343   // layers are stripped.
3344   if (!Init)
3345     return Init;
3346 
3347   if (auto *FE = dyn_cast<FullExpr>(Init))
3348     Init = FE->getSubExpr();
3349 
3350   if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init))
3351     Init = AIL->getCommonExpr();
3352 
3353   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
3354     Init = MTE->GetTemporaryExpr();
3355 
3356   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3357     Init = Binder->getSubExpr();
3358 
3359   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3360     Init = ICE->getSubExprAsWritten();
3361 
3362   if (CXXStdInitializerListExpr *ILE =
3363           dyn_cast<CXXStdInitializerListExpr>(Init))
3364     return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
3365 
3366   // If this is copy-initialization, we only need to reconstruct
3367   // InitListExprs. Other forms of copy-initialization will be a no-op if
3368   // the initializer is already the right type.
3369   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
3370   if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
3371     return getDerived().TransformExpr(Init);
3372 
3373   // Revert value-initialization back to empty parens.
3374   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
3375     SourceRange Parens = VIE->getSourceRange();
3376     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
3377                                              Parens.getEnd());
3378   }
3379 
3380   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
3381   if (isa<ImplicitValueInitExpr>(Init))
3382     return getDerived().RebuildParenListExpr(SourceLocation(), None,
3383                                              SourceLocation());
3384 
3385   // Revert initialization by constructor back to a parenthesized or braced list
3386   // of expressions. Any other form of initializer can just be reused directly.
3387   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
3388     return getDerived().TransformExpr(Init);
3389 
3390   // If the initialization implicitly converted an initializer list to a
3391   // std::initializer_list object, unwrap the std::initializer_list too.
3392   if (Construct && Construct->isStdInitListInitialization())
3393     return TransformInitializer(Construct->getArg(0), NotCopyInit);
3394 
3395   // Enter a list-init context if this was list initialization.
3396   EnterExpressionEvaluationContext Context(
3397       getSema(), EnterExpressionEvaluationContext::InitList,
3398       Construct->isListInitialization());
3399 
3400   SmallVector<Expr*, 8> NewArgs;
3401   bool ArgChanged = false;
3402   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
3403                                   /*IsCall*/true, NewArgs, &ArgChanged))
3404     return ExprError();
3405 
3406   // If this was list initialization, revert to syntactic list form.
3407   if (Construct->isListInitialization())
3408     return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
3409                                         Construct->getEndLoc());
3410 
3411   // Build a ParenListExpr to represent anything else.
3412   SourceRange Parens = Construct->getParenOrBraceRange();
3413   if (Parens.isInvalid()) {
3414     // This was a variable declaration's initialization for which no initializer
3415     // was specified.
3416     assert(NewArgs.empty() &&
3417            "no parens or braces but have direct init with arguments?");
3418     return ExprEmpty();
3419   }
3420   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
3421                                            Parens.getEnd());
3422 }
3423 
3424 template<typename Derived>
TransformExprs(Expr * const * Inputs,unsigned NumInputs,bool IsCall,SmallVectorImpl<Expr * > & Outputs,bool * ArgChanged)3425 bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
3426                                             unsigned NumInputs,
3427                                             bool IsCall,
3428                                       SmallVectorImpl<Expr *> &Outputs,
3429                                             bool *ArgChanged) {
3430   for (unsigned I = 0; I != NumInputs; ++I) {
3431     // If requested, drop call arguments that need to be dropped.
3432     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
3433       if (ArgChanged)
3434         *ArgChanged = true;
3435 
3436       break;
3437     }
3438 
3439     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
3440       Expr *Pattern = Expansion->getPattern();
3441 
3442       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3443       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3444       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3445 
3446       // Determine whether the set of unexpanded parameter packs can and should
3447       // be expanded.
3448       bool Expand = true;
3449       bool RetainExpansion = false;
3450       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
3451       Optional<unsigned> NumExpansions = OrigNumExpansions;
3452       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
3453                                                Pattern->getSourceRange(),
3454                                                Unexpanded,
3455                                                Expand, RetainExpansion,
3456                                                NumExpansions))
3457         return true;
3458 
3459       if (!Expand) {
3460         // The transform has determined that we should perform a simple
3461         // transformation on the pack expansion, producing another pack
3462         // expansion.
3463         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3464         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
3465         if (OutPattern.isInvalid())
3466           return true;
3467 
3468         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
3469                                                 Expansion->getEllipsisLoc(),
3470                                                            NumExpansions);
3471         if (Out.isInvalid())
3472           return true;
3473 
3474         if (ArgChanged)
3475           *ArgChanged = true;
3476         Outputs.push_back(Out.get());
3477         continue;
3478       }
3479 
3480       // Record right away that the argument was changed.  This needs
3481       // to happen even if the array expands to nothing.
3482       if (ArgChanged) *ArgChanged = true;
3483 
3484       // The transform has determined that we should perform an elementwise
3485       // expansion of the pattern. Do so.
3486       for (unsigned I = 0; I != *NumExpansions; ++I) {
3487         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3488         ExprResult Out = getDerived().TransformExpr(Pattern);
3489         if (Out.isInvalid())
3490           return true;
3491 
3492         if (Out.get()->containsUnexpandedParameterPack()) {
3493           Out = getDerived().RebuildPackExpansion(
3494               Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3495           if (Out.isInvalid())
3496             return true;
3497         }
3498 
3499         Outputs.push_back(Out.get());
3500       }
3501 
3502       // If we're supposed to retain a pack expansion, do so by temporarily
3503       // forgetting the partially-substituted parameter pack.
3504       if (RetainExpansion) {
3505         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3506 
3507         ExprResult Out = getDerived().TransformExpr(Pattern);
3508         if (Out.isInvalid())
3509           return true;
3510 
3511         Out = getDerived().RebuildPackExpansion(
3512             Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
3513         if (Out.isInvalid())
3514           return true;
3515 
3516         Outputs.push_back(Out.get());
3517       }
3518 
3519       continue;
3520     }
3521 
3522     ExprResult Result =
3523       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
3524              : getDerived().TransformExpr(Inputs[I]);
3525     if (Result.isInvalid())
3526       return true;
3527 
3528     if (Result.get() != Inputs[I] && ArgChanged)
3529       *ArgChanged = true;
3530 
3531     Outputs.push_back(Result.get());
3532   }
3533 
3534   return false;
3535 }
3536 
3537 template <typename Derived>
TransformCondition(SourceLocation Loc,VarDecl * Var,Expr * Expr,Sema::ConditionKind Kind)3538 Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
3539     SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
3540   if (Var) {
3541     VarDecl *ConditionVar = cast_or_null<VarDecl>(
3542         getDerived().TransformDefinition(Var->getLocation(), Var));
3543 
3544     if (!ConditionVar)
3545       return Sema::ConditionError();
3546 
3547     return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
3548   }
3549 
3550   if (Expr) {
3551     ExprResult CondExpr = getDerived().TransformExpr(Expr);
3552 
3553     if (CondExpr.isInvalid())
3554       return Sema::ConditionError();
3555 
3556     return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind);
3557   }
3558 
3559   return Sema::ConditionResult();
3560 }
3561 
3562 template<typename Derived>
3563 NestedNameSpecifierLoc
TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,QualType ObjectType,NamedDecl * FirstQualifierInScope)3564 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
3565                                                     NestedNameSpecifierLoc NNS,
3566                                                      QualType ObjectType,
3567                                              NamedDecl *FirstQualifierInScope) {
3568   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
3569   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
3570        Qualifier = Qualifier.getPrefix())
3571     Qualifiers.push_back(Qualifier);
3572 
3573   CXXScopeSpec SS;
3574   while (!Qualifiers.empty()) {
3575     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
3576     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
3577 
3578     switch (QNNS->getKind()) {
3579     case NestedNameSpecifier::Identifier: {
3580       Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
3581                           Q.getLocalBeginLoc(), Q.getLocalEndLoc(), ObjectType);
3582       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
3583                                               SS, FirstQualifierInScope, false))
3584         return NestedNameSpecifierLoc();
3585     }
3586       break;
3587 
3588     case NestedNameSpecifier::Namespace: {
3589       NamespaceDecl *NS
3590         = cast_or_null<NamespaceDecl>(
3591                                     getDerived().TransformDecl(
3592                                                           Q.getLocalBeginLoc(),
3593                                                        QNNS->getAsNamespace()));
3594       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
3595       break;
3596     }
3597 
3598     case NestedNameSpecifier::NamespaceAlias: {
3599       NamespaceAliasDecl *Alias
3600         = cast_or_null<NamespaceAliasDecl>(
3601                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
3602                                                  QNNS->getAsNamespaceAlias()));
3603       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
3604                 Q.getLocalEndLoc());
3605       break;
3606     }
3607 
3608     case NestedNameSpecifier::Global:
3609       // There is no meaningful transformation that one could perform on the
3610       // global scope.
3611       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
3612       break;
3613 
3614     case NestedNameSpecifier::Super: {
3615       CXXRecordDecl *RD =
3616           cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
3617               SourceLocation(), QNNS->getAsRecordDecl()));
3618       SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
3619       break;
3620     }
3621 
3622     case NestedNameSpecifier::TypeSpecWithTemplate:
3623     case NestedNameSpecifier::TypeSpec: {
3624       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
3625                                               FirstQualifierInScope, SS);
3626 
3627       if (!TL)
3628         return NestedNameSpecifierLoc();
3629 
3630       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
3631           (SemaRef.getLangOpts().CPlusPlus11 &&
3632            TL.getType()->isEnumeralType())) {
3633         assert(!TL.getType().hasLocalQualifiers() &&
3634                "Can't get cv-qualifiers here");
3635         if (TL.getType()->isEnumeralType())
3636           SemaRef.Diag(TL.getBeginLoc(),
3637                        diag::warn_cxx98_compat_enum_nested_name_spec);
3638         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
3639                   Q.getLocalEndLoc());
3640         break;
3641       }
3642       // If the nested-name-specifier is an invalid type def, don't emit an
3643       // error because a previous error should have already been emitted.
3644       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
3645       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
3646         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
3647           << TL.getType() << SS.getRange();
3648       }
3649       return NestedNameSpecifierLoc();
3650     }
3651     }
3652 
3653     // The qualifier-in-scope and object type only apply to the leftmost entity.
3654     FirstQualifierInScope = nullptr;
3655     ObjectType = QualType();
3656   }
3657 
3658   // Don't rebuild the nested-name-specifier if we don't have to.
3659   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
3660       !getDerived().AlwaysRebuild())
3661     return NNS;
3662 
3663   // If we can re-use the source-location data from the original
3664   // nested-name-specifier, do so.
3665   if (SS.location_size() == NNS.getDataLength() &&
3666       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
3667     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
3668 
3669   // Allocate new nested-name-specifier location information.
3670   return SS.getWithLocInContext(SemaRef.Context);
3671 }
3672 
3673 template<typename Derived>
3674 DeclarationNameInfo
3675 TreeTransform<Derived>
TransformDeclarationNameInfo(const DeclarationNameInfo & NameInfo)3676 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
3677   DeclarationName Name = NameInfo.getName();
3678   if (!Name)
3679     return DeclarationNameInfo();
3680 
3681   switch (Name.getNameKind()) {
3682   case DeclarationName::Identifier:
3683   case DeclarationName::ObjCZeroArgSelector:
3684   case DeclarationName::ObjCOneArgSelector:
3685   case DeclarationName::ObjCMultiArgSelector:
3686   case DeclarationName::CXXOperatorName:
3687   case DeclarationName::CXXLiteralOperatorName:
3688   case DeclarationName::CXXUsingDirective:
3689     return NameInfo;
3690 
3691   case DeclarationName::CXXDeductionGuideName: {
3692     TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
3693     TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
3694         getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
3695     if (!NewTemplate)
3696       return DeclarationNameInfo();
3697 
3698     DeclarationNameInfo NewNameInfo(NameInfo);
3699     NewNameInfo.setName(
3700         SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
3701     return NewNameInfo;
3702   }
3703 
3704   case DeclarationName::CXXConstructorName:
3705   case DeclarationName::CXXDestructorName:
3706   case DeclarationName::CXXConversionFunctionName: {
3707     TypeSourceInfo *NewTInfo;
3708     CanQualType NewCanTy;
3709     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
3710       NewTInfo = getDerived().TransformType(OldTInfo);
3711       if (!NewTInfo)
3712         return DeclarationNameInfo();
3713       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
3714     }
3715     else {
3716       NewTInfo = nullptr;
3717       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
3718       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
3719       if (NewT.isNull())
3720         return DeclarationNameInfo();
3721       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
3722     }
3723 
3724     DeclarationName NewName
3725       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
3726                                                            NewCanTy);
3727     DeclarationNameInfo NewNameInfo(NameInfo);
3728     NewNameInfo.setName(NewName);
3729     NewNameInfo.setNamedTypeInfo(NewTInfo);
3730     return NewNameInfo;
3731   }
3732   }
3733 
3734   llvm_unreachable("Unknown name kind.");
3735 }
3736 
3737 template<typename Derived>
3738 TemplateName
TransformTemplateName(CXXScopeSpec & SS,TemplateName Name,SourceLocation NameLoc,QualType ObjectType,NamedDecl * FirstQualifierInScope,bool AllowInjectedClassName)3739 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
3740                                               TemplateName Name,
3741                                               SourceLocation NameLoc,
3742                                               QualType ObjectType,
3743                                               NamedDecl *FirstQualifierInScope,
3744                                               bool AllowInjectedClassName) {
3745   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
3746     TemplateDecl *Template = QTN->getTemplateDecl();
3747     assert(Template && "qualified template name must refer to a template");
3748 
3749     TemplateDecl *TransTemplate
3750       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3751                                                               Template));
3752     if (!TransTemplate)
3753       return TemplateName();
3754 
3755     if (!getDerived().AlwaysRebuild() &&
3756         SS.getScopeRep() == QTN->getQualifier() &&
3757         TransTemplate == Template)
3758       return Name;
3759 
3760     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
3761                                             TransTemplate);
3762   }
3763 
3764   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3765     if (SS.getScopeRep()) {
3766       // These apply to the scope specifier, not the template.
3767       ObjectType = QualType();
3768       FirstQualifierInScope = nullptr;
3769     }
3770 
3771     if (!getDerived().AlwaysRebuild() &&
3772         SS.getScopeRep() == DTN->getQualifier() &&
3773         ObjectType.isNull())
3774       return Name;
3775 
3776     // FIXME: Preserve the location of the "template" keyword.
3777     SourceLocation TemplateKWLoc = NameLoc;
3778 
3779     if (DTN->isIdentifier()) {
3780       return getDerived().RebuildTemplateName(SS,
3781                                               TemplateKWLoc,
3782                                               *DTN->getIdentifier(),
3783                                               NameLoc,
3784                                               ObjectType,
3785                                               FirstQualifierInScope,
3786                                               AllowInjectedClassName);
3787     }
3788 
3789     return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
3790                                             DTN->getOperator(), NameLoc,
3791                                             ObjectType, AllowInjectedClassName);
3792   }
3793 
3794   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3795     TemplateDecl *TransTemplate
3796       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
3797                                                               Template));
3798     if (!TransTemplate)
3799       return TemplateName();
3800 
3801     if (!getDerived().AlwaysRebuild() &&
3802         TransTemplate == Template)
3803       return Name;
3804 
3805     return TemplateName(TransTemplate);
3806   }
3807 
3808   if (SubstTemplateTemplateParmPackStorage *SubstPack
3809       = Name.getAsSubstTemplateTemplateParmPack()) {
3810     TemplateTemplateParmDecl *TransParam
3811     = cast_or_null<TemplateTemplateParmDecl>(
3812             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3813     if (!TransParam)
3814       return TemplateName();
3815 
3816     if (!getDerived().AlwaysRebuild() &&
3817         TransParam == SubstPack->getParameterPack())
3818       return Name;
3819 
3820     return getDerived().RebuildTemplateName(TransParam,
3821                                             SubstPack->getArgumentPack());
3822   }
3823 
3824   // These should be getting filtered out before they reach the AST.
3825   llvm_unreachable("overloaded function decl survived to here");
3826 }
3827 
3828 template<typename Derived>
InventTemplateArgumentLoc(const TemplateArgument & Arg,TemplateArgumentLoc & Output)3829 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3830                                          const TemplateArgument &Arg,
3831                                          TemplateArgumentLoc &Output) {
3832   SourceLocation Loc = getDerived().getBaseLocation();
3833   switch (Arg.getKind()) {
3834   case TemplateArgument::Null:
3835     llvm_unreachable("null template argument in TreeTransform");
3836     break;
3837 
3838   case TemplateArgument::Type:
3839     Output = TemplateArgumentLoc(Arg,
3840                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3841 
3842     break;
3843 
3844   case TemplateArgument::Template:
3845   case TemplateArgument::TemplateExpansion: {
3846     NestedNameSpecifierLocBuilder Builder;
3847     TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
3848     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3849       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3850     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3851       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3852 
3853     if (Arg.getKind() == TemplateArgument::Template)
3854       Output = TemplateArgumentLoc(Arg,
3855                                    Builder.getWithLocInContext(SemaRef.Context),
3856                                    Loc);
3857     else
3858       Output = TemplateArgumentLoc(Arg,
3859                                    Builder.getWithLocInContext(SemaRef.Context),
3860                                    Loc, Loc);
3861 
3862     break;
3863   }
3864 
3865   case TemplateArgument::Expression:
3866     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3867     break;
3868 
3869   case TemplateArgument::Declaration:
3870   case TemplateArgument::Integral:
3871   case TemplateArgument::Pack:
3872   case TemplateArgument::NullPtr:
3873     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3874     break;
3875   }
3876 }
3877 
3878 template<typename Derived>
TransformTemplateArgument(const TemplateArgumentLoc & Input,TemplateArgumentLoc & Output,bool Uneval)3879 bool TreeTransform<Derived>::TransformTemplateArgument(
3880                                          const TemplateArgumentLoc &Input,
3881                                          TemplateArgumentLoc &Output, bool Uneval) {
3882   EnterExpressionEvaluationContext EEEC(
3883       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated,
3884       /*LambdaContextDecl=*/nullptr, /*ExprContext=*/
3885       Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
3886   const TemplateArgument &Arg = Input.getArgument();
3887   switch (Arg.getKind()) {
3888   case TemplateArgument::Null:
3889   case TemplateArgument::Integral:
3890   case TemplateArgument::Pack:
3891   case TemplateArgument::Declaration:
3892   case TemplateArgument::NullPtr:
3893     llvm_unreachable("Unexpected TemplateArgument");
3894 
3895   case TemplateArgument::Type: {
3896     TypeSourceInfo *DI = Input.getTypeSourceInfo();
3897     if (!DI)
3898       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3899 
3900     DI = getDerived().TransformType(DI);
3901     if (!DI) return true;
3902 
3903     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3904     return false;
3905   }
3906 
3907   case TemplateArgument::Template: {
3908     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3909     if (QualifierLoc) {
3910       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3911       if (!QualifierLoc)
3912         return true;
3913     }
3914 
3915     CXXScopeSpec SS;
3916     SS.Adopt(QualifierLoc);
3917     TemplateName Template
3918       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3919                                            Input.getTemplateNameLoc());
3920     if (Template.isNull())
3921       return true;
3922 
3923     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3924                                  Input.getTemplateNameLoc());
3925     return false;
3926   }
3927 
3928   case TemplateArgument::TemplateExpansion:
3929     llvm_unreachable("Caller should expand pack expansions");
3930 
3931   case TemplateArgument::Expression: {
3932     // Template argument expressions are constant expressions.
3933     EnterExpressionEvaluationContext Unevaluated(
3934         getSema(), Uneval
3935                        ? Sema::ExpressionEvaluationContext::Unevaluated
3936                        : Sema::ExpressionEvaluationContext::ConstantEvaluated);
3937 
3938     Expr *InputExpr = Input.getSourceExpression();
3939     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
3940 
3941     ExprResult E = getDerived().TransformExpr(InputExpr);
3942     E = SemaRef.ActOnConstantExpression(E);
3943     if (E.isInvalid()) return true;
3944     Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
3945     return false;
3946   }
3947   }
3948 
3949   // Work around bogus GCC warning
3950   return true;
3951 }
3952 
3953 /// Iterator adaptor that invents template argument location information
3954 /// for each of the template arguments in its underlying iterator.
3955 template<typename Derived, typename InputIterator>
3956 class TemplateArgumentLocInventIterator {
3957   TreeTransform<Derived> &Self;
3958   InputIterator Iter;
3959 
3960 public:
3961   typedef TemplateArgumentLoc value_type;
3962   typedef TemplateArgumentLoc reference;
3963   typedef typename std::iterator_traits<InputIterator>::difference_type
3964     difference_type;
3965   typedef std::input_iterator_tag iterator_category;
3966 
3967   class pointer {
3968     TemplateArgumentLoc Arg;
3969 
3970   public:
pointer(TemplateArgumentLoc Arg)3971     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
3972 
3973     const TemplateArgumentLoc *operator->() const { return &Arg; }
3974   };
3975 
TemplateArgumentLocInventIterator()3976   TemplateArgumentLocInventIterator() { }
3977 
TemplateArgumentLocInventIterator(TreeTransform<Derived> & Self,InputIterator Iter)3978   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
3979                                              InputIterator Iter)
3980     : Self(Self), Iter(Iter) { }
3981 
3982   TemplateArgumentLocInventIterator &operator++() {
3983     ++Iter;
3984     return *this;
3985   }
3986 
3987   TemplateArgumentLocInventIterator operator++(int) {
3988     TemplateArgumentLocInventIterator Old(*this);
3989     ++(*this);
3990     return Old;
3991   }
3992 
3993   reference operator*() const {
3994     TemplateArgumentLoc Result;
3995     Self.InventTemplateArgumentLoc(*Iter, Result);
3996     return Result;
3997   }
3998 
3999   pointer operator->() const { return pointer(**this); }
4000 
4001   friend bool operator==(const TemplateArgumentLocInventIterator &X,
4002                          const TemplateArgumentLocInventIterator &Y) {
4003     return X.Iter == Y.Iter;
4004   }
4005 
4006   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4007                          const TemplateArgumentLocInventIterator &Y) {
4008     return X.Iter != Y.Iter;
4009   }
4010 };
4011 
4012 template<typename Derived>
4013 template<typename InputIterator>
TransformTemplateArguments(InputIterator First,InputIterator Last,TemplateArgumentListInfo & Outputs,bool Uneval)4014 bool TreeTransform<Derived>::TransformTemplateArguments(
4015     InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4016     bool Uneval) {
4017   for (; First != Last; ++First) {
4018     TemplateArgumentLoc Out;
4019     TemplateArgumentLoc In = *First;
4020 
4021     if (In.getArgument().getKind() == TemplateArgument::Pack) {
4022       // Unpack argument packs, which we translate them into separate
4023       // arguments.
4024       // FIXME: We could do much better if we could guarantee that the
4025       // TemplateArgumentLocInfo for the pack expansion would be usable for
4026       // all of the template arguments in the argument pack.
4027       typedef TemplateArgumentLocInventIterator<Derived,
4028                                                 TemplateArgument::pack_iterator>
4029         PackLocIterator;
4030       if (TransformTemplateArguments(PackLocIterator(*this,
4031                                                  In.getArgument().pack_begin()),
4032                                      PackLocIterator(*this,
4033                                                    In.getArgument().pack_end()),
4034                                      Outputs, Uneval))
4035         return true;
4036 
4037       continue;
4038     }
4039 
4040     if (In.getArgument().isPackExpansion()) {
4041       // We have a pack expansion, for which we will be substituting into
4042       // the pattern.
4043       SourceLocation Ellipsis;
4044       Optional<unsigned> OrigNumExpansions;
4045       TemplateArgumentLoc Pattern
4046         = getSema().getTemplateArgumentPackExpansionPattern(
4047               In, Ellipsis, OrigNumExpansions);
4048 
4049       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4050       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4051       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4052 
4053       // Determine whether the set of unexpanded parameter packs can and should
4054       // be expanded.
4055       bool Expand = true;
4056       bool RetainExpansion = false;
4057       Optional<unsigned> NumExpansions = OrigNumExpansions;
4058       if (getDerived().TryExpandParameterPacks(Ellipsis,
4059                                                Pattern.getSourceRange(),
4060                                                Unexpanded,
4061                                                Expand,
4062                                                RetainExpansion,
4063                                                NumExpansions))
4064         return true;
4065 
4066       if (!Expand) {
4067         // The transform has determined that we should perform a simple
4068         // transformation on the pack expansion, producing another pack
4069         // expansion.
4070         TemplateArgumentLoc OutPattern;
4071         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4072         if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4073           return true;
4074 
4075         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4076                                                 NumExpansions);
4077         if (Out.getArgument().isNull())
4078           return true;
4079 
4080         Outputs.addArgument(Out);
4081         continue;
4082       }
4083 
4084       // The transform has determined that we should perform an elementwise
4085       // expansion of the pattern. Do so.
4086       for (unsigned I = 0; I != *NumExpansions; ++I) {
4087         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4088 
4089         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4090           return true;
4091 
4092         if (Out.getArgument().containsUnexpandedParameterPack()) {
4093           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4094                                                   OrigNumExpansions);
4095           if (Out.getArgument().isNull())
4096             return true;
4097         }
4098 
4099         Outputs.addArgument(Out);
4100       }
4101 
4102       // If we're supposed to retain a pack expansion, do so by temporarily
4103       // forgetting the partially-substituted parameter pack.
4104       if (RetainExpansion) {
4105         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4106 
4107         if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4108           return true;
4109 
4110         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4111                                                 OrigNumExpansions);
4112         if (Out.getArgument().isNull())
4113           return true;
4114 
4115         Outputs.addArgument(Out);
4116       }
4117 
4118       continue;
4119     }
4120 
4121     // The simple case:
4122     if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4123       return true;
4124 
4125     Outputs.addArgument(Out);
4126   }
4127 
4128   return false;
4129 
4130 }
4131 
4132 //===----------------------------------------------------------------------===//
4133 // Type transformation
4134 //===----------------------------------------------------------------------===//
4135 
4136 template<typename Derived>
TransformType(QualType T)4137 QualType TreeTransform<Derived>::TransformType(QualType T) {
4138   if (getDerived().AlreadyTransformed(T))
4139     return T;
4140 
4141   // Temporary workaround.  All of these transformations should
4142   // eventually turn into transformations on TypeLocs.
4143   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4144                                                 getDerived().getBaseLocation());
4145 
4146   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4147 
4148   if (!NewDI)
4149     return QualType();
4150 
4151   return NewDI->getType();
4152 }
4153 
4154 template<typename Derived>
TransformType(TypeSourceInfo * DI)4155 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4156   // Refine the base location to the type's location.
4157   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4158                        getDerived().getBaseEntity());
4159   if (getDerived().AlreadyTransformed(DI->getType()))
4160     return DI;
4161 
4162   TypeLocBuilder TLB;
4163 
4164   TypeLoc TL = DI->getTypeLoc();
4165   TLB.reserve(TL.getFullDataSize());
4166 
4167   QualType Result = getDerived().TransformType(TLB, TL);
4168   if (Result.isNull())
4169     return nullptr;
4170 
4171   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4172 }
4173 
4174 template<typename Derived>
4175 QualType
TransformType(TypeLocBuilder & TLB,TypeLoc T)4176 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4177   switch (T.getTypeLocClass()) {
4178 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4179 #define TYPELOC(CLASS, PARENT)                                                 \
4180   case TypeLoc::CLASS:                                                         \
4181     return getDerived().Transform##CLASS##Type(TLB,                            \
4182                                                T.castAs<CLASS##TypeLoc>());
4183 #include "clang/AST/TypeLocNodes.def"
4184   }
4185 
4186   llvm_unreachable("unhandled type loc!");
4187 }
4188 
4189 template<typename Derived>
TransformTypeWithDeducedTST(QualType T)4190 QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4191   if (!isa<DependentNameType>(T))
4192     return TransformType(T);
4193 
4194   if (getDerived().AlreadyTransformed(T))
4195     return T;
4196   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4197                                                 getDerived().getBaseLocation());
4198   TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4199   return NewDI ? NewDI->getType() : QualType();
4200 }
4201 
4202 template<typename Derived>
4203 TypeSourceInfo *
TransformTypeWithDeducedTST(TypeSourceInfo * DI)4204 TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4205   if (!isa<DependentNameType>(DI->getType()))
4206     return TransformType(DI);
4207 
4208   // Refine the base location to the type's location.
4209   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4210                        getDerived().getBaseEntity());
4211   if (getDerived().AlreadyTransformed(DI->getType()))
4212     return DI;
4213 
4214   TypeLocBuilder TLB;
4215 
4216   TypeLoc TL = DI->getTypeLoc();
4217   TLB.reserve(TL.getFullDataSize());
4218 
4219   auto QTL = TL.getAs<QualifiedTypeLoc>();
4220   if (QTL)
4221     TL = QTL.getUnqualifiedLoc();
4222 
4223   auto DNTL = TL.castAs<DependentNameTypeLoc>();
4224 
4225   QualType Result = getDerived().TransformDependentNameType(
4226       TLB, DNTL, /*DeducedTSTContext*/true);
4227   if (Result.isNull())
4228     return nullptr;
4229 
4230   if (QTL) {
4231     Result = getDerived().RebuildQualifiedType(Result, QTL);
4232     if (Result.isNull())
4233       return nullptr;
4234     TLB.TypeWasModifiedSafely(Result);
4235   }
4236 
4237   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4238 }
4239 
4240 template<typename Derived>
4241 QualType
TransformQualifiedType(TypeLocBuilder & TLB,QualifiedTypeLoc T)4242 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4243                                                QualifiedTypeLoc T) {
4244   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
4245   if (Result.isNull())
4246     return QualType();
4247 
4248   Result = getDerived().RebuildQualifiedType(Result, T);
4249 
4250   if (Result.isNull())
4251     return QualType();
4252 
4253   // RebuildQualifiedType might have updated the type, but not in a way
4254   // that invalidates the TypeLoc. (There's no location information for
4255   // qualifiers.)
4256   TLB.TypeWasModifiedSafely(Result);
4257 
4258   return Result;
4259 }
4260 
4261 template <typename Derived>
RebuildQualifiedType(QualType T,QualifiedTypeLoc TL)4262 QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4263                                                       QualifiedTypeLoc TL) {
4264 
4265   SourceLocation Loc = TL.getBeginLoc();
4266   Qualifiers Quals = TL.getType().getLocalQualifiers();
4267 
4268   if (((T.getAddressSpace() != LangAS::Default &&
4269         Quals.getAddressSpace() != LangAS::Default)) &&
4270       T.getAddressSpace() != Quals.getAddressSpace()) {
4271     SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4272         << TL.getType() << T;
4273     return QualType();
4274   }
4275 
4276   // C++ [dcl.fct]p7:
4277   //   [When] adding cv-qualifications on top of the function type [...] the
4278   //   cv-qualifiers are ignored.
4279   if (T->isFunctionType()) {
4280     T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4281                                                      Quals.getAddressSpace());
4282     return T;
4283   }
4284 
4285   // C++ [dcl.ref]p1:
4286   //   when the cv-qualifiers are introduced through the use of a typedef-name
4287   //   or decltype-specifier [...] the cv-qualifiers are ignored.
4288   // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4289   // applied to a reference type.
4290   if (T->isReferenceType()) {
4291     // The only qualifier that applies to a reference type is restrict.
4292     if (!Quals.hasRestrict())
4293       return T;
4294     Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4295   }
4296 
4297   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4298   // resulting type.
4299   if (Quals.hasObjCLifetime()) {
4300     if (!T->isObjCLifetimeType() && !T->isDependentType())
4301       Quals.removeObjCLifetime();
4302     else if (T.getObjCLifetime()) {
4303       // Objective-C ARC:
4304       //   A lifetime qualifier applied to a substituted template parameter
4305       //   overrides the lifetime qualifier from the template argument.
4306       const AutoType *AutoTy;
4307       if (const SubstTemplateTypeParmType *SubstTypeParam
4308                                 = dyn_cast<SubstTemplateTypeParmType>(T)) {
4309         QualType Replacement = SubstTypeParam->getReplacementType();
4310         Qualifiers Qs = Replacement.getQualifiers();
4311         Qs.removeObjCLifetime();
4312         Replacement = SemaRef.Context.getQualifiedType(
4313             Replacement.getUnqualifiedType(), Qs);
4314         T = SemaRef.Context.getSubstTemplateTypeParmType(
4315             SubstTypeParam->getReplacedParameter(), Replacement);
4316       } else if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4317         // 'auto' types behave the same way as template parameters.
4318         QualType Deduced = AutoTy->getDeducedType();
4319         Qualifiers Qs = Deduced.getQualifiers();
4320         Qs.removeObjCLifetime();
4321         Deduced =
4322             SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
4323         T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
4324                                         AutoTy->isDependentType());
4325       } else {
4326         // Otherwise, complain about the addition of a qualifier to an
4327         // already-qualified type.
4328         // FIXME: Why is this check not in Sema::BuildQualifiedType?
4329         SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
4330         Quals.removeObjCLifetime();
4331       }
4332     }
4333   }
4334 
4335   return SemaRef.BuildQualifiedType(T, Loc, Quals);
4336 }
4337 
4338 template<typename Derived>
4339 TypeLoc
TransformTypeInObjectScope(TypeLoc TL,QualType ObjectType,NamedDecl * UnqualLookup,CXXScopeSpec & SS)4340 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
4341                                                    QualType ObjectType,
4342                                                    NamedDecl *UnqualLookup,
4343                                                    CXXScopeSpec &SS) {
4344   if (getDerived().AlreadyTransformed(TL.getType()))
4345     return TL;
4346 
4347   TypeSourceInfo *TSI =
4348       TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
4349   if (TSI)
4350     return TSI->getTypeLoc();
4351   return TypeLoc();
4352 }
4353 
4354 template<typename Derived>
4355 TypeSourceInfo *
TransformTypeInObjectScope(TypeSourceInfo * TSInfo,QualType ObjectType,NamedDecl * UnqualLookup,CXXScopeSpec & SS)4356 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
4357                                                    QualType ObjectType,
4358                                                    NamedDecl *UnqualLookup,
4359                                                    CXXScopeSpec &SS) {
4360   if (getDerived().AlreadyTransformed(TSInfo->getType()))
4361     return TSInfo;
4362 
4363   return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
4364                                    UnqualLookup, SS);
4365 }
4366 
4367 template <typename Derived>
TransformTSIInObjectScope(TypeLoc TL,QualType ObjectType,NamedDecl * UnqualLookup,CXXScopeSpec & SS)4368 TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
4369     TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
4370     CXXScopeSpec &SS) {
4371   QualType T = TL.getType();
4372   assert(!getDerived().AlreadyTransformed(T));
4373 
4374   TypeLocBuilder TLB;
4375   QualType Result;
4376 
4377   if (isa<TemplateSpecializationType>(T)) {
4378     TemplateSpecializationTypeLoc SpecTL =
4379         TL.castAs<TemplateSpecializationTypeLoc>();
4380 
4381     TemplateName Template = getDerived().TransformTemplateName(
4382         SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
4383         ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
4384     if (Template.isNull())
4385       return nullptr;
4386 
4387     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
4388                                                               Template);
4389   } else if (isa<DependentTemplateSpecializationType>(T)) {
4390     DependentTemplateSpecializationTypeLoc SpecTL =
4391         TL.castAs<DependentTemplateSpecializationTypeLoc>();
4392 
4393     TemplateName Template
4394       = getDerived().RebuildTemplateName(SS,
4395                                          SpecTL.getTemplateKeywordLoc(),
4396                                          *SpecTL.getTypePtr()->getIdentifier(),
4397                                          SpecTL.getTemplateNameLoc(),
4398                                          ObjectType, UnqualLookup,
4399                                          /*AllowInjectedClassName*/true);
4400     if (Template.isNull())
4401       return nullptr;
4402 
4403     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
4404                                                                        SpecTL,
4405                                                                        Template,
4406                                                                        SS);
4407   } else {
4408     // Nothing special needs to be done for these.
4409     Result = getDerived().TransformType(TLB, TL);
4410   }
4411 
4412   if (Result.isNull())
4413     return nullptr;
4414 
4415   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4416 }
4417 
4418 template <class TyLoc> static inline
TransformTypeSpecType(TypeLocBuilder & TLB,TyLoc T)4419 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
4420   TyLoc NewT = TLB.push<TyLoc>(T.getType());
4421   NewT.setNameLoc(T.getNameLoc());
4422   return T.getType();
4423 }
4424 
4425 template<typename Derived>
TransformBuiltinType(TypeLocBuilder & TLB,BuiltinTypeLoc T)4426 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
4427                                                       BuiltinTypeLoc T) {
4428   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
4429   NewT.setBuiltinLoc(T.getBuiltinLoc());
4430   if (T.needsExtraLocalData())
4431     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
4432   return T.getType();
4433 }
4434 
4435 template<typename Derived>
TransformComplexType(TypeLocBuilder & TLB,ComplexTypeLoc T)4436 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
4437                                                       ComplexTypeLoc T) {
4438   // FIXME: recurse?
4439   return TransformTypeSpecType(TLB, T);
4440 }
4441 
4442 template <typename Derived>
TransformAdjustedType(TypeLocBuilder & TLB,AdjustedTypeLoc TL)4443 QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
4444                                                        AdjustedTypeLoc TL) {
4445   // Adjustments applied during transformation are handled elsewhere.
4446   return getDerived().TransformType(TLB, TL.getOriginalLoc());
4447 }
4448 
4449 template<typename Derived>
TransformDecayedType(TypeLocBuilder & TLB,DecayedTypeLoc TL)4450 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
4451                                                       DecayedTypeLoc TL) {
4452   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
4453   if (OriginalType.isNull())
4454     return QualType();
4455 
4456   QualType Result = TL.getType();
4457   if (getDerived().AlwaysRebuild() ||
4458       OriginalType != TL.getOriginalLoc().getType())
4459     Result = SemaRef.Context.getDecayedType(OriginalType);
4460   TLB.push<DecayedTypeLoc>(Result);
4461   // Nothing to set for DecayedTypeLoc.
4462   return Result;
4463 }
4464 
4465 template<typename Derived>
TransformPointerType(TypeLocBuilder & TLB,PointerTypeLoc TL)4466 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
4467                                                       PointerTypeLoc TL) {
4468   QualType PointeeType
4469     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4470   if (PointeeType.isNull())
4471     return QualType();
4472 
4473   QualType Result = TL.getType();
4474   if (PointeeType->getAs<ObjCObjectType>()) {
4475     // A dependent pointer type 'T *' has is being transformed such
4476     // that an Objective-C class type is being replaced for 'T'. The
4477     // resulting pointer type is an ObjCObjectPointerType, not a
4478     // PointerType.
4479     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
4480 
4481     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
4482     NewT.setStarLoc(TL.getStarLoc());
4483     return Result;
4484   }
4485 
4486   if (getDerived().AlwaysRebuild() ||
4487       PointeeType != TL.getPointeeLoc().getType()) {
4488     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
4489     if (Result.isNull())
4490       return QualType();
4491   }
4492 
4493   // Objective-C ARC can add lifetime qualifiers to the type that we're
4494   // pointing to.
4495   TLB.TypeWasModifiedSafely(Result->getPointeeType());
4496 
4497   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
4498   NewT.setSigilLoc(TL.getSigilLoc());
4499   return Result;
4500 }
4501 
4502 template<typename Derived>
4503 QualType
TransformBlockPointerType(TypeLocBuilder & TLB,BlockPointerTypeLoc TL)4504 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
4505                                                   BlockPointerTypeLoc TL) {
4506   QualType PointeeType
4507     = getDerived().TransformType(TLB, TL.getPointeeLoc());
4508   if (PointeeType.isNull())
4509     return QualType();
4510 
4511   QualType Result = TL.getType();
4512   if (getDerived().AlwaysRebuild() ||
4513       PointeeType != TL.getPointeeLoc().getType()) {
4514     Result = getDerived().RebuildBlockPointerType(PointeeType,
4515                                                   TL.getSigilLoc());
4516     if (Result.isNull())
4517       return QualType();
4518   }
4519 
4520   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
4521   NewT.setSigilLoc(TL.getSigilLoc());
4522   return Result;
4523 }
4524 
4525 /// Transforms a reference type.  Note that somewhat paradoxically we
4526 /// don't care whether the type itself is an l-value type or an r-value
4527 /// type;  we only care if the type was *written* as an l-value type
4528 /// or an r-value type.
4529 template<typename Derived>
4530 QualType
TransformReferenceType(TypeLocBuilder & TLB,ReferenceTypeLoc TL)4531 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
4532                                                ReferenceTypeLoc TL) {
4533   const ReferenceType *T = TL.getTypePtr();
4534 
4535   // Note that this works with the pointee-as-written.
4536   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4537   if (PointeeType.isNull())
4538     return QualType();
4539 
4540   QualType Result = TL.getType();
4541   if (getDerived().AlwaysRebuild() ||
4542       PointeeType != T->getPointeeTypeAsWritten()) {
4543     Result = getDerived().RebuildReferenceType(PointeeType,
4544                                                T->isSpelledAsLValue(),
4545                                                TL.getSigilLoc());
4546     if (Result.isNull())
4547       return QualType();
4548   }
4549 
4550   // Objective-C ARC can add lifetime qualifiers to the type that we're
4551   // referring to.
4552   TLB.TypeWasModifiedSafely(
4553                      Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
4554 
4555   // r-value references can be rebuilt as l-value references.
4556   ReferenceTypeLoc NewTL;
4557   if (isa<LValueReferenceType>(Result))
4558     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
4559   else
4560     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
4561   NewTL.setSigilLoc(TL.getSigilLoc());
4562 
4563   return Result;
4564 }
4565 
4566 template<typename Derived>
4567 QualType
TransformLValueReferenceType(TypeLocBuilder & TLB,LValueReferenceTypeLoc TL)4568 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
4569                                                  LValueReferenceTypeLoc TL) {
4570   return TransformReferenceType(TLB, TL);
4571 }
4572 
4573 template<typename Derived>
4574 QualType
TransformRValueReferenceType(TypeLocBuilder & TLB,RValueReferenceTypeLoc TL)4575 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
4576                                                  RValueReferenceTypeLoc TL) {
4577   return TransformReferenceType(TLB, TL);
4578 }
4579 
4580 template<typename Derived>
4581 QualType
TransformMemberPointerType(TypeLocBuilder & TLB,MemberPointerTypeLoc TL)4582 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
4583                                                    MemberPointerTypeLoc TL) {
4584   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
4585   if (PointeeType.isNull())
4586     return QualType();
4587 
4588   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
4589   TypeSourceInfo *NewClsTInfo = nullptr;
4590   if (OldClsTInfo) {
4591     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
4592     if (!NewClsTInfo)
4593       return QualType();
4594   }
4595 
4596   const MemberPointerType *T = TL.getTypePtr();
4597   QualType OldClsType = QualType(T->getClass(), 0);
4598   QualType NewClsType;
4599   if (NewClsTInfo)
4600     NewClsType = NewClsTInfo->getType();
4601   else {
4602     NewClsType = getDerived().TransformType(OldClsType);
4603     if (NewClsType.isNull())
4604       return QualType();
4605   }
4606 
4607   QualType Result = TL.getType();
4608   if (getDerived().AlwaysRebuild() ||
4609       PointeeType != T->getPointeeType() ||
4610       NewClsType != OldClsType) {
4611     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
4612                                                    TL.getStarLoc());
4613     if (Result.isNull())
4614       return QualType();
4615   }
4616 
4617   // If we had to adjust the pointee type when building a member pointer, make
4618   // sure to push TypeLoc info for it.
4619   const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
4620   if (MPT && PointeeType != MPT->getPointeeType()) {
4621     assert(isa<AdjustedType>(MPT->getPointeeType()));
4622     TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
4623   }
4624 
4625   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
4626   NewTL.setSigilLoc(TL.getSigilLoc());
4627   NewTL.setClassTInfo(NewClsTInfo);
4628 
4629   return Result;
4630 }
4631 
4632 template<typename Derived>
4633 QualType
TransformConstantArrayType(TypeLocBuilder & TLB,ConstantArrayTypeLoc TL)4634 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
4635                                                    ConstantArrayTypeLoc TL) {
4636   const ConstantArrayType *T = TL.getTypePtr();
4637   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4638   if (ElementType.isNull())
4639     return QualType();
4640 
4641   QualType Result = TL.getType();
4642   if (getDerived().AlwaysRebuild() ||
4643       ElementType != T->getElementType()) {
4644     Result = getDerived().RebuildConstantArrayType(ElementType,
4645                                                    T->getSizeModifier(),
4646                                                    T->getSize(),
4647                                              T->getIndexTypeCVRQualifiers(),
4648                                                    TL.getBracketsRange());
4649     if (Result.isNull())
4650       return QualType();
4651   }
4652 
4653   // We might have either a ConstantArrayType or a VariableArrayType now:
4654   // a ConstantArrayType is allowed to have an element type which is a
4655   // VariableArrayType if the type is dependent.  Fortunately, all array
4656   // types have the same location layout.
4657   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4658   NewTL.setLBracketLoc(TL.getLBracketLoc());
4659   NewTL.setRBracketLoc(TL.getRBracketLoc());
4660 
4661   Expr *Size = TL.getSizeExpr();
4662   if (Size) {
4663     EnterExpressionEvaluationContext Unevaluated(
4664         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4665     Size = getDerived().TransformExpr(Size).template getAs<Expr>();
4666     Size = SemaRef.ActOnConstantExpression(Size).get();
4667   }
4668   NewTL.setSizeExpr(Size);
4669 
4670   return Result;
4671 }
4672 
4673 template<typename Derived>
TransformIncompleteArrayType(TypeLocBuilder & TLB,IncompleteArrayTypeLoc TL)4674 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
4675                                               TypeLocBuilder &TLB,
4676                                               IncompleteArrayTypeLoc TL) {
4677   const IncompleteArrayType *T = TL.getTypePtr();
4678   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4679   if (ElementType.isNull())
4680     return QualType();
4681 
4682   QualType Result = TL.getType();
4683   if (getDerived().AlwaysRebuild() ||
4684       ElementType != T->getElementType()) {
4685     Result = getDerived().RebuildIncompleteArrayType(ElementType,
4686                                                      T->getSizeModifier(),
4687                                            T->getIndexTypeCVRQualifiers(),
4688                                                      TL.getBracketsRange());
4689     if (Result.isNull())
4690       return QualType();
4691   }
4692 
4693   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
4694   NewTL.setLBracketLoc(TL.getLBracketLoc());
4695   NewTL.setRBracketLoc(TL.getRBracketLoc());
4696   NewTL.setSizeExpr(nullptr);
4697 
4698   return Result;
4699 }
4700 
4701 template<typename Derived>
4702 QualType
TransformVariableArrayType(TypeLocBuilder & TLB,VariableArrayTypeLoc TL)4703 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
4704                                                    VariableArrayTypeLoc TL) {
4705   const VariableArrayType *T = TL.getTypePtr();
4706   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4707   if (ElementType.isNull())
4708     return QualType();
4709 
4710   ExprResult SizeResult;
4711   {
4712     EnterExpressionEvaluationContext Context(
4713         SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4714     SizeResult = getDerived().TransformExpr(T->getSizeExpr());
4715   }
4716   if (SizeResult.isInvalid())
4717     return QualType();
4718   SizeResult = SemaRef.ActOnFinishFullExpr(SizeResult.get());
4719   if (SizeResult.isInvalid())
4720     return QualType();
4721 
4722   Expr *Size = SizeResult.get();
4723 
4724   QualType Result = TL.getType();
4725   if (getDerived().AlwaysRebuild() ||
4726       ElementType != T->getElementType() ||
4727       Size != T->getSizeExpr()) {
4728     Result = getDerived().RebuildVariableArrayType(ElementType,
4729                                                    T->getSizeModifier(),
4730                                                    Size,
4731                                              T->getIndexTypeCVRQualifiers(),
4732                                                    TL.getBracketsRange());
4733     if (Result.isNull())
4734       return QualType();
4735   }
4736 
4737   // We might have constant size array now, but fortunately it has the same
4738   // location layout.
4739   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4740   NewTL.setLBracketLoc(TL.getLBracketLoc());
4741   NewTL.setRBracketLoc(TL.getRBracketLoc());
4742   NewTL.setSizeExpr(Size);
4743 
4744   return Result;
4745 }
4746 
4747 template<typename Derived>
4748 QualType
TransformDependentSizedArrayType(TypeLocBuilder & TLB,DependentSizedArrayTypeLoc TL)4749 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
4750                                              DependentSizedArrayTypeLoc TL) {
4751   const DependentSizedArrayType *T = TL.getTypePtr();
4752   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
4753   if (ElementType.isNull())
4754     return QualType();
4755 
4756   // Array bounds are constant expressions.
4757   EnterExpressionEvaluationContext Unevaluated(
4758       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4759 
4760   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
4761   Expr *origSize = TL.getSizeExpr();
4762   if (!origSize) origSize = T->getSizeExpr();
4763 
4764   ExprResult sizeResult
4765     = getDerived().TransformExpr(origSize);
4766   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
4767   if (sizeResult.isInvalid())
4768     return QualType();
4769 
4770   Expr *size = sizeResult.get();
4771 
4772   QualType Result = TL.getType();
4773   if (getDerived().AlwaysRebuild() ||
4774       ElementType != T->getElementType() ||
4775       size != origSize) {
4776     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
4777                                                          T->getSizeModifier(),
4778                                                          size,
4779                                                 T->getIndexTypeCVRQualifiers(),
4780                                                         TL.getBracketsRange());
4781     if (Result.isNull())
4782       return QualType();
4783   }
4784 
4785   // We might have any sort of array type now, but fortunately they
4786   // all have the same location layout.
4787   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
4788   NewTL.setLBracketLoc(TL.getLBracketLoc());
4789   NewTL.setRBracketLoc(TL.getRBracketLoc());
4790   NewTL.setSizeExpr(size);
4791 
4792   return Result;
4793 }
4794 
4795 template <typename Derived>
TransformDependentVectorType(TypeLocBuilder & TLB,DependentVectorTypeLoc TL)4796 QualType TreeTransform<Derived>::TransformDependentVectorType(
4797     TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
4798   const DependentVectorType *T = TL.getTypePtr();
4799   QualType ElementType = getDerived().TransformType(T->getElementType());
4800   if (ElementType.isNull())
4801     return QualType();
4802 
4803   EnterExpressionEvaluationContext Unevaluated(
4804       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4805 
4806   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4807   Size = SemaRef.ActOnConstantExpression(Size);
4808   if (Size.isInvalid())
4809     return QualType();
4810 
4811   QualType Result = TL.getType();
4812   if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
4813       Size.get() != T->getSizeExpr()) {
4814     Result = getDerived().RebuildDependentVectorType(
4815         ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
4816     if (Result.isNull())
4817       return QualType();
4818   }
4819 
4820   // Result might be dependent or not.
4821   if (isa<DependentVectorType>(Result)) {
4822     DependentVectorTypeLoc NewTL =
4823         TLB.push<DependentVectorTypeLoc>(Result);
4824     NewTL.setNameLoc(TL.getNameLoc());
4825   } else {
4826     VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4827     NewTL.setNameLoc(TL.getNameLoc());
4828   }
4829 
4830   return Result;
4831 }
4832 
4833 template<typename Derived>
TransformDependentSizedExtVectorType(TypeLocBuilder & TLB,DependentSizedExtVectorTypeLoc TL)4834 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
4835                                       TypeLocBuilder &TLB,
4836                                       DependentSizedExtVectorTypeLoc TL) {
4837   const DependentSizedExtVectorType *T = TL.getTypePtr();
4838 
4839   // FIXME: ext vector locs should be nested
4840   QualType ElementType = getDerived().TransformType(T->getElementType());
4841   if (ElementType.isNull())
4842     return QualType();
4843 
4844   // Vector sizes are constant expressions.
4845   EnterExpressionEvaluationContext Unevaluated(
4846       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4847 
4848   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
4849   Size = SemaRef.ActOnConstantExpression(Size);
4850   if (Size.isInvalid())
4851     return QualType();
4852 
4853   QualType Result = TL.getType();
4854   if (getDerived().AlwaysRebuild() ||
4855       ElementType != T->getElementType() ||
4856       Size.get() != T->getSizeExpr()) {
4857     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
4858                                                              Size.get(),
4859                                                          T->getAttributeLoc());
4860     if (Result.isNull())
4861       return QualType();
4862   }
4863 
4864   // Result might be dependent or not.
4865   if (isa<DependentSizedExtVectorType>(Result)) {
4866     DependentSizedExtVectorTypeLoc NewTL
4867       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
4868     NewTL.setNameLoc(TL.getNameLoc());
4869   } else {
4870     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4871     NewTL.setNameLoc(TL.getNameLoc());
4872   }
4873 
4874   return Result;
4875 }
4876 
4877 template <typename Derived>
TransformDependentAddressSpaceType(TypeLocBuilder & TLB,DependentAddressSpaceTypeLoc TL)4878 QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
4879     TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
4880   const DependentAddressSpaceType *T = TL.getTypePtr();
4881 
4882   QualType pointeeType = getDerived().TransformType(T->getPointeeType());
4883 
4884   if (pointeeType.isNull())
4885     return QualType();
4886 
4887   // Address spaces are constant expressions.
4888   EnterExpressionEvaluationContext Unevaluated(
4889       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4890 
4891   ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
4892   AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
4893   if (AddrSpace.isInvalid())
4894     return QualType();
4895 
4896   QualType Result = TL.getType();
4897   if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
4898       AddrSpace.get() != T->getAddrSpaceExpr()) {
4899     Result = getDerived().RebuildDependentAddressSpaceType(
4900         pointeeType, AddrSpace.get(), T->getAttributeLoc());
4901     if (Result.isNull())
4902       return QualType();
4903   }
4904 
4905   // Result might be dependent or not.
4906   if (isa<DependentAddressSpaceType>(Result)) {
4907     DependentAddressSpaceTypeLoc NewTL =
4908         TLB.push<DependentAddressSpaceTypeLoc>(Result);
4909 
4910     NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
4911     NewTL.setAttrExprOperand(TL.getAttrExprOperand());
4912     NewTL.setAttrNameLoc(TL.getAttrNameLoc());
4913 
4914   } else {
4915     TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
4916         Result, getDerived().getBaseLocation());
4917     TransformType(TLB, DI->getTypeLoc());
4918   }
4919 
4920   return Result;
4921 }
4922 
4923 template <typename Derived>
TransformVectorType(TypeLocBuilder & TLB,VectorTypeLoc TL)4924 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
4925                                                      VectorTypeLoc TL) {
4926   const VectorType *T = TL.getTypePtr();
4927   QualType ElementType = getDerived().TransformType(T->getElementType());
4928   if (ElementType.isNull())
4929     return QualType();
4930 
4931   QualType Result = TL.getType();
4932   if (getDerived().AlwaysRebuild() ||
4933       ElementType != T->getElementType()) {
4934     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
4935                                             T->getVectorKind());
4936     if (Result.isNull())
4937       return QualType();
4938   }
4939 
4940   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
4941   NewTL.setNameLoc(TL.getNameLoc());
4942 
4943   return Result;
4944 }
4945 
4946 template<typename Derived>
TransformExtVectorType(TypeLocBuilder & TLB,ExtVectorTypeLoc TL)4947 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
4948                                                         ExtVectorTypeLoc TL) {
4949   const VectorType *T = TL.getTypePtr();
4950   QualType ElementType = getDerived().TransformType(T->getElementType());
4951   if (ElementType.isNull())
4952     return QualType();
4953 
4954   QualType Result = TL.getType();
4955   if (getDerived().AlwaysRebuild() ||
4956       ElementType != T->getElementType()) {
4957     Result = getDerived().RebuildExtVectorType(ElementType,
4958                                                T->getNumElements(),
4959                                                /*FIXME*/ SourceLocation());
4960     if (Result.isNull())
4961       return QualType();
4962   }
4963 
4964   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
4965   NewTL.setNameLoc(TL.getNameLoc());
4966 
4967   return Result;
4968 }
4969 
4970 template <typename Derived>
TransformFunctionTypeParam(ParmVarDecl * OldParm,int indexAdjustment,Optional<unsigned> NumExpansions,bool ExpectParameterPack)4971 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
4972     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
4973     bool ExpectParameterPack) {
4974   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
4975   TypeSourceInfo *NewDI = nullptr;
4976 
4977   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
4978     // If we're substituting into a pack expansion type and we know the
4979     // length we want to expand to, just substitute for the pattern.
4980     TypeLoc OldTL = OldDI->getTypeLoc();
4981     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
4982 
4983     TypeLocBuilder TLB;
4984     TypeLoc NewTL = OldDI->getTypeLoc();
4985     TLB.reserve(NewTL.getFullDataSize());
4986 
4987     QualType Result = getDerived().TransformType(TLB,
4988                                                OldExpansionTL.getPatternLoc());
4989     if (Result.isNull())
4990       return nullptr;
4991 
4992     Result = RebuildPackExpansionType(Result,
4993                                 OldExpansionTL.getPatternLoc().getSourceRange(),
4994                                       OldExpansionTL.getEllipsisLoc(),
4995                                       NumExpansions);
4996     if (Result.isNull())
4997       return nullptr;
4998 
4999     PackExpansionTypeLoc NewExpansionTL
5000       = TLB.push<PackExpansionTypeLoc>(Result);
5001     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5002     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5003   } else
5004     NewDI = getDerived().TransformType(OldDI);
5005   if (!NewDI)
5006     return nullptr;
5007 
5008   if (NewDI == OldDI && indexAdjustment == 0)
5009     return OldParm;
5010 
5011   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5012                                              OldParm->getDeclContext(),
5013                                              OldParm->getInnerLocStart(),
5014                                              OldParm->getLocation(),
5015                                              OldParm->getIdentifier(),
5016                                              NewDI->getType(),
5017                                              NewDI,
5018                                              OldParm->getStorageClass(),
5019                                              /* DefArg */ nullptr);
5020   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5021                         OldParm->getFunctionScopeIndex() + indexAdjustment);
5022   return newParm;
5023 }
5024 
5025 template <typename Derived>
TransformFunctionTypeParams(SourceLocation Loc,ArrayRef<ParmVarDecl * > Params,const QualType * ParamTypes,const FunctionProtoType::ExtParameterInfo * ParamInfos,SmallVectorImpl<QualType> & OutParamTypes,SmallVectorImpl<ParmVarDecl * > * PVars,Sema::ExtParameterInfoBuilder & PInfos)5026 bool TreeTransform<Derived>::TransformFunctionTypeParams(
5027     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5028     const QualType *ParamTypes,
5029     const FunctionProtoType::ExtParameterInfo *ParamInfos,
5030     SmallVectorImpl<QualType> &OutParamTypes,
5031     SmallVectorImpl<ParmVarDecl *> *PVars,
5032     Sema::ExtParameterInfoBuilder &PInfos) {
5033   int indexAdjustment = 0;
5034 
5035   unsigned NumParams = Params.size();
5036   for (unsigned i = 0; i != NumParams; ++i) {
5037     if (ParmVarDecl *OldParm = Params[i]) {
5038       assert(OldParm->getFunctionScopeIndex() == i);
5039 
5040       Optional<unsigned> NumExpansions;
5041       ParmVarDecl *NewParm = nullptr;
5042       if (OldParm->isParameterPack()) {
5043         // We have a function parameter pack that may need to be expanded.
5044         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5045 
5046         // Find the parameter packs that could be expanded.
5047         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5048         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5049         TypeLoc Pattern = ExpansionTL.getPatternLoc();
5050         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5051         assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
5052 
5053         // Determine whether we should expand the parameter packs.
5054         bool ShouldExpand = false;
5055         bool RetainExpansion = false;
5056         Optional<unsigned> OrigNumExpansions =
5057             ExpansionTL.getTypePtr()->getNumExpansions();
5058         NumExpansions = OrigNumExpansions;
5059         if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5060                                                  Pattern.getSourceRange(),
5061                                                  Unexpanded,
5062                                                  ShouldExpand,
5063                                                  RetainExpansion,
5064                                                  NumExpansions)) {
5065           return true;
5066         }
5067 
5068         if (ShouldExpand) {
5069           // Expand the function parameter pack into multiple, separate
5070           // parameters.
5071           getDerived().ExpandingFunctionParameterPack(OldParm);
5072           for (unsigned I = 0; I != *NumExpansions; ++I) {
5073             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5074             ParmVarDecl *NewParm
5075               = getDerived().TransformFunctionTypeParam(OldParm,
5076                                                         indexAdjustment++,
5077                                                         OrigNumExpansions,
5078                                                 /*ExpectParameterPack=*/false);
5079             if (!NewParm)
5080               return true;
5081 
5082             if (ParamInfos)
5083               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5084             OutParamTypes.push_back(NewParm->getType());
5085             if (PVars)
5086               PVars->push_back(NewParm);
5087           }
5088 
5089           // If we're supposed to retain a pack expansion, do so by temporarily
5090           // forgetting the partially-substituted parameter pack.
5091           if (RetainExpansion) {
5092             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5093             ParmVarDecl *NewParm
5094               = getDerived().TransformFunctionTypeParam(OldParm,
5095                                                         indexAdjustment++,
5096                                                         OrigNumExpansions,
5097                                                 /*ExpectParameterPack=*/false);
5098             if (!NewParm)
5099               return true;
5100 
5101             if (ParamInfos)
5102               PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5103             OutParamTypes.push_back(NewParm->getType());
5104             if (PVars)
5105               PVars->push_back(NewParm);
5106           }
5107 
5108           // The next parameter should have the same adjustment as the
5109           // last thing we pushed, but we post-incremented indexAdjustment
5110           // on every push.  Also, if we push nothing, the adjustment should
5111           // go down by one.
5112           indexAdjustment--;
5113 
5114           // We're done with the pack expansion.
5115           continue;
5116         }
5117 
5118         // We'll substitute the parameter now without expanding the pack
5119         // expansion.
5120         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5121         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5122                                                           indexAdjustment,
5123                                                           NumExpansions,
5124                                                   /*ExpectParameterPack=*/true);
5125       } else {
5126         NewParm = getDerived().TransformFunctionTypeParam(
5127             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
5128       }
5129 
5130       if (!NewParm)
5131         return true;
5132 
5133       if (ParamInfos)
5134         PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5135       OutParamTypes.push_back(NewParm->getType());
5136       if (PVars)
5137         PVars->push_back(NewParm);
5138       continue;
5139     }
5140 
5141     // Deal with the possibility that we don't have a parameter
5142     // declaration for this parameter.
5143     QualType OldType = ParamTypes[i];
5144     bool IsPackExpansion = false;
5145     Optional<unsigned> NumExpansions;
5146     QualType NewType;
5147     if (const PackExpansionType *Expansion
5148                                        = dyn_cast<PackExpansionType>(OldType)) {
5149       // We have a function parameter pack that may need to be expanded.
5150       QualType Pattern = Expansion->getPattern();
5151       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5152       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5153 
5154       // Determine whether we should expand the parameter packs.
5155       bool ShouldExpand = false;
5156       bool RetainExpansion = false;
5157       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5158                                                Unexpanded,
5159                                                ShouldExpand,
5160                                                RetainExpansion,
5161                                                NumExpansions)) {
5162         return true;
5163       }
5164 
5165       if (ShouldExpand) {
5166         // Expand the function parameter pack into multiple, separate
5167         // parameters.
5168         for (unsigned I = 0; I != *NumExpansions; ++I) {
5169           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5170           QualType NewType = getDerived().TransformType(Pattern);
5171           if (NewType.isNull())
5172             return true;
5173 
5174           if (NewType->containsUnexpandedParameterPack()) {
5175             NewType =
5176                 getSema().getASTContext().getPackExpansionType(NewType, None);
5177 
5178             if (NewType.isNull())
5179               return true;
5180           }
5181 
5182           if (ParamInfos)
5183             PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5184           OutParamTypes.push_back(NewType);
5185           if (PVars)
5186             PVars->push_back(nullptr);
5187         }
5188 
5189         // We're done with the pack expansion.
5190         continue;
5191       }
5192 
5193       // If we're supposed to retain a pack expansion, do so by temporarily
5194       // forgetting the partially-substituted parameter pack.
5195       if (RetainExpansion) {
5196         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5197         QualType NewType = getDerived().TransformType(Pattern);
5198         if (NewType.isNull())
5199           return true;
5200 
5201         if (ParamInfos)
5202           PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5203         OutParamTypes.push_back(NewType);
5204         if (PVars)
5205           PVars->push_back(nullptr);
5206       }
5207 
5208       // We'll substitute the parameter now without expanding the pack
5209       // expansion.
5210       OldType = Expansion->getPattern();
5211       IsPackExpansion = true;
5212       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5213       NewType = getDerived().TransformType(OldType);
5214     } else {
5215       NewType = getDerived().TransformType(OldType);
5216     }
5217 
5218     if (NewType.isNull())
5219       return true;
5220 
5221     if (IsPackExpansion)
5222       NewType = getSema().Context.getPackExpansionType(NewType,
5223                                                        NumExpansions);
5224 
5225     if (ParamInfos)
5226       PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5227     OutParamTypes.push_back(NewType);
5228     if (PVars)
5229       PVars->push_back(nullptr);
5230   }
5231 
5232 #ifndef NDEBUG
5233   if (PVars) {
5234     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
5235       if (ParmVarDecl *parm = (*PVars)[i])
5236         assert(parm->getFunctionScopeIndex() == i);
5237   }
5238 #endif
5239 
5240   return false;
5241 }
5242 
5243 template<typename Derived>
5244 QualType
TransformFunctionProtoType(TypeLocBuilder & TLB,FunctionProtoTypeLoc TL)5245 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
5246                                                    FunctionProtoTypeLoc TL) {
5247   SmallVector<QualType, 4> ExceptionStorage;
5248   TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
5249   return getDerived().TransformFunctionProtoType(
5250       TLB, TL, nullptr, Qualifiers(),
5251       [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
5252         return This->TransformExceptionSpec(TL.getBeginLoc(), ESI,
5253                                             ExceptionStorage, Changed);
5254       });
5255 }
5256 
5257 template<typename Derived> template<typename Fn>
TransformFunctionProtoType(TypeLocBuilder & TLB,FunctionProtoTypeLoc TL,CXXRecordDecl * ThisContext,Qualifiers ThisTypeQuals,Fn TransformExceptionSpec)5258 QualType TreeTransform<Derived>::TransformFunctionProtoType(
5259     TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
5260     Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
5261 
5262   // Transform the parameters and return type.
5263   //
5264   // We are required to instantiate the params and return type in source order.
5265   // When the function has a trailing return type, we instantiate the
5266   // parameters before the return type,  since the return type can then refer
5267   // to the parameters themselves (via decltype, sizeof, etc.).
5268   //
5269   SmallVector<QualType, 4> ParamTypes;
5270   SmallVector<ParmVarDecl*, 4> ParamDecls;
5271   Sema::ExtParameterInfoBuilder ExtParamInfos;
5272   const FunctionProtoType *T = TL.getTypePtr();
5273 
5274   QualType ResultType;
5275 
5276   if (T->hasTrailingReturn()) {
5277     if (getDerived().TransformFunctionTypeParams(
5278             TL.getBeginLoc(), TL.getParams(),
5279             TL.getTypePtr()->param_type_begin(),
5280             T->getExtParameterInfosOrNull(),
5281             ParamTypes, &ParamDecls, ExtParamInfos))
5282       return QualType();
5283 
5284     {
5285       // C++11 [expr.prim.general]p3:
5286       //   If a declaration declares a member function or member function
5287       //   template of a class X, the expression this is a prvalue of type
5288       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
5289       //   and the end of the function-definition, member-declarator, or
5290       //   declarator.
5291       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
5292 
5293       ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5294       if (ResultType.isNull())
5295         return QualType();
5296     }
5297   }
5298   else {
5299     ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5300     if (ResultType.isNull())
5301       return QualType();
5302 
5303     // Return type can not be qualified with an address space.
5304     if (ResultType.getAddressSpace() != LangAS::Default) {
5305       SemaRef.Diag(TL.getReturnLoc().getBeginLoc(),
5306                    diag::err_attribute_address_function_type);
5307       return QualType();
5308     }
5309 
5310     if (getDerived().TransformFunctionTypeParams(
5311             TL.getBeginLoc(), TL.getParams(),
5312             TL.getTypePtr()->param_type_begin(),
5313             T->getExtParameterInfosOrNull(),
5314             ParamTypes, &ParamDecls, ExtParamInfos))
5315       return QualType();
5316   }
5317 
5318   FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
5319 
5320   bool EPIChanged = false;
5321   if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
5322     return QualType();
5323 
5324   // Handle extended parameter information.
5325   if (auto NewExtParamInfos =
5326         ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
5327     if (!EPI.ExtParameterInfos ||
5328         llvm::makeArrayRef(EPI.ExtParameterInfos, TL.getNumParams())
5329           != llvm::makeArrayRef(NewExtParamInfos, ParamTypes.size())) {
5330       EPIChanged = true;
5331     }
5332     EPI.ExtParameterInfos = NewExtParamInfos;
5333   } else if (EPI.ExtParameterInfos) {
5334     EPIChanged = true;
5335     EPI.ExtParameterInfos = nullptr;
5336   }
5337 
5338   QualType Result = TL.getType();
5339   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
5340       T->getParamTypes() != llvm::makeArrayRef(ParamTypes) || EPIChanged) {
5341     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
5342     if (Result.isNull())
5343       return QualType();
5344   }
5345 
5346   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
5347   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5348   NewTL.setLParenLoc(TL.getLParenLoc());
5349   NewTL.setRParenLoc(TL.getRParenLoc());
5350   NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
5351   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5352   for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
5353     NewTL.setParam(i, ParamDecls[i]);
5354 
5355   return Result;
5356 }
5357 
5358 template<typename Derived>
TransformExceptionSpec(SourceLocation Loc,FunctionProtoType::ExceptionSpecInfo & ESI,SmallVectorImpl<QualType> & Exceptions,bool & Changed)5359 bool TreeTransform<Derived>::TransformExceptionSpec(
5360     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
5361     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
5362   assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated);
5363 
5364   // Instantiate a dynamic noexcept expression, if any.
5365   if (isComputedNoexcept(ESI.Type)) {
5366     EnterExpressionEvaluationContext Unevaluated(
5367         getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
5368     ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
5369     if (NoexceptExpr.isInvalid())
5370       return true;
5371 
5372     ExceptionSpecificationType EST = ESI.Type;
5373     NoexceptExpr =
5374         getSema().ActOnNoexceptSpec(Loc, NoexceptExpr.get(), EST);
5375     if (NoexceptExpr.isInvalid())
5376       return true;
5377 
5378     if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
5379       Changed = true;
5380     ESI.NoexceptExpr = NoexceptExpr.get();
5381     ESI.Type = EST;
5382   }
5383 
5384   if (ESI.Type != EST_Dynamic)
5385     return false;
5386 
5387   // Instantiate a dynamic exception specification's type.
5388   for (QualType T : ESI.Exceptions) {
5389     if (const PackExpansionType *PackExpansion =
5390             T->getAs<PackExpansionType>()) {
5391       Changed = true;
5392 
5393       // We have a pack expansion. Instantiate it.
5394       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5395       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
5396                                               Unexpanded);
5397       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
5398 
5399       // Determine whether the set of unexpanded parameter packs can and
5400       // should
5401       // be expanded.
5402       bool Expand = false;
5403       bool RetainExpansion = false;
5404       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
5405       // FIXME: Track the location of the ellipsis (and track source location
5406       // information for the types in the exception specification in general).
5407       if (getDerived().TryExpandParameterPacks(
5408               Loc, SourceRange(), Unexpanded, Expand,
5409               RetainExpansion, NumExpansions))
5410         return true;
5411 
5412       if (!Expand) {
5413         // We can't expand this pack expansion into separate arguments yet;
5414         // just substitute into the pattern and create a new pack expansion
5415         // type.
5416         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5417         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5418         if (U.isNull())
5419           return true;
5420 
5421         U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
5422         Exceptions.push_back(U);
5423         continue;
5424       }
5425 
5426       // Substitute into the pack expansion pattern for each slice of the
5427       // pack.
5428       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
5429         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
5430 
5431         QualType U = getDerived().TransformType(PackExpansion->getPattern());
5432         if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5433           return true;
5434 
5435         Exceptions.push_back(U);
5436       }
5437     } else {
5438       QualType U = getDerived().TransformType(T);
5439       if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
5440         return true;
5441       if (T != U)
5442         Changed = true;
5443 
5444       Exceptions.push_back(U);
5445     }
5446   }
5447 
5448   ESI.Exceptions = Exceptions;
5449   if (ESI.Exceptions.empty())
5450     ESI.Type = EST_DynamicNone;
5451   return false;
5452 }
5453 
5454 template<typename Derived>
TransformFunctionNoProtoType(TypeLocBuilder & TLB,FunctionNoProtoTypeLoc TL)5455 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
5456                                                  TypeLocBuilder &TLB,
5457                                                  FunctionNoProtoTypeLoc TL) {
5458   const FunctionNoProtoType *T = TL.getTypePtr();
5459   QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
5460   if (ResultType.isNull())
5461     return QualType();
5462 
5463   QualType Result = TL.getType();
5464   if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
5465     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
5466 
5467   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
5468   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
5469   NewTL.setLParenLoc(TL.getLParenLoc());
5470   NewTL.setRParenLoc(TL.getRParenLoc());
5471   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
5472 
5473   return Result;
5474 }
5475 
5476 template<typename Derived> QualType
TransformUnresolvedUsingType(TypeLocBuilder & TLB,UnresolvedUsingTypeLoc TL)5477 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
5478                                                  UnresolvedUsingTypeLoc TL) {
5479   const UnresolvedUsingType *T = TL.getTypePtr();
5480   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
5481   if (!D)
5482     return QualType();
5483 
5484   QualType Result = TL.getType();
5485   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
5486     Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
5487     if (Result.isNull())
5488       return QualType();
5489   }
5490 
5491   // We might get an arbitrary type spec type back.  We should at
5492   // least always get a type spec type, though.
5493   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
5494   NewTL.setNameLoc(TL.getNameLoc());
5495 
5496   return Result;
5497 }
5498 
5499 template<typename Derived>
TransformTypedefType(TypeLocBuilder & TLB,TypedefTypeLoc TL)5500 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
5501                                                       TypedefTypeLoc TL) {
5502   const TypedefType *T = TL.getTypePtr();
5503   TypedefNameDecl *Typedef
5504     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5505                                                                T->getDecl()));
5506   if (!Typedef)
5507     return QualType();
5508 
5509   QualType Result = TL.getType();
5510   if (getDerived().AlwaysRebuild() ||
5511       Typedef != T->getDecl()) {
5512     Result = getDerived().RebuildTypedefType(Typedef);
5513     if (Result.isNull())
5514       return QualType();
5515   }
5516 
5517   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
5518   NewTL.setNameLoc(TL.getNameLoc());
5519 
5520   return Result;
5521 }
5522 
5523 template<typename Derived>
TransformTypeOfExprType(TypeLocBuilder & TLB,TypeOfExprTypeLoc TL)5524 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
5525                                                       TypeOfExprTypeLoc TL) {
5526   // typeof expressions are not potentially evaluated contexts
5527   EnterExpressionEvaluationContext Unevaluated(
5528       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
5529       Sema::ReuseLambdaContextDecl);
5530 
5531   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
5532   if (E.isInvalid())
5533     return QualType();
5534 
5535   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
5536   if (E.isInvalid())
5537     return QualType();
5538 
5539   QualType Result = TL.getType();
5540   if (getDerived().AlwaysRebuild() ||
5541       E.get() != TL.getUnderlyingExpr()) {
5542     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
5543     if (Result.isNull())
5544       return QualType();
5545   }
5546   else E.get();
5547 
5548   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
5549   NewTL.setTypeofLoc(TL.getTypeofLoc());
5550   NewTL.setLParenLoc(TL.getLParenLoc());
5551   NewTL.setRParenLoc(TL.getRParenLoc());
5552 
5553   return Result;
5554 }
5555 
5556 template<typename Derived>
TransformTypeOfType(TypeLocBuilder & TLB,TypeOfTypeLoc TL)5557 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
5558                                                      TypeOfTypeLoc TL) {
5559   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
5560   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
5561   if (!New_Under_TI)
5562     return QualType();
5563 
5564   QualType Result = TL.getType();
5565   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
5566     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
5567     if (Result.isNull())
5568       return QualType();
5569   }
5570 
5571   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
5572   NewTL.setTypeofLoc(TL.getTypeofLoc());
5573   NewTL.setLParenLoc(TL.getLParenLoc());
5574   NewTL.setRParenLoc(TL.getRParenLoc());
5575   NewTL.setUnderlyingTInfo(New_Under_TI);
5576 
5577   return Result;
5578 }
5579 
5580 template<typename Derived>
TransformDecltypeType(TypeLocBuilder & TLB,DecltypeTypeLoc TL)5581 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
5582                                                        DecltypeTypeLoc TL) {
5583   const DecltypeType *T = TL.getTypePtr();
5584 
5585   // decltype expressions are not potentially evaluated contexts
5586   EnterExpressionEvaluationContext Unevaluated(
5587       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
5588       Sema::ExpressionEvaluationContextRecord::EK_Decltype);
5589 
5590   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
5591   if (E.isInvalid())
5592     return QualType();
5593 
5594   E = getSema().ActOnDecltypeExpression(E.get());
5595   if (E.isInvalid())
5596     return QualType();
5597 
5598   QualType Result = TL.getType();
5599   if (getDerived().AlwaysRebuild() ||
5600       E.get() != T->getUnderlyingExpr()) {
5601     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
5602     if (Result.isNull())
5603       return QualType();
5604   }
5605   else E.get();
5606 
5607   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
5608   NewTL.setNameLoc(TL.getNameLoc());
5609 
5610   return Result;
5611 }
5612 
5613 template<typename Derived>
TransformUnaryTransformType(TypeLocBuilder & TLB,UnaryTransformTypeLoc TL)5614 QualType TreeTransform<Derived>::TransformUnaryTransformType(
5615                                                             TypeLocBuilder &TLB,
5616                                                      UnaryTransformTypeLoc TL) {
5617   QualType Result = TL.getType();
5618   if (Result->isDependentType()) {
5619     const UnaryTransformType *T = TL.getTypePtr();
5620     QualType NewBase =
5621       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
5622     Result = getDerived().RebuildUnaryTransformType(NewBase,
5623                                                     T->getUTTKind(),
5624                                                     TL.getKWLoc());
5625     if (Result.isNull())
5626       return QualType();
5627   }
5628 
5629   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
5630   NewTL.setKWLoc(TL.getKWLoc());
5631   NewTL.setParensRange(TL.getParensRange());
5632   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
5633   return Result;
5634 }
5635 
5636 template<typename Derived>
TransformAutoType(TypeLocBuilder & TLB,AutoTypeLoc TL)5637 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
5638                                                    AutoTypeLoc TL) {
5639   const AutoType *T = TL.getTypePtr();
5640   QualType OldDeduced = T->getDeducedType();
5641   QualType NewDeduced;
5642   if (!OldDeduced.isNull()) {
5643     NewDeduced = getDerived().TransformType(OldDeduced);
5644     if (NewDeduced.isNull())
5645       return QualType();
5646   }
5647 
5648   QualType Result = TL.getType();
5649   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
5650       T->isDependentType()) {
5651     Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword());
5652     if (Result.isNull())
5653       return QualType();
5654   }
5655 
5656   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
5657   NewTL.setNameLoc(TL.getNameLoc());
5658 
5659   return Result;
5660 }
5661 
5662 template<typename Derived>
TransformDeducedTemplateSpecializationType(TypeLocBuilder & TLB,DeducedTemplateSpecializationTypeLoc TL)5663 QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
5664     TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5665   const DeducedTemplateSpecializationType *T = TL.getTypePtr();
5666 
5667   CXXScopeSpec SS;
5668   TemplateName TemplateName = getDerived().TransformTemplateName(
5669       SS, T->getTemplateName(), TL.getTemplateNameLoc());
5670   if (TemplateName.isNull())
5671     return QualType();
5672 
5673   QualType OldDeduced = T->getDeducedType();
5674   QualType NewDeduced;
5675   if (!OldDeduced.isNull()) {
5676     NewDeduced = getDerived().TransformType(OldDeduced);
5677     if (NewDeduced.isNull())
5678       return QualType();
5679   }
5680 
5681   QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
5682       TemplateName, NewDeduced);
5683   if (Result.isNull())
5684     return QualType();
5685 
5686   DeducedTemplateSpecializationTypeLoc NewTL =
5687       TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5688   NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5689 
5690   return Result;
5691 }
5692 
5693 template<typename Derived>
TransformRecordType(TypeLocBuilder & TLB,RecordTypeLoc TL)5694 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
5695                                                      RecordTypeLoc TL) {
5696   const RecordType *T = TL.getTypePtr();
5697   RecordDecl *Record
5698     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5699                                                           T->getDecl()));
5700   if (!Record)
5701     return QualType();
5702 
5703   QualType Result = TL.getType();
5704   if (getDerived().AlwaysRebuild() ||
5705       Record != T->getDecl()) {
5706     Result = getDerived().RebuildRecordType(Record);
5707     if (Result.isNull())
5708       return QualType();
5709   }
5710 
5711   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5712   NewTL.setNameLoc(TL.getNameLoc());
5713 
5714   return Result;
5715 }
5716 
5717 template<typename Derived>
TransformEnumType(TypeLocBuilder & TLB,EnumTypeLoc TL)5718 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
5719                                                    EnumTypeLoc TL) {
5720   const EnumType *T = TL.getTypePtr();
5721   EnumDecl *Enum
5722     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
5723                                                         T->getDecl()));
5724   if (!Enum)
5725     return QualType();
5726 
5727   QualType Result = TL.getType();
5728   if (getDerived().AlwaysRebuild() ||
5729       Enum != T->getDecl()) {
5730     Result = getDerived().RebuildEnumType(Enum);
5731     if (Result.isNull())
5732       return QualType();
5733   }
5734 
5735   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
5736   NewTL.setNameLoc(TL.getNameLoc());
5737 
5738   return Result;
5739 }
5740 
5741 template<typename Derived>
TransformInjectedClassNameType(TypeLocBuilder & TLB,InjectedClassNameTypeLoc TL)5742 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
5743                                          TypeLocBuilder &TLB,
5744                                          InjectedClassNameTypeLoc TL) {
5745   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
5746                                        TL.getTypePtr()->getDecl());
5747   if (!D) return QualType();
5748 
5749   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
5750   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
5751   return T;
5752 }
5753 
5754 template<typename Derived>
TransformTemplateTypeParmType(TypeLocBuilder & TLB,TemplateTypeParmTypeLoc TL)5755 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
5756                                                 TypeLocBuilder &TLB,
5757                                                 TemplateTypeParmTypeLoc TL) {
5758   return TransformTypeSpecType(TLB, TL);
5759 }
5760 
5761 template<typename Derived>
TransformSubstTemplateTypeParmType(TypeLocBuilder & TLB,SubstTemplateTypeParmTypeLoc TL)5762 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
5763                                          TypeLocBuilder &TLB,
5764                                          SubstTemplateTypeParmTypeLoc TL) {
5765   const SubstTemplateTypeParmType *T = TL.getTypePtr();
5766 
5767   // Substitute into the replacement type, which itself might involve something
5768   // that needs to be transformed. This only tends to occur with default
5769   // template arguments of template template parameters.
5770   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
5771   QualType Replacement = getDerived().TransformType(T->getReplacementType());
5772   if (Replacement.isNull())
5773     return QualType();
5774 
5775   // Always canonicalize the replacement type.
5776   Replacement = SemaRef.Context.getCanonicalType(Replacement);
5777   QualType Result
5778     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
5779                                                    Replacement);
5780 
5781   // Propagate type-source information.
5782   SubstTemplateTypeParmTypeLoc NewTL
5783     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
5784   NewTL.setNameLoc(TL.getNameLoc());
5785   return Result;
5786 
5787 }
5788 
5789 template<typename Derived>
TransformSubstTemplateTypeParmPackType(TypeLocBuilder & TLB,SubstTemplateTypeParmPackTypeLoc TL)5790 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
5791                                           TypeLocBuilder &TLB,
5792                                           SubstTemplateTypeParmPackTypeLoc TL) {
5793   return TransformTypeSpecType(TLB, TL);
5794 }
5795 
5796 template<typename Derived>
TransformTemplateSpecializationType(TypeLocBuilder & TLB,TemplateSpecializationTypeLoc TL)5797 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5798                                                         TypeLocBuilder &TLB,
5799                                            TemplateSpecializationTypeLoc TL) {
5800   const TemplateSpecializationType *T = TL.getTypePtr();
5801 
5802   // The nested-name-specifier never matters in a TemplateSpecializationType,
5803   // because we can't have a dependent nested-name-specifier anyway.
5804   CXXScopeSpec SS;
5805   TemplateName Template
5806     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
5807                                          TL.getTemplateNameLoc());
5808   if (Template.isNull())
5809     return QualType();
5810 
5811   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
5812 }
5813 
5814 template<typename Derived>
TransformAtomicType(TypeLocBuilder & TLB,AtomicTypeLoc TL)5815 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
5816                                                      AtomicTypeLoc TL) {
5817   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5818   if (ValueType.isNull())
5819     return QualType();
5820 
5821   QualType Result = TL.getType();
5822   if (getDerived().AlwaysRebuild() ||
5823       ValueType != TL.getValueLoc().getType()) {
5824     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
5825     if (Result.isNull())
5826       return QualType();
5827   }
5828 
5829   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
5830   NewTL.setKWLoc(TL.getKWLoc());
5831   NewTL.setLParenLoc(TL.getLParenLoc());
5832   NewTL.setRParenLoc(TL.getRParenLoc());
5833 
5834   return Result;
5835 }
5836 
5837 template <typename Derived>
TransformPipeType(TypeLocBuilder & TLB,PipeTypeLoc TL)5838 QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
5839                                                    PipeTypeLoc TL) {
5840   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
5841   if (ValueType.isNull())
5842     return QualType();
5843 
5844   QualType Result = TL.getType();
5845   if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
5846     const PipeType *PT = Result->getAs<PipeType>();
5847     bool isReadPipe = PT->isReadOnly();
5848     Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
5849     if (Result.isNull())
5850       return QualType();
5851   }
5852 
5853   PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
5854   NewTL.setKWLoc(TL.getKWLoc());
5855 
5856   return Result;
5857 }
5858 
5859   /// Simple iterator that traverses the template arguments in a
5860   /// container that provides a \c getArgLoc() member function.
5861   ///
5862   /// This iterator is intended to be used with the iterator form of
5863   /// \c TreeTransform<Derived>::TransformTemplateArguments().
5864   template<typename ArgLocContainer>
5865   class TemplateArgumentLocContainerIterator {
5866     ArgLocContainer *Container;
5867     unsigned Index;
5868 
5869   public:
5870     typedef TemplateArgumentLoc value_type;
5871     typedef TemplateArgumentLoc reference;
5872     typedef int difference_type;
5873     typedef std::input_iterator_tag iterator_category;
5874 
5875     class pointer {
5876       TemplateArgumentLoc Arg;
5877 
5878     public:
pointer(TemplateArgumentLoc Arg)5879       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
5880 
5881       const TemplateArgumentLoc *operator->() const {
5882         return &Arg;
5883       }
5884     };
5885 
5886 
TemplateArgumentLocContainerIterator()5887     TemplateArgumentLocContainerIterator() {}
5888 
TemplateArgumentLocContainerIterator(ArgLocContainer & Container,unsigned Index)5889     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
5890                                  unsigned Index)
5891       : Container(&Container), Index(Index) { }
5892 
5893     TemplateArgumentLocContainerIterator &operator++() {
5894       ++Index;
5895       return *this;
5896     }
5897 
5898     TemplateArgumentLocContainerIterator operator++(int) {
5899       TemplateArgumentLocContainerIterator Old(*this);
5900       ++(*this);
5901       return Old;
5902     }
5903 
5904     TemplateArgumentLoc operator*() const {
5905       return Container->getArgLoc(Index);
5906     }
5907 
5908     pointer operator->() const {
5909       return pointer(Container->getArgLoc(Index));
5910     }
5911 
5912     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
5913                            const TemplateArgumentLocContainerIterator &Y) {
5914       return X.Container == Y.Container && X.Index == Y.Index;
5915     }
5916 
5917     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
5918                            const TemplateArgumentLocContainerIterator &Y) {
5919       return !(X == Y);
5920     }
5921   };
5922 
5923 
5924 template <typename Derived>
TransformTemplateSpecializationType(TypeLocBuilder & TLB,TemplateSpecializationTypeLoc TL,TemplateName Template)5925 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
5926                                                         TypeLocBuilder &TLB,
5927                                            TemplateSpecializationTypeLoc TL,
5928                                                       TemplateName Template) {
5929   TemplateArgumentListInfo NewTemplateArgs;
5930   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5931   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5932   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
5933     ArgIterator;
5934   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5935                                               ArgIterator(TL, TL.getNumArgs()),
5936                                               NewTemplateArgs))
5937     return QualType();
5938 
5939   // FIXME: maybe don't rebuild if all the template arguments are the same.
5940 
5941   QualType Result =
5942     getDerived().RebuildTemplateSpecializationType(Template,
5943                                                    TL.getTemplateNameLoc(),
5944                                                    NewTemplateArgs);
5945 
5946   if (!Result.isNull()) {
5947     // Specializations of template template parameters are represented as
5948     // TemplateSpecializationTypes, and substitution of type alias templates
5949     // within a dependent context can transform them into
5950     // DependentTemplateSpecializationTypes.
5951     if (isa<DependentTemplateSpecializationType>(Result)) {
5952       DependentTemplateSpecializationTypeLoc NewTL
5953         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5954       NewTL.setElaboratedKeywordLoc(SourceLocation());
5955       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
5956       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5957       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5958       NewTL.setLAngleLoc(TL.getLAngleLoc());
5959       NewTL.setRAngleLoc(TL.getRAngleLoc());
5960       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5961         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5962       return Result;
5963     }
5964 
5965     TemplateSpecializationTypeLoc NewTL
5966       = TLB.push<TemplateSpecializationTypeLoc>(Result);
5967     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5968     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5969     NewTL.setLAngleLoc(TL.getLAngleLoc());
5970     NewTL.setRAngleLoc(TL.getRAngleLoc());
5971     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
5972       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
5973   }
5974 
5975   return Result;
5976 }
5977 
5978 template <typename Derived>
TransformDependentTemplateSpecializationType(TypeLocBuilder & TLB,DependentTemplateSpecializationTypeLoc TL,TemplateName Template,CXXScopeSpec & SS)5979 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
5980                                      TypeLocBuilder &TLB,
5981                                      DependentTemplateSpecializationTypeLoc TL,
5982                                      TemplateName Template,
5983                                      CXXScopeSpec &SS) {
5984   TemplateArgumentListInfo NewTemplateArgs;
5985   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5986   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5987   typedef TemplateArgumentLocContainerIterator<
5988             DependentTemplateSpecializationTypeLoc> ArgIterator;
5989   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5990                                               ArgIterator(TL, TL.getNumArgs()),
5991                                               NewTemplateArgs))
5992     return QualType();
5993 
5994   // FIXME: maybe don't rebuild if all the template arguments are the same.
5995 
5996   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
5997     QualType Result
5998       = getSema().Context.getDependentTemplateSpecializationType(
5999                                                 TL.getTypePtr()->getKeyword(),
6000                                                          DTN->getQualifier(),
6001                                                          DTN->getIdentifier(),
6002                                                                NewTemplateArgs);
6003 
6004     DependentTemplateSpecializationTypeLoc NewTL
6005       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6006     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6007     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6008     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6009     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6010     NewTL.setLAngleLoc(TL.getLAngleLoc());
6011     NewTL.setRAngleLoc(TL.getRAngleLoc());
6012     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6013       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6014     return Result;
6015   }
6016 
6017   QualType Result
6018     = getDerived().RebuildTemplateSpecializationType(Template,
6019                                                      TL.getTemplateNameLoc(),
6020                                                      NewTemplateArgs);
6021 
6022   if (!Result.isNull()) {
6023     /// FIXME: Wrap this in an elaborated-type-specifier?
6024     TemplateSpecializationTypeLoc NewTL
6025       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6026     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6027     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6028     NewTL.setLAngleLoc(TL.getLAngleLoc());
6029     NewTL.setRAngleLoc(TL.getRAngleLoc());
6030     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6031       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6032   }
6033 
6034   return Result;
6035 }
6036 
6037 template<typename Derived>
6038 QualType
TransformElaboratedType(TypeLocBuilder & TLB,ElaboratedTypeLoc TL)6039 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6040                                                 ElaboratedTypeLoc TL) {
6041   const ElaboratedType *T = TL.getTypePtr();
6042 
6043   NestedNameSpecifierLoc QualifierLoc;
6044   // NOTE: the qualifier in an ElaboratedType is optional.
6045   if (TL.getQualifierLoc()) {
6046     QualifierLoc
6047       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6048     if (!QualifierLoc)
6049       return QualType();
6050   }
6051 
6052   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6053   if (NamedT.isNull())
6054     return QualType();
6055 
6056   // C++0x [dcl.type.elab]p2:
6057   //   If the identifier resolves to a typedef-name or the simple-template-id
6058   //   resolves to an alias template specialization, the
6059   //   elaborated-type-specifier is ill-formed.
6060   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6061     if (const TemplateSpecializationType *TST =
6062           NamedT->getAs<TemplateSpecializationType>()) {
6063       TemplateName Template = TST->getTemplateName();
6064       if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6065               Template.getAsTemplateDecl())) {
6066         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6067                      diag::err_tag_reference_non_tag)
6068             << TAT << Sema::NTK_TypeAliasTemplate
6069             << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6070         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6071       }
6072     }
6073   }
6074 
6075   QualType Result = TL.getType();
6076   if (getDerived().AlwaysRebuild() ||
6077       QualifierLoc != TL.getQualifierLoc() ||
6078       NamedT != T->getNamedType()) {
6079     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6080                                                 T->getKeyword(),
6081                                                 QualifierLoc, NamedT);
6082     if (Result.isNull())
6083       return QualType();
6084   }
6085 
6086   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6087   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6088   NewTL.setQualifierLoc(QualifierLoc);
6089   return Result;
6090 }
6091 
6092 template<typename Derived>
TransformAttributedType(TypeLocBuilder & TLB,AttributedTypeLoc TL)6093 QualType TreeTransform<Derived>::TransformAttributedType(
6094                                                 TypeLocBuilder &TLB,
6095                                                 AttributedTypeLoc TL) {
6096   const AttributedType *oldType = TL.getTypePtr();
6097   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
6098   if (modifiedType.isNull())
6099     return QualType();
6100 
6101   // oldAttr can be null if we started with a QualType rather than a TypeLoc.
6102   const Attr *oldAttr = TL.getAttr();
6103   const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
6104   if (oldAttr && !newAttr)
6105     return QualType();
6106 
6107   QualType result = TL.getType();
6108 
6109   // FIXME: dependent operand expressions?
6110   if (getDerived().AlwaysRebuild() ||
6111       modifiedType != oldType->getModifiedType()) {
6112     // TODO: this is really lame; we should really be rebuilding the
6113     // equivalent type from first principles.
6114     QualType equivalentType
6115       = getDerived().TransformType(oldType->getEquivalentType());
6116     if (equivalentType.isNull())
6117       return QualType();
6118 
6119     // Check whether we can add nullability; it is only represented as
6120     // type sugar, and therefore cannot be diagnosed in any other way.
6121     if (auto nullability = oldType->getImmediateNullability()) {
6122       if (!modifiedType->canHaveNullability()) {
6123         SemaRef.Diag(TL.getAttr()->getLocation(),
6124                      diag::err_nullability_nonpointer)
6125             << DiagNullabilityKind(*nullability, false) << modifiedType;
6126         return QualType();
6127       }
6128     }
6129 
6130     result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
6131                                                modifiedType,
6132                                                equivalentType);
6133   }
6134 
6135   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
6136   newTL.setAttr(newAttr);
6137   return result;
6138 }
6139 
6140 template<typename Derived>
6141 QualType
TransformParenType(TypeLocBuilder & TLB,ParenTypeLoc TL)6142 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
6143                                            ParenTypeLoc TL) {
6144   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
6145   if (Inner.isNull())
6146     return QualType();
6147 
6148   QualType Result = TL.getType();
6149   if (getDerived().AlwaysRebuild() ||
6150       Inner != TL.getInnerLoc().getType()) {
6151     Result = getDerived().RebuildParenType(Inner);
6152     if (Result.isNull())
6153       return QualType();
6154   }
6155 
6156   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
6157   NewTL.setLParenLoc(TL.getLParenLoc());
6158   NewTL.setRParenLoc(TL.getRParenLoc());
6159   return Result;
6160 }
6161 
6162 template<typename Derived>
TransformDependentNameType(TypeLocBuilder & TLB,DependentNameTypeLoc TL)6163 QualType TreeTransform<Derived>::TransformDependentNameType(
6164     TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
6165   return TransformDependentNameType(TLB, TL, false);
6166 }
6167 
6168 template<typename Derived>
TransformDependentNameType(TypeLocBuilder & TLB,DependentNameTypeLoc TL,bool DeducedTSTContext)6169 QualType TreeTransform<Derived>::TransformDependentNameType(
6170     TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
6171   const DependentNameType *T = TL.getTypePtr();
6172 
6173   NestedNameSpecifierLoc QualifierLoc
6174     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6175   if (!QualifierLoc)
6176     return QualType();
6177 
6178   QualType Result
6179     = getDerived().RebuildDependentNameType(T->getKeyword(),
6180                                             TL.getElaboratedKeywordLoc(),
6181                                             QualifierLoc,
6182                                             T->getIdentifier(),
6183                                             TL.getNameLoc(),
6184                                             DeducedTSTContext);
6185   if (Result.isNull())
6186     return QualType();
6187 
6188   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
6189     QualType NamedT = ElabT->getNamedType();
6190     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
6191 
6192     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6193     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6194     NewTL.setQualifierLoc(QualifierLoc);
6195   } else {
6196     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
6197     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6198     NewTL.setQualifierLoc(QualifierLoc);
6199     NewTL.setNameLoc(TL.getNameLoc());
6200   }
6201   return Result;
6202 }
6203 
6204 template<typename Derived>
6205 QualType TreeTransform<Derived>::
TransformDependentTemplateSpecializationType(TypeLocBuilder & TLB,DependentTemplateSpecializationTypeLoc TL)6206           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6207                                  DependentTemplateSpecializationTypeLoc TL) {
6208   NestedNameSpecifierLoc QualifierLoc;
6209   if (TL.getQualifierLoc()) {
6210     QualifierLoc
6211       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6212     if (!QualifierLoc)
6213       return QualType();
6214   }
6215 
6216   return getDerived()
6217            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
6218 }
6219 
6220 template<typename Derived>
6221 QualType TreeTransform<Derived>::
TransformDependentTemplateSpecializationType(TypeLocBuilder & TLB,DependentTemplateSpecializationTypeLoc TL,NestedNameSpecifierLoc QualifierLoc)6222 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
6223                                    DependentTemplateSpecializationTypeLoc TL,
6224                                        NestedNameSpecifierLoc QualifierLoc) {
6225   const DependentTemplateSpecializationType *T = TL.getTypePtr();
6226 
6227   TemplateArgumentListInfo NewTemplateArgs;
6228   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6229   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6230 
6231   typedef TemplateArgumentLocContainerIterator<
6232   DependentTemplateSpecializationTypeLoc> ArgIterator;
6233   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6234                                               ArgIterator(TL, TL.getNumArgs()),
6235                                               NewTemplateArgs))
6236     return QualType();
6237 
6238   QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
6239       T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
6240       T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
6241       /*AllowInjectedClassName*/ false);
6242   if (Result.isNull())
6243     return QualType();
6244 
6245   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
6246     QualType NamedT = ElabT->getNamedType();
6247 
6248     // Copy information relevant to the template specialization.
6249     TemplateSpecializationTypeLoc NamedTL
6250       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
6251     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6252     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6253     NamedTL.setLAngleLoc(TL.getLAngleLoc());
6254     NamedTL.setRAngleLoc(TL.getRAngleLoc());
6255     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6256       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6257 
6258     // Copy information relevant to the elaborated type.
6259     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6260     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6261     NewTL.setQualifierLoc(QualifierLoc);
6262   } else if (isa<DependentTemplateSpecializationType>(Result)) {
6263     DependentTemplateSpecializationTypeLoc SpecTL
6264       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6265     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6266     SpecTL.setQualifierLoc(QualifierLoc);
6267     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6268     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6269     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6270     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6271     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6272       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6273   } else {
6274     TemplateSpecializationTypeLoc SpecTL
6275       = TLB.push<TemplateSpecializationTypeLoc>(Result);
6276     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6277     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6278     SpecTL.setLAngleLoc(TL.getLAngleLoc());
6279     SpecTL.setRAngleLoc(TL.getRAngleLoc());
6280     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
6281       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
6282   }
6283   return Result;
6284 }
6285 
6286 template<typename Derived>
TransformPackExpansionType(TypeLocBuilder & TLB,PackExpansionTypeLoc TL)6287 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
6288                                                       PackExpansionTypeLoc TL) {
6289   QualType Pattern
6290     = getDerived().TransformType(TLB, TL.getPatternLoc());
6291   if (Pattern.isNull())
6292     return QualType();
6293 
6294   QualType Result = TL.getType();
6295   if (getDerived().AlwaysRebuild() ||
6296       Pattern != TL.getPatternLoc().getType()) {
6297     Result = getDerived().RebuildPackExpansionType(Pattern,
6298                                            TL.getPatternLoc().getSourceRange(),
6299                                                    TL.getEllipsisLoc(),
6300                                            TL.getTypePtr()->getNumExpansions());
6301     if (Result.isNull())
6302       return QualType();
6303   }
6304 
6305   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
6306   NewT.setEllipsisLoc(TL.getEllipsisLoc());
6307   return Result;
6308 }
6309 
6310 template<typename Derived>
6311 QualType
TransformObjCInterfaceType(TypeLocBuilder & TLB,ObjCInterfaceTypeLoc TL)6312 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
6313                                                    ObjCInterfaceTypeLoc TL) {
6314   // ObjCInterfaceType is never dependent.
6315   TLB.pushFullCopy(TL);
6316   return TL.getType();
6317 }
6318 
6319 template<typename Derived>
6320 QualType
TransformObjCTypeParamType(TypeLocBuilder & TLB,ObjCTypeParamTypeLoc TL)6321 TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
6322                                                    ObjCTypeParamTypeLoc TL) {
6323   const ObjCTypeParamType *T = TL.getTypePtr();
6324   ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
6325       getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
6326   if (!OTP)
6327     return QualType();
6328 
6329   QualType Result = TL.getType();
6330   if (getDerived().AlwaysRebuild() ||
6331       OTP != T->getDecl()) {
6332     Result = getDerived().RebuildObjCTypeParamType(OTP,
6333                  TL.getProtocolLAngleLoc(),
6334                  llvm::makeArrayRef(TL.getTypePtr()->qual_begin(),
6335                                     TL.getNumProtocols()),
6336                  TL.getProtocolLocs(),
6337                  TL.getProtocolRAngleLoc());
6338     if (Result.isNull())
6339       return QualType();
6340   }
6341 
6342   ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
6343   if (TL.getNumProtocols()) {
6344     NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6345     for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6346       NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
6347     NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6348   }
6349   return Result;
6350 }
6351 
6352 template<typename Derived>
6353 QualType
TransformObjCObjectType(TypeLocBuilder & TLB,ObjCObjectTypeLoc TL)6354 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
6355                                                 ObjCObjectTypeLoc TL) {
6356   // Transform base type.
6357   QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
6358   if (BaseType.isNull())
6359     return QualType();
6360 
6361   bool AnyChanged = BaseType != TL.getBaseLoc().getType();
6362 
6363   // Transform type arguments.
6364   SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
6365   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
6366     TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
6367     TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
6368     QualType TypeArg = TypeArgInfo->getType();
6369     if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
6370       AnyChanged = true;
6371 
6372       // We have a pack expansion. Instantiate it.
6373       const auto *PackExpansion = PackExpansionLoc.getType()
6374                                     ->castAs<PackExpansionType>();
6375       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6376       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6377                                               Unexpanded);
6378       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
6379 
6380       // Determine whether the set of unexpanded parameter packs can
6381       // and should be expanded.
6382       TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
6383       bool Expand = false;
6384       bool RetainExpansion = false;
6385       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6386       if (getDerived().TryExpandParameterPacks(
6387             PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
6388             Unexpanded, Expand, RetainExpansion, NumExpansions))
6389         return QualType();
6390 
6391       if (!Expand) {
6392         // We can't expand this pack expansion into separate arguments yet;
6393         // just substitute into the pattern and create a new pack expansion
6394         // type.
6395         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6396 
6397         TypeLocBuilder TypeArgBuilder;
6398         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6399         QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
6400                                                              PatternLoc);
6401         if (NewPatternType.isNull())
6402           return QualType();
6403 
6404         QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
6405                                       NewPatternType, NumExpansions);
6406         auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
6407         NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
6408         NewTypeArgInfos.push_back(
6409           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
6410         continue;
6411       }
6412 
6413       // Substitute into the pack expansion pattern for each slice of the
6414       // pack.
6415       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6416         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6417 
6418         TypeLocBuilder TypeArgBuilder;
6419         TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
6420 
6421         QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
6422                                                          PatternLoc);
6423         if (NewTypeArg.isNull())
6424           return QualType();
6425 
6426         NewTypeArgInfos.push_back(
6427           TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6428       }
6429 
6430       continue;
6431     }
6432 
6433     TypeLocBuilder TypeArgBuilder;
6434     TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
6435     QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
6436     if (NewTypeArg.isNull())
6437       return QualType();
6438 
6439     // If nothing changed, just keep the old TypeSourceInfo.
6440     if (NewTypeArg == TypeArg) {
6441       NewTypeArgInfos.push_back(TypeArgInfo);
6442       continue;
6443     }
6444 
6445     NewTypeArgInfos.push_back(
6446       TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
6447     AnyChanged = true;
6448   }
6449 
6450   QualType Result = TL.getType();
6451   if (getDerived().AlwaysRebuild() || AnyChanged) {
6452     // Rebuild the type.
6453     Result = getDerived().RebuildObjCObjectType(
6454         BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
6455         TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
6456         llvm::makeArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
6457         TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
6458 
6459     if (Result.isNull())
6460       return QualType();
6461   }
6462 
6463   ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
6464   NewT.setHasBaseTypeAsWritten(true);
6465   NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
6466   for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
6467     NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
6468   NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
6469   NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
6470   for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
6471     NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
6472   NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
6473   return Result;
6474 }
6475 
6476 template<typename Derived>
6477 QualType
TransformObjCObjectPointerType(TypeLocBuilder & TLB,ObjCObjectPointerTypeLoc TL)6478 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
6479                                                ObjCObjectPointerTypeLoc TL) {
6480   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
6481   if (PointeeType.isNull())
6482     return QualType();
6483 
6484   QualType Result = TL.getType();
6485   if (getDerived().AlwaysRebuild() ||
6486       PointeeType != TL.getPointeeLoc().getType()) {
6487     Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
6488                                                        TL.getStarLoc());
6489     if (Result.isNull())
6490       return QualType();
6491   }
6492 
6493   ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
6494   NewT.setStarLoc(TL.getStarLoc());
6495   return Result;
6496 }
6497 
6498 //===----------------------------------------------------------------------===//
6499 // Statement transformation
6500 //===----------------------------------------------------------------------===//
6501 template<typename Derived>
6502 StmtResult
TransformNullStmt(NullStmt * S)6503 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
6504   return S;
6505 }
6506 
6507 template<typename Derived>
6508 StmtResult
TransformCompoundStmt(CompoundStmt * S)6509 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
6510   return getDerived().TransformCompoundStmt(S, false);
6511 }
6512 
6513 template<typename Derived>
6514 StmtResult
TransformCompoundStmt(CompoundStmt * S,bool IsStmtExpr)6515 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
6516                                               bool IsStmtExpr) {
6517   Sema::CompoundScopeRAII CompoundScope(getSema());
6518 
6519   bool SubStmtInvalid = false;
6520   bool SubStmtChanged = false;
6521   SmallVector<Stmt*, 8> Statements;
6522   for (auto *B : S->body()) {
6523     StmtResult Result = getDerived().TransformStmt(B);
6524     if (Result.isInvalid()) {
6525       // Immediately fail if this was a DeclStmt, since it's very
6526       // likely that this will cause problems for future statements.
6527       if (isa<DeclStmt>(B))
6528         return StmtError();
6529 
6530       // Otherwise, just keep processing substatements and fail later.
6531       SubStmtInvalid = true;
6532       continue;
6533     }
6534 
6535     SubStmtChanged = SubStmtChanged || Result.get() != B;
6536     Statements.push_back(Result.getAs<Stmt>());
6537   }
6538 
6539   if (SubStmtInvalid)
6540     return StmtError();
6541 
6542   if (!getDerived().AlwaysRebuild() &&
6543       !SubStmtChanged)
6544     return S;
6545 
6546   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
6547                                           Statements,
6548                                           S->getRBracLoc(),
6549                                           IsStmtExpr);
6550 }
6551 
6552 template<typename Derived>
6553 StmtResult
TransformCaseStmt(CaseStmt * S)6554 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
6555   ExprResult LHS, RHS;
6556   {
6557     EnterExpressionEvaluationContext Unevaluated(
6558         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6559 
6560     // Transform the left-hand case value.
6561     LHS = getDerived().TransformExpr(S->getLHS());
6562     LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
6563     if (LHS.isInvalid())
6564       return StmtError();
6565 
6566     // Transform the right-hand case value (for the GNU case-range extension).
6567     RHS = getDerived().TransformExpr(S->getRHS());
6568     RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
6569     if (RHS.isInvalid())
6570       return StmtError();
6571   }
6572 
6573   // Build the case statement.
6574   // Case statements are always rebuilt so that they will attached to their
6575   // transformed switch statement.
6576   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
6577                                                        LHS.get(),
6578                                                        S->getEllipsisLoc(),
6579                                                        RHS.get(),
6580                                                        S->getColonLoc());
6581   if (Case.isInvalid())
6582     return StmtError();
6583 
6584   // Transform the statement following the case
6585   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6586   if (SubStmt.isInvalid())
6587     return StmtError();
6588 
6589   // Attach the body to the case statement
6590   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
6591 }
6592 
6593 template<typename Derived>
6594 StmtResult
TransformDefaultStmt(DefaultStmt * S)6595 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
6596   // Transform the statement following the default case
6597   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6598   if (SubStmt.isInvalid())
6599     return StmtError();
6600 
6601   // Default statements are always rebuilt
6602   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
6603                                          SubStmt.get());
6604 }
6605 
6606 template<typename Derived>
6607 StmtResult
TransformLabelStmt(LabelStmt * S)6608 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
6609   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6610   if (SubStmt.isInvalid())
6611     return StmtError();
6612 
6613   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
6614                                         S->getDecl());
6615   if (!LD)
6616     return StmtError();
6617 
6618 
6619   // FIXME: Pass the real colon location in.
6620   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
6621                                        cast<LabelDecl>(LD), SourceLocation(),
6622                                        SubStmt.get());
6623 }
6624 
6625 template <typename Derived>
TransformAttr(const Attr * R)6626 const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
6627   if (!R)
6628     return R;
6629 
6630   switch (R->getKind()) {
6631 // Transform attributes with a pragma spelling by calling TransformXXXAttr.
6632 #define ATTR(X)
6633 #define PRAGMA_SPELLING_ATTR(X)                                                \
6634   case attr::X:                                                                \
6635     return getDerived().Transform##X##Attr(cast<X##Attr>(R));
6636 #include "clang/Basic/AttrList.inc"
6637   default:
6638     return R;
6639   }
6640 }
6641 
6642 template <typename Derived>
TransformAttributedStmt(AttributedStmt * S)6643 StmtResult TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
6644   bool AttrsChanged = false;
6645   SmallVector<const Attr *, 1> Attrs;
6646 
6647   // Visit attributes and keep track if any are transformed.
6648   for (const auto *I : S->getAttrs()) {
6649     const Attr *R = getDerived().TransformAttr(I);
6650     AttrsChanged |= (I != R);
6651     Attrs.push_back(R);
6652   }
6653 
6654   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
6655   if (SubStmt.isInvalid())
6656     return StmtError();
6657 
6658   if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
6659     return S;
6660 
6661   return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
6662                                             SubStmt.get());
6663 }
6664 
6665 template<typename Derived>
6666 StmtResult
TransformIfStmt(IfStmt * S)6667 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
6668   // Transform the initialization statement
6669   StmtResult Init = getDerived().TransformStmt(S->getInit());
6670   if (Init.isInvalid())
6671     return StmtError();
6672 
6673   // Transform the condition
6674   Sema::ConditionResult Cond = getDerived().TransformCondition(
6675       S->getIfLoc(), S->getConditionVariable(), S->getCond(),
6676       S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
6677                        : Sema::ConditionKind::Boolean);
6678   if (Cond.isInvalid())
6679     return StmtError();
6680 
6681   // If this is a constexpr if, determine which arm we should instantiate.
6682   llvm::Optional<bool> ConstexprConditionValue;
6683   if (S->isConstexpr())
6684     ConstexprConditionValue = Cond.getKnownValue();
6685 
6686   // Transform the "then" branch.
6687   StmtResult Then;
6688   if (!ConstexprConditionValue || *ConstexprConditionValue) {
6689     Then = getDerived().TransformStmt(S->getThen());
6690     if (Then.isInvalid())
6691       return StmtError();
6692   } else {
6693     Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
6694   }
6695 
6696   // Transform the "else" branch.
6697   StmtResult Else;
6698   if (!ConstexprConditionValue || !*ConstexprConditionValue) {
6699     Else = getDerived().TransformStmt(S->getElse());
6700     if (Else.isInvalid())
6701       return StmtError();
6702   }
6703 
6704   if (!getDerived().AlwaysRebuild() &&
6705       Init.get() == S->getInit() &&
6706       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6707       Then.get() == S->getThen() &&
6708       Else.get() == S->getElse())
6709     return S;
6710 
6711   return getDerived().RebuildIfStmt(S->getIfLoc(), S->isConstexpr(), Cond,
6712                                     Init.get(), Then.get(), S->getElseLoc(),
6713                                     Else.get());
6714 }
6715 
6716 template<typename Derived>
6717 StmtResult
TransformSwitchStmt(SwitchStmt * S)6718 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
6719   // Transform the initialization statement
6720   StmtResult Init = getDerived().TransformStmt(S->getInit());
6721   if (Init.isInvalid())
6722     return StmtError();
6723 
6724   // Transform the condition.
6725   Sema::ConditionResult Cond = getDerived().TransformCondition(
6726       S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
6727       Sema::ConditionKind::Switch);
6728   if (Cond.isInvalid())
6729     return StmtError();
6730 
6731   // Rebuild the switch statement.
6732   StmtResult Switch
6733     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Init.get(), Cond);
6734   if (Switch.isInvalid())
6735     return StmtError();
6736 
6737   // Transform the body of the switch statement.
6738   StmtResult Body = getDerived().TransformStmt(S->getBody());
6739   if (Body.isInvalid())
6740     return StmtError();
6741 
6742   // Complete the switch statement.
6743   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
6744                                             Body.get());
6745 }
6746 
6747 template<typename Derived>
6748 StmtResult
TransformWhileStmt(WhileStmt * S)6749 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
6750   // Transform the condition
6751   Sema::ConditionResult Cond = getDerived().TransformCondition(
6752       S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
6753       Sema::ConditionKind::Boolean);
6754   if (Cond.isInvalid())
6755     return StmtError();
6756 
6757   // Transform the body
6758   StmtResult Body = getDerived().TransformStmt(S->getBody());
6759   if (Body.isInvalid())
6760     return StmtError();
6761 
6762   if (!getDerived().AlwaysRebuild() &&
6763       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6764       Body.get() == S->getBody())
6765     return Owned(S);
6766 
6767   return getDerived().RebuildWhileStmt(S->getWhileLoc(), Cond, Body.get());
6768 }
6769 
6770 template<typename Derived>
6771 StmtResult
TransformDoStmt(DoStmt * S)6772 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
6773   // Transform the body
6774   StmtResult Body = getDerived().TransformStmt(S->getBody());
6775   if (Body.isInvalid())
6776     return StmtError();
6777 
6778   // Transform the condition
6779   ExprResult Cond = getDerived().TransformExpr(S->getCond());
6780   if (Cond.isInvalid())
6781     return StmtError();
6782 
6783   if (!getDerived().AlwaysRebuild() &&
6784       Cond.get() == S->getCond() &&
6785       Body.get() == S->getBody())
6786     return S;
6787 
6788   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
6789                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
6790                                     S->getRParenLoc());
6791 }
6792 
6793 template<typename Derived>
6794 StmtResult
TransformForStmt(ForStmt * S)6795 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
6796   if (getSema().getLangOpts().OpenMP)
6797     getSema().startOpenMPLoop();
6798 
6799   // Transform the initialization statement
6800   StmtResult Init = getDerived().TransformStmt(S->getInit());
6801   if (Init.isInvalid())
6802     return StmtError();
6803 
6804   // In OpenMP loop region loop control variable must be captured and be
6805   // private. Perform analysis of first part (if any).
6806   if (getSema().getLangOpts().OpenMP && Init.isUsable())
6807     getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
6808 
6809   // Transform the condition
6810   Sema::ConditionResult Cond = getDerived().TransformCondition(
6811       S->getForLoc(), S->getConditionVariable(), S->getCond(),
6812       Sema::ConditionKind::Boolean);
6813   if (Cond.isInvalid())
6814     return StmtError();
6815 
6816   // Transform the increment
6817   ExprResult Inc = getDerived().TransformExpr(S->getInc());
6818   if (Inc.isInvalid())
6819     return StmtError();
6820 
6821   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
6822   if (S->getInc() && !FullInc.get())
6823     return StmtError();
6824 
6825   // Transform the body
6826   StmtResult Body = getDerived().TransformStmt(S->getBody());
6827   if (Body.isInvalid())
6828     return StmtError();
6829 
6830   if (!getDerived().AlwaysRebuild() &&
6831       Init.get() == S->getInit() &&
6832       Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
6833       Inc.get() == S->getInc() &&
6834       Body.get() == S->getBody())
6835     return S;
6836 
6837   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
6838                                      Init.get(), Cond, FullInc,
6839                                      S->getRParenLoc(), Body.get());
6840 }
6841 
6842 template<typename Derived>
6843 StmtResult
TransformGotoStmt(GotoStmt * S)6844 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
6845   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
6846                                         S->getLabel());
6847   if (!LD)
6848     return StmtError();
6849 
6850   // Goto statements must always be rebuilt, to resolve the label.
6851   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
6852                                       cast<LabelDecl>(LD));
6853 }
6854 
6855 template<typename Derived>
6856 StmtResult
TransformIndirectGotoStmt(IndirectGotoStmt * S)6857 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
6858   ExprResult Target = getDerived().TransformExpr(S->getTarget());
6859   if (Target.isInvalid())
6860     return StmtError();
6861   Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
6862 
6863   if (!getDerived().AlwaysRebuild() &&
6864       Target.get() == S->getTarget())
6865     return S;
6866 
6867   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
6868                                               Target.get());
6869 }
6870 
6871 template<typename Derived>
6872 StmtResult
TransformContinueStmt(ContinueStmt * S)6873 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
6874   return S;
6875 }
6876 
6877 template<typename Derived>
6878 StmtResult
TransformBreakStmt(BreakStmt * S)6879 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
6880   return S;
6881 }
6882 
6883 template<typename Derived>
6884 StmtResult
TransformReturnStmt(ReturnStmt * S)6885 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
6886   ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
6887                                                         /*NotCopyInit*/false);
6888   if (Result.isInvalid())
6889     return StmtError();
6890 
6891   // FIXME: We always rebuild the return statement because there is no way
6892   // to tell whether the return type of the function has changed.
6893   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
6894 }
6895 
6896 template<typename Derived>
6897 StmtResult
TransformDeclStmt(DeclStmt * S)6898 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
6899   bool DeclChanged = false;
6900   SmallVector<Decl *, 4> Decls;
6901   for (auto *D : S->decls()) {
6902     Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
6903     if (!Transformed)
6904       return StmtError();
6905 
6906     if (Transformed != D)
6907       DeclChanged = true;
6908 
6909     Decls.push_back(Transformed);
6910   }
6911 
6912   if (!getDerived().AlwaysRebuild() && !DeclChanged)
6913     return S;
6914 
6915   return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
6916 }
6917 
6918 template<typename Derived>
6919 StmtResult
TransformGCCAsmStmt(GCCAsmStmt * S)6920 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
6921 
6922   SmallVector<Expr*, 8> Constraints;
6923   SmallVector<Expr*, 8> Exprs;
6924   SmallVector<IdentifierInfo *, 4> Names;
6925 
6926   ExprResult AsmString;
6927   SmallVector<Expr*, 8> Clobbers;
6928 
6929   bool ExprsChanged = false;
6930 
6931   // Go through the outputs.
6932   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
6933     Names.push_back(S->getOutputIdentifier(I));
6934 
6935     // No need to transform the constraint literal.
6936     Constraints.push_back(S->getOutputConstraintLiteral(I));
6937 
6938     // Transform the output expr.
6939     Expr *OutputExpr = S->getOutputExpr(I);
6940     ExprResult Result = getDerived().TransformExpr(OutputExpr);
6941     if (Result.isInvalid())
6942       return StmtError();
6943 
6944     ExprsChanged |= Result.get() != OutputExpr;
6945 
6946     Exprs.push_back(Result.get());
6947   }
6948 
6949   // Go through the inputs.
6950   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
6951     Names.push_back(S->getInputIdentifier(I));
6952 
6953     // No need to transform the constraint literal.
6954     Constraints.push_back(S->getInputConstraintLiteral(I));
6955 
6956     // Transform the input expr.
6957     Expr *InputExpr = S->getInputExpr(I);
6958     ExprResult Result = getDerived().TransformExpr(InputExpr);
6959     if (Result.isInvalid())
6960       return StmtError();
6961 
6962     ExprsChanged |= Result.get() != InputExpr;
6963 
6964     Exprs.push_back(Result.get());
6965   }
6966 
6967   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
6968     return S;
6969 
6970   // Go through the clobbers.
6971   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
6972     Clobbers.push_back(S->getClobberStringLiteral(I));
6973 
6974   // No need to transform the asm string literal.
6975   AsmString = S->getAsmString();
6976   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
6977                                         S->isVolatile(), S->getNumOutputs(),
6978                                         S->getNumInputs(), Names.data(),
6979                                         Constraints, Exprs, AsmString.get(),
6980                                         Clobbers, S->getRParenLoc());
6981 }
6982 
6983 template<typename Derived>
6984 StmtResult
TransformMSAsmStmt(MSAsmStmt * S)6985 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
6986   ArrayRef<Token> AsmToks =
6987     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
6988 
6989   bool HadError = false, HadChange = false;
6990 
6991   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
6992   SmallVector<Expr*, 8> TransformedExprs;
6993   TransformedExprs.reserve(SrcExprs.size());
6994   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
6995     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
6996     if (!Result.isUsable()) {
6997       HadError = true;
6998     } else {
6999       HadChange |= (Result.get() != SrcExprs[i]);
7000       TransformedExprs.push_back(Result.get());
7001     }
7002   }
7003 
7004   if (HadError) return StmtError();
7005   if (!HadChange && !getDerived().AlwaysRebuild())
7006     return Owned(S);
7007 
7008   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7009                                        AsmToks, S->getAsmString(),
7010                                        S->getNumOutputs(), S->getNumInputs(),
7011                                        S->getAllConstraints(), S->getClobbers(),
7012                                        TransformedExprs, S->getEndLoc());
7013 }
7014 
7015 // C++ Coroutines TS
7016 
7017 template<typename Derived>
7018 StmtResult
TransformCoroutineBodyStmt(CoroutineBodyStmt * S)7019 TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
7020   auto *ScopeInfo = SemaRef.getCurFunction();
7021   auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
7022   assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&
7023          ScopeInfo->NeedsCoroutineSuspends &&
7024          ScopeInfo->CoroutineSuspends.first == nullptr &&
7025          ScopeInfo->CoroutineSuspends.second == nullptr &&
7026          "expected clean scope info");
7027 
7028   // Set that we have (possibly-invalid) suspend points before we do anything
7029   // that may fail.
7030   ScopeInfo->setNeedsCoroutineSuspends(false);
7031 
7032   // The new CoroutinePromise object needs to be built and put into the current
7033   // FunctionScopeInfo before any transformations or rebuilding occurs.
7034   if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
7035     return StmtError();
7036   auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
7037   if (!Promise)
7038     return StmtError();
7039   getDerived().transformedLocalDecl(S->getPromiseDecl(), Promise);
7040   ScopeInfo->CoroutinePromise = Promise;
7041 
7042   // Transform the implicit coroutine statements we built during the initial
7043   // parse.
7044   StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
7045   if (InitSuspend.isInvalid())
7046     return StmtError();
7047   StmtResult FinalSuspend =
7048       getDerived().TransformStmt(S->getFinalSuspendStmt());
7049   if (FinalSuspend.isInvalid())
7050     return StmtError();
7051   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
7052   assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()));
7053 
7054   StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
7055   if (BodyRes.isInvalid())
7056     return StmtError();
7057 
7058   CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
7059   if (Builder.isInvalid())
7060     return StmtError();
7061 
7062   Expr *ReturnObject = S->getReturnValueInit();
7063   assert(ReturnObject && "the return object is expected to be valid");
7064   ExprResult Res = getDerived().TransformInitializer(ReturnObject,
7065                                                      /*NoCopyInit*/ false);
7066   if (Res.isInvalid())
7067     return StmtError();
7068   Builder.ReturnValue = Res.get();
7069 
7070   if (S->hasDependentPromiseType()) {
7071     assert(!Promise->getType()->isDependentType() &&
7072            "the promise type must no longer be dependent");
7073     assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&
7074            !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&
7075            "these nodes should not have been built yet");
7076     if (!Builder.buildDependentStatements())
7077       return StmtError();
7078   } else {
7079     if (auto *OnFallthrough = S->getFallthroughHandler()) {
7080       StmtResult Res = getDerived().TransformStmt(OnFallthrough);
7081       if (Res.isInvalid())
7082         return StmtError();
7083       Builder.OnFallthrough = Res.get();
7084     }
7085 
7086     if (auto *OnException = S->getExceptionHandler()) {
7087       StmtResult Res = getDerived().TransformStmt(OnException);
7088       if (Res.isInvalid())
7089         return StmtError();
7090       Builder.OnException = Res.get();
7091     }
7092 
7093     if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
7094       StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
7095       if (Res.isInvalid())
7096         return StmtError();
7097       Builder.ReturnStmtOnAllocFailure = Res.get();
7098     }
7099 
7100     // Transform any additional statements we may have already built
7101     assert(S->getAllocate() && S->getDeallocate() &&
7102            "allocation and deallocation calls must already be built");
7103     ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
7104     if (AllocRes.isInvalid())
7105       return StmtError();
7106     Builder.Allocate = AllocRes.get();
7107 
7108     ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
7109     if (DeallocRes.isInvalid())
7110       return StmtError();
7111     Builder.Deallocate = DeallocRes.get();
7112 
7113     assert(S->getResultDecl() && "ResultDecl must already be built");
7114     StmtResult ResultDecl = getDerived().TransformStmt(S->getResultDecl());
7115     if (ResultDecl.isInvalid())
7116       return StmtError();
7117     Builder.ResultDecl = ResultDecl.get();
7118 
7119     if (auto *ReturnStmt = S->getReturnStmt()) {
7120       StmtResult Res = getDerived().TransformStmt(ReturnStmt);
7121       if (Res.isInvalid())
7122         return StmtError();
7123       Builder.ReturnStmt = Res.get();
7124     }
7125   }
7126 
7127   return getDerived().RebuildCoroutineBodyStmt(Builder);
7128 }
7129 
7130 template<typename Derived>
7131 StmtResult
TransformCoreturnStmt(CoreturnStmt * S)7132 TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
7133   ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
7134                                                         /*NotCopyInit*/false);
7135   if (Result.isInvalid())
7136     return StmtError();
7137 
7138   // Always rebuild; we don't know if this needs to be injected into a new
7139   // context or if the promise type has changed.
7140   return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
7141                                           S->isImplicit());
7142 }
7143 
7144 template<typename Derived>
7145 ExprResult
TransformCoawaitExpr(CoawaitExpr * E)7146 TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
7147   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7148                                                         /*NotCopyInit*/false);
7149   if (Result.isInvalid())
7150     return ExprError();
7151 
7152   // Always rebuild; we don't know if this needs to be injected into a new
7153   // context or if the promise type has changed.
7154   return getDerived().RebuildCoawaitExpr(E->getKeywordLoc(), Result.get(),
7155                                          E->isImplicit());
7156 }
7157 
7158 template <typename Derived>
7159 ExprResult
TransformDependentCoawaitExpr(DependentCoawaitExpr * E)7160 TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
7161   ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
7162                                                         /*NotCopyInit*/ false);
7163   if (OperandResult.isInvalid())
7164     return ExprError();
7165 
7166   ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
7167           E->getOperatorCoawaitLookup());
7168 
7169   if (LookupResult.isInvalid())
7170     return ExprError();
7171 
7172   // Always rebuild; we don't know if this needs to be injected into a new
7173   // context or if the promise type has changed.
7174   return getDerived().RebuildDependentCoawaitExpr(
7175       E->getKeywordLoc(), OperandResult.get(),
7176       cast<UnresolvedLookupExpr>(LookupResult.get()));
7177 }
7178 
7179 template<typename Derived>
7180 ExprResult
TransformCoyieldExpr(CoyieldExpr * E)7181 TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
7182   ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
7183                                                         /*NotCopyInit*/false);
7184   if (Result.isInvalid())
7185     return ExprError();
7186 
7187   // Always rebuild; we don't know if this needs to be injected into a new
7188   // context or if the promise type has changed.
7189   return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
7190 }
7191 
7192 // Objective-C Statements.
7193 
7194 template<typename Derived>
7195 StmtResult
TransformObjCAtTryStmt(ObjCAtTryStmt * S)7196 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
7197   // Transform the body of the @try.
7198   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
7199   if (TryBody.isInvalid())
7200     return StmtError();
7201 
7202   // Transform the @catch statements (if present).
7203   bool AnyCatchChanged = false;
7204   SmallVector<Stmt*, 8> CatchStmts;
7205   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
7206     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
7207     if (Catch.isInvalid())
7208       return StmtError();
7209     if (Catch.get() != S->getCatchStmt(I))
7210       AnyCatchChanged = true;
7211     CatchStmts.push_back(Catch.get());
7212   }
7213 
7214   // Transform the @finally statement (if present).
7215   StmtResult Finally;
7216   if (S->getFinallyStmt()) {
7217     Finally = getDerived().TransformStmt(S->getFinallyStmt());
7218     if (Finally.isInvalid())
7219       return StmtError();
7220   }
7221 
7222   // If nothing changed, just retain this statement.
7223   if (!getDerived().AlwaysRebuild() &&
7224       TryBody.get() == S->getTryBody() &&
7225       !AnyCatchChanged &&
7226       Finally.get() == S->getFinallyStmt())
7227     return S;
7228 
7229   // Build a new statement.
7230   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
7231                                            CatchStmts, Finally.get());
7232 }
7233 
7234 template<typename Derived>
7235 StmtResult
TransformObjCAtCatchStmt(ObjCAtCatchStmt * S)7236 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7237   // Transform the @catch parameter, if there is one.
7238   VarDecl *Var = nullptr;
7239   if (VarDecl *FromVar = S->getCatchParamDecl()) {
7240     TypeSourceInfo *TSInfo = nullptr;
7241     if (FromVar->getTypeSourceInfo()) {
7242       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
7243       if (!TSInfo)
7244         return StmtError();
7245     }
7246 
7247     QualType T;
7248     if (TSInfo)
7249       T = TSInfo->getType();
7250     else {
7251       T = getDerived().TransformType(FromVar->getType());
7252       if (T.isNull())
7253         return StmtError();
7254     }
7255 
7256     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
7257     if (!Var)
7258       return StmtError();
7259   }
7260 
7261   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
7262   if (Body.isInvalid())
7263     return StmtError();
7264 
7265   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
7266                                              S->getRParenLoc(),
7267                                              Var, Body.get());
7268 }
7269 
7270 template<typename Derived>
7271 StmtResult
TransformObjCAtFinallyStmt(ObjCAtFinallyStmt * S)7272 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7273   // Transform the body.
7274   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
7275   if (Body.isInvalid())
7276     return StmtError();
7277 
7278   // If nothing changed, just retain this statement.
7279   if (!getDerived().AlwaysRebuild() &&
7280       Body.get() == S->getFinallyBody())
7281     return S;
7282 
7283   // Build a new statement.
7284   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
7285                                                Body.get());
7286 }
7287 
7288 template<typename Derived>
7289 StmtResult
TransformObjCAtThrowStmt(ObjCAtThrowStmt * S)7290 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7291   ExprResult Operand;
7292   if (S->getThrowExpr()) {
7293     Operand = getDerived().TransformExpr(S->getThrowExpr());
7294     if (Operand.isInvalid())
7295       return StmtError();
7296   }
7297 
7298   if (!getDerived().AlwaysRebuild() &&
7299       Operand.get() == S->getThrowExpr())
7300     return S;
7301 
7302   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
7303 }
7304 
7305 template<typename Derived>
7306 StmtResult
TransformObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt * S)7307 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
7308                                                   ObjCAtSynchronizedStmt *S) {
7309   // Transform the object we are locking.
7310   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
7311   if (Object.isInvalid())
7312     return StmtError();
7313   Object =
7314     getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
7315                                                   Object.get());
7316   if (Object.isInvalid())
7317     return StmtError();
7318 
7319   // Transform the body.
7320   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
7321   if (Body.isInvalid())
7322     return StmtError();
7323 
7324   // If nothing change, just retain the current statement.
7325   if (!getDerived().AlwaysRebuild() &&
7326       Object.get() == S->getSynchExpr() &&
7327       Body.get() == S->getSynchBody())
7328     return S;
7329 
7330   // Build a new statement.
7331   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
7332                                                     Object.get(), Body.get());
7333 }
7334 
7335 template<typename Derived>
7336 StmtResult
TransformObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt * S)7337 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
7338                                               ObjCAutoreleasePoolStmt *S) {
7339   // Transform the body.
7340   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
7341   if (Body.isInvalid())
7342     return StmtError();
7343 
7344   // If nothing changed, just retain this statement.
7345   if (!getDerived().AlwaysRebuild() &&
7346       Body.get() == S->getSubStmt())
7347     return S;
7348 
7349   // Build a new statement.
7350   return getDerived().RebuildObjCAutoreleasePoolStmt(
7351                         S->getAtLoc(), Body.get());
7352 }
7353 
7354 template<typename Derived>
7355 StmtResult
TransformObjCForCollectionStmt(ObjCForCollectionStmt * S)7356 TreeTransform<Derived>::TransformObjCForCollectionStmt(
7357                                                   ObjCForCollectionStmt *S) {
7358   // Transform the element statement.
7359   StmtResult Element = getDerived().TransformStmt(S->getElement());
7360   if (Element.isInvalid())
7361     return StmtError();
7362 
7363   // Transform the collection expression.
7364   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
7365   if (Collection.isInvalid())
7366     return StmtError();
7367 
7368   // Transform the body.
7369   StmtResult Body = getDerived().TransformStmt(S->getBody());
7370   if (Body.isInvalid())
7371     return StmtError();
7372 
7373   // If nothing changed, just retain this statement.
7374   if (!getDerived().AlwaysRebuild() &&
7375       Element.get() == S->getElement() &&
7376       Collection.get() == S->getCollection() &&
7377       Body.get() == S->getBody())
7378     return S;
7379 
7380   // Build a new statement.
7381   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
7382                                                    Element.get(),
7383                                                    Collection.get(),
7384                                                    S->getRParenLoc(),
7385                                                    Body.get());
7386 }
7387 
7388 template <typename Derived>
TransformCXXCatchStmt(CXXCatchStmt * S)7389 StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
7390   // Transform the exception declaration, if any.
7391   VarDecl *Var = nullptr;
7392   if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
7393     TypeSourceInfo *T =
7394         getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
7395     if (!T)
7396       return StmtError();
7397 
7398     Var = getDerived().RebuildExceptionDecl(
7399         ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
7400         ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
7401     if (!Var || Var->isInvalidDecl())
7402       return StmtError();
7403   }
7404 
7405   // Transform the actual exception handler.
7406   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
7407   if (Handler.isInvalid())
7408     return StmtError();
7409 
7410   if (!getDerived().AlwaysRebuild() && !Var &&
7411       Handler.get() == S->getHandlerBlock())
7412     return S;
7413 
7414   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
7415 }
7416 
7417 template <typename Derived>
TransformCXXTryStmt(CXXTryStmt * S)7418 StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
7419   // Transform the try block itself.
7420   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7421   if (TryBlock.isInvalid())
7422     return StmtError();
7423 
7424   // Transform the handlers.
7425   bool HandlerChanged = false;
7426   SmallVector<Stmt *, 8> Handlers;
7427   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
7428     StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
7429     if (Handler.isInvalid())
7430       return StmtError();
7431 
7432     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
7433     Handlers.push_back(Handler.getAs<Stmt>());
7434   }
7435 
7436   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7437       !HandlerChanged)
7438     return S;
7439 
7440   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
7441                                         Handlers);
7442 }
7443 
7444 template<typename Derived>
7445 StmtResult
TransformCXXForRangeStmt(CXXForRangeStmt * S)7446 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
7447   StmtResult Init =
7448       S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
7449   if (Init.isInvalid())
7450     return StmtError();
7451 
7452   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
7453   if (Range.isInvalid())
7454     return StmtError();
7455 
7456   StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
7457   if (Begin.isInvalid())
7458     return StmtError();
7459   StmtResult End = getDerived().TransformStmt(S->getEndStmt());
7460   if (End.isInvalid())
7461     return StmtError();
7462 
7463   ExprResult Cond = getDerived().TransformExpr(S->getCond());
7464   if (Cond.isInvalid())
7465     return StmtError();
7466   if (Cond.get())
7467     Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
7468   if (Cond.isInvalid())
7469     return StmtError();
7470   if (Cond.get())
7471     Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
7472 
7473   ExprResult Inc = getDerived().TransformExpr(S->getInc());
7474   if (Inc.isInvalid())
7475     return StmtError();
7476   if (Inc.get())
7477     Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
7478 
7479   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
7480   if (LoopVar.isInvalid())
7481     return StmtError();
7482 
7483   StmtResult NewStmt = S;
7484   if (getDerived().AlwaysRebuild() ||
7485       Init.get() != S->getInit() ||
7486       Range.get() != S->getRangeStmt() ||
7487       Begin.get() != S->getBeginStmt() ||
7488       End.get() != S->getEndStmt() ||
7489       Cond.get() != S->getCond() ||
7490       Inc.get() != S->getInc() ||
7491       LoopVar.get() != S->getLoopVarStmt()) {
7492     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7493                                                   S->getCoawaitLoc(), Init.get(),
7494                                                   S->getColonLoc(), Range.get(),
7495                                                   Begin.get(), End.get(),
7496                                                   Cond.get(),
7497                                                   Inc.get(), LoopVar.get(),
7498                                                   S->getRParenLoc());
7499     if (NewStmt.isInvalid())
7500       return StmtError();
7501   }
7502 
7503   StmtResult Body = getDerived().TransformStmt(S->getBody());
7504   if (Body.isInvalid())
7505     return StmtError();
7506 
7507   // Body has changed but we didn't rebuild the for-range statement. Rebuild
7508   // it now so we have a new statement to attach the body to.
7509   if (Body.get() != S->getBody() && NewStmt.get() == S) {
7510     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
7511                                                   S->getCoawaitLoc(), Init.get(),
7512                                                   S->getColonLoc(), Range.get(),
7513                                                   Begin.get(), End.get(),
7514                                                   Cond.get(),
7515                                                   Inc.get(), LoopVar.get(),
7516                                                   S->getRParenLoc());
7517     if (NewStmt.isInvalid())
7518       return StmtError();
7519   }
7520 
7521   if (NewStmt.get() == S)
7522     return S;
7523 
7524   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
7525 }
7526 
7527 template<typename Derived>
7528 StmtResult
TransformMSDependentExistsStmt(MSDependentExistsStmt * S)7529 TreeTransform<Derived>::TransformMSDependentExistsStmt(
7530                                                     MSDependentExistsStmt *S) {
7531   // Transform the nested-name-specifier, if any.
7532   NestedNameSpecifierLoc QualifierLoc;
7533   if (S->getQualifierLoc()) {
7534     QualifierLoc
7535       = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
7536     if (!QualifierLoc)
7537       return StmtError();
7538   }
7539 
7540   // Transform the declaration name.
7541   DeclarationNameInfo NameInfo = S->getNameInfo();
7542   if (NameInfo.getName()) {
7543     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
7544     if (!NameInfo.getName())
7545       return StmtError();
7546   }
7547 
7548   // Check whether anything changed.
7549   if (!getDerived().AlwaysRebuild() &&
7550       QualifierLoc == S->getQualifierLoc() &&
7551       NameInfo.getName() == S->getNameInfo().getName())
7552     return S;
7553 
7554   // Determine whether this name exists, if we can.
7555   CXXScopeSpec SS;
7556   SS.Adopt(QualifierLoc);
7557   bool Dependent = false;
7558   switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
7559   case Sema::IER_Exists:
7560     if (S->isIfExists())
7561       break;
7562 
7563     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7564 
7565   case Sema::IER_DoesNotExist:
7566     if (S->isIfNotExists())
7567       break;
7568 
7569     return new (getSema().Context) NullStmt(S->getKeywordLoc());
7570 
7571   case Sema::IER_Dependent:
7572     Dependent = true;
7573     break;
7574 
7575   case Sema::IER_Error:
7576     return StmtError();
7577   }
7578 
7579   // We need to continue with the instantiation, so do so now.
7580   StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
7581   if (SubStmt.isInvalid())
7582     return StmtError();
7583 
7584   // If we have resolved the name, just transform to the substatement.
7585   if (!Dependent)
7586     return SubStmt;
7587 
7588   // The name is still dependent, so build a dependent expression again.
7589   return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
7590                                                    S->isIfExists(),
7591                                                    QualifierLoc,
7592                                                    NameInfo,
7593                                                    SubStmt.get());
7594 }
7595 
7596 template<typename Derived>
7597 ExprResult
TransformMSPropertyRefExpr(MSPropertyRefExpr * E)7598 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
7599   NestedNameSpecifierLoc QualifierLoc;
7600   if (E->getQualifierLoc()) {
7601     QualifierLoc
7602     = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7603     if (!QualifierLoc)
7604       return ExprError();
7605   }
7606 
7607   MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
7608     getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
7609   if (!PD)
7610     return ExprError();
7611 
7612   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
7613   if (Base.isInvalid())
7614     return ExprError();
7615 
7616   return new (SemaRef.getASTContext())
7617       MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
7618                         SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
7619                         QualifierLoc, E->getMemberLoc());
7620 }
7621 
7622 template <typename Derived>
TransformMSPropertySubscriptExpr(MSPropertySubscriptExpr * E)7623 ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
7624     MSPropertySubscriptExpr *E) {
7625   auto BaseRes = getDerived().TransformExpr(E->getBase());
7626   if (BaseRes.isInvalid())
7627     return ExprError();
7628   auto IdxRes = getDerived().TransformExpr(E->getIdx());
7629   if (IdxRes.isInvalid())
7630     return ExprError();
7631 
7632   if (!getDerived().AlwaysRebuild() &&
7633       BaseRes.get() == E->getBase() &&
7634       IdxRes.get() == E->getIdx())
7635     return E;
7636 
7637   return getDerived().RebuildArraySubscriptExpr(
7638       BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
7639 }
7640 
7641 template <typename Derived>
TransformSEHTryStmt(SEHTryStmt * S)7642 StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
7643   StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
7644   if (TryBlock.isInvalid())
7645     return StmtError();
7646 
7647   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
7648   if (Handler.isInvalid())
7649     return StmtError();
7650 
7651   if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
7652       Handler.get() == S->getHandler())
7653     return S;
7654 
7655   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
7656                                         TryBlock.get(), Handler.get());
7657 }
7658 
7659 template <typename Derived>
TransformSEHFinallyStmt(SEHFinallyStmt * S)7660 StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
7661   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7662   if (Block.isInvalid())
7663     return StmtError();
7664 
7665   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
7666 }
7667 
7668 template <typename Derived>
TransformSEHExceptStmt(SEHExceptStmt * S)7669 StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
7670   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
7671   if (FilterExpr.isInvalid())
7672     return StmtError();
7673 
7674   StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
7675   if (Block.isInvalid())
7676     return StmtError();
7677 
7678   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
7679                                            Block.get());
7680 }
7681 
7682 template <typename Derived>
TransformSEHHandler(Stmt * Handler)7683 StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
7684   if (isa<SEHFinallyStmt>(Handler))
7685     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
7686   else
7687     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
7688 }
7689 
7690 template<typename Derived>
7691 StmtResult
TransformSEHLeaveStmt(SEHLeaveStmt * S)7692 TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
7693   return S;
7694 }
7695 
7696 //===----------------------------------------------------------------------===//
7697 // OpenMP directive transformation
7698 //===----------------------------------------------------------------------===//
7699 template <typename Derived>
TransformOMPExecutableDirective(OMPExecutableDirective * D)7700 StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
7701     OMPExecutableDirective *D) {
7702 
7703   // Transform the clauses
7704   llvm::SmallVector<OMPClause *, 16> TClauses;
7705   ArrayRef<OMPClause *> Clauses = D->clauses();
7706   TClauses.reserve(Clauses.size());
7707   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
7708        I != E; ++I) {
7709     if (*I) {
7710       getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
7711       OMPClause *Clause = getDerived().TransformOMPClause(*I);
7712       getDerived().getSema().EndOpenMPClause();
7713       if (Clause)
7714         TClauses.push_back(Clause);
7715     } else {
7716       TClauses.push_back(nullptr);
7717     }
7718   }
7719   StmtResult AssociatedStmt;
7720   if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
7721     getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
7722                                                   /*CurScope=*/nullptr);
7723     StmtResult Body;
7724     {
7725       Sema::CompoundScopeRAII CompoundScope(getSema());
7726       Stmt *CS = D->getInnermostCapturedStmt()->getCapturedStmt();
7727       Body = getDerived().TransformStmt(CS);
7728     }
7729     AssociatedStmt =
7730         getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
7731     if (AssociatedStmt.isInvalid()) {
7732       return StmtError();
7733     }
7734   }
7735   if (TClauses.size() != Clauses.size()) {
7736     return StmtError();
7737   }
7738 
7739   // Transform directive name for 'omp critical' directive.
7740   DeclarationNameInfo DirName;
7741   if (D->getDirectiveKind() == OMPD_critical) {
7742     DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
7743     DirName = getDerived().TransformDeclarationNameInfo(DirName);
7744   }
7745   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
7746   if (D->getDirectiveKind() == OMPD_cancellation_point) {
7747     CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
7748   } else if (D->getDirectiveKind() == OMPD_cancel) {
7749     CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
7750   }
7751 
7752   return getDerived().RebuildOMPExecutableDirective(
7753       D->getDirectiveKind(), DirName, CancelRegion, TClauses,
7754       AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
7755 }
7756 
7757 template <typename Derived>
7758 StmtResult
TransformOMPParallelDirective(OMPParallelDirective * D)7759 TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
7760   DeclarationNameInfo DirName;
7761   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
7762                                              D->getBeginLoc());
7763   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7764   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7765   return Res;
7766 }
7767 
7768 template <typename Derived>
7769 StmtResult
TransformOMPSimdDirective(OMPSimdDirective * D)7770 TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
7771   DeclarationNameInfo DirName;
7772   getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
7773                                              D->getBeginLoc());
7774   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7775   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7776   return Res;
7777 }
7778 
7779 template <typename Derived>
7780 StmtResult
TransformOMPForDirective(OMPForDirective * D)7781 TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
7782   DeclarationNameInfo DirName;
7783   getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
7784                                              D->getBeginLoc());
7785   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7786   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7787   return Res;
7788 }
7789 
7790 template <typename Derived>
7791 StmtResult
TransformOMPForSimdDirective(OMPForSimdDirective * D)7792 TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
7793   DeclarationNameInfo DirName;
7794   getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
7795                                              D->getBeginLoc());
7796   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7797   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7798   return Res;
7799 }
7800 
7801 template <typename Derived>
7802 StmtResult
TransformOMPSectionsDirective(OMPSectionsDirective * D)7803 TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
7804   DeclarationNameInfo DirName;
7805   getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
7806                                              D->getBeginLoc());
7807   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7808   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7809   return Res;
7810 }
7811 
7812 template <typename Derived>
7813 StmtResult
TransformOMPSectionDirective(OMPSectionDirective * D)7814 TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
7815   DeclarationNameInfo DirName;
7816   getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
7817                                              D->getBeginLoc());
7818   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7819   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7820   return Res;
7821 }
7822 
7823 template <typename Derived>
7824 StmtResult
TransformOMPSingleDirective(OMPSingleDirective * D)7825 TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
7826   DeclarationNameInfo DirName;
7827   getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
7828                                              D->getBeginLoc());
7829   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7830   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7831   return Res;
7832 }
7833 
7834 template <typename Derived>
7835 StmtResult
TransformOMPMasterDirective(OMPMasterDirective * D)7836 TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
7837   DeclarationNameInfo DirName;
7838   getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
7839                                              D->getBeginLoc());
7840   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7841   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7842   return Res;
7843 }
7844 
7845 template <typename Derived>
7846 StmtResult
TransformOMPCriticalDirective(OMPCriticalDirective * D)7847 TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
7848   getDerived().getSema().StartOpenMPDSABlock(
7849       OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
7850   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7851   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7852   return Res;
7853 }
7854 
7855 template <typename Derived>
TransformOMPParallelForDirective(OMPParallelForDirective * D)7856 StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
7857     OMPParallelForDirective *D) {
7858   DeclarationNameInfo DirName;
7859   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
7860                                              nullptr, D->getBeginLoc());
7861   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7862   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7863   return Res;
7864 }
7865 
7866 template <typename Derived>
TransformOMPParallelForSimdDirective(OMPParallelForSimdDirective * D)7867 StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
7868     OMPParallelForSimdDirective *D) {
7869   DeclarationNameInfo DirName;
7870   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
7871                                              nullptr, D->getBeginLoc());
7872   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7873   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7874   return Res;
7875 }
7876 
7877 template <typename Derived>
TransformOMPParallelSectionsDirective(OMPParallelSectionsDirective * D)7878 StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
7879     OMPParallelSectionsDirective *D) {
7880   DeclarationNameInfo DirName;
7881   getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
7882                                              nullptr, D->getBeginLoc());
7883   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7884   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7885   return Res;
7886 }
7887 
7888 template <typename Derived>
7889 StmtResult
TransformOMPTaskDirective(OMPTaskDirective * D)7890 TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
7891   DeclarationNameInfo DirName;
7892   getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
7893                                              D->getBeginLoc());
7894   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7895   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7896   return Res;
7897 }
7898 
7899 template <typename Derived>
TransformOMPTaskyieldDirective(OMPTaskyieldDirective * D)7900 StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
7901     OMPTaskyieldDirective *D) {
7902   DeclarationNameInfo DirName;
7903   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
7904                                              D->getBeginLoc());
7905   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7906   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7907   return Res;
7908 }
7909 
7910 template <typename Derived>
7911 StmtResult
TransformOMPBarrierDirective(OMPBarrierDirective * D)7912 TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
7913   DeclarationNameInfo DirName;
7914   getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
7915                                              D->getBeginLoc());
7916   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7917   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7918   return Res;
7919 }
7920 
7921 template <typename Derived>
7922 StmtResult
TransformOMPTaskwaitDirective(OMPTaskwaitDirective * D)7923 TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
7924   DeclarationNameInfo DirName;
7925   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
7926                                              D->getBeginLoc());
7927   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7928   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7929   return Res;
7930 }
7931 
7932 template <typename Derived>
TransformOMPTaskgroupDirective(OMPTaskgroupDirective * D)7933 StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
7934     OMPTaskgroupDirective *D) {
7935   DeclarationNameInfo DirName;
7936   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
7937                                              D->getBeginLoc());
7938   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7939   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7940   return Res;
7941 }
7942 
7943 template <typename Derived>
7944 StmtResult
TransformOMPFlushDirective(OMPFlushDirective * D)7945 TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
7946   DeclarationNameInfo DirName;
7947   getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
7948                                              D->getBeginLoc());
7949   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7950   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7951   return Res;
7952 }
7953 
7954 template <typename Derived>
7955 StmtResult
TransformOMPOrderedDirective(OMPOrderedDirective * D)7956 TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
7957   DeclarationNameInfo DirName;
7958   getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
7959                                              D->getBeginLoc());
7960   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7961   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7962   return Res;
7963 }
7964 
7965 template <typename Derived>
7966 StmtResult
TransformOMPAtomicDirective(OMPAtomicDirective * D)7967 TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
7968   DeclarationNameInfo DirName;
7969   getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
7970                                              D->getBeginLoc());
7971   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7972   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7973   return Res;
7974 }
7975 
7976 template <typename Derived>
7977 StmtResult
TransformOMPTargetDirective(OMPTargetDirective * D)7978 TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
7979   DeclarationNameInfo DirName;
7980   getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
7981                                              D->getBeginLoc());
7982   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7983   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7984   return Res;
7985 }
7986 
7987 template <typename Derived>
TransformOMPTargetDataDirective(OMPTargetDataDirective * D)7988 StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
7989     OMPTargetDataDirective *D) {
7990   DeclarationNameInfo DirName;
7991   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
7992                                              D->getBeginLoc());
7993   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
7994   getDerived().getSema().EndOpenMPDSABlock(Res.get());
7995   return Res;
7996 }
7997 
7998 template <typename Derived>
TransformOMPTargetEnterDataDirective(OMPTargetEnterDataDirective * D)7999 StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
8000     OMPTargetEnterDataDirective *D) {
8001   DeclarationNameInfo DirName;
8002   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
8003                                              nullptr, D->getBeginLoc());
8004   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8005   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8006   return Res;
8007 }
8008 
8009 template <typename Derived>
TransformOMPTargetExitDataDirective(OMPTargetExitDataDirective * D)8010 StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
8011     OMPTargetExitDataDirective *D) {
8012   DeclarationNameInfo DirName;
8013   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
8014                                              nullptr, D->getBeginLoc());
8015   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8016   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8017   return Res;
8018 }
8019 
8020 template <typename Derived>
TransformOMPTargetParallelDirective(OMPTargetParallelDirective * D)8021 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
8022     OMPTargetParallelDirective *D) {
8023   DeclarationNameInfo DirName;
8024   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
8025                                              nullptr, D->getBeginLoc());
8026   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8027   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8028   return Res;
8029 }
8030 
8031 template <typename Derived>
TransformOMPTargetParallelForDirective(OMPTargetParallelForDirective * D)8032 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
8033     OMPTargetParallelForDirective *D) {
8034   DeclarationNameInfo DirName;
8035   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
8036                                              nullptr, D->getBeginLoc());
8037   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8038   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8039   return Res;
8040 }
8041 
8042 template <typename Derived>
TransformOMPTargetUpdateDirective(OMPTargetUpdateDirective * D)8043 StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
8044     OMPTargetUpdateDirective *D) {
8045   DeclarationNameInfo DirName;
8046   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
8047                                              nullptr, D->getBeginLoc());
8048   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8049   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8050   return Res;
8051 }
8052 
8053 template <typename Derived>
8054 StmtResult
TransformOMPTeamsDirective(OMPTeamsDirective * D)8055 TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
8056   DeclarationNameInfo DirName;
8057   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
8058                                              D->getBeginLoc());
8059   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8060   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8061   return Res;
8062 }
8063 
8064 template <typename Derived>
TransformOMPCancellationPointDirective(OMPCancellationPointDirective * D)8065 StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
8066     OMPCancellationPointDirective *D) {
8067   DeclarationNameInfo DirName;
8068   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
8069                                              nullptr, D->getBeginLoc());
8070   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8071   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8072   return Res;
8073 }
8074 
8075 template <typename Derived>
8076 StmtResult
TransformOMPCancelDirective(OMPCancelDirective * D)8077 TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
8078   DeclarationNameInfo DirName;
8079   getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
8080                                              D->getBeginLoc());
8081   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8082   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8083   return Res;
8084 }
8085 
8086 template <typename Derived>
8087 StmtResult
TransformOMPTaskLoopDirective(OMPTaskLoopDirective * D)8088 TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
8089   DeclarationNameInfo DirName;
8090   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
8091                                              D->getBeginLoc());
8092   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8093   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8094   return Res;
8095 }
8096 
8097 template <typename Derived>
TransformOMPTaskLoopSimdDirective(OMPTaskLoopSimdDirective * D)8098 StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
8099     OMPTaskLoopSimdDirective *D) {
8100   DeclarationNameInfo DirName;
8101   getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
8102                                              nullptr, D->getBeginLoc());
8103   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8104   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8105   return Res;
8106 }
8107 
8108 template <typename Derived>
TransformOMPDistributeDirective(OMPDistributeDirective * D)8109 StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
8110     OMPDistributeDirective *D) {
8111   DeclarationNameInfo DirName;
8112   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
8113                                              D->getBeginLoc());
8114   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8115   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8116   return Res;
8117 }
8118 
8119 template <typename Derived>
TransformOMPDistributeParallelForDirective(OMPDistributeParallelForDirective * D)8120 StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
8121     OMPDistributeParallelForDirective *D) {
8122   DeclarationNameInfo DirName;
8123   getDerived().getSema().StartOpenMPDSABlock(
8124       OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8125   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8126   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8127   return Res;
8128 }
8129 
8130 template <typename Derived>
8131 StmtResult
TransformOMPDistributeParallelForSimdDirective(OMPDistributeParallelForSimdDirective * D)8132 TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
8133     OMPDistributeParallelForSimdDirective *D) {
8134   DeclarationNameInfo DirName;
8135   getDerived().getSema().StartOpenMPDSABlock(
8136       OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8137   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8138   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8139   return Res;
8140 }
8141 
8142 template <typename Derived>
TransformOMPDistributeSimdDirective(OMPDistributeSimdDirective * D)8143 StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
8144     OMPDistributeSimdDirective *D) {
8145   DeclarationNameInfo DirName;
8146   getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
8147                                              nullptr, D->getBeginLoc());
8148   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8149   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8150   return Res;
8151 }
8152 
8153 template <typename Derived>
TransformOMPTargetParallelForSimdDirective(OMPTargetParallelForSimdDirective * D)8154 StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
8155     OMPTargetParallelForSimdDirective *D) {
8156   DeclarationNameInfo DirName;
8157   getDerived().getSema().StartOpenMPDSABlock(
8158       OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
8159   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8160   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8161   return Res;
8162 }
8163 
8164 template <typename Derived>
TransformOMPTargetSimdDirective(OMPTargetSimdDirective * D)8165 StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
8166     OMPTargetSimdDirective *D) {
8167   DeclarationNameInfo DirName;
8168   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
8169                                              D->getBeginLoc());
8170   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8171   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8172   return Res;
8173 }
8174 
8175 template <typename Derived>
TransformOMPTeamsDistributeDirective(OMPTeamsDistributeDirective * D)8176 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
8177     OMPTeamsDistributeDirective *D) {
8178   DeclarationNameInfo DirName;
8179   getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
8180                                              nullptr, D->getBeginLoc());
8181   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8182   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8183   return Res;
8184 }
8185 
8186 template <typename Derived>
TransformOMPTeamsDistributeSimdDirective(OMPTeamsDistributeSimdDirective * D)8187 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
8188     OMPTeamsDistributeSimdDirective *D) {
8189   DeclarationNameInfo DirName;
8190   getDerived().getSema().StartOpenMPDSABlock(
8191       OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8192   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8193   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8194   return Res;
8195 }
8196 
8197 template <typename Derived>
TransformOMPTeamsDistributeParallelForSimdDirective(OMPTeamsDistributeParallelForSimdDirective * D)8198 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
8199     OMPTeamsDistributeParallelForSimdDirective *D) {
8200   DeclarationNameInfo DirName;
8201   getDerived().getSema().StartOpenMPDSABlock(
8202       OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
8203       D->getBeginLoc());
8204   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8205   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8206   return Res;
8207 }
8208 
8209 template <typename Derived>
TransformOMPTeamsDistributeParallelForDirective(OMPTeamsDistributeParallelForDirective * D)8210 StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
8211     OMPTeamsDistributeParallelForDirective *D) {
8212   DeclarationNameInfo DirName;
8213   getDerived().getSema().StartOpenMPDSABlock(
8214       OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
8215   StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8216   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8217   return Res;
8218 }
8219 
8220 template <typename Derived>
TransformOMPTargetTeamsDirective(OMPTargetTeamsDirective * D)8221 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
8222     OMPTargetTeamsDirective *D) {
8223   DeclarationNameInfo DirName;
8224   getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
8225                                              nullptr, D->getBeginLoc());
8226   auto Res = getDerived().TransformOMPExecutableDirective(D);
8227   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8228   return Res;
8229 }
8230 
8231 template <typename Derived>
TransformOMPTargetTeamsDistributeDirective(OMPTargetTeamsDistributeDirective * D)8232 StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
8233     OMPTargetTeamsDistributeDirective *D) {
8234   DeclarationNameInfo DirName;
8235   getDerived().getSema().StartOpenMPDSABlock(
8236       OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
8237   auto Res = getDerived().TransformOMPExecutableDirective(D);
8238   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8239   return Res;
8240 }
8241 
8242 template <typename Derived>
8243 StmtResult
TransformOMPTargetTeamsDistributeParallelForDirective(OMPTargetTeamsDistributeParallelForDirective * D)8244 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
8245     OMPTargetTeamsDistributeParallelForDirective *D) {
8246   DeclarationNameInfo DirName;
8247   getDerived().getSema().StartOpenMPDSABlock(
8248       OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
8249       D->getBeginLoc());
8250   auto Res = getDerived().TransformOMPExecutableDirective(D);
8251   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8252   return Res;
8253 }
8254 
8255 template <typename Derived>
8256 StmtResult TreeTransform<Derived>::
TransformOMPTargetTeamsDistributeParallelForSimdDirective(OMPTargetTeamsDistributeParallelForSimdDirective * D)8257     TransformOMPTargetTeamsDistributeParallelForSimdDirective(
8258         OMPTargetTeamsDistributeParallelForSimdDirective *D) {
8259   DeclarationNameInfo DirName;
8260   getDerived().getSema().StartOpenMPDSABlock(
8261       OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
8262       D->getBeginLoc());
8263   auto Res = getDerived().TransformOMPExecutableDirective(D);
8264   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8265   return Res;
8266 }
8267 
8268 template <typename Derived>
8269 StmtResult
TransformOMPTargetTeamsDistributeSimdDirective(OMPTargetTeamsDistributeSimdDirective * D)8270 TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
8271     OMPTargetTeamsDistributeSimdDirective *D) {
8272   DeclarationNameInfo DirName;
8273   getDerived().getSema().StartOpenMPDSABlock(
8274       OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
8275   auto Res = getDerived().TransformOMPExecutableDirective(D);
8276   getDerived().getSema().EndOpenMPDSABlock(Res.get());
8277   return Res;
8278 }
8279 
8280 
8281 //===----------------------------------------------------------------------===//
8282 // OpenMP clause transformation
8283 //===----------------------------------------------------------------------===//
8284 template <typename Derived>
TransformOMPIfClause(OMPIfClause * C)8285 OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
8286   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8287   if (Cond.isInvalid())
8288     return nullptr;
8289   return getDerived().RebuildOMPIfClause(
8290       C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
8291       C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
8292 }
8293 
8294 template <typename Derived>
TransformOMPFinalClause(OMPFinalClause * C)8295 OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
8296   ExprResult Cond = getDerived().TransformExpr(C->getCondition());
8297   if (Cond.isInvalid())
8298     return nullptr;
8299   return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
8300                                             C->getLParenLoc(), C->getEndLoc());
8301 }
8302 
8303 template <typename Derived>
8304 OMPClause *
TransformOMPNumThreadsClause(OMPNumThreadsClause * C)8305 TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
8306   ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
8307   if (NumThreads.isInvalid())
8308     return nullptr;
8309   return getDerived().RebuildOMPNumThreadsClause(
8310       NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8311 }
8312 
8313 template <typename Derived>
8314 OMPClause *
TransformOMPSafelenClause(OMPSafelenClause * C)8315 TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
8316   ExprResult E = getDerived().TransformExpr(C->getSafelen());
8317   if (E.isInvalid())
8318     return nullptr;
8319   return getDerived().RebuildOMPSafelenClause(
8320       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8321 }
8322 
8323 template <typename Derived>
8324 OMPClause *
TransformOMPSimdlenClause(OMPSimdlenClause * C)8325 TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
8326   ExprResult E = getDerived().TransformExpr(C->getSimdlen());
8327   if (E.isInvalid())
8328     return nullptr;
8329   return getDerived().RebuildOMPSimdlenClause(
8330       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8331 }
8332 
8333 template <typename Derived>
8334 OMPClause *
TransformOMPCollapseClause(OMPCollapseClause * C)8335 TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
8336   ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
8337   if (E.isInvalid())
8338     return nullptr;
8339   return getDerived().RebuildOMPCollapseClause(
8340       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8341 }
8342 
8343 template <typename Derived>
8344 OMPClause *
TransformOMPDefaultClause(OMPDefaultClause * C)8345 TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
8346   return getDerived().RebuildOMPDefaultClause(
8347       C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
8348       C->getLParenLoc(), C->getEndLoc());
8349 }
8350 
8351 template <typename Derived>
8352 OMPClause *
TransformOMPProcBindClause(OMPProcBindClause * C)8353 TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
8354   return getDerived().RebuildOMPProcBindClause(
8355       C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
8356       C->getLParenLoc(), C->getEndLoc());
8357 }
8358 
8359 template <typename Derived>
8360 OMPClause *
TransformOMPScheduleClause(OMPScheduleClause * C)8361 TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
8362   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8363   if (E.isInvalid())
8364     return nullptr;
8365   return getDerived().RebuildOMPScheduleClause(
8366       C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
8367       C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
8368       C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
8369       C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
8370 }
8371 
8372 template <typename Derived>
8373 OMPClause *
TransformOMPOrderedClause(OMPOrderedClause * C)8374 TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
8375   ExprResult E;
8376   if (auto *Num = C->getNumForLoops()) {
8377     E = getDerived().TransformExpr(Num);
8378     if (E.isInvalid())
8379       return nullptr;
8380   }
8381   return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
8382                                               C->getLParenLoc(), E.get());
8383 }
8384 
8385 template <typename Derived>
8386 OMPClause *
TransformOMPNowaitClause(OMPNowaitClause * C)8387 TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
8388   // No need to rebuild this clause, no template-dependent parameters.
8389   return C;
8390 }
8391 
8392 template <typename Derived>
8393 OMPClause *
TransformOMPUntiedClause(OMPUntiedClause * C)8394 TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
8395   // No need to rebuild this clause, no template-dependent parameters.
8396   return C;
8397 }
8398 
8399 template <typename Derived>
8400 OMPClause *
TransformOMPMergeableClause(OMPMergeableClause * C)8401 TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
8402   // No need to rebuild this clause, no template-dependent parameters.
8403   return C;
8404 }
8405 
8406 template <typename Derived>
TransformOMPReadClause(OMPReadClause * C)8407 OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
8408   // No need to rebuild this clause, no template-dependent parameters.
8409   return C;
8410 }
8411 
8412 template <typename Derived>
TransformOMPWriteClause(OMPWriteClause * C)8413 OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
8414   // No need to rebuild this clause, no template-dependent parameters.
8415   return C;
8416 }
8417 
8418 template <typename Derived>
8419 OMPClause *
TransformOMPUpdateClause(OMPUpdateClause * C)8420 TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
8421   // No need to rebuild this clause, no template-dependent parameters.
8422   return C;
8423 }
8424 
8425 template <typename Derived>
8426 OMPClause *
TransformOMPCaptureClause(OMPCaptureClause * C)8427 TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
8428   // No need to rebuild this clause, no template-dependent parameters.
8429   return C;
8430 }
8431 
8432 template <typename Derived>
8433 OMPClause *
TransformOMPSeqCstClause(OMPSeqCstClause * C)8434 TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
8435   // No need to rebuild this clause, no template-dependent parameters.
8436   return C;
8437 }
8438 
8439 template <typename Derived>
8440 OMPClause *
TransformOMPThreadsClause(OMPThreadsClause * C)8441 TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
8442   // No need to rebuild this clause, no template-dependent parameters.
8443   return C;
8444 }
8445 
8446 template <typename Derived>
TransformOMPSIMDClause(OMPSIMDClause * C)8447 OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
8448   // No need to rebuild this clause, no template-dependent parameters.
8449   return C;
8450 }
8451 
8452 template <typename Derived>
8453 OMPClause *
TransformOMPNogroupClause(OMPNogroupClause * C)8454 TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
8455   // No need to rebuild this clause, no template-dependent parameters.
8456   return C;
8457 }
8458 
8459 template <typename Derived>
TransformOMPUnifiedAddressClause(OMPUnifiedAddressClause * C)8460 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
8461     OMPUnifiedAddressClause *C) {
8462   llvm_unreachable("unified_address clause cannot appear in dependent context");
8463 }
8464 
8465 template <typename Derived>
TransformOMPUnifiedSharedMemoryClause(OMPUnifiedSharedMemoryClause * C)8466 OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
8467     OMPUnifiedSharedMemoryClause *C) {
8468   llvm_unreachable(
8469       "unified_shared_memory clause cannot appear in dependent context");
8470 }
8471 
8472 template <typename Derived>
TransformOMPReverseOffloadClause(OMPReverseOffloadClause * C)8473 OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
8474     OMPReverseOffloadClause *C) {
8475   llvm_unreachable("reverse_offload clause cannot appear in dependent context");
8476 }
8477 
8478 template <typename Derived>
TransformOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause * C)8479 OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
8480     OMPDynamicAllocatorsClause *C) {
8481   llvm_unreachable(
8482       "dynamic_allocators clause cannot appear in dependent context");
8483 }
8484 
8485 template <typename Derived>
TransformOMPAtomicDefaultMemOrderClause(OMPAtomicDefaultMemOrderClause * C)8486 OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
8487     OMPAtomicDefaultMemOrderClause *C) {
8488   llvm_unreachable(
8489       "atomic_default_mem_order clause cannot appear in dependent context");
8490 }
8491 
8492 template <typename Derived>
8493 OMPClause *
TransformOMPPrivateClause(OMPPrivateClause * C)8494 TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
8495   llvm::SmallVector<Expr *, 16> Vars;
8496   Vars.reserve(C->varlist_size());
8497   for (auto *VE : C->varlists()) {
8498     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8499     if (EVar.isInvalid())
8500       return nullptr;
8501     Vars.push_back(EVar.get());
8502   }
8503   return getDerived().RebuildOMPPrivateClause(
8504       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8505 }
8506 
8507 template <typename Derived>
TransformOMPFirstprivateClause(OMPFirstprivateClause * C)8508 OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
8509     OMPFirstprivateClause *C) {
8510   llvm::SmallVector<Expr *, 16> Vars;
8511   Vars.reserve(C->varlist_size());
8512   for (auto *VE : C->varlists()) {
8513     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8514     if (EVar.isInvalid())
8515       return nullptr;
8516     Vars.push_back(EVar.get());
8517   }
8518   return getDerived().RebuildOMPFirstprivateClause(
8519       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8520 }
8521 
8522 template <typename Derived>
8523 OMPClause *
TransformOMPLastprivateClause(OMPLastprivateClause * C)8524 TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
8525   llvm::SmallVector<Expr *, 16> Vars;
8526   Vars.reserve(C->varlist_size());
8527   for (auto *VE : C->varlists()) {
8528     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8529     if (EVar.isInvalid())
8530       return nullptr;
8531     Vars.push_back(EVar.get());
8532   }
8533   return getDerived().RebuildOMPLastprivateClause(
8534       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8535 }
8536 
8537 template <typename Derived>
8538 OMPClause *
TransformOMPSharedClause(OMPSharedClause * C)8539 TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
8540   llvm::SmallVector<Expr *, 16> Vars;
8541   Vars.reserve(C->varlist_size());
8542   for (auto *VE : C->varlists()) {
8543     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8544     if (EVar.isInvalid())
8545       return nullptr;
8546     Vars.push_back(EVar.get());
8547   }
8548   return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
8549                                              C->getLParenLoc(), C->getEndLoc());
8550 }
8551 
8552 template <typename Derived>
8553 OMPClause *
TransformOMPReductionClause(OMPReductionClause * C)8554 TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
8555   llvm::SmallVector<Expr *, 16> Vars;
8556   Vars.reserve(C->varlist_size());
8557   for (auto *VE : C->varlists()) {
8558     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8559     if (EVar.isInvalid())
8560       return nullptr;
8561     Vars.push_back(EVar.get());
8562   }
8563   CXXScopeSpec ReductionIdScopeSpec;
8564   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8565 
8566   DeclarationNameInfo NameInfo = C->getNameInfo();
8567   if (NameInfo.getName()) {
8568     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8569     if (!NameInfo.getName())
8570       return nullptr;
8571   }
8572   // Build a list of all UDR decls with the same names ranged by the Scopes.
8573   // The Scope boundary is a duplication of the previous decl.
8574   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8575   for (auto *E : C->reduction_ops()) {
8576     // Transform all the decls.
8577     if (E) {
8578       auto *ULE = cast<UnresolvedLookupExpr>(E);
8579       UnresolvedSet<8> Decls;
8580       for (auto *D : ULE->decls()) {
8581         NamedDecl *InstD =
8582             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8583         Decls.addDecl(InstD, InstD->getAccess());
8584       }
8585       UnresolvedReductions.push_back(
8586        UnresolvedLookupExpr::Create(
8587           SemaRef.Context, /*NamingClass=*/nullptr,
8588           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
8589           NameInfo, /*ADL=*/true, ULE->isOverloaded(),
8590           Decls.begin(), Decls.end()));
8591     } else
8592       UnresolvedReductions.push_back(nullptr);
8593   }
8594   return getDerived().RebuildOMPReductionClause(
8595       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8596       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8597 }
8598 
8599 template <typename Derived>
TransformOMPTaskReductionClause(OMPTaskReductionClause * C)8600 OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
8601     OMPTaskReductionClause *C) {
8602   llvm::SmallVector<Expr *, 16> Vars;
8603   Vars.reserve(C->varlist_size());
8604   for (auto *VE : C->varlists()) {
8605     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8606     if (EVar.isInvalid())
8607       return nullptr;
8608     Vars.push_back(EVar.get());
8609   }
8610   CXXScopeSpec ReductionIdScopeSpec;
8611   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8612 
8613   DeclarationNameInfo NameInfo = C->getNameInfo();
8614   if (NameInfo.getName()) {
8615     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8616     if (!NameInfo.getName())
8617       return nullptr;
8618   }
8619   // Build a list of all UDR decls with the same names ranged by the Scopes.
8620   // The Scope boundary is a duplication of the previous decl.
8621   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8622   for (auto *E : C->reduction_ops()) {
8623     // Transform all the decls.
8624     if (E) {
8625       auto *ULE = cast<UnresolvedLookupExpr>(E);
8626       UnresolvedSet<8> Decls;
8627       for (auto *D : ULE->decls()) {
8628         NamedDecl *InstD =
8629             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8630         Decls.addDecl(InstD, InstD->getAccess());
8631       }
8632       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8633           SemaRef.Context, /*NamingClass=*/nullptr,
8634           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8635           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8636     } else
8637       UnresolvedReductions.push_back(nullptr);
8638   }
8639   return getDerived().RebuildOMPTaskReductionClause(
8640       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8641       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8642 }
8643 
8644 template <typename Derived>
8645 OMPClause *
TransformOMPInReductionClause(OMPInReductionClause * C)8646 TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
8647   llvm::SmallVector<Expr *, 16> Vars;
8648   Vars.reserve(C->varlist_size());
8649   for (auto *VE : C->varlists()) {
8650     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8651     if (EVar.isInvalid())
8652       return nullptr;
8653     Vars.push_back(EVar.get());
8654   }
8655   CXXScopeSpec ReductionIdScopeSpec;
8656   ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
8657 
8658   DeclarationNameInfo NameInfo = C->getNameInfo();
8659   if (NameInfo.getName()) {
8660     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8661     if (!NameInfo.getName())
8662       return nullptr;
8663   }
8664   // Build a list of all UDR decls with the same names ranged by the Scopes.
8665   // The Scope boundary is a duplication of the previous decl.
8666   llvm::SmallVector<Expr *, 16> UnresolvedReductions;
8667   for (auto *E : C->reduction_ops()) {
8668     // Transform all the decls.
8669     if (E) {
8670       auto *ULE = cast<UnresolvedLookupExpr>(E);
8671       UnresolvedSet<8> Decls;
8672       for (auto *D : ULE->decls()) {
8673         NamedDecl *InstD =
8674             cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
8675         Decls.addDecl(InstD, InstD->getAccess());
8676       }
8677       UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
8678           SemaRef.Context, /*NamingClass=*/nullptr,
8679           ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
8680           /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
8681     } else
8682       UnresolvedReductions.push_back(nullptr);
8683   }
8684   return getDerived().RebuildOMPInReductionClause(
8685       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
8686       C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
8687 }
8688 
8689 template <typename Derived>
8690 OMPClause *
TransformOMPLinearClause(OMPLinearClause * C)8691 TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
8692   llvm::SmallVector<Expr *, 16> Vars;
8693   Vars.reserve(C->varlist_size());
8694   for (auto *VE : C->varlists()) {
8695     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8696     if (EVar.isInvalid())
8697       return nullptr;
8698     Vars.push_back(EVar.get());
8699   }
8700   ExprResult Step = getDerived().TransformExpr(C->getStep());
8701   if (Step.isInvalid())
8702     return nullptr;
8703   return getDerived().RebuildOMPLinearClause(
8704       Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
8705       C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
8706 }
8707 
8708 template <typename Derived>
8709 OMPClause *
TransformOMPAlignedClause(OMPAlignedClause * C)8710 TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
8711   llvm::SmallVector<Expr *, 16> Vars;
8712   Vars.reserve(C->varlist_size());
8713   for (auto *VE : C->varlists()) {
8714     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8715     if (EVar.isInvalid())
8716       return nullptr;
8717     Vars.push_back(EVar.get());
8718   }
8719   ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
8720   if (Alignment.isInvalid())
8721     return nullptr;
8722   return getDerived().RebuildOMPAlignedClause(
8723       Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
8724       C->getColonLoc(), C->getEndLoc());
8725 }
8726 
8727 template <typename Derived>
8728 OMPClause *
TransformOMPCopyinClause(OMPCopyinClause * C)8729 TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
8730   llvm::SmallVector<Expr *, 16> Vars;
8731   Vars.reserve(C->varlist_size());
8732   for (auto *VE : C->varlists()) {
8733     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8734     if (EVar.isInvalid())
8735       return nullptr;
8736     Vars.push_back(EVar.get());
8737   }
8738   return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
8739                                              C->getLParenLoc(), C->getEndLoc());
8740 }
8741 
8742 template <typename Derived>
8743 OMPClause *
TransformOMPCopyprivateClause(OMPCopyprivateClause * C)8744 TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
8745   llvm::SmallVector<Expr *, 16> Vars;
8746   Vars.reserve(C->varlist_size());
8747   for (auto *VE : C->varlists()) {
8748     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8749     if (EVar.isInvalid())
8750       return nullptr;
8751     Vars.push_back(EVar.get());
8752   }
8753   return getDerived().RebuildOMPCopyprivateClause(
8754       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8755 }
8756 
8757 template <typename Derived>
TransformOMPFlushClause(OMPFlushClause * C)8758 OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
8759   llvm::SmallVector<Expr *, 16> Vars;
8760   Vars.reserve(C->varlist_size());
8761   for (auto *VE : C->varlists()) {
8762     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8763     if (EVar.isInvalid())
8764       return nullptr;
8765     Vars.push_back(EVar.get());
8766   }
8767   return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
8768                                             C->getLParenLoc(), C->getEndLoc());
8769 }
8770 
8771 template <typename Derived>
8772 OMPClause *
TransformOMPDependClause(OMPDependClause * C)8773 TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
8774   llvm::SmallVector<Expr *, 16> Vars;
8775   Vars.reserve(C->varlist_size());
8776   for (auto *VE : C->varlists()) {
8777     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8778     if (EVar.isInvalid())
8779       return nullptr;
8780     Vars.push_back(EVar.get());
8781   }
8782   return getDerived().RebuildOMPDependClause(
8783       C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(), Vars,
8784       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8785 }
8786 
8787 template <typename Derived>
8788 OMPClause *
TransformOMPDeviceClause(OMPDeviceClause * C)8789 TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
8790   ExprResult E = getDerived().TransformExpr(C->getDevice());
8791   if (E.isInvalid())
8792     return nullptr;
8793   return getDerived().RebuildOMPDeviceClause(E.get(), C->getBeginLoc(),
8794                                              C->getLParenLoc(), C->getEndLoc());
8795 }
8796 
8797 template <typename Derived>
TransformOMPMapClause(OMPMapClause * C)8798 OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
8799   llvm::SmallVector<Expr *, 16> Vars;
8800   Vars.reserve(C->varlist_size());
8801   for (auto *VE : C->varlists()) {
8802     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8803     if (EVar.isInvalid())
8804       return nullptr;
8805     Vars.push_back(EVar.get());
8806   }
8807   return getDerived().RebuildOMPMapClause(
8808       C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), C->getMapType(),
8809       C->isImplicitMapType(), C->getMapLoc(), C->getColonLoc(), Vars,
8810       C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8811 }
8812 
8813 template <typename Derived>
8814 OMPClause *
TransformOMPNumTeamsClause(OMPNumTeamsClause * C)8815 TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
8816   ExprResult E = getDerived().TransformExpr(C->getNumTeams());
8817   if (E.isInvalid())
8818     return nullptr;
8819   return getDerived().RebuildOMPNumTeamsClause(
8820       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8821 }
8822 
8823 template <typename Derived>
8824 OMPClause *
TransformOMPThreadLimitClause(OMPThreadLimitClause * C)8825 TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
8826   ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
8827   if (E.isInvalid())
8828     return nullptr;
8829   return getDerived().RebuildOMPThreadLimitClause(
8830       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8831 }
8832 
8833 template <typename Derived>
8834 OMPClause *
TransformOMPPriorityClause(OMPPriorityClause * C)8835 TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
8836   ExprResult E = getDerived().TransformExpr(C->getPriority());
8837   if (E.isInvalid())
8838     return nullptr;
8839   return getDerived().RebuildOMPPriorityClause(
8840       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8841 }
8842 
8843 template <typename Derived>
8844 OMPClause *
TransformOMPGrainsizeClause(OMPGrainsizeClause * C)8845 TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
8846   ExprResult E = getDerived().TransformExpr(C->getGrainsize());
8847   if (E.isInvalid())
8848     return nullptr;
8849   return getDerived().RebuildOMPGrainsizeClause(
8850       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8851 }
8852 
8853 template <typename Derived>
8854 OMPClause *
TransformOMPNumTasksClause(OMPNumTasksClause * C)8855 TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
8856   ExprResult E = getDerived().TransformExpr(C->getNumTasks());
8857   if (E.isInvalid())
8858     return nullptr;
8859   return getDerived().RebuildOMPNumTasksClause(
8860       E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8861 }
8862 
8863 template <typename Derived>
TransformOMPHintClause(OMPHintClause * C)8864 OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
8865   ExprResult E = getDerived().TransformExpr(C->getHint());
8866   if (E.isInvalid())
8867     return nullptr;
8868   return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
8869                                            C->getLParenLoc(), C->getEndLoc());
8870 }
8871 
8872 template <typename Derived>
TransformOMPDistScheduleClause(OMPDistScheduleClause * C)8873 OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
8874     OMPDistScheduleClause *C) {
8875   ExprResult E = getDerived().TransformExpr(C->getChunkSize());
8876   if (E.isInvalid())
8877     return nullptr;
8878   return getDerived().RebuildOMPDistScheduleClause(
8879       C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
8880       C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
8881 }
8882 
8883 template <typename Derived>
8884 OMPClause *
TransformOMPDefaultmapClause(OMPDefaultmapClause * C)8885 TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
8886   return C;
8887 }
8888 
8889 template <typename Derived>
TransformOMPToClause(OMPToClause * C)8890 OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
8891   llvm::SmallVector<Expr *, 16> Vars;
8892   Vars.reserve(C->varlist_size());
8893   for (auto *VE : C->varlists()) {
8894     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8895     if (EVar.isInvalid())
8896       return 0;
8897     Vars.push_back(EVar.get());
8898   }
8899   return getDerived().RebuildOMPToClause(Vars, C->getBeginLoc(),
8900                                          C->getLParenLoc(), C->getEndLoc());
8901 }
8902 
8903 template <typename Derived>
TransformOMPFromClause(OMPFromClause * C)8904 OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
8905   llvm::SmallVector<Expr *, 16> Vars;
8906   Vars.reserve(C->varlist_size());
8907   for (auto *VE : C->varlists()) {
8908     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8909     if (EVar.isInvalid())
8910       return 0;
8911     Vars.push_back(EVar.get());
8912   }
8913   return getDerived().RebuildOMPFromClause(Vars, C->getBeginLoc(),
8914                                            C->getLParenLoc(), C->getEndLoc());
8915 }
8916 
8917 template <typename Derived>
TransformOMPUseDevicePtrClause(OMPUseDevicePtrClause * C)8918 OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
8919     OMPUseDevicePtrClause *C) {
8920   llvm::SmallVector<Expr *, 16> Vars;
8921   Vars.reserve(C->varlist_size());
8922   for (auto *VE : C->varlists()) {
8923     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8924     if (EVar.isInvalid())
8925       return nullptr;
8926     Vars.push_back(EVar.get());
8927   }
8928   return getDerived().RebuildOMPUseDevicePtrClause(
8929       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8930 }
8931 
8932 template <typename Derived>
8933 OMPClause *
TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause * C)8934 TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
8935   llvm::SmallVector<Expr *, 16> Vars;
8936   Vars.reserve(C->varlist_size());
8937   for (auto *VE : C->varlists()) {
8938     ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
8939     if (EVar.isInvalid())
8940       return nullptr;
8941     Vars.push_back(EVar.get());
8942   }
8943   return getDerived().RebuildOMPIsDevicePtrClause(
8944       Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
8945 }
8946 
8947 //===----------------------------------------------------------------------===//
8948 // Expression transformation
8949 //===----------------------------------------------------------------------===//
8950 template<typename Derived>
8951 ExprResult
TransformConstantExpr(ConstantExpr * E)8952 TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
8953   return TransformExpr(E->getSubExpr());
8954 }
8955 
8956 template<typename Derived>
8957 ExprResult
TransformPredefinedExpr(PredefinedExpr * E)8958 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
8959   if (!E->isTypeDependent())
8960     return E;
8961 
8962   return getDerived().RebuildPredefinedExpr(E->getLocation(),
8963                                             E->getIdentKind());
8964 }
8965 
8966 template<typename Derived>
8967 ExprResult
TransformDeclRefExpr(DeclRefExpr * E)8968 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
8969   NestedNameSpecifierLoc QualifierLoc;
8970   if (E->getQualifierLoc()) {
8971     QualifierLoc
8972       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8973     if (!QualifierLoc)
8974       return ExprError();
8975   }
8976 
8977   ValueDecl *ND
8978     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
8979                                                          E->getDecl()));
8980   if (!ND)
8981     return ExprError();
8982 
8983   DeclarationNameInfo NameInfo = E->getNameInfo();
8984   if (NameInfo.getName()) {
8985     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8986     if (!NameInfo.getName())
8987       return ExprError();
8988   }
8989 
8990   if (!getDerived().AlwaysRebuild() &&
8991       QualifierLoc == E->getQualifierLoc() &&
8992       ND == E->getDecl() &&
8993       NameInfo.getName() == E->getDecl()->getDeclName() &&
8994       !E->hasExplicitTemplateArgs()) {
8995 
8996     // Mark it referenced in the new context regardless.
8997     // FIXME: this is a bit instantiation-specific.
8998     SemaRef.MarkDeclRefReferenced(E);
8999 
9000     return E;
9001   }
9002 
9003   TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
9004   if (E->hasExplicitTemplateArgs()) {
9005     TemplateArgs = &TransArgs;
9006     TransArgs.setLAngleLoc(E->getLAngleLoc());
9007     TransArgs.setRAngleLoc(E->getRAngleLoc());
9008     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9009                                                 E->getNumTemplateArgs(),
9010                                                 TransArgs))
9011       return ExprError();
9012   }
9013 
9014   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
9015                                          TemplateArgs);
9016 }
9017 
9018 template<typename Derived>
9019 ExprResult
TransformIntegerLiteral(IntegerLiteral * E)9020 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
9021   return E;
9022 }
9023 
9024 template <typename Derived>
TransformFixedPointLiteral(FixedPointLiteral * E)9025 ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
9026     FixedPointLiteral *E) {
9027   return E;
9028 }
9029 
9030 template<typename Derived>
9031 ExprResult
TransformFloatingLiteral(FloatingLiteral * E)9032 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
9033   return E;
9034 }
9035 
9036 template<typename Derived>
9037 ExprResult
TransformImaginaryLiteral(ImaginaryLiteral * E)9038 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
9039   return E;
9040 }
9041 
9042 template<typename Derived>
9043 ExprResult
TransformStringLiteral(StringLiteral * E)9044 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
9045   return E;
9046 }
9047 
9048 template<typename Derived>
9049 ExprResult
TransformCharacterLiteral(CharacterLiteral * E)9050 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
9051   return E;
9052 }
9053 
9054 template<typename Derived>
9055 ExprResult
TransformUserDefinedLiteral(UserDefinedLiteral * E)9056 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
9057   if (FunctionDecl *FD = E->getDirectCallee())
9058     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), FD);
9059   return SemaRef.MaybeBindToTemporary(E);
9060 }
9061 
9062 template<typename Derived>
9063 ExprResult
TransformGenericSelectionExpr(GenericSelectionExpr * E)9064 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
9065   ExprResult ControllingExpr =
9066     getDerived().TransformExpr(E->getControllingExpr());
9067   if (ControllingExpr.isInvalid())
9068     return ExprError();
9069 
9070   SmallVector<Expr *, 4> AssocExprs;
9071   SmallVector<TypeSourceInfo *, 4> AssocTypes;
9072   for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
9073     TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
9074     if (TS) {
9075       TypeSourceInfo *AssocType = getDerived().TransformType(TS);
9076       if (!AssocType)
9077         return ExprError();
9078       AssocTypes.push_back(AssocType);
9079     } else {
9080       AssocTypes.push_back(nullptr);
9081     }
9082 
9083     ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
9084     if (AssocExpr.isInvalid())
9085       return ExprError();
9086     AssocExprs.push_back(AssocExpr.get());
9087   }
9088 
9089   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
9090                                                   E->getDefaultLoc(),
9091                                                   E->getRParenLoc(),
9092                                                   ControllingExpr.get(),
9093                                                   AssocTypes,
9094                                                   AssocExprs);
9095 }
9096 
9097 template<typename Derived>
9098 ExprResult
TransformParenExpr(ParenExpr * E)9099 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
9100   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9101   if (SubExpr.isInvalid())
9102     return ExprError();
9103 
9104   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9105     return E;
9106 
9107   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
9108                                        E->getRParen());
9109 }
9110 
9111 /// The operand of a unary address-of operator has special rules: it's
9112 /// allowed to refer to a non-static member of a class even if there's no 'this'
9113 /// object available.
9114 template<typename Derived>
9115 ExprResult
TransformAddressOfOperand(Expr * E)9116 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
9117   if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
9118     return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
9119   else
9120     return getDerived().TransformExpr(E);
9121 }
9122 
9123 template<typename Derived>
9124 ExprResult
TransformUnaryOperator(UnaryOperator * E)9125 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
9126   ExprResult SubExpr;
9127   if (E->getOpcode() == UO_AddrOf)
9128     SubExpr = TransformAddressOfOperand(E->getSubExpr());
9129   else
9130     SubExpr = TransformExpr(E->getSubExpr());
9131   if (SubExpr.isInvalid())
9132     return ExprError();
9133 
9134   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
9135     return E;
9136 
9137   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
9138                                            E->getOpcode(),
9139                                            SubExpr.get());
9140 }
9141 
9142 template<typename Derived>
9143 ExprResult
TransformOffsetOfExpr(OffsetOfExpr * E)9144 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
9145   // Transform the type.
9146   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
9147   if (!Type)
9148     return ExprError();
9149 
9150   // Transform all of the components into components similar to what the
9151   // parser uses.
9152   // FIXME: It would be slightly more efficient in the non-dependent case to
9153   // just map FieldDecls, rather than requiring the rebuilder to look for
9154   // the fields again. However, __builtin_offsetof is rare enough in
9155   // template code that we don't care.
9156   bool ExprChanged = false;
9157   typedef Sema::OffsetOfComponent Component;
9158   SmallVector<Component, 4> Components;
9159   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
9160     const OffsetOfNode &ON = E->getComponent(I);
9161     Component Comp;
9162     Comp.isBrackets = true;
9163     Comp.LocStart = ON.getSourceRange().getBegin();
9164     Comp.LocEnd = ON.getSourceRange().getEnd();
9165     switch (ON.getKind()) {
9166     case OffsetOfNode::Array: {
9167       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
9168       ExprResult Index = getDerived().TransformExpr(FromIndex);
9169       if (Index.isInvalid())
9170         return ExprError();
9171 
9172       ExprChanged = ExprChanged || Index.get() != FromIndex;
9173       Comp.isBrackets = true;
9174       Comp.U.E = Index.get();
9175       break;
9176     }
9177 
9178     case OffsetOfNode::Field:
9179     case OffsetOfNode::Identifier:
9180       Comp.isBrackets = false;
9181       Comp.U.IdentInfo = ON.getFieldName();
9182       if (!Comp.U.IdentInfo)
9183         continue;
9184 
9185       break;
9186 
9187     case OffsetOfNode::Base:
9188       // Will be recomputed during the rebuild.
9189       continue;
9190     }
9191 
9192     Components.push_back(Comp);
9193   }
9194 
9195   // If nothing changed, retain the existing expression.
9196   if (!getDerived().AlwaysRebuild() &&
9197       Type == E->getTypeSourceInfo() &&
9198       !ExprChanged)
9199     return E;
9200 
9201   // Build a new offsetof expression.
9202   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
9203                                           Components, E->getRParenLoc());
9204 }
9205 
9206 template<typename Derived>
9207 ExprResult
TransformOpaqueValueExpr(OpaqueValueExpr * E)9208 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
9209   assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&
9210          "opaque value expression requires transformation");
9211   return E;
9212 }
9213 
9214 template<typename Derived>
9215 ExprResult
TransformTypoExpr(TypoExpr * E)9216 TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
9217   return E;
9218 }
9219 
9220 template<typename Derived>
9221 ExprResult
TransformPseudoObjectExpr(PseudoObjectExpr * E)9222 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
9223   // Rebuild the syntactic form.  The original syntactic form has
9224   // opaque-value expressions in it, so strip those away and rebuild
9225   // the result.  This is a really awful way of doing this, but the
9226   // better solution (rebuilding the semantic expressions and
9227   // rebinding OVEs as necessary) doesn't work; we'd need
9228   // TreeTransform to not strip away implicit conversions.
9229   Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
9230   ExprResult result = getDerived().TransformExpr(newSyntacticForm);
9231   if (result.isInvalid()) return ExprError();
9232 
9233   // If that gives us a pseudo-object result back, the pseudo-object
9234   // expression must have been an lvalue-to-rvalue conversion which we
9235   // should reapply.
9236   if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
9237     result = SemaRef.checkPseudoObjectRValue(result.get());
9238 
9239   return result;
9240 }
9241 
9242 template<typename Derived>
9243 ExprResult
TransformUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr * E)9244 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
9245                                                 UnaryExprOrTypeTraitExpr *E) {
9246   if (E->isArgumentType()) {
9247     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
9248 
9249     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9250     if (!NewT)
9251       return ExprError();
9252 
9253     if (!getDerived().AlwaysRebuild() && OldT == NewT)
9254       return E;
9255 
9256     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
9257                                                     E->getKind(),
9258                                                     E->getSourceRange());
9259   }
9260 
9261   // C++0x [expr.sizeof]p1:
9262   //   The operand is either an expression, which is an unevaluated operand
9263   //   [...]
9264   EnterExpressionEvaluationContext Unevaluated(
9265       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
9266       Sema::ReuseLambdaContextDecl);
9267 
9268   // Try to recover if we have something like sizeof(T::X) where X is a type.
9269   // Notably, there must be *exactly* one set of parens if X is a type.
9270   TypeSourceInfo *RecoveryTSI = nullptr;
9271   ExprResult SubExpr;
9272   auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
9273   if (auto *DRE =
9274           PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
9275     SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
9276         PE, DRE, false, &RecoveryTSI);
9277   else
9278     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
9279 
9280   if (RecoveryTSI) {
9281     return getDerived().RebuildUnaryExprOrTypeTrait(
9282         RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
9283   } else if (SubExpr.isInvalid())
9284     return ExprError();
9285 
9286   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
9287     return E;
9288 
9289   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
9290                                                   E->getOperatorLoc(),
9291                                                   E->getKind(),
9292                                                   E->getSourceRange());
9293 }
9294 
9295 template<typename Derived>
9296 ExprResult
TransformArraySubscriptExpr(ArraySubscriptExpr * E)9297 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
9298   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9299   if (LHS.isInvalid())
9300     return ExprError();
9301 
9302   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9303   if (RHS.isInvalid())
9304     return ExprError();
9305 
9306 
9307   if (!getDerived().AlwaysRebuild() &&
9308       LHS.get() == E->getLHS() &&
9309       RHS.get() == E->getRHS())
9310     return E;
9311 
9312   return getDerived().RebuildArraySubscriptExpr(
9313       LHS.get(),
9314       /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
9315 }
9316 
9317 template <typename Derived>
9318 ExprResult
TransformOMPArraySectionExpr(OMPArraySectionExpr * E)9319 TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
9320   ExprResult Base = getDerived().TransformExpr(E->getBase());
9321   if (Base.isInvalid())
9322     return ExprError();
9323 
9324   ExprResult LowerBound;
9325   if (E->getLowerBound()) {
9326     LowerBound = getDerived().TransformExpr(E->getLowerBound());
9327     if (LowerBound.isInvalid())
9328       return ExprError();
9329   }
9330 
9331   ExprResult Length;
9332   if (E->getLength()) {
9333     Length = getDerived().TransformExpr(E->getLength());
9334     if (Length.isInvalid())
9335       return ExprError();
9336   }
9337 
9338   if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
9339       LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
9340     return E;
9341 
9342   return getDerived().RebuildOMPArraySectionExpr(
9343       Base.get(), E->getBase()->getEndLoc(), LowerBound.get(), E->getColonLoc(),
9344       Length.get(), E->getRBracketLoc());
9345 }
9346 
9347 template<typename Derived>
9348 ExprResult
TransformCallExpr(CallExpr * E)9349 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
9350   // Transform the callee.
9351   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9352   if (Callee.isInvalid())
9353     return ExprError();
9354 
9355   // Transform arguments.
9356   bool ArgChanged = false;
9357   SmallVector<Expr*, 8> Args;
9358   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9359                                   &ArgChanged))
9360     return ExprError();
9361 
9362   if (!getDerived().AlwaysRebuild() &&
9363       Callee.get() == E->getCallee() &&
9364       !ArgChanged)
9365     return SemaRef.MaybeBindToTemporary(E);
9366 
9367   // FIXME: Wrong source location information for the '('.
9368   SourceLocation FakeLParenLoc
9369     = ((Expr *)Callee.get())->getSourceRange().getBegin();
9370   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
9371                                       Args,
9372                                       E->getRParenLoc());
9373 }
9374 
9375 template<typename Derived>
9376 ExprResult
TransformMemberExpr(MemberExpr * E)9377 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
9378   ExprResult Base = getDerived().TransformExpr(E->getBase());
9379   if (Base.isInvalid())
9380     return ExprError();
9381 
9382   NestedNameSpecifierLoc QualifierLoc;
9383   if (E->hasQualifier()) {
9384     QualifierLoc
9385       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
9386 
9387     if (!QualifierLoc)
9388       return ExprError();
9389   }
9390   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
9391 
9392   ValueDecl *Member
9393     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
9394                                                          E->getMemberDecl()));
9395   if (!Member)
9396     return ExprError();
9397 
9398   NamedDecl *FoundDecl = E->getFoundDecl();
9399   if (FoundDecl == E->getMemberDecl()) {
9400     FoundDecl = Member;
9401   } else {
9402     FoundDecl = cast_or_null<NamedDecl>(
9403                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
9404     if (!FoundDecl)
9405       return ExprError();
9406   }
9407 
9408   if (!getDerived().AlwaysRebuild() &&
9409       Base.get() == E->getBase() &&
9410       QualifierLoc == E->getQualifierLoc() &&
9411       Member == E->getMemberDecl() &&
9412       FoundDecl == E->getFoundDecl() &&
9413       !E->hasExplicitTemplateArgs()) {
9414 
9415     // Mark it referenced in the new context regardless.
9416     // FIXME: this is a bit instantiation-specific.
9417     SemaRef.MarkMemberReferenced(E);
9418 
9419     return E;
9420   }
9421 
9422   TemplateArgumentListInfo TransArgs;
9423   if (E->hasExplicitTemplateArgs()) {
9424     TransArgs.setLAngleLoc(E->getLAngleLoc());
9425     TransArgs.setRAngleLoc(E->getRAngleLoc());
9426     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
9427                                                 E->getNumTemplateArgs(),
9428                                                 TransArgs))
9429       return ExprError();
9430   }
9431 
9432   // FIXME: Bogus source location for the operator
9433   SourceLocation FakeOperatorLoc =
9434       SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
9435 
9436   // FIXME: to do this check properly, we will need to preserve the
9437   // first-qualifier-in-scope here, just in case we had a dependent
9438   // base (and therefore couldn't do the check) and a
9439   // nested-name-qualifier (and therefore could do the lookup).
9440   NamedDecl *FirstQualifierInScope = nullptr;
9441   DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
9442   if (MemberNameInfo.getName()) {
9443     MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
9444     if (!MemberNameInfo.getName())
9445       return ExprError();
9446   }
9447 
9448   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
9449                                         E->isArrow(),
9450                                         QualifierLoc,
9451                                         TemplateKWLoc,
9452                                         MemberNameInfo,
9453                                         Member,
9454                                         FoundDecl,
9455                                         (E->hasExplicitTemplateArgs()
9456                                            ? &TransArgs : nullptr),
9457                                         FirstQualifierInScope);
9458 }
9459 
9460 template<typename Derived>
9461 ExprResult
TransformBinaryOperator(BinaryOperator * E)9462 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
9463   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9464   if (LHS.isInvalid())
9465     return ExprError();
9466 
9467   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9468   if (RHS.isInvalid())
9469     return ExprError();
9470 
9471   if (!getDerived().AlwaysRebuild() &&
9472       LHS.get() == E->getLHS() &&
9473       RHS.get() == E->getRHS())
9474     return E;
9475 
9476   Sema::FPContractStateRAII FPContractState(getSema());
9477   getSema().FPFeatures = E->getFPFeatures();
9478 
9479   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
9480                                             LHS.get(), RHS.get());
9481 }
9482 
9483 template<typename Derived>
9484 ExprResult
TransformCompoundAssignOperator(CompoundAssignOperator * E)9485 TreeTransform<Derived>::TransformCompoundAssignOperator(
9486                                                       CompoundAssignOperator *E) {
9487   return getDerived().TransformBinaryOperator(E);
9488 }
9489 
9490 template<typename Derived>
9491 ExprResult TreeTransform<Derived>::
TransformBinaryConditionalOperator(BinaryConditionalOperator * e)9492 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
9493   // Just rebuild the common and RHS expressions and see whether we
9494   // get any changes.
9495 
9496   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
9497   if (commonExpr.isInvalid())
9498     return ExprError();
9499 
9500   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
9501   if (rhs.isInvalid())
9502     return ExprError();
9503 
9504   if (!getDerived().AlwaysRebuild() &&
9505       commonExpr.get() == e->getCommon() &&
9506       rhs.get() == e->getFalseExpr())
9507     return e;
9508 
9509   return getDerived().RebuildConditionalOperator(commonExpr.get(),
9510                                                  e->getQuestionLoc(),
9511                                                  nullptr,
9512                                                  e->getColonLoc(),
9513                                                  rhs.get());
9514 }
9515 
9516 template<typename Derived>
9517 ExprResult
TransformConditionalOperator(ConditionalOperator * E)9518 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
9519   ExprResult Cond = getDerived().TransformExpr(E->getCond());
9520   if (Cond.isInvalid())
9521     return ExprError();
9522 
9523   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9524   if (LHS.isInvalid())
9525     return ExprError();
9526 
9527   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9528   if (RHS.isInvalid())
9529     return ExprError();
9530 
9531   if (!getDerived().AlwaysRebuild() &&
9532       Cond.get() == E->getCond() &&
9533       LHS.get() == E->getLHS() &&
9534       RHS.get() == E->getRHS())
9535     return E;
9536 
9537   return getDerived().RebuildConditionalOperator(Cond.get(),
9538                                                  E->getQuestionLoc(),
9539                                                  LHS.get(),
9540                                                  E->getColonLoc(),
9541                                                  RHS.get());
9542 }
9543 
9544 template<typename Derived>
9545 ExprResult
TransformImplicitCastExpr(ImplicitCastExpr * E)9546 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
9547   // Implicit casts are eliminated during transformation, since they
9548   // will be recomputed by semantic analysis after transformation.
9549   return getDerived().TransformExpr(E->getSubExprAsWritten());
9550 }
9551 
9552 template<typename Derived>
9553 ExprResult
TransformCStyleCastExpr(CStyleCastExpr * E)9554 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
9555   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
9556   if (!Type)
9557     return ExprError();
9558 
9559   ExprResult SubExpr
9560     = getDerived().TransformExpr(E->getSubExprAsWritten());
9561   if (SubExpr.isInvalid())
9562     return ExprError();
9563 
9564   if (!getDerived().AlwaysRebuild() &&
9565       Type == E->getTypeInfoAsWritten() &&
9566       SubExpr.get() == E->getSubExpr())
9567     return E;
9568 
9569   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
9570                                             Type,
9571                                             E->getRParenLoc(),
9572                                             SubExpr.get());
9573 }
9574 
9575 template<typename Derived>
9576 ExprResult
TransformCompoundLiteralExpr(CompoundLiteralExpr * E)9577 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
9578   TypeSourceInfo *OldT = E->getTypeSourceInfo();
9579   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
9580   if (!NewT)
9581     return ExprError();
9582 
9583   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
9584   if (Init.isInvalid())
9585     return ExprError();
9586 
9587   if (!getDerived().AlwaysRebuild() &&
9588       OldT == NewT &&
9589       Init.get() == E->getInitializer())
9590     return SemaRef.MaybeBindToTemporary(E);
9591 
9592   // Note: the expression type doesn't necessarily match the
9593   // type-as-written, but that's okay, because it should always be
9594   // derivable from the initializer.
9595 
9596   return getDerived().RebuildCompoundLiteralExpr(
9597       E->getLParenLoc(), NewT,
9598       /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
9599 }
9600 
9601 template<typename Derived>
9602 ExprResult
TransformExtVectorElementExpr(ExtVectorElementExpr * E)9603 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
9604   ExprResult Base = getDerived().TransformExpr(E->getBase());
9605   if (Base.isInvalid())
9606     return ExprError();
9607 
9608   if (!getDerived().AlwaysRebuild() &&
9609       Base.get() == E->getBase())
9610     return E;
9611 
9612   // FIXME: Bad source location
9613   SourceLocation FakeOperatorLoc =
9614       SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
9615   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
9616                                                   E->getAccessorLoc(),
9617                                                   E->getAccessor());
9618 }
9619 
9620 template<typename Derived>
9621 ExprResult
TransformInitListExpr(InitListExpr * E)9622 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
9623   if (InitListExpr *Syntactic = E->getSyntacticForm())
9624     E = Syntactic;
9625 
9626   bool InitChanged = false;
9627 
9628   EnterExpressionEvaluationContext Context(
9629       getSema(), EnterExpressionEvaluationContext::InitList);
9630 
9631   SmallVector<Expr*, 4> Inits;
9632   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
9633                                   Inits, &InitChanged))
9634     return ExprError();
9635 
9636   if (!getDerived().AlwaysRebuild() && !InitChanged) {
9637     // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
9638     // in some cases. We can't reuse it in general, because the syntactic and
9639     // semantic forms are linked, and we can't know that semantic form will
9640     // match even if the syntactic form does.
9641   }
9642 
9643   return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
9644                                       E->getRBraceLoc());
9645 }
9646 
9647 template<typename Derived>
9648 ExprResult
TransformDesignatedInitExpr(DesignatedInitExpr * E)9649 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
9650   Designation Desig;
9651 
9652   // transform the initializer value
9653   ExprResult Init = getDerived().TransformExpr(E->getInit());
9654   if (Init.isInvalid())
9655     return ExprError();
9656 
9657   // transform the designators.
9658   SmallVector<Expr*, 4> ArrayExprs;
9659   bool ExprChanged = false;
9660   for (const DesignatedInitExpr::Designator &D : E->designators()) {
9661     if (D.isFieldDesignator()) {
9662       Desig.AddDesignator(Designator::getField(D.getFieldName(),
9663                                                D.getDotLoc(),
9664                                                D.getFieldLoc()));
9665       if (D.getField()) {
9666         FieldDecl *Field = cast_or_null<FieldDecl>(
9667             getDerived().TransformDecl(D.getFieldLoc(), D.getField()));
9668         if (Field != D.getField())
9669           // Rebuild the expression when the transformed FieldDecl is
9670           // different to the already assigned FieldDecl.
9671           ExprChanged = true;
9672       } else {
9673         // Ensure that the designator expression is rebuilt when there isn't
9674         // a resolved FieldDecl in the designator as we don't want to assign
9675         // a FieldDecl to a pattern designator that will be instantiated again.
9676         ExprChanged = true;
9677       }
9678       continue;
9679     }
9680 
9681     if (D.isArrayDesignator()) {
9682       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
9683       if (Index.isInvalid())
9684         return ExprError();
9685 
9686       Desig.AddDesignator(
9687           Designator::getArray(Index.get(), D.getLBracketLoc()));
9688 
9689       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
9690       ArrayExprs.push_back(Index.get());
9691       continue;
9692     }
9693 
9694     assert(D.isArrayRangeDesignator() && "New kind of designator?");
9695     ExprResult Start
9696       = getDerived().TransformExpr(E->getArrayRangeStart(D));
9697     if (Start.isInvalid())
9698       return ExprError();
9699 
9700     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
9701     if (End.isInvalid())
9702       return ExprError();
9703 
9704     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
9705                                                   End.get(),
9706                                                   D.getLBracketLoc(),
9707                                                   D.getEllipsisLoc()));
9708 
9709     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
9710                   End.get() != E->getArrayRangeEnd(D);
9711 
9712     ArrayExprs.push_back(Start.get());
9713     ArrayExprs.push_back(End.get());
9714   }
9715 
9716   if (!getDerived().AlwaysRebuild() &&
9717       Init.get() == E->getInit() &&
9718       !ExprChanged)
9719     return E;
9720 
9721   return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
9722                                                 E->getEqualOrColonLoc(),
9723                                                 E->usesGNUSyntax(), Init.get());
9724 }
9725 
9726 // Seems that if TransformInitListExpr() only works on the syntactic form of an
9727 // InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
9728 template<typename Derived>
9729 ExprResult
TransformDesignatedInitUpdateExpr(DesignatedInitUpdateExpr * E)9730 TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
9731     DesignatedInitUpdateExpr *E) {
9732   llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "
9733                    "initializer");
9734   return ExprError();
9735 }
9736 
9737 template<typename Derived>
9738 ExprResult
TransformNoInitExpr(NoInitExpr * E)9739 TreeTransform<Derived>::TransformNoInitExpr(
9740     NoInitExpr *E) {
9741   llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer");
9742   return ExprError();
9743 }
9744 
9745 template<typename Derived>
9746 ExprResult
TransformArrayInitLoopExpr(ArrayInitLoopExpr * E)9747 TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
9748   llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer");
9749   return ExprError();
9750 }
9751 
9752 template<typename Derived>
9753 ExprResult
TransformArrayInitIndexExpr(ArrayInitIndexExpr * E)9754 TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
9755   llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer");
9756   return ExprError();
9757 }
9758 
9759 template<typename Derived>
9760 ExprResult
TransformImplicitValueInitExpr(ImplicitValueInitExpr * E)9761 TreeTransform<Derived>::TransformImplicitValueInitExpr(
9762                                                      ImplicitValueInitExpr *E) {
9763   TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
9764 
9765   // FIXME: Will we ever have proper type location here? Will we actually
9766   // need to transform the type?
9767   QualType T = getDerived().TransformType(E->getType());
9768   if (T.isNull())
9769     return ExprError();
9770 
9771   if (!getDerived().AlwaysRebuild() &&
9772       T == E->getType())
9773     return E;
9774 
9775   return getDerived().RebuildImplicitValueInitExpr(T);
9776 }
9777 
9778 template<typename Derived>
9779 ExprResult
TransformVAArgExpr(VAArgExpr * E)9780 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
9781   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
9782   if (!TInfo)
9783     return ExprError();
9784 
9785   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
9786   if (SubExpr.isInvalid())
9787     return ExprError();
9788 
9789   if (!getDerived().AlwaysRebuild() &&
9790       TInfo == E->getWrittenTypeInfo() &&
9791       SubExpr.get() == E->getSubExpr())
9792     return E;
9793 
9794   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
9795                                        TInfo, E->getRParenLoc());
9796 }
9797 
9798 template<typename Derived>
9799 ExprResult
TransformParenListExpr(ParenListExpr * E)9800 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
9801   bool ArgumentChanged = false;
9802   SmallVector<Expr*, 4> Inits;
9803   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
9804                      &ArgumentChanged))
9805     return ExprError();
9806 
9807   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
9808                                            Inits,
9809                                            E->getRParenLoc());
9810 }
9811 
9812 /// Transform an address-of-label expression.
9813 ///
9814 /// By default, the transformation of an address-of-label expression always
9815 /// rebuilds the expression, so that the label identifier can be resolved to
9816 /// the corresponding label statement by semantic analysis.
9817 template<typename Derived>
9818 ExprResult
TransformAddrLabelExpr(AddrLabelExpr * E)9819 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
9820   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
9821                                         E->getLabel());
9822   if (!LD)
9823     return ExprError();
9824 
9825   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
9826                                            cast<LabelDecl>(LD));
9827 }
9828 
9829 template<typename Derived>
9830 ExprResult
TransformStmtExpr(StmtExpr * E)9831 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
9832   SemaRef.ActOnStartStmtExpr();
9833   StmtResult SubStmt
9834     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
9835   if (SubStmt.isInvalid()) {
9836     SemaRef.ActOnStmtExprError();
9837     return ExprError();
9838   }
9839 
9840   if (!getDerived().AlwaysRebuild() &&
9841       SubStmt.get() == E->getSubStmt()) {
9842     // Calling this an 'error' is unintuitive, but it does the right thing.
9843     SemaRef.ActOnStmtExprError();
9844     return SemaRef.MaybeBindToTemporary(E);
9845   }
9846 
9847   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
9848                                       SubStmt.get(),
9849                                       E->getRParenLoc());
9850 }
9851 
9852 template<typename Derived>
9853 ExprResult
TransformChooseExpr(ChooseExpr * E)9854 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
9855   ExprResult Cond = getDerived().TransformExpr(E->getCond());
9856   if (Cond.isInvalid())
9857     return ExprError();
9858 
9859   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
9860   if (LHS.isInvalid())
9861     return ExprError();
9862 
9863   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
9864   if (RHS.isInvalid())
9865     return ExprError();
9866 
9867   if (!getDerived().AlwaysRebuild() &&
9868       Cond.get() == E->getCond() &&
9869       LHS.get() == E->getLHS() &&
9870       RHS.get() == E->getRHS())
9871     return E;
9872 
9873   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
9874                                         Cond.get(), LHS.get(), RHS.get(),
9875                                         E->getRParenLoc());
9876 }
9877 
9878 template<typename Derived>
9879 ExprResult
TransformGNUNullExpr(GNUNullExpr * E)9880 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
9881   return E;
9882 }
9883 
9884 template<typename Derived>
9885 ExprResult
TransformCXXOperatorCallExpr(CXXOperatorCallExpr * E)9886 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9887   switch (E->getOperator()) {
9888   case OO_New:
9889   case OO_Delete:
9890   case OO_Array_New:
9891   case OO_Array_Delete:
9892     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
9893 
9894   case OO_Call: {
9895     // This is a call to an object's operator().
9896     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
9897 
9898     // Transform the object itself.
9899     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
9900     if (Object.isInvalid())
9901       return ExprError();
9902 
9903     // FIXME: Poor location information
9904     SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
9905         static_cast<Expr *>(Object.get())->getEndLoc());
9906 
9907     // Transform the call arguments.
9908     SmallVector<Expr*, 8> Args;
9909     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
9910                                     Args))
9911       return ExprError();
9912 
9913     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
9914                                         E->getEndLoc());
9915   }
9916 
9917 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9918   case OO_##Name:
9919 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
9920 #include "clang/Basic/OperatorKinds.def"
9921   case OO_Subscript:
9922     // Handled below.
9923     break;
9924 
9925   case OO_Conditional:
9926     llvm_unreachable("conditional operator is not actually overloadable");
9927 
9928   case OO_None:
9929   case NUM_OVERLOADED_OPERATORS:
9930     llvm_unreachable("not an overloaded operator?");
9931   }
9932 
9933   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9934   if (Callee.isInvalid())
9935     return ExprError();
9936 
9937   ExprResult First;
9938   if (E->getOperator() == OO_Amp)
9939     First = getDerived().TransformAddressOfOperand(E->getArg(0));
9940   else
9941     First = getDerived().TransformExpr(E->getArg(0));
9942   if (First.isInvalid())
9943     return ExprError();
9944 
9945   ExprResult Second;
9946   if (E->getNumArgs() == 2) {
9947     Second = getDerived().TransformExpr(E->getArg(1));
9948     if (Second.isInvalid())
9949       return ExprError();
9950   }
9951 
9952   if (!getDerived().AlwaysRebuild() &&
9953       Callee.get() == E->getCallee() &&
9954       First.get() == E->getArg(0) &&
9955       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
9956     return SemaRef.MaybeBindToTemporary(E);
9957 
9958   Sema::FPContractStateRAII FPContractState(getSema());
9959   getSema().FPFeatures = E->getFPFeatures();
9960 
9961   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
9962                                                  E->getOperatorLoc(),
9963                                                  Callee.get(),
9964                                                  First.get(),
9965                                                  Second.get());
9966 }
9967 
9968 template<typename Derived>
9969 ExprResult
TransformCXXMemberCallExpr(CXXMemberCallExpr * E)9970 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
9971   return getDerived().TransformCallExpr(E);
9972 }
9973 
9974 template<typename Derived>
9975 ExprResult
TransformCUDAKernelCallExpr(CUDAKernelCallExpr * E)9976 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
9977   // Transform the callee.
9978   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
9979   if (Callee.isInvalid())
9980     return ExprError();
9981 
9982   // Transform exec config.
9983   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
9984   if (EC.isInvalid())
9985     return ExprError();
9986 
9987   // Transform arguments.
9988   bool ArgChanged = false;
9989   SmallVector<Expr*, 8> Args;
9990   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
9991                                   &ArgChanged))
9992     return ExprError();
9993 
9994   if (!getDerived().AlwaysRebuild() &&
9995       Callee.get() == E->getCallee() &&
9996       !ArgChanged)
9997     return SemaRef.MaybeBindToTemporary(E);
9998 
9999   // FIXME: Wrong source location information for the '('.
10000   SourceLocation FakeLParenLoc
10001     = ((Expr *)Callee.get())->getSourceRange().getBegin();
10002   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
10003                                       Args,
10004                                       E->getRParenLoc(), EC.get());
10005 }
10006 
10007 template<typename Derived>
10008 ExprResult
TransformCXXNamedCastExpr(CXXNamedCastExpr * E)10009 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
10010   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
10011   if (!Type)
10012     return ExprError();
10013 
10014   ExprResult SubExpr
10015     = getDerived().TransformExpr(E->getSubExprAsWritten());
10016   if (SubExpr.isInvalid())
10017     return ExprError();
10018 
10019   if (!getDerived().AlwaysRebuild() &&
10020       Type == E->getTypeInfoAsWritten() &&
10021       SubExpr.get() == E->getSubExpr())
10022     return E;
10023   return getDerived().RebuildCXXNamedCastExpr(
10024       E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
10025       Type, E->getAngleBrackets().getEnd(),
10026       // FIXME. this should be '(' location
10027       E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
10028 }
10029 
10030 template<typename Derived>
10031 ExprResult
TransformCXXStaticCastExpr(CXXStaticCastExpr * E)10032 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
10033   return getDerived().TransformCXXNamedCastExpr(E);
10034 }
10035 
10036 template<typename Derived>
10037 ExprResult
TransformCXXDynamicCastExpr(CXXDynamicCastExpr * E)10038 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
10039   return getDerived().TransformCXXNamedCastExpr(E);
10040 }
10041 
10042 template<typename Derived>
10043 ExprResult
TransformCXXReinterpretCastExpr(CXXReinterpretCastExpr * E)10044 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
10045                                                       CXXReinterpretCastExpr *E) {
10046   return getDerived().TransformCXXNamedCastExpr(E);
10047 }
10048 
10049 template<typename Derived>
10050 ExprResult
TransformCXXConstCastExpr(CXXConstCastExpr * E)10051 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
10052   return getDerived().TransformCXXNamedCastExpr(E);
10053 }
10054 
10055 template<typename Derived>
10056 ExprResult
TransformCXXFunctionalCastExpr(CXXFunctionalCastExpr * E)10057 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
10058                                                      CXXFunctionalCastExpr *E) {
10059   TypeSourceInfo *Type =
10060       getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
10061   if (!Type)
10062     return ExprError();
10063 
10064   ExprResult SubExpr
10065     = getDerived().TransformExpr(E->getSubExprAsWritten());
10066   if (SubExpr.isInvalid())
10067     return ExprError();
10068 
10069   if (!getDerived().AlwaysRebuild() &&
10070       Type == E->getTypeInfoAsWritten() &&
10071       SubExpr.get() == E->getSubExpr())
10072     return E;
10073 
10074   return getDerived().RebuildCXXFunctionalCastExpr(Type,
10075                                                    E->getLParenLoc(),
10076                                                    SubExpr.get(),
10077                                                    E->getRParenLoc(),
10078                                                    E->isListInitialization());
10079 }
10080 
10081 template<typename Derived>
10082 ExprResult
TransformCXXTypeidExpr(CXXTypeidExpr * E)10083 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
10084   if (E->isTypeOperand()) {
10085     TypeSourceInfo *TInfo
10086       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10087     if (!TInfo)
10088       return ExprError();
10089 
10090     if (!getDerived().AlwaysRebuild() &&
10091         TInfo == E->getTypeOperandSourceInfo())
10092       return E;
10093 
10094     return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10095                                              TInfo, E->getEndLoc());
10096   }
10097 
10098   // We don't know whether the subexpression is potentially evaluated until
10099   // after we perform semantic analysis.  We speculatively assume it is
10100   // unevaluated; it will get fixed later if the subexpression is in fact
10101   // potentially evaluated.
10102   EnterExpressionEvaluationContext Unevaluated(
10103       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
10104       Sema::ReuseLambdaContextDecl);
10105 
10106   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10107   if (SubExpr.isInvalid())
10108     return ExprError();
10109 
10110   if (!getDerived().AlwaysRebuild() &&
10111       SubExpr.get() == E->getExprOperand())
10112     return E;
10113 
10114   return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
10115                                            SubExpr.get(), E->getEndLoc());
10116 }
10117 
10118 template<typename Derived>
10119 ExprResult
TransformCXXUuidofExpr(CXXUuidofExpr * E)10120 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
10121   if (E->isTypeOperand()) {
10122     TypeSourceInfo *TInfo
10123       = getDerived().TransformType(E->getTypeOperandSourceInfo());
10124     if (!TInfo)
10125       return ExprError();
10126 
10127     if (!getDerived().AlwaysRebuild() &&
10128         TInfo == E->getTypeOperandSourceInfo())
10129       return E;
10130 
10131     return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10132                                              TInfo, E->getEndLoc());
10133   }
10134 
10135   EnterExpressionEvaluationContext Unevaluated(
10136       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10137 
10138   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
10139   if (SubExpr.isInvalid())
10140     return ExprError();
10141 
10142   if (!getDerived().AlwaysRebuild() &&
10143       SubExpr.get() == E->getExprOperand())
10144     return E;
10145 
10146   return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
10147                                            SubExpr.get(), E->getEndLoc());
10148 }
10149 
10150 template<typename Derived>
10151 ExprResult
TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr * E)10152 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
10153   return E;
10154 }
10155 
10156 template<typename Derived>
10157 ExprResult
TransformCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr * E)10158 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
10159                                                      CXXNullPtrLiteralExpr *E) {
10160   return E;
10161 }
10162 
10163 template<typename Derived>
10164 ExprResult
TransformCXXThisExpr(CXXThisExpr * E)10165 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
10166   QualType T = getSema().getCurrentThisType();
10167 
10168   if (!getDerived().AlwaysRebuild() && T == E->getType()) {
10169     // Make sure that we capture 'this'.
10170     getSema().CheckCXXThisCapture(E->getBeginLoc());
10171     return E;
10172   }
10173 
10174   return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
10175 }
10176 
10177 template<typename Derived>
10178 ExprResult
TransformCXXThrowExpr(CXXThrowExpr * E)10179 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
10180   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10181   if (SubExpr.isInvalid())
10182     return ExprError();
10183 
10184   if (!getDerived().AlwaysRebuild() &&
10185       SubExpr.get() == E->getSubExpr())
10186     return E;
10187 
10188   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
10189                                           E->isThrownVariableInScope());
10190 }
10191 
10192 template<typename Derived>
10193 ExprResult
TransformCXXDefaultArgExpr(CXXDefaultArgExpr * E)10194 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10195   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
10196       getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
10197   if (!Param)
10198     return ExprError();
10199 
10200   if (!getDerived().AlwaysRebuild() &&
10201       Param == E->getParam())
10202     return E;
10203 
10204   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
10205 }
10206 
10207 template<typename Derived>
10208 ExprResult
TransformCXXDefaultInitExpr(CXXDefaultInitExpr * E)10209 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
10210   FieldDecl *Field = cast_or_null<FieldDecl>(
10211       getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
10212   if (!Field)
10213     return ExprError();
10214 
10215   if (!getDerived().AlwaysRebuild() && Field == E->getField())
10216     return E;
10217 
10218   return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
10219 }
10220 
10221 template<typename Derived>
10222 ExprResult
TransformCXXScalarValueInitExpr(CXXScalarValueInitExpr * E)10223 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
10224                                                     CXXScalarValueInitExpr *E) {
10225   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
10226   if (!T)
10227     return ExprError();
10228 
10229   if (!getDerived().AlwaysRebuild() &&
10230       T == E->getTypeSourceInfo())
10231     return E;
10232 
10233   return getDerived().RebuildCXXScalarValueInitExpr(T,
10234                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
10235                                                     E->getRParenLoc());
10236 }
10237 
10238 template<typename Derived>
10239 ExprResult
TransformCXXNewExpr(CXXNewExpr * E)10240 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
10241   // Transform the type that we're allocating
10242   TypeSourceInfo *AllocTypeInfo =
10243       getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
10244   if (!AllocTypeInfo)
10245     return ExprError();
10246 
10247   // Transform the size of the array we're allocating (if any).
10248   ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
10249   if (ArraySize.isInvalid())
10250     return ExprError();
10251 
10252   // Transform the placement arguments (if any).
10253   bool ArgumentChanged = false;
10254   SmallVector<Expr*, 8> PlacementArgs;
10255   if (getDerived().TransformExprs(E->getPlacementArgs(),
10256                                   E->getNumPlacementArgs(), true,
10257                                   PlacementArgs, &ArgumentChanged))
10258     return ExprError();
10259 
10260   // Transform the initializer (if any).
10261   Expr *OldInit = E->getInitializer();
10262   ExprResult NewInit;
10263   if (OldInit)
10264     NewInit = getDerived().TransformInitializer(OldInit, true);
10265   if (NewInit.isInvalid())
10266     return ExprError();
10267 
10268   // Transform new operator and delete operator.
10269   FunctionDecl *OperatorNew = nullptr;
10270   if (E->getOperatorNew()) {
10271     OperatorNew = cast_or_null<FunctionDecl>(
10272         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
10273     if (!OperatorNew)
10274       return ExprError();
10275   }
10276 
10277   FunctionDecl *OperatorDelete = nullptr;
10278   if (E->getOperatorDelete()) {
10279     OperatorDelete = cast_or_null<FunctionDecl>(
10280         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10281     if (!OperatorDelete)
10282       return ExprError();
10283   }
10284 
10285   if (!getDerived().AlwaysRebuild() &&
10286       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
10287       ArraySize.get() == E->getArraySize() &&
10288       NewInit.get() == OldInit &&
10289       OperatorNew == E->getOperatorNew() &&
10290       OperatorDelete == E->getOperatorDelete() &&
10291       !ArgumentChanged) {
10292     // Mark any declarations we need as referenced.
10293     // FIXME: instantiation-specific.
10294     if (OperatorNew)
10295       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
10296     if (OperatorDelete)
10297       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10298 
10299     if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
10300       QualType ElementType
10301         = SemaRef.Context.getBaseElementType(E->getAllocatedType());
10302       if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
10303         CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
10304         if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
10305           SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
10306         }
10307       }
10308     }
10309 
10310     return E;
10311   }
10312 
10313   QualType AllocType = AllocTypeInfo->getType();
10314   if (!ArraySize.get()) {
10315     // If no array size was specified, but the new expression was
10316     // instantiated with an array type (e.g., "new T" where T is
10317     // instantiated with "int[4]"), extract the outer bound from the
10318     // array type as our array size. We do this with constant and
10319     // dependently-sized array types.
10320     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
10321     if (!ArrayT) {
10322       // Do nothing
10323     } else if (const ConstantArrayType *ConsArrayT
10324                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
10325       ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
10326                                          SemaRef.Context.getSizeType(),
10327                                          /*FIXME:*/ E->getBeginLoc());
10328       AllocType = ConsArrayT->getElementType();
10329     } else if (const DependentSizedArrayType *DepArrayT
10330                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
10331       if (DepArrayT->getSizeExpr()) {
10332         ArraySize = DepArrayT->getSizeExpr();
10333         AllocType = DepArrayT->getElementType();
10334       }
10335     }
10336   }
10337 
10338   return getDerived().RebuildCXXNewExpr(
10339       E->getBeginLoc(), E->isGlobalNew(),
10340       /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
10341       /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
10342       AllocTypeInfo, ArraySize.get(), E->getDirectInitRange(), NewInit.get());
10343 }
10344 
10345 template<typename Derived>
10346 ExprResult
TransformCXXDeleteExpr(CXXDeleteExpr * E)10347 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
10348   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
10349   if (Operand.isInvalid())
10350     return ExprError();
10351 
10352   // Transform the delete operator, if known.
10353   FunctionDecl *OperatorDelete = nullptr;
10354   if (E->getOperatorDelete()) {
10355     OperatorDelete = cast_or_null<FunctionDecl>(
10356         getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
10357     if (!OperatorDelete)
10358       return ExprError();
10359   }
10360 
10361   if (!getDerived().AlwaysRebuild() &&
10362       Operand.get() == E->getArgument() &&
10363       OperatorDelete == E->getOperatorDelete()) {
10364     // Mark any declarations we need as referenced.
10365     // FIXME: instantiation-specific.
10366     if (OperatorDelete)
10367       SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
10368 
10369     if (!E->getArgument()->isTypeDependent()) {
10370       QualType Destroyed = SemaRef.Context.getBaseElementType(
10371                                                          E->getDestroyedType());
10372       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10373         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
10374         SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
10375                                        SemaRef.LookupDestructor(Record));
10376       }
10377     }
10378 
10379     return E;
10380   }
10381 
10382   return getDerived().RebuildCXXDeleteExpr(
10383       E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
10384 }
10385 
10386 template<typename Derived>
10387 ExprResult
TransformCXXPseudoDestructorExpr(CXXPseudoDestructorExpr * E)10388 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
10389                                                      CXXPseudoDestructorExpr *E) {
10390   ExprResult Base = getDerived().TransformExpr(E->getBase());
10391   if (Base.isInvalid())
10392     return ExprError();
10393 
10394   ParsedType ObjectTypePtr;
10395   bool MayBePseudoDestructor = false;
10396   Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
10397                                               E->getOperatorLoc(),
10398                                         E->isArrow()? tok::arrow : tok::period,
10399                                               ObjectTypePtr,
10400                                               MayBePseudoDestructor);
10401   if (Base.isInvalid())
10402     return ExprError();
10403 
10404   QualType ObjectType = ObjectTypePtr.get();
10405   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
10406   if (QualifierLoc) {
10407     QualifierLoc
10408       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
10409     if (!QualifierLoc)
10410       return ExprError();
10411   }
10412   CXXScopeSpec SS;
10413   SS.Adopt(QualifierLoc);
10414 
10415   PseudoDestructorTypeStorage Destroyed;
10416   if (E->getDestroyedTypeInfo()) {
10417     TypeSourceInfo *DestroyedTypeInfo
10418       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
10419                                                 ObjectType, nullptr, SS);
10420     if (!DestroyedTypeInfo)
10421       return ExprError();
10422     Destroyed = DestroyedTypeInfo;
10423   } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
10424     // We aren't likely to be able to resolve the identifier down to a type
10425     // now anyway, so just retain the identifier.
10426     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
10427                                             E->getDestroyedTypeLoc());
10428   } else {
10429     // Look for a destructor known with the given name.
10430     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
10431                                               *E->getDestroyedTypeIdentifier(),
10432                                                 E->getDestroyedTypeLoc(),
10433                                                 /*Scope=*/nullptr,
10434                                                 SS, ObjectTypePtr,
10435                                                 false);
10436     if (!T)
10437       return ExprError();
10438 
10439     Destroyed
10440       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
10441                                                  E->getDestroyedTypeLoc());
10442   }
10443 
10444   TypeSourceInfo *ScopeTypeInfo = nullptr;
10445   if (E->getScopeTypeInfo()) {
10446     CXXScopeSpec EmptySS;
10447     ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
10448                       E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
10449     if (!ScopeTypeInfo)
10450       return ExprError();
10451   }
10452 
10453   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
10454                                                      E->getOperatorLoc(),
10455                                                      E->isArrow(),
10456                                                      SS,
10457                                                      ScopeTypeInfo,
10458                                                      E->getColonColonLoc(),
10459                                                      E->getTildeLoc(),
10460                                                      Destroyed);
10461 }
10462 
10463 template <typename Derived>
TransformOverloadExprDecls(OverloadExpr * Old,bool RequiresADL,LookupResult & R)10464 bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
10465                                                         bool RequiresADL,
10466                                                         LookupResult &R) {
10467   // Transform all the decls.
10468   bool AllEmptyPacks = true;
10469   for (auto *OldD : Old->decls()) {
10470     Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
10471     if (!InstD) {
10472       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
10473       // This can happen because of dependent hiding.
10474       if (isa<UsingShadowDecl>(OldD))
10475         continue;
10476       else {
10477         R.clear();
10478         return true;
10479       }
10480     }
10481 
10482     // Expand using pack declarations.
10483     NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
10484     ArrayRef<NamedDecl*> Decls = SingleDecl;
10485     if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
10486       Decls = UPD->expansions();
10487 
10488     // Expand using declarations.
10489     for (auto *D : Decls) {
10490       if (auto *UD = dyn_cast<UsingDecl>(D)) {
10491         for (auto *SD : UD->shadows())
10492           R.addDecl(SD);
10493       } else {
10494         R.addDecl(D);
10495       }
10496     }
10497 
10498     AllEmptyPacks &= Decls.empty();
10499   };
10500 
10501   // C++ [temp.res]/8.4.2:
10502   //   The program is ill-formed, no diagnostic required, if [...] lookup for
10503   //   a name in the template definition found a using-declaration, but the
10504   //   lookup in the corresponding scope in the instantiation odoes not find
10505   //   any declarations because the using-declaration was a pack expansion and
10506   //   the corresponding pack is empty
10507   if (AllEmptyPacks && !RequiresADL) {
10508     getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
10509         << isa<UnresolvedMemberExpr>(Old) << Old->getName();
10510     return true;
10511   }
10512 
10513   // Resolve a kind, but don't do any further analysis.  If it's
10514   // ambiguous, the callee needs to deal with it.
10515   R.resolveKind();
10516   return false;
10517 }
10518 
10519 template<typename Derived>
10520 ExprResult
TransformUnresolvedLookupExpr(UnresolvedLookupExpr * Old)10521 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
10522                                                   UnresolvedLookupExpr *Old) {
10523   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
10524                  Sema::LookupOrdinaryName);
10525 
10526   // Transform the declaration set.
10527   if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
10528     return ExprError();
10529 
10530   // Rebuild the nested-name qualifier, if present.
10531   CXXScopeSpec SS;
10532   if (Old->getQualifierLoc()) {
10533     NestedNameSpecifierLoc QualifierLoc
10534       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
10535     if (!QualifierLoc)
10536       return ExprError();
10537 
10538     SS.Adopt(QualifierLoc);
10539   }
10540 
10541   if (Old->getNamingClass()) {
10542     CXXRecordDecl *NamingClass
10543       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
10544                                                             Old->getNameLoc(),
10545                                                         Old->getNamingClass()));
10546     if (!NamingClass) {
10547       R.clear();
10548       return ExprError();
10549     }
10550 
10551     R.setNamingClass(NamingClass);
10552   }
10553 
10554   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
10555 
10556   // If we have neither explicit template arguments, nor the template keyword,
10557   // it's a normal declaration name or member reference.
10558   if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
10559     NamedDecl *D = R.getAsSingle<NamedDecl>();
10560     // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
10561     // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
10562     // give a good diagnostic.
10563     if (D && D->isCXXInstanceMember()) {
10564       return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10565                                                      /*TemplateArgs=*/nullptr,
10566                                                      /*Scope=*/nullptr);
10567     }
10568 
10569     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
10570   }
10571 
10572   // If we have template arguments, rebuild them, then rebuild the
10573   // templateid expression.
10574   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
10575   if (Old->hasExplicitTemplateArgs() &&
10576       getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
10577                                               Old->getNumTemplateArgs(),
10578                                               TransArgs)) {
10579     R.clear();
10580     return ExprError();
10581   }
10582 
10583   return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
10584                                             Old->requiresADL(), &TransArgs);
10585 }
10586 
10587 template<typename Derived>
10588 ExprResult
TransformTypeTraitExpr(TypeTraitExpr * E)10589 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
10590   bool ArgChanged = false;
10591   SmallVector<TypeSourceInfo *, 4> Args;
10592   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
10593     TypeSourceInfo *From = E->getArg(I);
10594     TypeLoc FromTL = From->getTypeLoc();
10595     if (!FromTL.getAs<PackExpansionTypeLoc>()) {
10596       TypeLocBuilder TLB;
10597       TLB.reserve(FromTL.getFullDataSize());
10598       QualType To = getDerived().TransformType(TLB, FromTL);
10599       if (To.isNull())
10600         return ExprError();
10601 
10602       if (To == From->getType())
10603         Args.push_back(From);
10604       else {
10605         Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10606         ArgChanged = true;
10607       }
10608       continue;
10609     }
10610 
10611     ArgChanged = true;
10612 
10613     // We have a pack expansion. Instantiate it.
10614     PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
10615     TypeLoc PatternTL = ExpansionTL.getPatternLoc();
10616     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
10617     SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
10618 
10619     // Determine whether the set of unexpanded parameter packs can and should
10620     // be expanded.
10621     bool Expand = true;
10622     bool RetainExpansion = false;
10623     Optional<unsigned> OrigNumExpansions =
10624         ExpansionTL.getTypePtr()->getNumExpansions();
10625     Optional<unsigned> NumExpansions = OrigNumExpansions;
10626     if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
10627                                              PatternTL.getSourceRange(),
10628                                              Unexpanded,
10629                                              Expand, RetainExpansion,
10630                                              NumExpansions))
10631       return ExprError();
10632 
10633     if (!Expand) {
10634       // The transform has determined that we should perform a simple
10635       // transformation on the pack expansion, producing another pack
10636       // expansion.
10637       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
10638 
10639       TypeLocBuilder TLB;
10640       TLB.reserve(From->getTypeLoc().getFullDataSize());
10641 
10642       QualType To = getDerived().TransformType(TLB, PatternTL);
10643       if (To.isNull())
10644         return ExprError();
10645 
10646       To = getDerived().RebuildPackExpansionType(To,
10647                                                  PatternTL.getSourceRange(),
10648                                                  ExpansionTL.getEllipsisLoc(),
10649                                                  NumExpansions);
10650       if (To.isNull())
10651         return ExprError();
10652 
10653       PackExpansionTypeLoc ToExpansionTL
10654         = TLB.push<PackExpansionTypeLoc>(To);
10655       ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10656       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10657       continue;
10658     }
10659 
10660     // Expand the pack expansion by substituting for each argument in the
10661     // pack(s).
10662     for (unsigned I = 0; I != *NumExpansions; ++I) {
10663       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
10664       TypeLocBuilder TLB;
10665       TLB.reserve(PatternTL.getFullDataSize());
10666       QualType To = getDerived().TransformType(TLB, PatternTL);
10667       if (To.isNull())
10668         return ExprError();
10669 
10670       if (To->containsUnexpandedParameterPack()) {
10671         To = getDerived().RebuildPackExpansionType(To,
10672                                                    PatternTL.getSourceRange(),
10673                                                    ExpansionTL.getEllipsisLoc(),
10674                                                    NumExpansions);
10675         if (To.isNull())
10676           return ExprError();
10677 
10678         PackExpansionTypeLoc ToExpansionTL
10679           = TLB.push<PackExpansionTypeLoc>(To);
10680         ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10681       }
10682 
10683       Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10684     }
10685 
10686     if (!RetainExpansion)
10687       continue;
10688 
10689     // If we're supposed to retain a pack expansion, do so by temporarily
10690     // forgetting the partially-substituted parameter pack.
10691     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
10692 
10693     TypeLocBuilder TLB;
10694     TLB.reserve(From->getTypeLoc().getFullDataSize());
10695 
10696     QualType To = getDerived().TransformType(TLB, PatternTL);
10697     if (To.isNull())
10698       return ExprError();
10699 
10700     To = getDerived().RebuildPackExpansionType(To,
10701                                                PatternTL.getSourceRange(),
10702                                                ExpansionTL.getEllipsisLoc(),
10703                                                NumExpansions);
10704     if (To.isNull())
10705       return ExprError();
10706 
10707     PackExpansionTypeLoc ToExpansionTL
10708       = TLB.push<PackExpansionTypeLoc>(To);
10709     ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
10710     Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
10711   }
10712 
10713   if (!getDerived().AlwaysRebuild() && !ArgChanged)
10714     return E;
10715 
10716   return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
10717                                        E->getEndLoc());
10718 }
10719 
10720 template<typename Derived>
10721 ExprResult
TransformArrayTypeTraitExpr(ArrayTypeTraitExpr * E)10722 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
10723   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
10724   if (!T)
10725     return ExprError();
10726 
10727   if (!getDerived().AlwaysRebuild() &&
10728       T == E->getQueriedTypeSourceInfo())
10729     return E;
10730 
10731   ExprResult SubExpr;
10732   {
10733     EnterExpressionEvaluationContext Unevaluated(
10734         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10735     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
10736     if (SubExpr.isInvalid())
10737       return ExprError();
10738 
10739     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
10740       return E;
10741   }
10742 
10743   return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
10744                                             SubExpr.get(), E->getEndLoc());
10745 }
10746 
10747 template<typename Derived>
10748 ExprResult
TransformExpressionTraitExpr(ExpressionTraitExpr * E)10749 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
10750   ExprResult SubExpr;
10751   {
10752     EnterExpressionEvaluationContext Unevaluated(
10753         SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
10754     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
10755     if (SubExpr.isInvalid())
10756       return ExprError();
10757 
10758     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
10759       return E;
10760   }
10761 
10762   return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
10763                                              SubExpr.get(), E->getEndLoc());
10764 }
10765 
10766 template <typename Derived>
TransformParenDependentScopeDeclRefExpr(ParenExpr * PE,DependentScopeDeclRefExpr * DRE,bool AddrTaken,TypeSourceInfo ** RecoveryTSI)10767 ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
10768     ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
10769     TypeSourceInfo **RecoveryTSI) {
10770   ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
10771       DRE, AddrTaken, RecoveryTSI);
10772 
10773   // Propagate both errors and recovered types, which return ExprEmpty.
10774   if (!NewDRE.isUsable())
10775     return NewDRE;
10776 
10777   // We got an expr, wrap it up in parens.
10778   if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
10779     return PE;
10780   return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
10781                                        PE->getRParen());
10782 }
10783 
10784 template <typename Derived>
TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr * E)10785 ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
10786     DependentScopeDeclRefExpr *E) {
10787   return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
10788                                             nullptr);
10789 }
10790 
10791 template<typename Derived>
10792 ExprResult
TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr * E,bool IsAddressOfOperand,TypeSourceInfo ** RecoveryTSI)10793 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
10794                                                DependentScopeDeclRefExpr *E,
10795                                                bool IsAddressOfOperand,
10796                                                TypeSourceInfo **RecoveryTSI) {
10797   assert(E->getQualifierLoc());
10798   NestedNameSpecifierLoc QualifierLoc
10799   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10800   if (!QualifierLoc)
10801     return ExprError();
10802   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
10803 
10804   // TODO: If this is a conversion-function-id, verify that the
10805   // destination type name (if present) resolves the same way after
10806   // instantiation as it did in the local scope.
10807 
10808   DeclarationNameInfo NameInfo
10809     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
10810   if (!NameInfo.getName())
10811     return ExprError();
10812 
10813   if (!E->hasExplicitTemplateArgs()) {
10814     if (!getDerived().AlwaysRebuild() &&
10815         QualifierLoc == E->getQualifierLoc() &&
10816         // Note: it is sufficient to compare the Name component of NameInfo:
10817         // if name has not changed, DNLoc has not changed either.
10818         NameInfo.getName() == E->getDeclName())
10819       return E;
10820 
10821     return getDerived().RebuildDependentScopeDeclRefExpr(
10822         QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
10823         IsAddressOfOperand, RecoveryTSI);
10824   }
10825 
10826   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
10827   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10828                                               E->getNumTemplateArgs(),
10829                                               TransArgs))
10830     return ExprError();
10831 
10832   return getDerived().RebuildDependentScopeDeclRefExpr(
10833       QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
10834       RecoveryTSI);
10835 }
10836 
10837 template<typename Derived>
10838 ExprResult
TransformCXXConstructExpr(CXXConstructExpr * E)10839 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
10840   // CXXConstructExprs other than for list-initialization and
10841   // CXXTemporaryObjectExpr are always implicit, so when we have
10842   // a 1-argument construction we just transform that argument.
10843   if ((E->getNumArgs() == 1 ||
10844        (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
10845       (!getDerived().DropCallArgument(E->getArg(0))) &&
10846       !E->isListInitialization())
10847     return getDerived().TransformExpr(E->getArg(0));
10848 
10849   TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
10850 
10851   QualType T = getDerived().TransformType(E->getType());
10852   if (T.isNull())
10853     return ExprError();
10854 
10855   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
10856       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
10857   if (!Constructor)
10858     return ExprError();
10859 
10860   bool ArgumentChanged = false;
10861   SmallVector<Expr*, 8> Args;
10862   {
10863     EnterExpressionEvaluationContext Context(
10864         getSema(), EnterExpressionEvaluationContext::InitList,
10865         E->isListInitialization());
10866     if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10867                                     &ArgumentChanged))
10868       return ExprError();
10869   }
10870 
10871   if (!getDerived().AlwaysRebuild() &&
10872       T == E->getType() &&
10873       Constructor == E->getConstructor() &&
10874       !ArgumentChanged) {
10875     // Mark the constructor as referenced.
10876     // FIXME: Instantiation-specific
10877     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
10878     return E;
10879   }
10880 
10881   return getDerived().RebuildCXXConstructExpr(
10882       T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
10883       E->hadMultipleCandidates(), E->isListInitialization(),
10884       E->isStdInitListInitialization(), E->requiresZeroInitialization(),
10885       E->getConstructionKind(), E->getParenOrBraceRange());
10886 }
10887 
10888 template<typename Derived>
TransformCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr * E)10889 ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
10890     CXXInheritedCtorInitExpr *E) {
10891   QualType T = getDerived().TransformType(E->getType());
10892   if (T.isNull())
10893     return ExprError();
10894 
10895   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
10896       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
10897   if (!Constructor)
10898     return ExprError();
10899 
10900   if (!getDerived().AlwaysRebuild() &&
10901       T == E->getType() &&
10902       Constructor == E->getConstructor()) {
10903     // Mark the constructor as referenced.
10904     // FIXME: Instantiation-specific
10905     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
10906     return E;
10907   }
10908 
10909   return getDerived().RebuildCXXInheritedCtorInitExpr(
10910       T, E->getLocation(), Constructor,
10911       E->constructsVBase(), E->inheritedFromVBase());
10912 }
10913 
10914 /// Transform a C++ temporary-binding expression.
10915 ///
10916 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
10917 /// transform the subexpression and return that.
10918 template<typename Derived>
10919 ExprResult
TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr * E)10920 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
10921   return getDerived().TransformExpr(E->getSubExpr());
10922 }
10923 
10924 /// Transform a C++ expression that contains cleanups that should
10925 /// be run after the expression is evaluated.
10926 ///
10927 /// Since ExprWithCleanups nodes are implicitly generated, we
10928 /// just transform the subexpression and return that.
10929 template<typename Derived>
10930 ExprResult
TransformExprWithCleanups(ExprWithCleanups * E)10931 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
10932   return getDerived().TransformExpr(E->getSubExpr());
10933 }
10934 
10935 template<typename Derived>
10936 ExprResult
TransformCXXTemporaryObjectExpr(CXXTemporaryObjectExpr * E)10937 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
10938                                                     CXXTemporaryObjectExpr *E) {
10939   TypeSourceInfo *T =
10940       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
10941   if (!T)
10942     return ExprError();
10943 
10944   CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
10945       getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
10946   if (!Constructor)
10947     return ExprError();
10948 
10949   bool ArgumentChanged = false;
10950   SmallVector<Expr*, 8> Args;
10951   Args.reserve(E->getNumArgs());
10952   {
10953     EnterExpressionEvaluationContext Context(
10954         getSema(), EnterExpressionEvaluationContext::InitList,
10955         E->isListInitialization());
10956     if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
10957                        &ArgumentChanged))
10958       return ExprError();
10959   }
10960 
10961   if (!getDerived().AlwaysRebuild() &&
10962       T == E->getTypeSourceInfo() &&
10963       Constructor == E->getConstructor() &&
10964       !ArgumentChanged) {
10965     // FIXME: Instantiation-specific
10966     SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
10967     return SemaRef.MaybeBindToTemporary(E);
10968   }
10969 
10970   // FIXME: We should just pass E->isListInitialization(), but we're not
10971   // prepared to handle list-initialization without a child InitListExpr.
10972   SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
10973   return getDerived().RebuildCXXTemporaryObjectExpr(
10974       T, LParenLoc, Args, E->getEndLoc(),
10975       /*ListInitialization=*/LParenLoc.isInvalid());
10976 }
10977 
10978 template<typename Derived>
10979 ExprResult
TransformLambdaExpr(LambdaExpr * E)10980 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
10981   // Transform any init-capture expressions before entering the scope of the
10982   // lambda body, because they are not semantically within that scope.
10983   typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
10984   SmallVector<InitCaptureInfoTy, 8> InitCaptureExprsAndTypes;
10985   InitCaptureExprsAndTypes.resize(E->explicit_capture_end() -
10986                                   E->explicit_capture_begin());
10987   for (LambdaExpr::capture_iterator C = E->capture_begin(),
10988                                     CEnd = E->capture_end();
10989        C != CEnd; ++C) {
10990     if (!E->isInitCapture(C))
10991       continue;
10992     EnterExpressionEvaluationContext EEEC(
10993         getSema(), Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
10994     ExprResult NewExprInitResult = getDerived().TransformInitializer(
10995         C->getCapturedVar()->getInit(),
10996         C->getCapturedVar()->getInitStyle() == VarDecl::CallInit);
10997 
10998     if (NewExprInitResult.isInvalid())
10999       return ExprError();
11000     Expr *NewExprInit = NewExprInitResult.get();
11001 
11002     VarDecl *OldVD = C->getCapturedVar();
11003     QualType NewInitCaptureType =
11004         getSema().buildLambdaInitCaptureInitialization(
11005             C->getLocation(), OldVD->getType()->isReferenceType(),
11006             OldVD->getIdentifier(),
11007             C->getCapturedVar()->getInitStyle() != VarDecl::CInit, NewExprInit);
11008     NewExprInitResult = NewExprInit;
11009     InitCaptureExprsAndTypes[C - E->capture_begin()] =
11010         std::make_pair(NewExprInitResult, NewInitCaptureType);
11011   }
11012 
11013   // Transform the template parameters, and add them to the current
11014   // instantiation scope. The null case is handled correctly.
11015   auto TPL = getDerived().TransformTemplateParameterList(
11016       E->getTemplateParameterList());
11017 
11018   // Transform the type of the original lambda's call operator.
11019   // The transformation MUST be done in the CurrentInstantiationScope since
11020   // it introduces a mapping of the original to the newly created
11021   // transformed parameters.
11022   TypeSourceInfo *NewCallOpTSI = nullptr;
11023   {
11024     TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
11025     FunctionProtoTypeLoc OldCallOpFPTL =
11026         OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
11027 
11028     TypeLocBuilder NewCallOpTLBuilder;
11029     SmallVector<QualType, 4> ExceptionStorage;
11030     TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
11031     QualType NewCallOpType = TransformFunctionProtoType(
11032         NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
11033         [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
11034           return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
11035                                               ExceptionStorage, Changed);
11036         });
11037     if (NewCallOpType.isNull())
11038       return ExprError();
11039     NewCallOpTSI = NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context,
11040                                                         NewCallOpType);
11041   }
11042 
11043   LambdaScopeInfo *LSI = getSema().PushLambdaScope();
11044   Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
11045   LSI->GLTemplateParameterList = TPL;
11046 
11047   // Create the local class that will describe the lambda.
11048   CXXRecordDecl *Class
11049     = getSema().createLambdaClosureType(E->getIntroducerRange(),
11050                                         NewCallOpTSI,
11051                                         /*KnownDependent=*/false,
11052                                         E->getCaptureDefault());
11053   getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
11054 
11055   // Build the call operator.
11056   CXXMethodDecl *NewCallOperator = getSema().startLambdaDefinition(
11057       Class, E->getIntroducerRange(), NewCallOpTSI,
11058       E->getCallOperator()->getEndLoc(),
11059       NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
11060       E->getCallOperator()->isConstexpr());
11061 
11062   LSI->CallOperator = NewCallOperator;
11063 
11064   for (unsigned I = 0, NumParams = NewCallOperator->getNumParams();
11065        I != NumParams; ++I) {
11066     auto *P = NewCallOperator->getParamDecl(I);
11067     if (P->hasUninstantiatedDefaultArg()) {
11068       EnterExpressionEvaluationContext Eval(
11069           getSema(),
11070           Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed, P);
11071       ExprResult R = getDerived().TransformExpr(
11072           E->getCallOperator()->getParamDecl(I)->getDefaultArg());
11073       P->setDefaultArg(R.get());
11074     }
11075   }
11076 
11077   getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
11078   getDerived().transformedLocalDecl(E->getCallOperator(), NewCallOperator);
11079 
11080   // Introduce the context of the call operator.
11081   Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
11082                                  /*NewThisContext*/false);
11083 
11084   // Enter the scope of the lambda.
11085   getSema().buildLambdaScope(LSI, NewCallOperator,
11086                              E->getIntroducerRange(),
11087                              E->getCaptureDefault(),
11088                              E->getCaptureDefaultLoc(),
11089                              E->hasExplicitParameters(),
11090                              E->hasExplicitResultType(),
11091                              E->isMutable());
11092 
11093   bool Invalid = false;
11094 
11095   // Transform captures.
11096   bool FinishedExplicitCaptures = false;
11097   for (LambdaExpr::capture_iterator C = E->capture_begin(),
11098                                  CEnd = E->capture_end();
11099        C != CEnd; ++C) {
11100     // When we hit the first implicit capture, tell Sema that we've finished
11101     // the list of explicit captures.
11102     if (!FinishedExplicitCaptures && C->isImplicit()) {
11103       getSema().finishLambdaExplicitCaptures(LSI);
11104       FinishedExplicitCaptures = true;
11105     }
11106 
11107     // Capturing 'this' is trivial.
11108     if (C->capturesThis()) {
11109       getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
11110                                     /*BuildAndDiagnose*/ true, nullptr,
11111                                     C->getCaptureKind() == LCK_StarThis);
11112       continue;
11113     }
11114     // Captured expression will be recaptured during captured variables
11115     // rebuilding.
11116     if (C->capturesVLAType())
11117       continue;
11118 
11119     // Rebuild init-captures, including the implied field declaration.
11120     if (E->isInitCapture(C)) {
11121       InitCaptureInfoTy InitExprTypePair =
11122           InitCaptureExprsAndTypes[C - E->capture_begin()];
11123       ExprResult Init = InitExprTypePair.first;
11124       QualType InitQualType = InitExprTypePair.second;
11125       if (Init.isInvalid() || InitQualType.isNull()) {
11126         Invalid = true;
11127         continue;
11128       }
11129       VarDecl *OldVD = C->getCapturedVar();
11130       VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
11131           OldVD->getLocation(), InitExprTypePair.second, OldVD->getIdentifier(),
11132           OldVD->getInitStyle(), Init.get());
11133       if (!NewVD)
11134         Invalid = true;
11135       else {
11136         getDerived().transformedLocalDecl(OldVD, NewVD);
11137       }
11138       getSema().buildInitCaptureField(LSI, NewVD);
11139       continue;
11140     }
11141 
11142     assert(C->capturesVariable() && "unexpected kind of lambda capture");
11143 
11144     // Determine the capture kind for Sema.
11145     Sema::TryCaptureKind Kind
11146       = C->isImplicit()? Sema::TryCapture_Implicit
11147                        : C->getCaptureKind() == LCK_ByCopy
11148                            ? Sema::TryCapture_ExplicitByVal
11149                            : Sema::TryCapture_ExplicitByRef;
11150     SourceLocation EllipsisLoc;
11151     if (C->isPackExpansion()) {
11152       UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
11153       bool ShouldExpand = false;
11154       bool RetainExpansion = false;
11155       Optional<unsigned> NumExpansions;
11156       if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
11157                                                C->getLocation(),
11158                                                Unexpanded,
11159                                                ShouldExpand, RetainExpansion,
11160                                                NumExpansions)) {
11161         Invalid = true;
11162         continue;
11163       }
11164 
11165       if (ShouldExpand) {
11166         // The transform has determined that we should perform an expansion;
11167         // transform and capture each of the arguments.
11168         // expansion of the pattern. Do so.
11169         VarDecl *Pack = C->getCapturedVar();
11170         for (unsigned I = 0; I != *NumExpansions; ++I) {
11171           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11172           VarDecl *CapturedVar
11173             = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11174                                                                Pack));
11175           if (!CapturedVar) {
11176             Invalid = true;
11177             continue;
11178           }
11179 
11180           // Capture the transformed variable.
11181           getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
11182         }
11183 
11184         // FIXME: Retain a pack expansion if RetainExpansion is true.
11185 
11186         continue;
11187       }
11188 
11189       EllipsisLoc = C->getEllipsisLoc();
11190     }
11191 
11192     // Transform the captured variable.
11193     VarDecl *CapturedVar
11194       = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
11195                                                          C->getCapturedVar()));
11196     if (!CapturedVar || CapturedVar->isInvalidDecl()) {
11197       Invalid = true;
11198       continue;
11199     }
11200 
11201     // Capture the transformed variable.
11202     getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
11203                                  EllipsisLoc);
11204   }
11205   if (!FinishedExplicitCaptures)
11206     getSema().finishLambdaExplicitCaptures(LSI);
11207 
11208   // Enter a new evaluation context to insulate the lambda from any
11209   // cleanups from the enclosing full-expression.
11210   getSema().PushExpressionEvaluationContext(
11211       Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
11212 
11213   // Instantiate the body of the lambda expression.
11214   StmtResult Body =
11215       Invalid ? StmtError() : getDerived().TransformStmt(E->getBody());
11216 
11217   // ActOnLambda* will pop the function scope for us.
11218   FuncScopeCleanup.disable();
11219 
11220   if (Body.isInvalid()) {
11221     SavedContext.pop();
11222     getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
11223                                /*IsInstantiation=*/true);
11224     return ExprError();
11225   }
11226 
11227   // Copy the LSI before ActOnFinishFunctionBody removes it.
11228   // FIXME: This is dumb. Store the lambda information somewhere that outlives
11229   // the call operator.
11230   auto LSICopy = *LSI;
11231   getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
11232                                     /*IsInstantiation*/ true);
11233   SavedContext.pop();
11234 
11235   return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
11236                                    &LSICopy);
11237 }
11238 
11239 template<typename Derived>
11240 ExprResult
TransformCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr * E)11241 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
11242                                                   CXXUnresolvedConstructExpr *E) {
11243   TypeSourceInfo *T =
11244       getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
11245   if (!T)
11246     return ExprError();
11247 
11248   bool ArgumentChanged = false;
11249   SmallVector<Expr*, 8> Args;
11250   Args.reserve(E->arg_size());
11251   {
11252     EnterExpressionEvaluationContext Context(
11253         getSema(), EnterExpressionEvaluationContext::InitList,
11254         E->isListInitialization());
11255     if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
11256                                     &ArgumentChanged))
11257       return ExprError();
11258   }
11259 
11260   if (!getDerived().AlwaysRebuild() &&
11261       T == E->getTypeSourceInfo() &&
11262       !ArgumentChanged)
11263     return E;
11264 
11265   // FIXME: we're faking the locations of the commas
11266   return getDerived().RebuildCXXUnresolvedConstructExpr(
11267       T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
11268 }
11269 
11270 template<typename Derived>
11271 ExprResult
TransformCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr * E)11272 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
11273                                              CXXDependentScopeMemberExpr *E) {
11274   // Transform the base of the expression.
11275   ExprResult Base((Expr*) nullptr);
11276   Expr *OldBase;
11277   QualType BaseType;
11278   QualType ObjectType;
11279   if (!E->isImplicitAccess()) {
11280     OldBase = E->getBase();
11281     Base = getDerived().TransformExpr(OldBase);
11282     if (Base.isInvalid())
11283       return ExprError();
11284 
11285     // Start the member reference and compute the object's type.
11286     ParsedType ObjectTy;
11287     bool MayBePseudoDestructor = false;
11288     Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
11289                                                 E->getOperatorLoc(),
11290                                       E->isArrow()? tok::arrow : tok::period,
11291                                                 ObjectTy,
11292                                                 MayBePseudoDestructor);
11293     if (Base.isInvalid())
11294       return ExprError();
11295 
11296     ObjectType = ObjectTy.get();
11297     BaseType = ((Expr*) Base.get())->getType();
11298   } else {
11299     OldBase = nullptr;
11300     BaseType = getDerived().TransformType(E->getBaseType());
11301     ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
11302   }
11303 
11304   // Transform the first part of the nested-name-specifier that qualifies
11305   // the member name.
11306   NamedDecl *FirstQualifierInScope
11307     = getDerived().TransformFirstQualifierInScope(
11308                                             E->getFirstQualifierFoundInScope(),
11309                                             E->getQualifierLoc().getBeginLoc());
11310 
11311   NestedNameSpecifierLoc QualifierLoc;
11312   if (E->getQualifier()) {
11313     QualifierLoc
11314       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
11315                                                      ObjectType,
11316                                                      FirstQualifierInScope);
11317     if (!QualifierLoc)
11318       return ExprError();
11319   }
11320 
11321   SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11322 
11323   // TODO: If this is a conversion-function-id, verify that the
11324   // destination type name (if present) resolves the same way after
11325   // instantiation as it did in the local scope.
11326 
11327   DeclarationNameInfo NameInfo
11328     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
11329   if (!NameInfo.getName())
11330     return ExprError();
11331 
11332   if (!E->hasExplicitTemplateArgs()) {
11333     // This is a reference to a member without an explicitly-specified
11334     // template argument list. Optimize for this common case.
11335     if (!getDerived().AlwaysRebuild() &&
11336         Base.get() == OldBase &&
11337         BaseType == E->getBaseType() &&
11338         QualifierLoc == E->getQualifierLoc() &&
11339         NameInfo.getName() == E->getMember() &&
11340         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
11341       return E;
11342 
11343     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11344                                                        BaseType,
11345                                                        E->isArrow(),
11346                                                        E->getOperatorLoc(),
11347                                                        QualifierLoc,
11348                                                        TemplateKWLoc,
11349                                                        FirstQualifierInScope,
11350                                                        NameInfo,
11351                                                        /*TemplateArgs*/nullptr);
11352   }
11353 
11354   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
11355   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11356                                               E->getNumTemplateArgs(),
11357                                               TransArgs))
11358     return ExprError();
11359 
11360   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
11361                                                      BaseType,
11362                                                      E->isArrow(),
11363                                                      E->getOperatorLoc(),
11364                                                      QualifierLoc,
11365                                                      TemplateKWLoc,
11366                                                      FirstQualifierInScope,
11367                                                      NameInfo,
11368                                                      &TransArgs);
11369 }
11370 
11371 template<typename Derived>
11372 ExprResult
TransformUnresolvedMemberExpr(UnresolvedMemberExpr * Old)11373 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
11374   // Transform the base of the expression.
11375   ExprResult Base((Expr*) nullptr);
11376   QualType BaseType;
11377   if (!Old->isImplicitAccess()) {
11378     Base = getDerived().TransformExpr(Old->getBase());
11379     if (Base.isInvalid())
11380       return ExprError();
11381     Base = getSema().PerformMemberExprBaseConversion(Base.get(),
11382                                                      Old->isArrow());
11383     if (Base.isInvalid())
11384       return ExprError();
11385     BaseType = Base.get()->getType();
11386   } else {
11387     BaseType = getDerived().TransformType(Old->getBaseType());
11388   }
11389 
11390   NestedNameSpecifierLoc QualifierLoc;
11391   if (Old->getQualifierLoc()) {
11392     QualifierLoc
11393     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
11394     if (!QualifierLoc)
11395       return ExprError();
11396   }
11397 
11398   SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
11399 
11400   LookupResult R(SemaRef, Old->getMemberNameInfo(),
11401                  Sema::LookupOrdinaryName);
11402 
11403   // Transform the declaration set.
11404   if (TransformOverloadExprDecls(Old, /*RequiresADL*/false, R))
11405     return ExprError();
11406 
11407   // Determine the naming class.
11408   if (Old->getNamingClass()) {
11409     CXXRecordDecl *NamingClass
11410       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
11411                                                           Old->getMemberLoc(),
11412                                                         Old->getNamingClass()));
11413     if (!NamingClass)
11414       return ExprError();
11415 
11416     R.setNamingClass(NamingClass);
11417   }
11418 
11419   TemplateArgumentListInfo TransArgs;
11420   if (Old->hasExplicitTemplateArgs()) {
11421     TransArgs.setLAngleLoc(Old->getLAngleLoc());
11422     TransArgs.setRAngleLoc(Old->getRAngleLoc());
11423     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
11424                                                 Old->getNumTemplateArgs(),
11425                                                 TransArgs))
11426       return ExprError();
11427   }
11428 
11429   // FIXME: to do this check properly, we will need to preserve the
11430   // first-qualifier-in-scope here, just in case we had a dependent
11431   // base (and therefore couldn't do the check) and a
11432   // nested-name-qualifier (and therefore could do the lookup).
11433   NamedDecl *FirstQualifierInScope = nullptr;
11434 
11435   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
11436                                                   BaseType,
11437                                                   Old->getOperatorLoc(),
11438                                                   Old->isArrow(),
11439                                                   QualifierLoc,
11440                                                   TemplateKWLoc,
11441                                                   FirstQualifierInScope,
11442                                                   R,
11443                                               (Old->hasExplicitTemplateArgs()
11444                                                   ? &TransArgs : nullptr));
11445 }
11446 
11447 template<typename Derived>
11448 ExprResult
TransformCXXNoexceptExpr(CXXNoexceptExpr * E)11449 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
11450   EnterExpressionEvaluationContext Unevaluated(
11451       SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
11452   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
11453   if (SubExpr.isInvalid())
11454     return ExprError();
11455 
11456   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
11457     return E;
11458 
11459   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
11460 }
11461 
11462 template<typename Derived>
11463 ExprResult
TransformPackExpansionExpr(PackExpansionExpr * E)11464 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
11465   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
11466   if (Pattern.isInvalid())
11467     return ExprError();
11468 
11469   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
11470     return E;
11471 
11472   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
11473                                            E->getNumExpansions());
11474 }
11475 
11476 template<typename Derived>
11477 ExprResult
TransformSizeOfPackExpr(SizeOfPackExpr * E)11478 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
11479   // If E is not value-dependent, then nothing will change when we transform it.
11480   // Note: This is an instantiation-centric view.
11481   if (!E->isValueDependent())
11482     return E;
11483 
11484   EnterExpressionEvaluationContext Unevaluated(
11485       getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
11486 
11487   ArrayRef<TemplateArgument> PackArgs;
11488   TemplateArgument ArgStorage;
11489 
11490   // Find the argument list to transform.
11491   if (E->isPartiallySubstituted()) {
11492     PackArgs = E->getPartialArguments();
11493   } else if (E->isValueDependent()) {
11494     UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
11495     bool ShouldExpand = false;
11496     bool RetainExpansion = false;
11497     Optional<unsigned> NumExpansions;
11498     if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
11499                                              Unexpanded,
11500                                              ShouldExpand, RetainExpansion,
11501                                              NumExpansions))
11502       return ExprError();
11503 
11504     // If we need to expand the pack, build a template argument from it and
11505     // expand that.
11506     if (ShouldExpand) {
11507       auto *Pack = E->getPack();
11508       if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
11509         ArgStorage = getSema().Context.getPackExpansionType(
11510             getSema().Context.getTypeDeclType(TTPD), None);
11511       } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
11512         ArgStorage = TemplateArgument(TemplateName(TTPD), None);
11513       } else {
11514         auto *VD = cast<ValueDecl>(Pack);
11515         ExprResult DRE = getSema().BuildDeclRefExpr(
11516             VD, VD->getType().getNonLValueExprType(getSema().Context),
11517             VD->getType()->isReferenceType() ? VK_LValue : VK_RValue,
11518             E->getPackLoc());
11519         if (DRE.isInvalid())
11520           return ExprError();
11521         ArgStorage = new (getSema().Context) PackExpansionExpr(
11522             getSema().Context.DependentTy, DRE.get(), E->getPackLoc(), None);
11523       }
11524       PackArgs = ArgStorage;
11525     }
11526   }
11527 
11528   // If we're not expanding the pack, just transform the decl.
11529   if (!PackArgs.size()) {
11530     auto *Pack = cast_or_null<NamedDecl>(
11531         getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
11532     if (!Pack)
11533       return ExprError();
11534     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
11535                                               E->getPackLoc(),
11536                                               E->getRParenLoc(), None, None);
11537   }
11538 
11539   // Try to compute the result without performing a partial substitution.
11540   Optional<unsigned> Result = 0;
11541   for (const TemplateArgument &Arg : PackArgs) {
11542     if (!Arg.isPackExpansion()) {
11543       Result = *Result + 1;
11544       continue;
11545     }
11546 
11547     TemplateArgumentLoc ArgLoc;
11548     InventTemplateArgumentLoc(Arg, ArgLoc);
11549 
11550     // Find the pattern of the pack expansion.
11551     SourceLocation Ellipsis;
11552     Optional<unsigned> OrigNumExpansions;
11553     TemplateArgumentLoc Pattern =
11554         getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
11555                                                           OrigNumExpansions);
11556 
11557     // Substitute under the pack expansion. Do not expand the pack (yet).
11558     TemplateArgumentLoc OutPattern;
11559     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11560     if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
11561                                                /*Uneval*/ true))
11562       return true;
11563 
11564     // See if we can determine the number of arguments from the result.
11565     Optional<unsigned> NumExpansions =
11566         getSema().getFullyPackExpandedSize(OutPattern.getArgument());
11567     if (!NumExpansions) {
11568       // No: we must be in an alias template expansion, and we're going to need
11569       // to actually expand the packs.
11570       Result = None;
11571       break;
11572     }
11573 
11574     Result = *Result + *NumExpansions;
11575   }
11576 
11577   // Common case: we could determine the number of expansions without
11578   // substituting.
11579   if (Result)
11580     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11581                                               E->getPackLoc(),
11582                                               E->getRParenLoc(), *Result, None);
11583 
11584   TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
11585                                                E->getPackLoc());
11586   {
11587     TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
11588     typedef TemplateArgumentLocInventIterator<
11589         Derived, const TemplateArgument*> PackLocIterator;
11590     if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
11591                                    PackLocIterator(*this, PackArgs.end()),
11592                                    TransformedPackArgs, /*Uneval*/true))
11593       return ExprError();
11594   }
11595 
11596   // Check whether we managed to fully-expand the pack.
11597   // FIXME: Is it possible for us to do so and not hit the early exit path?
11598   SmallVector<TemplateArgument, 8> Args;
11599   bool PartialSubstitution = false;
11600   for (auto &Loc : TransformedPackArgs.arguments()) {
11601     Args.push_back(Loc.getArgument());
11602     if (Loc.getArgument().isPackExpansion())
11603       PartialSubstitution = true;
11604   }
11605 
11606   if (PartialSubstitution)
11607     return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11608                                               E->getPackLoc(),
11609                                               E->getRParenLoc(), None, Args);
11610 
11611   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
11612                                             E->getPackLoc(), E->getRParenLoc(),
11613                                             Args.size(), None);
11614 }
11615 
11616 template<typename Derived>
11617 ExprResult
TransformSubstNonTypeTemplateParmPackExpr(SubstNonTypeTemplateParmPackExpr * E)11618 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
11619                                           SubstNonTypeTemplateParmPackExpr *E) {
11620   // Default behavior is to do nothing with this transformation.
11621   return E;
11622 }
11623 
11624 template<typename Derived>
11625 ExprResult
TransformSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr * E)11626 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
11627                                           SubstNonTypeTemplateParmExpr *E) {
11628   // Default behavior is to do nothing with this transformation.
11629   return E;
11630 }
11631 
11632 template<typename Derived>
11633 ExprResult
TransformFunctionParmPackExpr(FunctionParmPackExpr * E)11634 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
11635   // Default behavior is to do nothing with this transformation.
11636   return E;
11637 }
11638 
11639 template<typename Derived>
11640 ExprResult
TransformMaterializeTemporaryExpr(MaterializeTemporaryExpr * E)11641 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
11642                                                   MaterializeTemporaryExpr *E) {
11643   return getDerived().TransformExpr(E->GetTemporaryExpr());
11644 }
11645 
11646 template<typename Derived>
11647 ExprResult
TransformCXXFoldExpr(CXXFoldExpr * E)11648 TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
11649   Expr *Pattern = E->getPattern();
11650 
11651   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11652   getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
11653   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
11654 
11655   // Determine whether the set of unexpanded parameter packs can and should
11656   // be expanded.
11657   bool Expand = true;
11658   bool RetainExpansion = false;
11659   Optional<unsigned> NumExpansions;
11660   if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
11661                                            Pattern->getSourceRange(),
11662                                            Unexpanded,
11663                                            Expand, RetainExpansion,
11664                                            NumExpansions))
11665     return true;
11666 
11667   if (!Expand) {
11668     // Do not expand any packs here, just transform and rebuild a fold
11669     // expression.
11670     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11671 
11672     ExprResult LHS =
11673         E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
11674     if (LHS.isInvalid())
11675       return true;
11676 
11677     ExprResult RHS =
11678         E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
11679     if (RHS.isInvalid())
11680       return true;
11681 
11682     if (!getDerived().AlwaysRebuild() &&
11683         LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
11684       return E;
11685 
11686     return getDerived().RebuildCXXFoldExpr(
11687         E->getBeginLoc(), LHS.get(), E->getOperator(), E->getEllipsisLoc(),
11688         RHS.get(), E->getEndLoc());
11689   }
11690 
11691   // The transform has determined that we should perform an elementwise
11692   // expansion of the pattern. Do so.
11693   ExprResult Result = getDerived().TransformExpr(E->getInit());
11694   if (Result.isInvalid())
11695     return true;
11696   bool LeftFold = E->isLeftFold();
11697 
11698   // If we're retaining an expansion for a right fold, it is the innermost
11699   // component and takes the init (if any).
11700   if (!LeftFold && RetainExpansion) {
11701     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11702 
11703     ExprResult Out = getDerived().TransformExpr(Pattern);
11704     if (Out.isInvalid())
11705       return true;
11706 
11707     Result = getDerived().RebuildCXXFoldExpr(
11708         E->getBeginLoc(), Out.get(), E->getOperator(), E->getEllipsisLoc(),
11709         Result.get(), E->getEndLoc());
11710     if (Result.isInvalid())
11711       return true;
11712   }
11713 
11714   for (unsigned I = 0; I != *NumExpansions; ++I) {
11715     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
11716         getSema(), LeftFold ? I : *NumExpansions - I - 1);
11717     ExprResult Out = getDerived().TransformExpr(Pattern);
11718     if (Out.isInvalid())
11719       return true;
11720 
11721     if (Out.get()->containsUnexpandedParameterPack()) {
11722       // We still have a pack; retain a pack expansion for this slice.
11723       Result = getDerived().RebuildCXXFoldExpr(
11724           E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
11725           E->getOperator(), E->getEllipsisLoc(),
11726           LeftFold ? Out.get() : Result.get(), E->getEndLoc());
11727     } else if (Result.isUsable()) {
11728       // We've got down to a single element; build a binary operator.
11729       Result = getDerived().RebuildBinaryOperator(
11730           E->getEllipsisLoc(), E->getOperator(),
11731           LeftFold ? Result.get() : Out.get(),
11732           LeftFold ? Out.get() : Result.get());
11733     } else
11734       Result = Out;
11735 
11736     if (Result.isInvalid())
11737       return true;
11738   }
11739 
11740   // If we're retaining an expansion for a left fold, it is the outermost
11741   // component and takes the complete expansion so far as its init (if any).
11742   if (LeftFold && RetainExpansion) {
11743     ForgetPartiallySubstitutedPackRAII Forget(getDerived());
11744 
11745     ExprResult Out = getDerived().TransformExpr(Pattern);
11746     if (Out.isInvalid())
11747       return true;
11748 
11749     Result = getDerived().RebuildCXXFoldExpr(
11750         E->getBeginLoc(), Result.get(), E->getOperator(), E->getEllipsisLoc(),
11751         Out.get(), E->getEndLoc());
11752     if (Result.isInvalid())
11753       return true;
11754   }
11755 
11756   // If we had no init and an empty pack, and we're not retaining an expansion,
11757   // then produce a fallback value or error.
11758   if (Result.isUnset())
11759     return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
11760                                                 E->getOperator());
11761 
11762   return Result;
11763 }
11764 
11765 template<typename Derived>
11766 ExprResult
TransformCXXStdInitializerListExpr(CXXStdInitializerListExpr * E)11767 TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
11768     CXXStdInitializerListExpr *E) {
11769   return getDerived().TransformExpr(E->getSubExpr());
11770 }
11771 
11772 template<typename Derived>
11773 ExprResult
TransformObjCStringLiteral(ObjCStringLiteral * E)11774 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
11775   return SemaRef.MaybeBindToTemporary(E);
11776 }
11777 
11778 template<typename Derived>
11779 ExprResult
TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr * E)11780 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
11781   return E;
11782 }
11783 
11784 template<typename Derived>
11785 ExprResult
TransformObjCBoxedExpr(ObjCBoxedExpr * E)11786 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
11787   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11788   if (SubExpr.isInvalid())
11789     return ExprError();
11790 
11791   if (!getDerived().AlwaysRebuild() &&
11792       SubExpr.get() == E->getSubExpr())
11793     return E;
11794 
11795   return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
11796 }
11797 
11798 template<typename Derived>
11799 ExprResult
TransformObjCArrayLiteral(ObjCArrayLiteral * E)11800 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
11801   // Transform each of the elements.
11802   SmallVector<Expr *, 8> Elements;
11803   bool ArgChanged = false;
11804   if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
11805                                   /*IsCall=*/false, Elements, &ArgChanged))
11806     return ExprError();
11807 
11808   if (!getDerived().AlwaysRebuild() && !ArgChanged)
11809     return SemaRef.MaybeBindToTemporary(E);
11810 
11811   return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
11812                                               Elements.data(),
11813                                               Elements.size());
11814 }
11815 
11816 template<typename Derived>
11817 ExprResult
TransformObjCDictionaryLiteral(ObjCDictionaryLiteral * E)11818 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
11819                                                     ObjCDictionaryLiteral *E) {
11820   // Transform each of the elements.
11821   SmallVector<ObjCDictionaryElement, 8> Elements;
11822   bool ArgChanged = false;
11823   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
11824     ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
11825 
11826     if (OrigElement.isPackExpansion()) {
11827       // This key/value element is a pack expansion.
11828       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11829       getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
11830       getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
11831       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
11832 
11833       // Determine whether the set of unexpanded parameter packs can
11834       // and should be expanded.
11835       bool Expand = true;
11836       bool RetainExpansion = false;
11837       Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
11838       Optional<unsigned> NumExpansions = OrigNumExpansions;
11839       SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
11840                                OrigElement.Value->getEndLoc());
11841       if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
11842                                                PatternRange, Unexpanded, Expand,
11843                                                RetainExpansion, NumExpansions))
11844         return ExprError();
11845 
11846       if (!Expand) {
11847         // The transform has determined that we should perform a simple
11848         // transformation on the pack expansion, producing another pack
11849         // expansion.
11850         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
11851         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11852         if (Key.isInvalid())
11853           return ExprError();
11854 
11855         if (Key.get() != OrigElement.Key)
11856           ArgChanged = true;
11857 
11858         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
11859         if (Value.isInvalid())
11860           return ExprError();
11861 
11862         if (Value.get() != OrigElement.Value)
11863           ArgChanged = true;
11864 
11865         ObjCDictionaryElement Expansion = {
11866           Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
11867         };
11868         Elements.push_back(Expansion);
11869         continue;
11870       }
11871 
11872       // Record right away that the argument was changed.  This needs
11873       // to happen even if the array expands to nothing.
11874       ArgChanged = true;
11875 
11876       // The transform has determined that we should perform an elementwise
11877       // expansion of the pattern. Do so.
11878       for (unsigned I = 0; I != *NumExpansions; ++I) {
11879         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
11880         ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11881         if (Key.isInvalid())
11882           return ExprError();
11883 
11884         ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
11885         if (Value.isInvalid())
11886           return ExprError();
11887 
11888         ObjCDictionaryElement Element = {
11889           Key.get(), Value.get(), SourceLocation(), NumExpansions
11890         };
11891 
11892         // If any unexpanded parameter packs remain, we still have a
11893         // pack expansion.
11894         // FIXME: Can this really happen?
11895         if (Key.get()->containsUnexpandedParameterPack() ||
11896             Value.get()->containsUnexpandedParameterPack())
11897           Element.EllipsisLoc = OrigElement.EllipsisLoc;
11898 
11899         Elements.push_back(Element);
11900       }
11901 
11902       // FIXME: Retain a pack expansion if RetainExpansion is true.
11903 
11904       // We've finished with this pack expansion.
11905       continue;
11906     }
11907 
11908     // Transform and check key.
11909     ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
11910     if (Key.isInvalid())
11911       return ExprError();
11912 
11913     if (Key.get() != OrigElement.Key)
11914       ArgChanged = true;
11915 
11916     // Transform and check value.
11917     ExprResult Value
11918       = getDerived().TransformExpr(OrigElement.Value);
11919     if (Value.isInvalid())
11920       return ExprError();
11921 
11922     if (Value.get() != OrigElement.Value)
11923       ArgChanged = true;
11924 
11925     ObjCDictionaryElement Element = {
11926       Key.get(), Value.get(), SourceLocation(), None
11927     };
11928     Elements.push_back(Element);
11929   }
11930 
11931   if (!getDerived().AlwaysRebuild() && !ArgChanged)
11932     return SemaRef.MaybeBindToTemporary(E);
11933 
11934   return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
11935                                                    Elements);
11936 }
11937 
11938 template<typename Derived>
11939 ExprResult
TransformObjCEncodeExpr(ObjCEncodeExpr * E)11940 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
11941   TypeSourceInfo *EncodedTypeInfo
11942     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
11943   if (!EncodedTypeInfo)
11944     return ExprError();
11945 
11946   if (!getDerived().AlwaysRebuild() &&
11947       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
11948     return E;
11949 
11950   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
11951                                             EncodedTypeInfo,
11952                                             E->getRParenLoc());
11953 }
11954 
11955 template<typename Derived>
11956 ExprResult TreeTransform<Derived>::
TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr * E)11957 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
11958   // This is a kind of implicit conversion, and it needs to get dropped
11959   // and recomputed for the same general reasons that ImplicitCastExprs
11960   // do, as well a more specific one: this expression is only valid when
11961   // it appears *immediately* as an argument expression.
11962   return getDerived().TransformExpr(E->getSubExpr());
11963 }
11964 
11965 template<typename Derived>
11966 ExprResult TreeTransform<Derived>::
TransformObjCBridgedCastExpr(ObjCBridgedCastExpr * E)11967 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
11968   TypeSourceInfo *TSInfo
11969     = getDerived().TransformType(E->getTypeInfoAsWritten());
11970   if (!TSInfo)
11971     return ExprError();
11972 
11973   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
11974   if (Result.isInvalid())
11975     return ExprError();
11976 
11977   if (!getDerived().AlwaysRebuild() &&
11978       TSInfo == E->getTypeInfoAsWritten() &&
11979       Result.get() == E->getSubExpr())
11980     return E;
11981 
11982   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
11983                                       E->getBridgeKeywordLoc(), TSInfo,
11984                                       Result.get());
11985 }
11986 
11987 template <typename Derived>
TransformObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr * E)11988 ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
11989     ObjCAvailabilityCheckExpr *E) {
11990   return E;
11991 }
11992 
11993 template<typename Derived>
11994 ExprResult
TransformObjCMessageExpr(ObjCMessageExpr * E)11995 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
11996   // Transform arguments.
11997   bool ArgChanged = false;
11998   SmallVector<Expr*, 8> Args;
11999   Args.reserve(E->getNumArgs());
12000   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
12001                                   &ArgChanged))
12002     return ExprError();
12003 
12004   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
12005     // Class message: transform the receiver type.
12006     TypeSourceInfo *ReceiverTypeInfo
12007       = getDerived().TransformType(E->getClassReceiverTypeInfo());
12008     if (!ReceiverTypeInfo)
12009       return ExprError();
12010 
12011     // If nothing changed, just retain the existing message send.
12012     if (!getDerived().AlwaysRebuild() &&
12013         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
12014       return SemaRef.MaybeBindToTemporary(E);
12015 
12016     // Build a new class message send.
12017     SmallVector<SourceLocation, 16> SelLocs;
12018     E->getSelectorLocs(SelLocs);
12019     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
12020                                                E->getSelector(),
12021                                                SelLocs,
12022                                                E->getMethodDecl(),
12023                                                E->getLeftLoc(),
12024                                                Args,
12025                                                E->getRightLoc());
12026   }
12027   else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
12028            E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12029     if (!E->getMethodDecl())
12030       return ExprError();
12031 
12032     // Build a new class message send to 'super'.
12033     SmallVector<SourceLocation, 16> SelLocs;
12034     E->getSelectorLocs(SelLocs);
12035     return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
12036                                                E->getSelector(),
12037                                                SelLocs,
12038                                                E->getReceiverType(),
12039                                                E->getMethodDecl(),
12040                                                E->getLeftLoc(),
12041                                                Args,
12042                                                E->getRightLoc());
12043   }
12044 
12045   // Instance message: transform the receiver
12046   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
12047          "Only class and instance messages may be instantiated");
12048   ExprResult Receiver
12049     = getDerived().TransformExpr(E->getInstanceReceiver());
12050   if (Receiver.isInvalid())
12051     return ExprError();
12052 
12053   // If nothing changed, just retain the existing message send.
12054   if (!getDerived().AlwaysRebuild() &&
12055       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
12056     return SemaRef.MaybeBindToTemporary(E);
12057 
12058   // Build a new instance message send.
12059   SmallVector<SourceLocation, 16> SelLocs;
12060   E->getSelectorLocs(SelLocs);
12061   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
12062                                              E->getSelector(),
12063                                              SelLocs,
12064                                              E->getMethodDecl(),
12065                                              E->getLeftLoc(),
12066                                              Args,
12067                                              E->getRightLoc());
12068 }
12069 
12070 template<typename Derived>
12071 ExprResult
TransformObjCSelectorExpr(ObjCSelectorExpr * E)12072 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
12073   return E;
12074 }
12075 
12076 template<typename Derived>
12077 ExprResult
TransformObjCProtocolExpr(ObjCProtocolExpr * E)12078 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
12079   return E;
12080 }
12081 
12082 template<typename Derived>
12083 ExprResult
TransformObjCIvarRefExpr(ObjCIvarRefExpr * E)12084 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
12085   // Transform the base expression.
12086   ExprResult Base = getDerived().TransformExpr(E->getBase());
12087   if (Base.isInvalid())
12088     return ExprError();
12089 
12090   // We don't need to transform the ivar; it will never change.
12091 
12092   // If nothing changed, just retain the existing expression.
12093   if (!getDerived().AlwaysRebuild() &&
12094       Base.get() == E->getBase())
12095     return E;
12096 
12097   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
12098                                              E->getLocation(),
12099                                              E->isArrow(), E->isFreeIvar());
12100 }
12101 
12102 template<typename Derived>
12103 ExprResult
TransformObjCPropertyRefExpr(ObjCPropertyRefExpr * E)12104 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
12105   // 'super' and types never change. Property never changes. Just
12106   // retain the existing expression.
12107   if (!E->isObjectReceiver())
12108     return E;
12109 
12110   // Transform the base expression.
12111   ExprResult Base = getDerived().TransformExpr(E->getBase());
12112   if (Base.isInvalid())
12113     return ExprError();
12114 
12115   // We don't need to transform the property; it will never change.
12116 
12117   // If nothing changed, just retain the existing expression.
12118   if (!getDerived().AlwaysRebuild() &&
12119       Base.get() == E->getBase())
12120     return E;
12121 
12122   if (E->isExplicitProperty())
12123     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12124                                                    E->getExplicitProperty(),
12125                                                    E->getLocation());
12126 
12127   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
12128                                                  SemaRef.Context.PseudoObjectTy,
12129                                                  E->getImplicitPropertyGetter(),
12130                                                  E->getImplicitPropertySetter(),
12131                                                  E->getLocation());
12132 }
12133 
12134 template<typename Derived>
12135 ExprResult
TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr * E)12136 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
12137   // Transform the base expression.
12138   ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
12139   if (Base.isInvalid())
12140     return ExprError();
12141 
12142   // Transform the key expression.
12143   ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
12144   if (Key.isInvalid())
12145     return ExprError();
12146 
12147   // If nothing changed, just retain the existing expression.
12148   if (!getDerived().AlwaysRebuild() &&
12149       Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
12150     return E;
12151 
12152   return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
12153                                                   Base.get(), Key.get(),
12154                                                   E->getAtIndexMethodDecl(),
12155                                                   E->setAtIndexMethodDecl());
12156 }
12157 
12158 template<typename Derived>
12159 ExprResult
TransformObjCIsaExpr(ObjCIsaExpr * E)12160 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
12161   // Transform the base expression.
12162   ExprResult Base = getDerived().TransformExpr(E->getBase());
12163   if (Base.isInvalid())
12164     return ExprError();
12165 
12166   // If nothing changed, just retain the existing expression.
12167   if (!getDerived().AlwaysRebuild() &&
12168       Base.get() == E->getBase())
12169     return E;
12170 
12171   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
12172                                          E->getOpLoc(),
12173                                          E->isArrow());
12174 }
12175 
12176 template<typename Derived>
12177 ExprResult
TransformShuffleVectorExpr(ShuffleVectorExpr * E)12178 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
12179   bool ArgumentChanged = false;
12180   SmallVector<Expr*, 8> SubExprs;
12181   SubExprs.reserve(E->getNumSubExprs());
12182   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12183                                   SubExprs, &ArgumentChanged))
12184     return ExprError();
12185 
12186   if (!getDerived().AlwaysRebuild() &&
12187       !ArgumentChanged)
12188     return E;
12189 
12190   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
12191                                                SubExprs,
12192                                                E->getRParenLoc());
12193 }
12194 
12195 template<typename Derived>
12196 ExprResult
TransformConvertVectorExpr(ConvertVectorExpr * E)12197 TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
12198   ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
12199   if (SrcExpr.isInvalid())
12200     return ExprError();
12201 
12202   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
12203   if (!Type)
12204     return ExprError();
12205 
12206   if (!getDerived().AlwaysRebuild() &&
12207       Type == E->getTypeSourceInfo() &&
12208       SrcExpr.get() == E->getSrcExpr())
12209     return E;
12210 
12211   return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
12212                                                SrcExpr.get(), Type,
12213                                                E->getRParenLoc());
12214 }
12215 
12216 template<typename Derived>
12217 ExprResult
TransformBlockExpr(BlockExpr * E)12218 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
12219   BlockDecl *oldBlock = E->getBlockDecl();
12220 
12221   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
12222   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
12223 
12224   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
12225   blockScope->TheDecl->setBlockMissingReturnType(
12226                          oldBlock->blockMissingReturnType());
12227 
12228   SmallVector<ParmVarDecl*, 4> params;
12229   SmallVector<QualType, 4> paramTypes;
12230 
12231   const FunctionProtoType *exprFunctionType = E->getFunctionType();
12232 
12233   // Parameter substitution.
12234   Sema::ExtParameterInfoBuilder extParamInfos;
12235   if (getDerived().TransformFunctionTypeParams(
12236           E->getCaretLocation(), oldBlock->parameters(), nullptr,
12237           exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
12238           extParamInfos)) {
12239     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12240     return ExprError();
12241   }
12242 
12243   QualType exprResultType =
12244       getDerived().TransformType(exprFunctionType->getReturnType());
12245 
12246   auto epi = exprFunctionType->getExtProtoInfo();
12247   epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
12248 
12249   QualType functionType =
12250     getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
12251   blockScope->FunctionType = functionType;
12252 
12253   // Set the parameters on the block decl.
12254   if (!params.empty())
12255     blockScope->TheDecl->setParams(params);
12256 
12257   if (!oldBlock->blockMissingReturnType()) {
12258     blockScope->HasImplicitReturnType = false;
12259     blockScope->ReturnType = exprResultType;
12260   }
12261 
12262   // Transform the body
12263   StmtResult body = getDerived().TransformStmt(E->getBody());
12264   if (body.isInvalid()) {
12265     getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
12266     return ExprError();
12267   }
12268 
12269 #ifndef NDEBUG
12270   // In builds with assertions, make sure that we captured everything we
12271   // captured before.
12272   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
12273     for (const auto &I : oldBlock->captures()) {
12274       VarDecl *oldCapture = I.getVariable();
12275 
12276       // Ignore parameter packs.
12277       if (isa<ParmVarDecl>(oldCapture) &&
12278           cast<ParmVarDecl>(oldCapture)->isParameterPack())
12279         continue;
12280 
12281       VarDecl *newCapture =
12282         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
12283                                                  oldCapture));
12284       assert(blockScope->CaptureMap.count(newCapture));
12285     }
12286     assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
12287   }
12288 #endif
12289 
12290   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
12291                                     /*Scope=*/nullptr);
12292 }
12293 
12294 template<typename Derived>
12295 ExprResult
TransformAsTypeExpr(AsTypeExpr * E)12296 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
12297   llvm_unreachable("Cannot transform asType expressions yet");
12298 }
12299 
12300 template<typename Derived>
12301 ExprResult
TransformAtomicExpr(AtomicExpr * E)12302 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
12303   QualType RetTy = getDerived().TransformType(E->getType());
12304   bool ArgumentChanged = false;
12305   SmallVector<Expr*, 8> SubExprs;
12306   SubExprs.reserve(E->getNumSubExprs());
12307   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
12308                                   SubExprs, &ArgumentChanged))
12309     return ExprError();
12310 
12311   if (!getDerived().AlwaysRebuild() &&
12312       !ArgumentChanged)
12313     return E;
12314 
12315   return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
12316                                         RetTy, E->getOp(), E->getRParenLoc());
12317 }
12318 
12319 //===----------------------------------------------------------------------===//
12320 // Type reconstruction
12321 //===----------------------------------------------------------------------===//
12322 
12323 template<typename Derived>
RebuildPointerType(QualType PointeeType,SourceLocation Star)12324 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
12325                                                     SourceLocation Star) {
12326   return SemaRef.BuildPointerType(PointeeType, Star,
12327                                   getDerived().getBaseEntity());
12328 }
12329 
12330 template<typename Derived>
RebuildBlockPointerType(QualType PointeeType,SourceLocation Star)12331 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
12332                                                          SourceLocation Star) {
12333   return SemaRef.BuildBlockPointerType(PointeeType, Star,
12334                                        getDerived().getBaseEntity());
12335 }
12336 
12337 template<typename Derived>
12338 QualType
RebuildReferenceType(QualType ReferentType,bool WrittenAsLValue,SourceLocation Sigil)12339 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
12340                                              bool WrittenAsLValue,
12341                                              SourceLocation Sigil) {
12342   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
12343                                     Sigil, getDerived().getBaseEntity());
12344 }
12345 
12346 template<typename Derived>
12347 QualType
RebuildMemberPointerType(QualType PointeeType,QualType ClassType,SourceLocation Sigil)12348 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
12349                                                  QualType ClassType,
12350                                                  SourceLocation Sigil) {
12351   return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
12352                                         getDerived().getBaseEntity());
12353 }
12354 
12355 template<typename Derived>
RebuildObjCTypeParamType(const ObjCTypeParamDecl * Decl,SourceLocation ProtocolLAngleLoc,ArrayRef<ObjCProtocolDecl * > Protocols,ArrayRef<SourceLocation> ProtocolLocs,SourceLocation ProtocolRAngleLoc)12356 QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
12357            const ObjCTypeParamDecl *Decl,
12358            SourceLocation ProtocolLAngleLoc,
12359            ArrayRef<ObjCProtocolDecl *> Protocols,
12360            ArrayRef<SourceLocation> ProtocolLocs,
12361            SourceLocation ProtocolRAngleLoc) {
12362   return SemaRef.BuildObjCTypeParamType(Decl,
12363                                         ProtocolLAngleLoc, Protocols,
12364                                         ProtocolLocs, ProtocolRAngleLoc,
12365                                         /*FailOnError=*/true);
12366 }
12367 
12368 template<typename Derived>
RebuildObjCObjectType(QualType BaseType,SourceLocation Loc,SourceLocation TypeArgsLAngleLoc,ArrayRef<TypeSourceInfo * > TypeArgs,SourceLocation TypeArgsRAngleLoc,SourceLocation ProtocolLAngleLoc,ArrayRef<ObjCProtocolDecl * > Protocols,ArrayRef<SourceLocation> ProtocolLocs,SourceLocation ProtocolRAngleLoc)12369 QualType TreeTransform<Derived>::RebuildObjCObjectType(
12370            QualType BaseType,
12371            SourceLocation Loc,
12372            SourceLocation TypeArgsLAngleLoc,
12373            ArrayRef<TypeSourceInfo *> TypeArgs,
12374            SourceLocation TypeArgsRAngleLoc,
12375            SourceLocation ProtocolLAngleLoc,
12376            ArrayRef<ObjCProtocolDecl *> Protocols,
12377            ArrayRef<SourceLocation> ProtocolLocs,
12378            SourceLocation ProtocolRAngleLoc) {
12379   return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc,
12380                                      TypeArgs, TypeArgsRAngleLoc,
12381                                      ProtocolLAngleLoc, Protocols, ProtocolLocs,
12382                                      ProtocolRAngleLoc,
12383                                      /*FailOnError=*/true);
12384 }
12385 
12386 template<typename Derived>
RebuildObjCObjectPointerType(QualType PointeeType,SourceLocation Star)12387 QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
12388            QualType PointeeType,
12389            SourceLocation Star) {
12390   return SemaRef.Context.getObjCObjectPointerType(PointeeType);
12391 }
12392 
12393 template<typename Derived>
12394 QualType
RebuildArrayType(QualType ElementType,ArrayType::ArraySizeModifier SizeMod,const llvm::APInt * Size,Expr * SizeExpr,unsigned IndexTypeQuals,SourceRange BracketsRange)12395 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
12396                                          ArrayType::ArraySizeModifier SizeMod,
12397                                          const llvm::APInt *Size,
12398                                          Expr *SizeExpr,
12399                                          unsigned IndexTypeQuals,
12400                                          SourceRange BracketsRange) {
12401   if (SizeExpr || !Size)
12402     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
12403                                   IndexTypeQuals, BracketsRange,
12404                                   getDerived().getBaseEntity());
12405 
12406   QualType Types[] = {
12407     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
12408     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
12409     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
12410   };
12411   const unsigned NumTypes = llvm::array_lengthof(Types);
12412   QualType SizeType;
12413   for (unsigned I = 0; I != NumTypes; ++I)
12414     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
12415       SizeType = Types[I];
12416       break;
12417     }
12418 
12419   // Note that we can return a VariableArrayType here in the case where
12420   // the element type was a dependent VariableArrayType.
12421   IntegerLiteral *ArraySize
12422       = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
12423                                /*FIXME*/BracketsRange.getBegin());
12424   return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
12425                                 IndexTypeQuals, BracketsRange,
12426                                 getDerived().getBaseEntity());
12427 }
12428 
12429 template<typename Derived>
12430 QualType
RebuildConstantArrayType(QualType ElementType,ArrayType::ArraySizeModifier SizeMod,const llvm::APInt & Size,unsigned IndexTypeQuals,SourceRange BracketsRange)12431 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
12432                                                  ArrayType::ArraySizeModifier SizeMod,
12433                                                  const llvm::APInt &Size,
12434                                                  unsigned IndexTypeQuals,
12435                                                  SourceRange BracketsRange) {
12436   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, nullptr,
12437                                         IndexTypeQuals, BracketsRange);
12438 }
12439 
12440 template<typename Derived>
12441 QualType
RebuildIncompleteArrayType(QualType ElementType,ArrayType::ArraySizeModifier SizeMod,unsigned IndexTypeQuals,SourceRange BracketsRange)12442 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
12443                                           ArrayType::ArraySizeModifier SizeMod,
12444                                                  unsigned IndexTypeQuals,
12445                                                    SourceRange BracketsRange) {
12446   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
12447                                        IndexTypeQuals, BracketsRange);
12448 }
12449 
12450 template<typename Derived>
12451 QualType
RebuildVariableArrayType(QualType ElementType,ArrayType::ArraySizeModifier SizeMod,Expr * SizeExpr,unsigned IndexTypeQuals,SourceRange BracketsRange)12452 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
12453                                           ArrayType::ArraySizeModifier SizeMod,
12454                                                  Expr *SizeExpr,
12455                                                  unsigned IndexTypeQuals,
12456                                                  SourceRange BracketsRange) {
12457   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12458                                        SizeExpr,
12459                                        IndexTypeQuals, BracketsRange);
12460 }
12461 
12462 template<typename Derived>
12463 QualType
RebuildDependentSizedArrayType(QualType ElementType,ArrayType::ArraySizeModifier SizeMod,Expr * SizeExpr,unsigned IndexTypeQuals,SourceRange BracketsRange)12464 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
12465                                           ArrayType::ArraySizeModifier SizeMod,
12466                                                        Expr *SizeExpr,
12467                                                        unsigned IndexTypeQuals,
12468                                                    SourceRange BracketsRange) {
12469   return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
12470                                        SizeExpr,
12471                                        IndexTypeQuals, BracketsRange);
12472 }
12473 
12474 template <typename Derived>
RebuildDependentAddressSpaceType(QualType PointeeType,Expr * AddrSpaceExpr,SourceLocation AttributeLoc)12475 QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
12476     QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
12477   return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
12478                                           AttributeLoc);
12479 }
12480 
12481 template <typename Derived>
12482 QualType
RebuildVectorType(QualType ElementType,unsigned NumElements,VectorType::VectorKind VecKind)12483 TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
12484                                           unsigned NumElements,
12485                                           VectorType::VectorKind VecKind) {
12486   // FIXME: semantic checking!
12487   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
12488 }
12489 
12490 template <typename Derived>
RebuildDependentVectorType(QualType ElementType,Expr * SizeExpr,SourceLocation AttributeLoc,VectorType::VectorKind VecKind)12491 QualType TreeTransform<Derived>::RebuildDependentVectorType(
12492     QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
12493     VectorType::VectorKind VecKind) {
12494   return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
12495 }
12496 
12497 template<typename Derived>
RebuildExtVectorType(QualType ElementType,unsigned NumElements,SourceLocation AttributeLoc)12498 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
12499                                                       unsigned NumElements,
12500                                                  SourceLocation AttributeLoc) {
12501   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
12502                           NumElements, true);
12503   IntegerLiteral *VectorSize
12504     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
12505                              AttributeLoc);
12506   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
12507 }
12508 
12509 template<typename Derived>
12510 QualType
RebuildDependentSizedExtVectorType(QualType ElementType,Expr * SizeExpr,SourceLocation AttributeLoc)12511 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
12512                                                            Expr *SizeExpr,
12513                                                   SourceLocation AttributeLoc) {
12514   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
12515 }
12516 
12517 template<typename Derived>
RebuildFunctionProtoType(QualType T,MutableArrayRef<QualType> ParamTypes,const FunctionProtoType::ExtProtoInfo & EPI)12518 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
12519     QualType T,
12520     MutableArrayRef<QualType> ParamTypes,
12521     const FunctionProtoType::ExtProtoInfo &EPI) {
12522   return SemaRef.BuildFunctionType(T, ParamTypes,
12523                                    getDerived().getBaseLocation(),
12524                                    getDerived().getBaseEntity(),
12525                                    EPI);
12526 }
12527 
12528 template<typename Derived>
RebuildFunctionNoProtoType(QualType T)12529 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
12530   return SemaRef.Context.getFunctionNoProtoType(T);
12531 }
12532 
12533 template<typename Derived>
RebuildUnresolvedUsingType(SourceLocation Loc,Decl * D)12534 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
12535                                                             Decl *D) {
12536   assert(D && "no decl found");
12537   if (D->isInvalidDecl()) return QualType();
12538 
12539   // FIXME: Doesn't account for ObjCInterfaceDecl!
12540   TypeDecl *Ty;
12541   if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
12542     // A valid resolved using typename pack expansion decl can have multiple
12543     // UsingDecls, but they must each have exactly one type, and it must be
12544     // the same type in every case. But we must have at least one expansion!
12545     if (UPD->expansions().empty()) {
12546       getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
12547           << UPD->isCXXClassMember() << UPD;
12548       return QualType();
12549     }
12550 
12551     // We might still have some unresolved types. Try to pick a resolved type
12552     // if we can. The final instantiation will check that the remaining
12553     // unresolved types instantiate to the type we pick.
12554     QualType FallbackT;
12555     QualType T;
12556     for (auto *E : UPD->expansions()) {
12557       QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
12558       if (ThisT.isNull())
12559         continue;
12560       else if (ThisT->getAs<UnresolvedUsingType>())
12561         FallbackT = ThisT;
12562       else if (T.isNull())
12563         T = ThisT;
12564       else
12565         assert(getSema().Context.hasSameType(ThisT, T) &&
12566                "mismatched resolved types in using pack expansion");
12567     }
12568     return T.isNull() ? FallbackT : T;
12569   } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
12570     assert(Using->hasTypename() &&
12571            "UnresolvedUsingTypenameDecl transformed to non-typename using");
12572 
12573     // A valid resolved using typename decl points to exactly one type decl.
12574     assert(++Using->shadow_begin() == Using->shadow_end());
12575     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
12576   } else {
12577     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
12578            "UnresolvedUsingTypenameDecl transformed to non-using decl");
12579     Ty = cast<UnresolvedUsingTypenameDecl>(D);
12580   }
12581 
12582   return SemaRef.Context.getTypeDeclType(Ty);
12583 }
12584 
12585 template<typename Derived>
RebuildTypeOfExprType(Expr * E,SourceLocation Loc)12586 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
12587                                                        SourceLocation Loc) {
12588   return SemaRef.BuildTypeofExprType(E, Loc);
12589 }
12590 
12591 template<typename Derived>
RebuildTypeOfType(QualType Underlying)12592 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
12593   return SemaRef.Context.getTypeOfType(Underlying);
12594 }
12595 
12596 template<typename Derived>
RebuildDecltypeType(Expr * E,SourceLocation Loc)12597 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
12598                                                      SourceLocation Loc) {
12599   return SemaRef.BuildDecltypeType(E, Loc);
12600 }
12601 
12602 template<typename Derived>
RebuildUnaryTransformType(QualType BaseType,UnaryTransformType::UTTKind UKind,SourceLocation Loc)12603 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
12604                                             UnaryTransformType::UTTKind UKind,
12605                                             SourceLocation Loc) {
12606   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
12607 }
12608 
12609 template<typename Derived>
RebuildTemplateSpecializationType(TemplateName Template,SourceLocation TemplateNameLoc,TemplateArgumentListInfo & TemplateArgs)12610 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
12611                                                       TemplateName Template,
12612                                              SourceLocation TemplateNameLoc,
12613                                      TemplateArgumentListInfo &TemplateArgs) {
12614   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
12615 }
12616 
12617 template<typename Derived>
RebuildAtomicType(QualType ValueType,SourceLocation KWLoc)12618 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
12619                                                    SourceLocation KWLoc) {
12620   return SemaRef.BuildAtomicType(ValueType, KWLoc);
12621 }
12622 
12623 template<typename Derived>
RebuildPipeType(QualType ValueType,SourceLocation KWLoc,bool isReadPipe)12624 QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
12625                                                  SourceLocation KWLoc,
12626                                                  bool isReadPipe) {
12627   return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
12628                     : SemaRef.BuildWritePipeType(ValueType, KWLoc);
12629 }
12630 
12631 template<typename Derived>
12632 TemplateName
RebuildTemplateName(CXXScopeSpec & SS,bool TemplateKW,TemplateDecl * Template)12633 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12634                                             bool TemplateKW,
12635                                             TemplateDecl *Template) {
12636   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
12637                                                   Template);
12638 }
12639 
12640 template<typename Derived>
12641 TemplateName
RebuildTemplateName(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const IdentifierInfo & Name,SourceLocation NameLoc,QualType ObjectType,NamedDecl * FirstQualifierInScope,bool AllowInjectedClassName)12642 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12643                                             SourceLocation TemplateKWLoc,
12644                                             const IdentifierInfo &Name,
12645                                             SourceLocation NameLoc,
12646                                             QualType ObjectType,
12647                                             NamedDecl *FirstQualifierInScope,
12648                                             bool AllowInjectedClassName) {
12649   UnqualifiedId TemplateName;
12650   TemplateName.setIdentifier(&Name, NameLoc);
12651   Sema::TemplateTy Template;
12652   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
12653                                        SS, TemplateKWLoc, TemplateName,
12654                                        ParsedType::make(ObjectType),
12655                                        /*EnteringContext=*/false,
12656                                        Template, AllowInjectedClassName);
12657   return Template.get();
12658 }
12659 
12660 template<typename Derived>
12661 TemplateName
RebuildTemplateName(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,OverloadedOperatorKind Operator,SourceLocation NameLoc,QualType ObjectType,bool AllowInjectedClassName)12662 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
12663                                             SourceLocation TemplateKWLoc,
12664                                             OverloadedOperatorKind Operator,
12665                                             SourceLocation NameLoc,
12666                                             QualType ObjectType,
12667                                             bool AllowInjectedClassName) {
12668   UnqualifiedId Name;
12669   // FIXME: Bogus location information.
12670   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
12671   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
12672   Sema::TemplateTy Template;
12673   getSema().ActOnDependentTemplateName(/*Scope=*/nullptr,
12674                                        SS, TemplateKWLoc, Name,
12675                                        ParsedType::make(ObjectType),
12676                                        /*EnteringContext=*/false,
12677                                        Template, AllowInjectedClassName);
12678   return Template.get();
12679 }
12680 
12681 template<typename Derived>
12682 ExprResult
RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,SourceLocation OpLoc,Expr * OrigCallee,Expr * First,Expr * Second)12683 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
12684                                                    SourceLocation OpLoc,
12685                                                    Expr *OrigCallee,
12686                                                    Expr *First,
12687                                                    Expr *Second) {
12688   Expr *Callee = OrigCallee->IgnoreParenCasts();
12689   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
12690 
12691   if (First->getObjectKind() == OK_ObjCProperty) {
12692     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12693     if (BinaryOperator::isAssignmentOp(Opc))
12694       return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
12695                                                  First, Second);
12696     ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
12697     if (Result.isInvalid())
12698       return ExprError();
12699     First = Result.get();
12700   }
12701 
12702   if (Second && Second->getObjectKind() == OK_ObjCProperty) {
12703     ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
12704     if (Result.isInvalid())
12705       return ExprError();
12706     Second = Result.get();
12707   }
12708 
12709   // Determine whether this should be a builtin operation.
12710   if (Op == OO_Subscript) {
12711     if (!First->getType()->isOverloadableType() &&
12712         !Second->getType()->isOverloadableType())
12713       return getSema().CreateBuiltinArraySubscriptExpr(
12714           First, Callee->getBeginLoc(), Second, OpLoc);
12715   } else if (Op == OO_Arrow) {
12716     // -> is never a builtin operation.
12717     return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
12718   } else if (Second == nullptr || isPostIncDec) {
12719     if (!First->getType()->isOverloadableType() ||
12720         (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
12721       // The argument is not of overloadable type, or this is an expression
12722       // of the form &Class::member, so try to create a built-in unary
12723       // operation.
12724       UnaryOperatorKind Opc
12725         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
12726 
12727       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
12728     }
12729   } else {
12730     if (!First->getType()->isOverloadableType() &&
12731         !Second->getType()->isOverloadableType()) {
12732       // Neither of the arguments is an overloadable type, so try to
12733       // create a built-in binary operation.
12734       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12735       ExprResult Result
12736         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
12737       if (Result.isInvalid())
12738         return ExprError();
12739 
12740       return Result;
12741     }
12742   }
12743 
12744   // Compute the transformed set of functions (and function templates) to be
12745   // used during overload resolution.
12746   UnresolvedSet<16> Functions;
12747   bool RequiresADL;
12748 
12749   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
12750     Functions.append(ULE->decls_begin(), ULE->decls_end());
12751     // If the overload could not be resolved in the template definition
12752     // (because we had a dependent argument), ADL is performed as part of
12753     // template instantiation.
12754     RequiresADL = ULE->requiresADL();
12755   } else {
12756     // If we've resolved this to a particular non-member function, just call
12757     // that function. If we resolved it to a member function,
12758     // CreateOverloaded* will find that function for us.
12759     NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
12760     if (!isa<CXXMethodDecl>(ND))
12761       Functions.addDecl(ND);
12762     RequiresADL = false;
12763   }
12764 
12765   // Add any functions found via argument-dependent lookup.
12766   Expr *Args[2] = { First, Second };
12767   unsigned NumArgs = 1 + (Second != nullptr);
12768 
12769   // Create the overloaded operator invocation for unary operators.
12770   if (NumArgs == 1 || isPostIncDec) {
12771     UnaryOperatorKind Opc
12772       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
12773     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
12774                                            RequiresADL);
12775   }
12776 
12777   if (Op == OO_Subscript) {
12778     SourceLocation LBrace;
12779     SourceLocation RBrace;
12780 
12781     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
12782         DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
12783         LBrace = SourceLocation::getFromRawEncoding(
12784                     NameLoc.CXXOperatorName.BeginOpNameLoc);
12785         RBrace = SourceLocation::getFromRawEncoding(
12786                     NameLoc.CXXOperatorName.EndOpNameLoc);
12787     } else {
12788       LBrace = Callee->getBeginLoc();
12789       RBrace = OpLoc;
12790     }
12791 
12792     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
12793                                                       First, Second);
12794   }
12795 
12796   // Create the overloaded operator invocation for binary operators.
12797   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
12798   ExprResult Result = SemaRef.CreateOverloadedBinOp(
12799       OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
12800   if (Result.isInvalid())
12801     return ExprError();
12802 
12803   return Result;
12804 }
12805 
12806 template<typename Derived>
12807 ExprResult
RebuildCXXPseudoDestructorExpr(Expr * Base,SourceLocation OperatorLoc,bool isArrow,CXXScopeSpec & SS,TypeSourceInfo * ScopeType,SourceLocation CCLoc,SourceLocation TildeLoc,PseudoDestructorTypeStorage Destroyed)12808 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
12809                                                      SourceLocation OperatorLoc,
12810                                                        bool isArrow,
12811                                                        CXXScopeSpec &SS,
12812                                                      TypeSourceInfo *ScopeType,
12813                                                        SourceLocation CCLoc,
12814                                                        SourceLocation TildeLoc,
12815                                         PseudoDestructorTypeStorage Destroyed) {
12816   QualType BaseType = Base->getType();
12817   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
12818       (!isArrow && !BaseType->getAs<RecordType>()) ||
12819       (isArrow && BaseType->getAs<PointerType>() &&
12820        !BaseType->getAs<PointerType>()->getPointeeType()
12821                                               ->template getAs<RecordType>())){
12822     // This pseudo-destructor expression is still a pseudo-destructor.
12823     return SemaRef.BuildPseudoDestructorExpr(
12824         Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
12825         CCLoc, TildeLoc, Destroyed);
12826   }
12827 
12828   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
12829   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
12830                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
12831   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
12832   NameInfo.setNamedTypeInfo(DestroyedType);
12833 
12834   // The scope type is now known to be a valid nested name specifier
12835   // component. Tack it on to the end of the nested name specifier.
12836   if (ScopeType) {
12837     if (!ScopeType->getType()->getAs<TagType>()) {
12838       getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
12839                      diag::err_expected_class_or_namespace)
12840           << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
12841       return ExprError();
12842     }
12843     SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
12844               CCLoc);
12845   }
12846 
12847   SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
12848   return getSema().BuildMemberReferenceExpr(Base, BaseType,
12849                                             OperatorLoc, isArrow,
12850                                             SS, TemplateKWLoc,
12851                                             /*FIXME: FirstQualifier*/ nullptr,
12852                                             NameInfo,
12853                                             /*TemplateArgs*/ nullptr,
12854                                             /*S*/nullptr);
12855 }
12856 
12857 template<typename Derived>
12858 StmtResult
TransformCapturedStmt(CapturedStmt * S)12859 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
12860   SourceLocation Loc = S->getBeginLoc();
12861   CapturedDecl *CD = S->getCapturedDecl();
12862   unsigned NumParams = CD->getNumParams();
12863   unsigned ContextParamPos = CD->getContextParamPosition();
12864   SmallVector<Sema::CapturedParamNameType, 4> Params;
12865   for (unsigned I = 0; I < NumParams; ++I) {
12866     if (I != ContextParamPos) {
12867       Params.push_back(
12868              std::make_pair(
12869                   CD->getParam(I)->getName(),
12870                   getDerived().TransformType(CD->getParam(I)->getType())));
12871     } else {
12872       Params.push_back(std::make_pair(StringRef(), QualType()));
12873     }
12874   }
12875   getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
12876                                      S->getCapturedRegionKind(), Params);
12877   StmtResult Body;
12878   {
12879     Sema::CompoundScopeRAII CompoundScope(getSema());
12880     Body = getDerived().TransformStmt(S->getCapturedStmt());
12881   }
12882 
12883   if (Body.isInvalid()) {
12884     getSema().ActOnCapturedRegionError();
12885     return StmtError();
12886   }
12887 
12888   return getSema().ActOnCapturedRegionEnd(Body.get());
12889 }
12890 
12891 } // end namespace clang
12892 
12893 #endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
12894