1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
9 // This file implements a semantic tree transformation that takes a given
10 // AST and rebuilds it, possibly transforming some nodes in the process.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_SEMA_TREETRANSFORM_H
15 #define LLVM_CLANG_SEMA_TREETRANSFORM_H
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/Stmt.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/Designator.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/Ownership.h"
31 #include "clang/Sema/ParsedTemplate.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/SemaDiagnostic.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/Support/ErrorHandling.h"
42 /// \brief A semantic tree transformation that allows one to transform one
43 /// abstract syntax tree into another.
45 /// A new tree transformation is defined by creating a new subclass \c X of
46 /// \c TreeTransform<X> and then overriding certain operations to provide
47 /// behavior specific to that transformation. For example, template
48 /// instantiation is implemented as a tree transformation where the
49 /// transformation of TemplateTypeParmType nodes involves substituting the
50 /// template arguments for their corresponding template parameters; a similar
51 /// transformation is performed for non-type template parameters and
52 /// template template parameters.
54 /// This tree-transformation template uses static polymorphism to allow
55 /// subclasses to customize any of its operations. Thus, a subclass can
56 /// override any of the transformation or rebuild operators by providing an
57 /// operation with the same signature as the default implementation. The
58 /// overridding function should not be virtual.
60 /// Semantic tree transformations are split into two stages, either of which
61 /// can be replaced by a subclass. The "transform" step transforms an AST node
62 /// or the parts of an AST node using the various transformation functions,
63 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
64 /// node of the appropriate kind from the pieces. The default transformation
65 /// routines recursively transform the operands to composite AST nodes (e.g.,
66 /// the pointee type of a PointerType node) and, if any of those operand nodes
67 /// were changed by the transformation, invokes the rebuild operation to create
70 /// Subclasses can customize the transformation at various levels. The
71 /// most coarse-grained transformations involve replacing TransformType(),
72 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
73 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
74 /// new implementations.
76 /// For more fine-grained transformations, subclasses can replace any of the
77 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
78 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
79 /// replacing TransformTemplateTypeParmType() allows template instantiation
80 /// to substitute template arguments for their corresponding template
81 /// parameters. Additionally, subclasses can override the \c RebuildXXX
82 /// functions to control how AST nodes are rebuilt when their operands change.
83 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
84 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
85 /// be able to use more efficient rebuild steps.
87 /// There are a handful of other functions that can be overridden, allowing one
88 /// to avoid traversing nodes that don't need any transformation
89 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
90 /// operands have not changed (\c AlwaysRebuild()), and customize the
91 /// default locations and entity names used for type-checking
92 /// (\c getBaseLocation(), \c getBaseEntity()).
93 template<typename Derived>
95 /// \brief Private RAII object that helps us forget and then re-remember
96 /// the template argument corresponding to a partially-substituted parameter
98 class ForgetPartiallySubstitutedPackRAII {
100 TemplateArgument Old;
103 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
104 Old = Self.ForgetPartiallySubstitutedPack();
107 ~ForgetPartiallySubstitutedPackRAII() {
108 Self.RememberPartiallySubstitutedPack(Old);
115 /// \brief The set of local declarations that have been transformed, for
116 /// cases where we are forced to build new declarations within the transformer
117 /// rather than in the subclass (e.g., lambda closure types).
118 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
121 /// \brief Initializes a new tree transformer.
122 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
124 /// \brief Retrieves a reference to the derived class.
125 Derived &getDerived() { return static_cast<Derived&>(*this); }
127 /// \brief Retrieves a reference to the derived class.
128 const Derived &getDerived() const {
129 return static_cast<const Derived&>(*this);
132 static inline ExprResult Owned(Expr *E) { return E; }
133 static inline StmtResult Owned(Stmt *S) { return S; }
135 /// \brief Retrieves a reference to the semantic analysis object used for
136 /// this tree transform.
137 Sema &getSema() const { return SemaRef; }
139 /// \brief Whether the transformation should always rebuild AST nodes, even
140 /// if none of the children have changed.
142 /// Subclasses may override this function to specify when the transformation
143 /// should rebuild all AST nodes.
144 bool AlwaysRebuild() { return false; }
146 /// \brief Returns the location of the entity being transformed, if that
147 /// information was not available elsewhere in the AST.
149 /// By default, returns no source-location information. Subclasses can
150 /// provide an alternative implementation that provides better location
152 SourceLocation getBaseLocation() { return SourceLocation(); }
154 /// \brief Returns the name of the entity being transformed, if that
155 /// information was not available elsewhere in the AST.
157 /// By default, returns an empty name. Subclasses can provide an alternative
158 /// implementation with a more precise name.
159 DeclarationName getBaseEntity() { return DeclarationName(); }
161 /// \brief Sets the "base" location and entity when that
162 /// information is known based on another transformation.
164 /// By default, the source location and entity are ignored. Subclasses can
165 /// override this function to provide a customized implementation.
166 void setBase(SourceLocation Loc, DeclarationName Entity) { }
168 /// \brief RAII object that temporarily sets the base location and entity
169 /// used for reporting diagnostics in types.
170 class TemporaryBase {
172 SourceLocation OldLocation;
173 DeclarationName OldEntity;
176 TemporaryBase(TreeTransform &Self, SourceLocation Location,
177 DeclarationName Entity) : Self(Self) {
178 OldLocation = Self.getDerived().getBaseLocation();
179 OldEntity = Self.getDerived().getBaseEntity();
181 if (Location.isValid())
182 Self.getDerived().setBase(Location, Entity);
186 Self.getDerived().setBase(OldLocation, OldEntity);
190 /// \brief Determine whether the given type \p T has already been
193 /// Subclasses can provide an alternative implementation of this routine
194 /// to short-circuit evaluation when it is known that a given type will
195 /// not change. For example, template instantiation need not traverse
196 /// non-dependent types.
197 bool AlreadyTransformed(QualType T) {
201 /// \brief Determine whether the given call argument should be dropped, e.g.,
202 /// because it is a default argument.
204 /// Subclasses can provide an alternative implementation of this routine to
205 /// determine which kinds of call arguments get dropped. By default,
206 /// CXXDefaultArgument nodes are dropped (prior to transformation).
207 bool DropCallArgument(Expr *E) {
208 return E->isDefaultArgument();
211 /// \brief Determine whether we should expand a pack expansion with the
212 /// given set of parameter packs into separate arguments by repeatedly
213 /// transforming the pattern.
215 /// By default, the transformer never tries to expand pack expansions.
216 /// Subclasses can override this routine to provide different behavior.
218 /// \param EllipsisLoc The location of the ellipsis that identifies the
221 /// \param PatternRange The source range that covers the entire pattern of
222 /// the pack expansion.
224 /// \param Unexpanded The set of unexpanded parameter packs within the
227 /// \param ShouldExpand Will be set to \c true if the transformer should
228 /// expand the corresponding pack expansions into separate arguments. When
229 /// set, \c NumExpansions must also be set.
231 /// \param RetainExpansion Whether the caller should add an unexpanded
232 /// pack expansion after all of the expanded arguments. This is used
233 /// when extending explicitly-specified template argument packs per
234 /// C++0x [temp.arg.explicit]p9.
236 /// \param NumExpansions The number of separate arguments that will be in
237 /// the expanded form of the corresponding pack expansion. This is both an
238 /// input and an output parameter, which can be set by the caller if the
239 /// number of expansions is known a priori (e.g., due to a prior substitution)
240 /// and will be set by the callee when the number of expansions is known.
241 /// The callee must set this value when \c ShouldExpand is \c true; it may
242 /// set this value in other cases.
244 /// \returns true if an error occurred (e.g., because the parameter packs
245 /// are to be instantiated with arguments of different lengths), false
246 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
248 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
249 SourceRange PatternRange,
250 ArrayRef<UnexpandedParameterPack> Unexpanded,
252 bool &RetainExpansion,
253 Optional<unsigned> &NumExpansions) {
254 ShouldExpand = false;
258 /// \brief "Forget" about the partially-substituted pack template argument,
259 /// when performing an instantiation that must preserve the parameter pack
262 /// This routine is meant to be overridden by the template instantiator.
263 TemplateArgument ForgetPartiallySubstitutedPack() {
264 return TemplateArgument();
267 /// \brief "Remember" the partially-substituted pack template argument
268 /// after performing an instantiation that must preserve the parameter pack
271 /// This routine is meant to be overridden by the template instantiator.
272 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
274 /// \brief Note to the derived class when a function parameter pack is
276 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
278 /// \brief Transforms the given type into another type.
280 /// By default, this routine transforms a type by creating a
281 /// TypeSourceInfo for it and delegating to the appropriate
282 /// function. This is expensive, but we don't mind, because
283 /// this method is deprecated anyway; all users should be
284 /// switched to storing TypeSourceInfos.
286 /// \returns the transformed type.
287 QualType TransformType(QualType T);
289 /// \brief Transforms the given type-with-location into a new
290 /// type-with-location.
292 /// By default, this routine transforms a type by delegating to the
293 /// appropriate TransformXXXType to build a new type. Subclasses
294 /// may override this function (to take over all type
295 /// transformations) or some set of the TransformXXXType functions
296 /// to alter the transformation.
297 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
299 /// \brief Transform the given type-with-location into a new
300 /// type, collecting location information in the given builder
303 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
305 /// \brief Transform the given statement.
307 /// By default, this routine transforms a statement by delegating to the
308 /// appropriate TransformXXXStmt function to transform a specific kind of
309 /// statement or the TransformExpr() function to transform an expression.
310 /// Subclasses may override this function to transform statements using some
313 /// \returns the transformed statement.
314 StmtResult TransformStmt(Stmt *S);
316 /// \brief Transform the given expression.
318 /// By default, this routine transforms an expression by delegating to the
319 /// appropriate TransformXXXExpr function to build a new expression.
320 /// Subclasses may override this function to transform expressions using some
323 /// \returns the transformed expression.
324 ExprResult TransformExpr(Expr *E);
326 /// \brief Transform the given initializer.
328 /// By default, this routine transforms an initializer by stripping off the
329 /// semantic nodes added by initialization, then passing the result to
330 /// TransformExpr or TransformExprs.
332 /// \returns the transformed initializer.
333 ExprResult TransformInitializer(Expr *Init, bool CXXDirectInit);
335 /// \brief Transform the given list of expressions.
337 /// This routine transforms a list of expressions by invoking
338 /// \c TransformExpr() for each subexpression. However, it also provides
339 /// support for variadic templates by expanding any pack expansions (if the
340 /// derived class permits such expansion) along the way. When pack expansions
341 /// are present, the number of outputs may not equal the number of inputs.
343 /// \param Inputs The set of expressions to be transformed.
345 /// \param NumInputs The number of expressions in \c Inputs.
347 /// \param IsCall If \c true, then this transform is being performed on
348 /// function-call arguments, and any arguments that should be dropped, will
351 /// \param Outputs The transformed input expressions will be added to this
354 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
355 /// due to transformation.
357 /// \returns true if an error occurred, false otherwise.
358 bool TransformExprs(Expr **Inputs, unsigned NumInputs, bool IsCall,
359 SmallVectorImpl<Expr *> &Outputs,
360 bool *ArgChanged = 0);
362 /// \brief Transform the given declaration, which is referenced from a type
365 /// By default, acts as the identity function on declarations, unless the
366 /// transformer has had to transform the declaration itself. Subclasses
367 /// may override this function to provide alternate behavior.
368 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
369 llvm::DenseMap<Decl *, Decl *>::iterator Known
370 = TransformedLocalDecls.find(D);
371 if (Known != TransformedLocalDecls.end())
372 return Known->second;
377 /// \brief Transform the attributes associated with the given declaration and
378 /// place them on the new declaration.
380 /// By default, this operation does nothing. Subclasses may override this
381 /// behavior to transform attributes.
382 void transformAttrs(Decl *Old, Decl *New) { }
384 /// \brief Note that a local declaration has been transformed by this
387 /// Local declarations are typically transformed via a call to
388 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
389 /// the transformer itself has to transform the declarations. This routine
390 /// can be overridden by a subclass that keeps track of such mappings.
391 void transformedLocalDecl(Decl *Old, Decl *New) {
392 TransformedLocalDecls[Old] = New;
395 /// \brief Transform the definition of the given declaration.
397 /// By default, invokes TransformDecl() to transform the declaration.
398 /// Subclasses may override this function to provide alternate behavior.
399 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
400 return getDerived().TransformDecl(Loc, D);
403 /// \brief Transform the given declaration, which was the first part of a
404 /// nested-name-specifier in a member access expression.
406 /// This specific declaration transformation only applies to the first
407 /// identifier in a nested-name-specifier of a member access expression, e.g.,
408 /// the \c T in \c x->T::member
410 /// By default, invokes TransformDecl() to transform the declaration.
411 /// Subclasses may override this function to provide alternate behavior.
412 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
413 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
416 /// \brief Transform the given nested-name-specifier with source-location
419 /// By default, transforms all of the types and declarations within the
420 /// nested-name-specifier. Subclasses may override this function to provide
421 /// alternate behavior.
422 NestedNameSpecifierLoc TransformNestedNameSpecifierLoc(
423 NestedNameSpecifierLoc NNS,
424 QualType ObjectType = QualType(),
425 NamedDecl *FirstQualifierInScope = 0);
427 /// \brief Transform the given declaration name.
429 /// By default, transforms the types of conversion function, constructor,
430 /// and destructor names and then (if needed) rebuilds the declaration name.
431 /// Identifiers and selectors are returned unmodified. Sublcasses may
432 /// override this function to provide alternate behavior.
434 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
436 /// \brief Transform the given template name.
438 /// \param SS The nested-name-specifier that qualifies the template
439 /// name. This nested-name-specifier must already have been transformed.
441 /// \param Name The template name to transform.
443 /// \param NameLoc The source location of the template name.
445 /// \param ObjectType If we're translating a template name within a member
446 /// access expression, this is the type of the object whose member template
447 /// is being referenced.
449 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
450 /// also refers to a name within the current (lexical) scope, this is the
451 /// declaration it refers to.
453 /// By default, transforms the template name by transforming the declarations
454 /// and nested-name-specifiers that occur within the template name.
455 /// Subclasses may override this function to provide alternate behavior.
456 TemplateName TransformTemplateName(CXXScopeSpec &SS,
458 SourceLocation NameLoc,
459 QualType ObjectType = QualType(),
460 NamedDecl *FirstQualifierInScope = 0);
462 /// \brief Transform the given template argument.
464 /// By default, this operation transforms the type, expression, or
465 /// declaration stored within the template argument and constructs a
466 /// new template argument from the transformed result. Subclasses may
467 /// override this function to provide alternate behavior.
469 /// Returns true if there was an error.
470 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
471 TemplateArgumentLoc &Output);
473 /// \brief Transform the given set of template arguments.
475 /// By default, this operation transforms all of the template arguments
476 /// in the input set using \c TransformTemplateArgument(), and appends
477 /// the transformed arguments to the output list.
479 /// Note that this overload of \c TransformTemplateArguments() is merely
480 /// a convenience function. Subclasses that wish to override this behavior
481 /// should override the iterator-based member template version.
483 /// \param Inputs The set of template arguments to be transformed.
485 /// \param NumInputs The number of template arguments in \p Inputs.
487 /// \param Outputs The set of transformed template arguments output by this
490 /// Returns true if an error occurred.
491 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
493 TemplateArgumentListInfo &Outputs) {
494 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs);
497 /// \brief Transform the given set of template arguments.
499 /// By default, this operation transforms all of the template arguments
500 /// in the input set using \c TransformTemplateArgument(), and appends
501 /// the transformed arguments to the output list.
503 /// \param First An iterator to the first template argument.
505 /// \param Last An iterator one step past the last template argument.
507 /// \param Outputs The set of transformed template arguments output by this
510 /// Returns true if an error occurred.
511 template<typename InputIterator>
512 bool TransformTemplateArguments(InputIterator First,
514 TemplateArgumentListInfo &Outputs);
516 /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
517 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
518 TemplateArgumentLoc &ArgLoc);
520 /// \brief Fakes up a TypeSourceInfo for a type.
521 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
522 return SemaRef.Context.getTrivialTypeSourceInfo(T,
523 getDerived().getBaseLocation());
526 #define ABSTRACT_TYPELOC(CLASS, PARENT)
527 #define TYPELOC(CLASS, PARENT) \
528 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
529 #include "clang/AST/TypeLocNodes.def"
531 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
532 FunctionProtoTypeLoc TL,
533 CXXRecordDecl *ThisContext,
534 unsigned ThisTypeQuals);
537 TransformSEHHandler(Stmt *Handler);
540 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
541 TemplateSpecializationTypeLoc TL,
542 TemplateName Template);
545 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
546 DependentTemplateSpecializationTypeLoc TL,
547 TemplateName Template,
551 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
552 DependentTemplateSpecializationTypeLoc TL,
553 NestedNameSpecifierLoc QualifierLoc);
555 /// \brief Transforms the parameters of a function type into the
558 /// The result vectors should be kept in sync; null entries in the
559 /// variables vector are acceptable.
561 /// Return true on error.
562 bool TransformFunctionTypeParams(SourceLocation Loc,
563 ParmVarDecl **Params, unsigned NumParams,
564 const QualType *ParamTypes,
565 SmallVectorImpl<QualType> &PTypes,
566 SmallVectorImpl<ParmVarDecl*> *PVars);
568 /// \brief Transforms a single function-type parameter. Return null
571 /// \param indexAdjustment - A number to add to the parameter's
572 /// scope index; can be negative
573 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
575 Optional<unsigned> NumExpansions,
576 bool ExpectParameterPack);
578 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
580 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
581 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
583 /// \brief Transform the captures and body of a lambda expression.
584 ExprResult TransformLambdaScope(LambdaExpr *E, CXXMethodDecl *CallOperator);
586 ExprResult TransformAddressOfOperand(Expr *E);
587 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
588 bool IsAddressOfOperand);
590 #define STMT(Node, Parent) \
591 StmtResult Transform##Node(Node *S);
592 #define EXPR(Node, Parent) \
593 ExprResult Transform##Node(Node *E);
594 #define ABSTRACT_STMT(Stmt)
595 #include "clang/AST/StmtNodes.inc"
597 /// \brief Build a new pointer type given its pointee type.
599 /// By default, performs semantic analysis when building the pointer type.
600 /// Subclasses may override this routine to provide different behavior.
601 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
603 /// \brief Build a new block pointer type given its pointee type.
605 /// By default, performs semantic analysis when building the block pointer
606 /// type. Subclasses may override this routine to provide different behavior.
607 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
609 /// \brief Build a new reference type given the type it references.
611 /// By default, performs semantic analysis when building the
612 /// reference type. Subclasses may override this routine to provide
613 /// different behavior.
615 /// \param LValue whether the type was written with an lvalue sigil
616 /// or an rvalue sigil.
617 QualType RebuildReferenceType(QualType ReferentType,
619 SourceLocation Sigil);
621 /// \brief Build a new member pointer type given the pointee type and the
622 /// class type it refers into.
624 /// By default, performs semantic analysis when building the member pointer
625 /// type. Subclasses may override this routine to provide different behavior.
626 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
627 SourceLocation Sigil);
629 /// \brief Build a new array type given the element type, size
630 /// modifier, size of the array (if known), size expression, and index type
633 /// By default, performs semantic analysis when building the array type.
634 /// Subclasses may override this routine to provide different behavior.
635 /// Also by default, all of the other Rebuild*Array
636 QualType RebuildArrayType(QualType ElementType,
637 ArrayType::ArraySizeModifier SizeMod,
638 const llvm::APInt *Size,
640 unsigned IndexTypeQuals,
641 SourceRange BracketsRange);
643 /// \brief Build a new constant array type given the element type, size
644 /// modifier, (known) size of the array, and index type qualifiers.
646 /// By default, performs semantic analysis when building the array type.
647 /// Subclasses may override this routine to provide different behavior.
648 QualType RebuildConstantArrayType(QualType ElementType,
649 ArrayType::ArraySizeModifier SizeMod,
650 const llvm::APInt &Size,
651 unsigned IndexTypeQuals,
652 SourceRange BracketsRange);
654 /// \brief Build a new incomplete array type given the element type, size
655 /// modifier, and index type qualifiers.
657 /// By default, performs semantic analysis when building the array type.
658 /// Subclasses may override this routine to provide different behavior.
659 QualType RebuildIncompleteArrayType(QualType ElementType,
660 ArrayType::ArraySizeModifier SizeMod,
661 unsigned IndexTypeQuals,
662 SourceRange BracketsRange);
664 /// \brief Build a new variable-length array type given the element type,
665 /// size modifier, size expression, and index type qualifiers.
667 /// By default, performs semantic analysis when building the array type.
668 /// Subclasses may override this routine to provide different behavior.
669 QualType RebuildVariableArrayType(QualType ElementType,
670 ArrayType::ArraySizeModifier SizeMod,
672 unsigned IndexTypeQuals,
673 SourceRange BracketsRange);
675 /// \brief Build a new dependent-sized array type given the element type,
676 /// size modifier, size expression, and index type qualifiers.
678 /// By default, performs semantic analysis when building the array type.
679 /// Subclasses may override this routine to provide different behavior.
680 QualType RebuildDependentSizedArrayType(QualType ElementType,
681 ArrayType::ArraySizeModifier SizeMod,
683 unsigned IndexTypeQuals,
684 SourceRange BracketsRange);
686 /// \brief Build a new vector type given the element type and
687 /// number of elements.
689 /// By default, performs semantic analysis when building the vector type.
690 /// Subclasses may override this routine to provide different behavior.
691 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
692 VectorType::VectorKind VecKind);
694 /// \brief Build a new extended vector type given the element type and
695 /// number of elements.
697 /// By default, performs semantic analysis when building the vector type.
698 /// Subclasses may override this routine to provide different behavior.
699 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
700 SourceLocation AttributeLoc);
702 /// \brief Build a new potentially dependently-sized extended vector type
703 /// given the element type and number of elements.
705 /// By default, performs semantic analysis when building the vector type.
706 /// Subclasses may override this routine to provide different behavior.
707 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
709 SourceLocation AttributeLoc);
711 /// \brief Build a new function type.
713 /// By default, performs semantic analysis when building the function type.
714 /// Subclasses may override this routine to provide different behavior.
715 QualType RebuildFunctionProtoType(QualType T,
716 llvm::MutableArrayRef<QualType> ParamTypes,
717 const FunctionProtoType::ExtProtoInfo &EPI);
719 /// \brief Build a new unprototyped function type.
720 QualType RebuildFunctionNoProtoType(QualType ResultType);
722 /// \brief Rebuild an unresolved typename type, given the decl that
723 /// the UnresolvedUsingTypenameDecl was transformed to.
724 QualType RebuildUnresolvedUsingType(Decl *D);
726 /// \brief Build a new typedef type.
727 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
728 return SemaRef.Context.getTypeDeclType(Typedef);
731 /// \brief Build a new class/struct/union type.
732 QualType RebuildRecordType(RecordDecl *Record) {
733 return SemaRef.Context.getTypeDeclType(Record);
736 /// \brief Build a new Enum type.
737 QualType RebuildEnumType(EnumDecl *Enum) {
738 return SemaRef.Context.getTypeDeclType(Enum);
741 /// \brief Build a new typeof(expr) type.
743 /// By default, performs semantic analysis when building the typeof type.
744 /// Subclasses may override this routine to provide different behavior.
745 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
747 /// \brief Build a new typeof(type) type.
749 /// By default, builds a new TypeOfType with the given underlying type.
750 QualType RebuildTypeOfType(QualType Underlying);
752 /// \brief Build a new unary transform type.
753 QualType RebuildUnaryTransformType(QualType BaseType,
754 UnaryTransformType::UTTKind UKind,
757 /// \brief Build a new C++11 decltype type.
759 /// By default, performs semantic analysis when building the decltype type.
760 /// Subclasses may override this routine to provide different behavior.
761 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
763 /// \brief Build a new C++11 auto type.
765 /// By default, builds a new AutoType with the given deduced type.
766 QualType RebuildAutoType(QualType Deduced, bool IsDecltypeAuto) {
767 // Note, IsDependent is always false here: we implicitly convert an 'auto'
768 // which has been deduced to a dependent type into an undeduced 'auto', so
769 // that we'll retry deduction after the transformation.
770 return SemaRef.Context.getAutoType(Deduced, IsDecltypeAuto);
773 /// \brief Build a new template specialization type.
775 /// By default, performs semantic analysis when building the template
776 /// specialization type. Subclasses may override this routine to provide
777 /// different behavior.
778 QualType RebuildTemplateSpecializationType(TemplateName Template,
779 SourceLocation TemplateLoc,
780 TemplateArgumentListInfo &Args);
782 /// \brief Build a new parenthesized type.
784 /// By default, builds a new ParenType type from the inner type.
785 /// Subclasses may override this routine to provide different behavior.
786 QualType RebuildParenType(QualType InnerType) {
787 return SemaRef.Context.getParenType(InnerType);
790 /// \brief Build a new qualified name type.
792 /// By default, builds a new ElaboratedType type from the keyword,
793 /// the nested-name-specifier and the named type.
794 /// Subclasses may override this routine to provide different behavior.
795 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
796 ElaboratedTypeKeyword Keyword,
797 NestedNameSpecifierLoc QualifierLoc,
799 return SemaRef.Context.getElaboratedType(Keyword,
800 QualifierLoc.getNestedNameSpecifier(),
804 /// \brief Build a new typename type that refers to a template-id.
806 /// By default, builds a new DependentNameType type from the
807 /// nested-name-specifier and the given type. Subclasses may override
808 /// this routine to provide different behavior.
809 QualType RebuildDependentTemplateSpecializationType(
810 ElaboratedTypeKeyword Keyword,
811 NestedNameSpecifierLoc QualifierLoc,
812 const IdentifierInfo *Name,
813 SourceLocation NameLoc,
814 TemplateArgumentListInfo &Args) {
815 // Rebuild the template name.
816 // TODO: avoid TemplateName abstraction
818 SS.Adopt(QualifierLoc);
819 TemplateName InstName
820 = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(), 0);
822 if (InstName.isNull())
825 // If it's still dependent, make a dependent specialization.
826 if (InstName.getAsDependentTemplateName())
827 return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
828 QualifierLoc.getNestedNameSpecifier(),
832 // Otherwise, make an elaborated type wrapping a non-dependent
835 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
836 if (T.isNull()) return QualType();
838 if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == 0)
841 return SemaRef.Context.getElaboratedType(Keyword,
842 QualifierLoc.getNestedNameSpecifier(),
846 /// \brief Build a new typename type that refers to an identifier.
848 /// By default, performs semantic analysis when building the typename type
849 /// (or elaborated type). Subclasses may override this routine to provide
850 /// different behavior.
851 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
852 SourceLocation KeywordLoc,
853 NestedNameSpecifierLoc QualifierLoc,
854 const IdentifierInfo *Id,
855 SourceLocation IdLoc) {
857 SS.Adopt(QualifierLoc);
859 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
860 // If the name is still dependent, just build a new dependent name type.
861 if (!SemaRef.computeDeclContext(SS))
862 return SemaRef.Context.getDependentNameType(Keyword,
863 QualifierLoc.getNestedNameSpecifier(),
867 if (Keyword == ETK_None || Keyword == ETK_Typename)
868 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
871 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
873 // We had a dependent elaborated-type-specifier that has been transformed
874 // into a non-dependent elaborated-type-specifier. Find the tag we're
876 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
877 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
881 if (SemaRef.RequireCompleteDeclContext(SS, DC))
885 SemaRef.LookupQualifiedName(Result, DC);
886 switch (Result.getResultKind()) {
887 case LookupResult::NotFound:
888 case LookupResult::NotFoundInCurrentInstantiation:
891 case LookupResult::Found:
892 Tag = Result.getAsSingle<TagDecl>();
895 case LookupResult::FoundOverloaded:
896 case LookupResult::FoundUnresolvedValue:
897 llvm_unreachable("Tag lookup cannot find non-tags");
899 case LookupResult::Ambiguous:
900 // Let the LookupResult structure handle ambiguities.
905 // Check where the name exists but isn't a tag type and use that to emit
906 // better diagnostics.
907 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
908 SemaRef.LookupQualifiedName(Result, DC);
909 switch (Result.getResultKind()) {
910 case LookupResult::Found:
911 case LookupResult::FoundOverloaded:
912 case LookupResult::FoundUnresolvedValue: {
913 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
915 if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
916 else if (isa<TypeAliasDecl>(SomeDecl)) Kind = 2;
917 else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 3;
918 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
919 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
923 // FIXME: Would be nice to highlight just the source range.
924 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
931 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
933 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
934 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
938 // Build the elaborated-type-specifier type.
939 QualType T = SemaRef.Context.getTypeDeclType(Tag);
940 return SemaRef.Context.getElaboratedType(Keyword,
941 QualifierLoc.getNestedNameSpecifier(),
945 /// \brief Build a new pack expansion type.
947 /// By default, builds a new PackExpansionType type from the given pattern.
948 /// Subclasses may override this routine to provide different behavior.
949 QualType RebuildPackExpansionType(QualType Pattern,
950 SourceRange PatternRange,
951 SourceLocation EllipsisLoc,
952 Optional<unsigned> NumExpansions) {
953 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
957 /// \brief Build a new atomic type given its value type.
959 /// By default, performs semantic analysis when building the atomic type.
960 /// Subclasses may override this routine to provide different behavior.
961 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
963 /// \brief Build a new template name given a nested name specifier, a flag
964 /// indicating whether the "template" keyword was provided, and the template
965 /// that the template name refers to.
967 /// By default, builds the new template name directly. Subclasses may override
968 /// this routine to provide different behavior.
969 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
971 TemplateDecl *Template);
973 /// \brief Build a new template name given a nested name specifier and the
974 /// name that is referred to as a template.
976 /// By default, performs semantic analysis to determine whether the name can
977 /// be resolved to a specific template, then builds the appropriate kind of
978 /// template name. Subclasses may override this routine to provide different
980 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
981 const IdentifierInfo &Name,
982 SourceLocation NameLoc,
984 NamedDecl *FirstQualifierInScope);
986 /// \brief Build a new template name given a nested name specifier and the
987 /// overloaded operator name that is referred to as a template.
989 /// By default, performs semantic analysis to determine whether the name can
990 /// be resolved to a specific template, then builds the appropriate kind of
991 /// template name. Subclasses may override this routine to provide different
993 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
994 OverloadedOperatorKind Operator,
995 SourceLocation NameLoc,
996 QualType ObjectType);
998 /// \brief Build a new template name given a template template parameter pack
1001 /// By default, performs semantic analysis to determine whether the name can
1002 /// be resolved to a specific template, then builds the appropriate kind of
1003 /// template name. Subclasses may override this routine to provide different
1005 TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
1006 const TemplateArgument &ArgPack) {
1007 return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
1010 /// \brief Build a new compound statement.
1012 /// By default, performs semantic analysis to build the new statement.
1013 /// Subclasses may override this routine to provide different behavior.
1014 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1015 MultiStmtArg Statements,
1016 SourceLocation RBraceLoc,
1018 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1022 /// \brief Build a new case statement.
1024 /// By default, performs semantic analysis to build the new statement.
1025 /// Subclasses may override this routine to provide different behavior.
1026 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1028 SourceLocation EllipsisLoc,
1030 SourceLocation ColonLoc) {
1031 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1035 /// \brief Attach the body to a new case statement.
1037 /// By default, performs semantic analysis to build the new statement.
1038 /// Subclasses may override this routine to provide different behavior.
1039 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1040 getSema().ActOnCaseStmtBody(S, Body);
1044 /// \brief Build a new default statement.
1046 /// By default, performs semantic analysis to build the new statement.
1047 /// Subclasses may override this routine to provide different behavior.
1048 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1049 SourceLocation ColonLoc,
1051 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1055 /// \brief Build a new label statement.
1057 /// By default, performs semantic analysis to build the new statement.
1058 /// Subclasses may override this routine to provide different behavior.
1059 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1060 SourceLocation ColonLoc, Stmt *SubStmt) {
1061 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1064 /// \brief Build a new label statement.
1066 /// By default, performs semantic analysis to build the new statement.
1067 /// Subclasses may override this routine to provide different behavior.
1068 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1069 ArrayRef<const Attr*> Attrs,
1071 return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
1074 /// \brief Build a new "if" statement.
1076 /// By default, performs semantic analysis to build the new statement.
1077 /// Subclasses may override this routine to provide different behavior.
1078 StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
1079 VarDecl *CondVar, Stmt *Then,
1080 SourceLocation ElseLoc, Stmt *Else) {
1081 return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
1084 /// \brief Start building a new switch statement.
1086 /// By default, performs semantic analysis to build the new statement.
1087 /// Subclasses may override this routine to provide different behavior.
1088 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1089 Expr *Cond, VarDecl *CondVar) {
1090 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
1094 /// \brief Attach the body to the switch statement.
1096 /// By default, performs semantic analysis to build the new statement.
1097 /// Subclasses may override this routine to provide different behavior.
1098 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1099 Stmt *Switch, Stmt *Body) {
1100 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1103 /// \brief Build a new while statement.
1105 /// By default, performs semantic analysis to build the new statement.
1106 /// Subclasses may override this routine to provide different behavior.
1107 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, Sema::FullExprArg Cond,
1108 VarDecl *CondVar, Stmt *Body) {
1109 return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
1112 /// \brief Build a new do-while statement.
1114 /// By default, performs semantic analysis to build the new statement.
1115 /// Subclasses may override this routine to provide different behavior.
1116 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1117 SourceLocation WhileLoc, SourceLocation LParenLoc,
1118 Expr *Cond, SourceLocation RParenLoc) {
1119 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1123 /// \brief Build a new for statement.
1125 /// By default, performs semantic analysis to build the new statement.
1126 /// Subclasses may override this routine to provide different behavior.
1127 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1128 Stmt *Init, Sema::FullExprArg Cond,
1129 VarDecl *CondVar, Sema::FullExprArg Inc,
1130 SourceLocation RParenLoc, Stmt *Body) {
1131 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1132 CondVar, Inc, RParenLoc, Body);
1135 /// \brief Build a new goto statement.
1137 /// By default, performs semantic analysis to build the new statement.
1138 /// Subclasses may override this routine to provide different behavior.
1139 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1141 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1144 /// \brief Build a new indirect goto statement.
1146 /// By default, performs semantic analysis to build the new statement.
1147 /// Subclasses may override this routine to provide different behavior.
1148 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1149 SourceLocation StarLoc,
1151 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1154 /// \brief Build a new return statement.
1156 /// By default, performs semantic analysis to build the new statement.
1157 /// Subclasses may override this routine to provide different behavior.
1158 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1159 return getSema().ActOnReturnStmt(ReturnLoc, Result);
1162 /// \brief Build a new declaration statement.
1164 /// By default, performs semantic analysis to build the new statement.
1165 /// Subclasses may override this routine to provide different behavior.
1166 StmtResult RebuildDeclStmt(Decl **Decls, unsigned NumDecls,
1167 SourceLocation StartLoc,
1168 SourceLocation EndLoc) {
1169 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls, NumDecls);
1170 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1173 /// \brief Build a new inline asm statement.
1175 /// By default, performs semantic analysis to build the new statement.
1176 /// Subclasses may override this routine to provide different behavior.
1177 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1178 bool IsVolatile, unsigned NumOutputs,
1179 unsigned NumInputs, IdentifierInfo **Names,
1180 MultiExprArg Constraints, MultiExprArg Exprs,
1181 Expr *AsmString, MultiExprArg Clobbers,
1182 SourceLocation RParenLoc) {
1183 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1184 NumInputs, Names, Constraints, Exprs,
1185 AsmString, Clobbers, RParenLoc);
1188 /// \brief Build a new MS style inline asm statement.
1190 /// By default, performs semantic analysis to build the new statement.
1191 /// Subclasses may override this routine to provide different behavior.
1192 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1193 ArrayRef<Token> AsmToks,
1194 StringRef AsmString,
1195 unsigned NumOutputs, unsigned NumInputs,
1196 ArrayRef<StringRef> Constraints,
1197 ArrayRef<StringRef> Clobbers,
1198 ArrayRef<Expr*> Exprs,
1199 SourceLocation EndLoc) {
1200 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1201 NumOutputs, NumInputs,
1202 Constraints, Clobbers, Exprs, EndLoc);
1205 /// \brief Build a new Objective-C \@try statement.
1207 /// By default, performs semantic analysis to build the new statement.
1208 /// Subclasses may override this routine to provide different behavior.
1209 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1211 MultiStmtArg CatchStmts,
1213 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1217 /// \brief Rebuild an Objective-C exception declaration.
1219 /// By default, performs semantic analysis to build the new declaration.
1220 /// Subclasses may override this routine to provide different behavior.
1221 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1222 TypeSourceInfo *TInfo, QualType T) {
1223 return getSema().BuildObjCExceptionDecl(TInfo, T,
1224 ExceptionDecl->getInnerLocStart(),
1225 ExceptionDecl->getLocation(),
1226 ExceptionDecl->getIdentifier());
1229 /// \brief Build a new Objective-C \@catch statement.
1231 /// By default, performs semantic analysis to build the new statement.
1232 /// Subclasses may override this routine to provide different behavior.
1233 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1234 SourceLocation RParenLoc,
1237 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1241 /// \brief Build a new Objective-C \@finally statement.
1243 /// By default, performs semantic analysis to build the new statement.
1244 /// Subclasses may override this routine to provide different behavior.
1245 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1247 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1250 /// \brief Build a new Objective-C \@throw statement.
1252 /// By default, performs semantic analysis to build the new statement.
1253 /// Subclasses may override this routine to provide different behavior.
1254 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1256 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1259 /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
1261 /// By default, performs semantic analysis to build the new statement.
1262 /// Subclasses may override this routine to provide different behavior.
1263 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
1265 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
1268 /// \brief Build a new Objective-C \@synchronized statement.
1270 /// By default, performs semantic analysis to build the new statement.
1271 /// Subclasses may override this routine to provide different behavior.
1272 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
1273 Expr *Object, Stmt *Body) {
1274 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
1277 /// \brief Build a new Objective-C \@autoreleasepool statement.
1279 /// By default, performs semantic analysis to build the new statement.
1280 /// Subclasses may override this routine to provide different behavior.
1281 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
1283 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
1286 /// \brief Build a new Objective-C fast enumeration statement.
1288 /// By default, performs semantic analysis to build the new statement.
1289 /// Subclasses may override this routine to provide different behavior.
1290 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
1293 SourceLocation RParenLoc,
1295 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
1299 if (ForEachStmt.isInvalid())
1302 return getSema().FinishObjCForCollectionStmt(ForEachStmt.take(), Body);
1305 /// \brief Build a new C++ exception declaration.
1307 /// By default, performs semantic analysis to build the new decaration.
1308 /// Subclasses may override this routine to provide different behavior.
1309 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1310 TypeSourceInfo *Declarator,
1311 SourceLocation StartLoc,
1312 SourceLocation IdLoc,
1313 IdentifierInfo *Id) {
1314 VarDecl *Var = getSema().BuildExceptionDeclaration(0, Declarator,
1315 StartLoc, IdLoc, Id);
1317 getSema().CurContext->addDecl(Var);
1321 /// \brief Build a new C++ catch statement.
1323 /// By default, performs semantic analysis to build the new statement.
1324 /// Subclasses may override this routine to provide different behavior.
1325 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
1326 VarDecl *ExceptionDecl,
1328 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
1332 /// \brief Build a new C++ try statement.
1334 /// By default, performs semantic analysis to build the new statement.
1335 /// Subclasses may override this routine to provide different behavior.
1336 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc,
1338 MultiStmtArg Handlers) {
1339 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
1342 /// \brief Build a new C++0x range-based for statement.
1344 /// By default, performs semantic analysis to build the new statement.
1345 /// Subclasses may override this routine to provide different behavior.
1346 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
1347 SourceLocation ColonLoc,
1348 Stmt *Range, Stmt *BeginEnd,
1349 Expr *Cond, Expr *Inc,
1351 SourceLocation RParenLoc) {
1352 // If we've just learned that the range is actually an Objective-C
1353 // collection, treat this as an Objective-C fast enumeration loop.
1354 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
1355 if (RangeStmt->isSingleDecl()) {
1356 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
1357 if (RangeVar->isInvalidDecl())
1360 Expr *RangeExpr = RangeVar->getInit();
1361 if (!RangeExpr->isTypeDependent() &&
1362 RangeExpr->getType()->isObjCObjectPointerType())
1363 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
1369 return getSema().BuildCXXForRangeStmt(ForLoc, ColonLoc, Range, BeginEnd,
1370 Cond, Inc, LoopVar, RParenLoc,
1371 Sema::BFRK_Rebuild);
1374 /// \brief Build a new C++0x range-based for statement.
1376 /// By default, performs semantic analysis to build the new statement.
1377 /// Subclasses may override this routine to provide different behavior.
1378 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
1380 NestedNameSpecifierLoc QualifierLoc,
1381 DeclarationNameInfo NameInfo,
1383 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
1384 QualifierLoc, NameInfo, Nested);
1387 /// \brief Attach body to a C++0x range-based for statement.
1389 /// By default, performs semantic analysis to finish the new statement.
1390 /// Subclasses may override this routine to provide different behavior.
1391 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
1392 return getSema().FinishCXXForRangeStmt(ForRange, Body);
1395 StmtResult RebuildSEHTryStmt(bool IsCXXTry,
1396 SourceLocation TryLoc,
1399 return getSema().ActOnSEHTryBlock(IsCXXTry,TryLoc,TryBlock,Handler);
1402 StmtResult RebuildSEHExceptStmt(SourceLocation Loc,
1405 return getSema().ActOnSEHExceptBlock(Loc,FilterExpr,Block);
1408 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc,
1410 return getSema().ActOnSEHFinallyBlock(Loc,Block);
1413 /// \brief Build a new expression that references a declaration.
1415 /// By default, performs semantic analysis to build the new expression.
1416 /// Subclasses may override this routine to provide different behavior.
1417 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
1420 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
1424 /// \brief Build a new expression that references a declaration.
1426 /// By default, performs semantic analysis to build the new expression.
1427 /// Subclasses may override this routine to provide different behavior.
1428 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
1430 const DeclarationNameInfo &NameInfo,
1431 TemplateArgumentListInfo *TemplateArgs) {
1433 SS.Adopt(QualifierLoc);
1435 // FIXME: loses template args.
1437 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
1440 /// \brief Build a new expression in parentheses.
1442 /// By default, performs semantic analysis to build the new expression.
1443 /// Subclasses may override this routine to provide different behavior.
1444 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
1445 SourceLocation RParen) {
1446 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
1449 /// \brief Build a new pseudo-destructor expression.
1451 /// By default, performs semantic analysis to build the new expression.
1452 /// Subclasses may override this routine to provide different behavior.
1453 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
1454 SourceLocation OperatorLoc,
1457 TypeSourceInfo *ScopeType,
1458 SourceLocation CCLoc,
1459 SourceLocation TildeLoc,
1460 PseudoDestructorTypeStorage Destroyed);
1462 /// \brief Build a new unary operator expression.
1464 /// By default, performs semantic analysis to build the new expression.
1465 /// Subclasses may override this routine to provide different behavior.
1466 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
1467 UnaryOperatorKind Opc,
1469 return getSema().BuildUnaryOp(/*Scope=*/0, OpLoc, Opc, SubExpr);
1472 /// \brief Build a new builtin offsetof expression.
1474 /// By default, performs semantic analysis to build the new expression.
1475 /// Subclasses may override this routine to provide different behavior.
1476 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
1477 TypeSourceInfo *Type,
1478 Sema::OffsetOfComponent *Components,
1479 unsigned NumComponents,
1480 SourceLocation RParenLoc) {
1481 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
1482 NumComponents, RParenLoc);
1485 /// \brief Build a new sizeof, alignof or vec_step expression with a
1488 /// By default, performs semantic analysis to build the new expression.
1489 /// Subclasses may override this routine to provide different behavior.
1490 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
1491 SourceLocation OpLoc,
1492 UnaryExprOrTypeTrait ExprKind,
1494 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
1497 /// \brief Build a new sizeof, alignof or vec step expression with an
1498 /// expression argument.
1500 /// By default, performs semantic analysis to build the new expression.
1501 /// Subclasses may override this routine to provide different behavior.
1502 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
1503 UnaryExprOrTypeTrait ExprKind,
1506 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
1507 if (Result.isInvalid())
1513 /// \brief Build a new array subscript expression.
1515 /// By default, performs semantic analysis to build the new expression.
1516 /// Subclasses may override this routine to provide different behavior.
1517 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
1518 SourceLocation LBracketLoc,
1520 SourceLocation RBracketLoc) {
1521 return getSema().ActOnArraySubscriptExpr(/*Scope=*/0, LHS,
1526 /// \brief Build a new call expression.
1528 /// By default, performs semantic analysis to build the new expression.
1529 /// Subclasses may override this routine to provide different behavior.
1530 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
1532 SourceLocation RParenLoc,
1533 Expr *ExecConfig = 0) {
1534 return getSema().ActOnCallExpr(/*Scope=*/0, Callee, LParenLoc,
1535 Args, RParenLoc, ExecConfig);
1538 /// \brief Build a new member access expression.
1540 /// By default, performs semantic analysis to build the new expression.
1541 /// Subclasses may override this routine to provide different behavior.
1542 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
1544 NestedNameSpecifierLoc QualifierLoc,
1545 SourceLocation TemplateKWLoc,
1546 const DeclarationNameInfo &MemberNameInfo,
1548 NamedDecl *FoundDecl,
1549 const TemplateArgumentListInfo *ExplicitTemplateArgs,
1550 NamedDecl *FirstQualifierInScope) {
1551 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
1553 if (!Member->getDeclName()) {
1554 // We have a reference to an unnamed field. This is always the
1555 // base of an anonymous struct/union member access, i.e. the
1556 // field is always of record type.
1557 assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
1558 assert(Member->getType()->isRecordType() &&
1559 "unnamed member not of record type?");
1562 getSema().PerformObjectMemberConversion(BaseResult.take(),
1563 QualifierLoc.getNestedNameSpecifier(),
1565 if (BaseResult.isInvalid())
1567 Base = BaseResult.take();
1568 ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
1570 new (getSema().Context) MemberExpr(Base, isArrow,
1571 Member, MemberNameInfo,
1572 cast<FieldDecl>(Member)->getType(),
1574 return getSema().Owned(ME);
1578 SS.Adopt(QualifierLoc);
1580 Base = BaseResult.take();
1581 QualType BaseType = Base->getType();
1583 // FIXME: this involves duplicating earlier analysis in a lot of
1584 // cases; we should avoid this when possible.
1585 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
1586 R.addDecl(FoundDecl);
1589 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
1591 FirstQualifierInScope,
1592 R, ExplicitTemplateArgs);
1595 /// \brief Build a new binary operator expression.
1597 /// By default, performs semantic analysis to build the new expression.
1598 /// Subclasses may override this routine to provide different behavior.
1599 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
1600 BinaryOperatorKind Opc,
1601 Expr *LHS, Expr *RHS) {
1602 return getSema().BuildBinOp(/*Scope=*/0, OpLoc, Opc, LHS, RHS);
1605 /// \brief Build a new conditional operator expression.
1607 /// By default, performs semantic analysis to build the new expression.
1608 /// Subclasses may override this routine to provide different behavior.
1609 ExprResult RebuildConditionalOperator(Expr *Cond,
1610 SourceLocation QuestionLoc,
1612 SourceLocation ColonLoc,
1614 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
1618 /// \brief Build a new C-style cast expression.
1620 /// By default, performs semantic analysis to build the new expression.
1621 /// Subclasses may override this routine to provide different behavior.
1622 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
1623 TypeSourceInfo *TInfo,
1624 SourceLocation RParenLoc,
1626 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
1630 /// \brief Build a new compound literal expression.
1632 /// By default, performs semantic analysis to build the new expression.
1633 /// Subclasses may override this routine to provide different behavior.
1634 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
1635 TypeSourceInfo *TInfo,
1636 SourceLocation RParenLoc,
1638 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
1642 /// \brief Build a new extended vector element access expression.
1644 /// By default, performs semantic analysis to build the new expression.
1645 /// Subclasses may override this routine to provide different behavior.
1646 ExprResult RebuildExtVectorElementExpr(Expr *Base,
1647 SourceLocation OpLoc,
1648 SourceLocation AccessorLoc,
1649 IdentifierInfo &Accessor) {
1652 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
1653 return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
1654 OpLoc, /*IsArrow*/ false,
1655 SS, SourceLocation(),
1656 /*FirstQualifierInScope*/ 0,
1658 /* TemplateArgs */ 0);
1661 /// \brief Build a new initializer list expression.
1663 /// By default, performs semantic analysis to build the new expression.
1664 /// Subclasses may override this routine to provide different behavior.
1665 ExprResult RebuildInitList(SourceLocation LBraceLoc,
1667 SourceLocation RBraceLoc,
1668 QualType ResultTy) {
1670 = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
1671 if (Result.isInvalid() || ResultTy->isDependentType())
1674 // Patch in the result type we were given, which may have been computed
1675 // when the initial InitListExpr was built.
1676 InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
1677 ILE->setType(ResultTy);
1681 /// \brief Build a new designated initializer expression.
1683 /// By default, performs semantic analysis to build the new expression.
1684 /// Subclasses may override this routine to provide different behavior.
1685 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
1686 MultiExprArg ArrayExprs,
1687 SourceLocation EqualOrColonLoc,
1691 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
1693 if (Result.isInvalid())
1699 /// \brief Build a new value-initialized expression.
1701 /// By default, builds the implicit value initialization without performing
1702 /// any semantic analysis. Subclasses may override this routine to provide
1703 /// different behavior.
1704 ExprResult RebuildImplicitValueInitExpr(QualType T) {
1705 return SemaRef.Owned(new (SemaRef.Context) ImplicitValueInitExpr(T));
1708 /// \brief Build a new \c va_arg expression.
1710 /// By default, performs semantic analysis to build the new expression.
1711 /// Subclasses may override this routine to provide different behavior.
1712 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
1713 Expr *SubExpr, TypeSourceInfo *TInfo,
1714 SourceLocation RParenLoc) {
1715 return getSema().BuildVAArgExpr(BuiltinLoc,
1720 /// \brief Build a new expression list in parentheses.
1722 /// By default, performs semantic analysis to build the new expression.
1723 /// Subclasses may override this routine to provide different behavior.
1724 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
1725 MultiExprArg SubExprs,
1726 SourceLocation RParenLoc) {
1727 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
1730 /// \brief Build a new address-of-label expression.
1732 /// By default, performs semantic analysis, using the name of the label
1733 /// rather than attempting to map the label statement itself.
1734 /// Subclasses may override this routine to provide different behavior.
1735 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
1736 SourceLocation LabelLoc, LabelDecl *Label) {
1737 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
1740 /// \brief Build a new GNU statement expression.
1742 /// By default, performs semantic analysis to build the new expression.
1743 /// Subclasses may override this routine to provide different behavior.
1744 ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
1746 SourceLocation RParenLoc) {
1747 return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
1750 /// \brief Build a new __builtin_choose_expr expression.
1752 /// By default, performs semantic analysis to build the new expression.
1753 /// Subclasses may override this routine to provide different behavior.
1754 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
1755 Expr *Cond, Expr *LHS, Expr *RHS,
1756 SourceLocation RParenLoc) {
1757 return SemaRef.ActOnChooseExpr(BuiltinLoc,
1762 /// \brief Build a new generic selection expression.
1764 /// By default, performs semantic analysis to build the new expression.
1765 /// Subclasses may override this routine to provide different behavior.
1766 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
1767 SourceLocation DefaultLoc,
1768 SourceLocation RParenLoc,
1769 Expr *ControllingExpr,
1770 TypeSourceInfo **Types,
1772 unsigned NumAssocs) {
1773 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1774 ControllingExpr, Types, Exprs,
1778 /// \brief Build a new overloaded operator call expression.
1780 /// By default, performs semantic analysis to build the new expression.
1781 /// The semantic analysis provides the behavior of template instantiation,
1782 /// copying with transformations that turn what looks like an overloaded
1783 /// operator call into a use of a builtin operator, performing
1784 /// argument-dependent lookup, etc. Subclasses may override this routine to
1785 /// provide different behavior.
1786 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
1787 SourceLocation OpLoc,
1792 /// \brief Build a new C++ "named" cast expression, such as static_cast or
1793 /// reinterpret_cast.
1795 /// By default, this routine dispatches to one of the more-specific routines
1796 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
1797 /// Subclasses may override this routine to provide different behavior.
1798 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
1799 Stmt::StmtClass Class,
1800 SourceLocation LAngleLoc,
1801 TypeSourceInfo *TInfo,
1802 SourceLocation RAngleLoc,
1803 SourceLocation LParenLoc,
1805 SourceLocation RParenLoc) {
1807 case Stmt::CXXStaticCastExprClass:
1808 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
1809 RAngleLoc, LParenLoc,
1810 SubExpr, RParenLoc);
1812 case Stmt::CXXDynamicCastExprClass:
1813 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
1814 RAngleLoc, LParenLoc,
1815 SubExpr, RParenLoc);
1817 case Stmt::CXXReinterpretCastExprClass:
1818 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
1819 RAngleLoc, LParenLoc,
1823 case Stmt::CXXConstCastExprClass:
1824 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
1825 RAngleLoc, LParenLoc,
1826 SubExpr, RParenLoc);
1829 llvm_unreachable("Invalid C++ named cast");
1833 /// \brief Build a new C++ static_cast expression.
1835 /// By default, performs semantic analysis to build the new expression.
1836 /// Subclasses may override this routine to provide different behavior.
1837 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
1838 SourceLocation LAngleLoc,
1839 TypeSourceInfo *TInfo,
1840 SourceLocation RAngleLoc,
1841 SourceLocation LParenLoc,
1843 SourceLocation RParenLoc) {
1844 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
1846 SourceRange(LAngleLoc, RAngleLoc),
1847 SourceRange(LParenLoc, RParenLoc));
1850 /// \brief Build a new C++ dynamic_cast expression.
1852 /// By default, performs semantic analysis to build the new expression.
1853 /// Subclasses may override this routine to provide different behavior.
1854 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
1855 SourceLocation LAngleLoc,
1856 TypeSourceInfo *TInfo,
1857 SourceLocation RAngleLoc,
1858 SourceLocation LParenLoc,
1860 SourceLocation RParenLoc) {
1861 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
1863 SourceRange(LAngleLoc, RAngleLoc),
1864 SourceRange(LParenLoc, RParenLoc));
1867 /// \brief Build a new C++ reinterpret_cast expression.
1869 /// By default, performs semantic analysis to build the new expression.
1870 /// Subclasses may override this routine to provide different behavior.
1871 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
1872 SourceLocation LAngleLoc,
1873 TypeSourceInfo *TInfo,
1874 SourceLocation RAngleLoc,
1875 SourceLocation LParenLoc,
1877 SourceLocation RParenLoc) {
1878 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
1880 SourceRange(LAngleLoc, RAngleLoc),
1881 SourceRange(LParenLoc, RParenLoc));
1884 /// \brief Build a new C++ const_cast expression.
1886 /// By default, performs semantic analysis to build the new expression.
1887 /// Subclasses may override this routine to provide different behavior.
1888 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
1889 SourceLocation LAngleLoc,
1890 TypeSourceInfo *TInfo,
1891 SourceLocation RAngleLoc,
1892 SourceLocation LParenLoc,
1894 SourceLocation RParenLoc) {
1895 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
1897 SourceRange(LAngleLoc, RAngleLoc),
1898 SourceRange(LParenLoc, RParenLoc));
1901 /// \brief Build a new C++ functional-style cast expression.
1903 /// By default, performs semantic analysis to build the new expression.
1904 /// Subclasses may override this routine to provide different behavior.
1905 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
1906 SourceLocation LParenLoc,
1908 SourceLocation RParenLoc) {
1909 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
1910 MultiExprArg(&Sub, 1),
1914 /// \brief Build a new C++ typeid(type) expression.
1916 /// By default, performs semantic analysis to build the new expression.
1917 /// Subclasses may override this routine to provide different behavior.
1918 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
1919 SourceLocation TypeidLoc,
1920 TypeSourceInfo *Operand,
1921 SourceLocation RParenLoc) {
1922 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
1927 /// \brief Build a new C++ typeid(expr) expression.
1929 /// By default, performs semantic analysis to build the new expression.
1930 /// Subclasses may override this routine to provide different behavior.
1931 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
1932 SourceLocation TypeidLoc,
1934 SourceLocation RParenLoc) {
1935 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
1939 /// \brief Build a new C++ __uuidof(type) expression.
1941 /// By default, performs semantic analysis to build the new expression.
1942 /// Subclasses may override this routine to provide different behavior.
1943 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
1944 SourceLocation TypeidLoc,
1945 TypeSourceInfo *Operand,
1946 SourceLocation RParenLoc) {
1947 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
1951 /// \brief Build a new C++ __uuidof(expr) expression.
1953 /// By default, performs semantic analysis to build the new expression.
1954 /// Subclasses may override this routine to provide different behavior.
1955 ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
1956 SourceLocation TypeidLoc,
1958 SourceLocation RParenLoc) {
1959 return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
1963 /// \brief Build a new C++ "this" expression.
1965 /// By default, builds a new "this" expression without performing any
1966 /// semantic analysis. Subclasses may override this routine to provide
1967 /// different behavior.
1968 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
1971 getSema().CheckCXXThisCapture(ThisLoc);
1972 return getSema().Owned(
1973 new (getSema().Context) CXXThisExpr(ThisLoc, ThisType,
1977 /// \brief Build a new C++ throw expression.
1979 /// By default, performs semantic analysis to build the new expression.
1980 /// Subclasses may override this routine to provide different behavior.
1981 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
1982 bool IsThrownVariableInScope) {
1983 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
1986 /// \brief Build a new C++ default-argument expression.
1988 /// By default, builds a new default-argument expression, which does not
1989 /// require any semantic analysis. Subclasses may override this routine to
1990 /// provide different behavior.
1991 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
1992 ParmVarDecl *Param) {
1993 return getSema().Owned(CXXDefaultArgExpr::Create(getSema().Context, Loc,
1997 /// \brief Build a new C++11 default-initialization expression.
1999 /// By default, builds a new default field initialization expression, which
2000 /// does not require any semantic analysis. Subclasses may override this
2001 /// routine to provide different behavior.
2002 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
2004 return getSema().Owned(CXXDefaultInitExpr::Create(getSema().Context, Loc,
2008 /// \brief Build a new C++ zero-initialization expression.
2010 /// By default, performs semantic analysis to build the new expression.
2011 /// Subclasses may override this routine to provide different behavior.
2012 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
2013 SourceLocation LParenLoc,
2014 SourceLocation RParenLoc) {
2015 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
2019 /// \brief Build a new C++ "new" expression.
2021 /// By default, performs semantic analysis to build the new expression.
2022 /// Subclasses may override this routine to provide different behavior.
2023 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
2025 SourceLocation PlacementLParen,
2026 MultiExprArg PlacementArgs,
2027 SourceLocation PlacementRParen,
2028 SourceRange TypeIdParens,
2029 QualType AllocatedType,
2030 TypeSourceInfo *AllocatedTypeInfo,
2032 SourceRange DirectInitRange,
2033 Expr *Initializer) {
2034 return getSema().BuildCXXNew(StartLoc, UseGlobal,
2046 /// \brief Build a new C++ "delete" expression.
2048 /// By default, performs semantic analysis to build the new expression.
2049 /// Subclasses may override this routine to provide different behavior.
2050 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
2051 bool IsGlobalDelete,
2054 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
2058 /// \brief Build a new unary type trait expression.
2060 /// By default, performs semantic analysis to build the new expression.
2061 /// Subclasses may override this routine to provide different behavior.
2062 ExprResult RebuildUnaryTypeTrait(UnaryTypeTrait Trait,
2063 SourceLocation StartLoc,
2065 SourceLocation RParenLoc) {
2066 return getSema().BuildUnaryTypeTrait(Trait, StartLoc, T, RParenLoc);
2069 /// \brief Build a new binary type trait expression.
2071 /// By default, performs semantic analysis to build the new expression.
2072 /// Subclasses may override this routine to provide different behavior.
2073 ExprResult RebuildBinaryTypeTrait(BinaryTypeTrait Trait,
2074 SourceLocation StartLoc,
2075 TypeSourceInfo *LhsT,
2076 TypeSourceInfo *RhsT,
2077 SourceLocation RParenLoc) {
2078 return getSema().BuildBinaryTypeTrait(Trait, StartLoc, LhsT, RhsT, RParenLoc);
2081 /// \brief Build a new type trait expression.
2083 /// By default, performs semantic analysis to build the new expression.
2084 /// Subclasses may override this routine to provide different behavior.
2085 ExprResult RebuildTypeTrait(TypeTrait Trait,
2086 SourceLocation StartLoc,
2087 ArrayRef<TypeSourceInfo *> Args,
2088 SourceLocation RParenLoc) {
2089 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
2092 /// \brief Build a new array type trait expression.
2094 /// By default, performs semantic analysis to build the new expression.
2095 /// Subclasses may override this routine to provide different behavior.
2096 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
2097 SourceLocation StartLoc,
2098 TypeSourceInfo *TSInfo,
2100 SourceLocation RParenLoc) {
2101 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
2104 /// \brief Build a new expression trait expression.
2106 /// By default, performs semantic analysis to build the new expression.
2107 /// Subclasses may override this routine to provide different behavior.
2108 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
2109 SourceLocation StartLoc,
2111 SourceLocation RParenLoc) {
2112 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
2115 /// \brief Build a new (previously unresolved) declaration reference
2118 /// By default, performs semantic analysis to build the new expression.
2119 /// Subclasses may override this routine to provide different behavior.
2120 ExprResult RebuildDependentScopeDeclRefExpr(
2121 NestedNameSpecifierLoc QualifierLoc,
2122 SourceLocation TemplateKWLoc,
2123 const DeclarationNameInfo &NameInfo,
2124 const TemplateArgumentListInfo *TemplateArgs,
2125 bool IsAddressOfOperand) {
2127 SS.Adopt(QualifierLoc);
2129 if (TemplateArgs || TemplateKWLoc.isValid())
2130 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc,
2131 NameInfo, TemplateArgs);
2133 return getSema().BuildQualifiedDeclarationNameExpr(SS, NameInfo,
2134 IsAddressOfOperand);
2137 /// \brief Build a new template-id expression.
2139 /// By default, performs semantic analysis to build the new expression.
2140 /// Subclasses may override this routine to provide different behavior.
2141 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
2142 SourceLocation TemplateKWLoc,
2145 const TemplateArgumentListInfo *TemplateArgs) {
2146 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
2150 /// \brief Build a new object-construction expression.
2152 /// By default, performs semantic analysis to build the new expression.
2153 /// Subclasses may override this routine to provide different behavior.
2154 ExprResult RebuildCXXConstructExpr(QualType T,
2156 CXXConstructorDecl *Constructor,
2159 bool HadMultipleCandidates,
2160 bool ListInitialization,
2161 bool RequiresZeroInit,
2162 CXXConstructExpr::ConstructionKind ConstructKind,
2163 SourceRange ParenRange) {
2164 SmallVector<Expr*, 8> ConvertedArgs;
2165 if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
2169 return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
2171 HadMultipleCandidates,
2173 RequiresZeroInit, ConstructKind,
2177 /// \brief Build a new object-construction expression.
2179 /// By default, performs semantic analysis to build the new expression.
2180 /// Subclasses may override this routine to provide different behavior.
2181 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
2182 SourceLocation LParenLoc,
2184 SourceLocation RParenLoc) {
2185 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2191 /// \brief Build a new object-construction expression.
2193 /// By default, performs semantic analysis to build the new expression.
2194 /// Subclasses may override this routine to provide different behavior.
2195 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
2196 SourceLocation LParenLoc,
2198 SourceLocation RParenLoc) {
2199 return getSema().BuildCXXTypeConstructExpr(TSInfo,
2205 /// \brief Build a new member reference expression.
2207 /// By default, performs semantic analysis to build the new expression.
2208 /// Subclasses may override this routine to provide different behavior.
2209 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
2212 SourceLocation OperatorLoc,
2213 NestedNameSpecifierLoc QualifierLoc,
2214 SourceLocation TemplateKWLoc,
2215 NamedDecl *FirstQualifierInScope,
2216 const DeclarationNameInfo &MemberNameInfo,
2217 const TemplateArgumentListInfo *TemplateArgs) {
2219 SS.Adopt(QualifierLoc);
2221 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2222 OperatorLoc, IsArrow,
2224 FirstQualifierInScope,
2229 /// \brief Build a new member reference expression.
2231 /// By default, performs semantic analysis to build the new expression.
2232 /// Subclasses may override this routine to provide different behavior.
2233 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
2234 SourceLocation OperatorLoc,
2236 NestedNameSpecifierLoc QualifierLoc,
2237 SourceLocation TemplateKWLoc,
2238 NamedDecl *FirstQualifierInScope,
2240 const TemplateArgumentListInfo *TemplateArgs) {
2242 SS.Adopt(QualifierLoc);
2244 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
2245 OperatorLoc, IsArrow,
2247 FirstQualifierInScope,
2251 /// \brief Build a new noexcept expression.
2253 /// By default, performs semantic analysis to build the new expression.
2254 /// Subclasses may override this routine to provide different behavior.
2255 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
2256 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
2259 /// \brief Build a new expression to compute the length of a parameter pack.
2260 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
2261 SourceLocation PackLoc,
2262 SourceLocation RParenLoc,
2263 Optional<unsigned> Length) {
2265 return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2266 OperatorLoc, Pack, PackLoc,
2267 RParenLoc, *Length);
2269 return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
2270 OperatorLoc, Pack, PackLoc,
2274 /// \brief Build a new Objective-C boxed expression.
2276 /// By default, performs semantic analysis to build the new expression.
2277 /// Subclasses may override this routine to provide different behavior.
2278 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
2279 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
2282 /// \brief Build a new Objective-C array literal.
2284 /// By default, performs semantic analysis to build the new expression.
2285 /// Subclasses may override this routine to provide different behavior.
2286 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
2287 Expr **Elements, unsigned NumElements) {
2288 return getSema().BuildObjCArrayLiteral(Range,
2289 MultiExprArg(Elements, NumElements));
2292 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
2293 Expr *Base, Expr *Key,
2294 ObjCMethodDecl *getterMethod,
2295 ObjCMethodDecl *setterMethod) {
2296 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
2297 getterMethod, setterMethod);
2300 /// \brief Build a new Objective-C dictionary literal.
2302 /// By default, performs semantic analysis to build the new expression.
2303 /// Subclasses may override this routine to provide different behavior.
2304 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
2305 ObjCDictionaryElement *Elements,
2306 unsigned NumElements) {
2307 return getSema().BuildObjCDictionaryLiteral(Range, Elements, NumElements);
2310 /// \brief Build a new Objective-C \@encode expression.
2312 /// By default, performs semantic analysis to build the new expression.
2313 /// Subclasses may override this routine to provide different behavior.
2314 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
2315 TypeSourceInfo *EncodeTypeInfo,
2316 SourceLocation RParenLoc) {
2317 return SemaRef.Owned(SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo,
2321 /// \brief Build a new Objective-C class message.
2322 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
2324 ArrayRef<SourceLocation> SelectorLocs,
2325 ObjCMethodDecl *Method,
2326 SourceLocation LBracLoc,
2328 SourceLocation RBracLoc) {
2329 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
2330 ReceiverTypeInfo->getType(),
2331 /*SuperLoc=*/SourceLocation(),
2332 Sel, Method, LBracLoc, SelectorLocs,
2336 /// \brief Build a new Objective-C instance message.
2337 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
2339 ArrayRef<SourceLocation> SelectorLocs,
2340 ObjCMethodDecl *Method,
2341 SourceLocation LBracLoc,
2343 SourceLocation RBracLoc) {
2344 return SemaRef.BuildInstanceMessage(Receiver,
2345 Receiver->getType(),
2346 /*SuperLoc=*/SourceLocation(),
2347 Sel, Method, LBracLoc, SelectorLocs,
2351 /// \brief Build a new Objective-C ivar reference expression.
2353 /// By default, performs semantic analysis to build the new expression.
2354 /// Subclasses may override this routine to provide different behavior.
2355 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
2356 SourceLocation IvarLoc,
2357 bool IsArrow, bool IsFreeIvar) {
2358 // FIXME: We lose track of the IsFreeIvar bit.
2360 ExprResult Base = getSema().Owned(BaseArg);
2361 LookupResult R(getSema(), Ivar->getDeclName(), IvarLoc,
2362 Sema::LookupMemberName);
2363 ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
2367 if (Result.isInvalid() || Base.isInvalid())
2373 return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
2374 /*FIXME:*/IvarLoc, IsArrow,
2375 SS, SourceLocation(),
2376 /*FirstQualifierInScope=*/0,
2378 /*TemplateArgs=*/0);
2381 /// \brief Build a new Objective-C property reference expression.
2383 /// By default, performs semantic analysis to build the new expression.
2384 /// Subclasses may override this routine to provide different behavior.
2385 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
2386 ObjCPropertyDecl *Property,
2387 SourceLocation PropertyLoc) {
2389 ExprResult Base = getSema().Owned(BaseArg);
2390 LookupResult R(getSema(), Property->getDeclName(), PropertyLoc,
2391 Sema::LookupMemberName);
2392 bool IsArrow = false;
2393 ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
2394 /*FIME:*/PropertyLoc,
2396 if (Result.isInvalid() || Base.isInvalid())
2402 return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
2403 /*FIXME:*/PropertyLoc, IsArrow,
2404 SS, SourceLocation(),
2405 /*FirstQualifierInScope=*/0,
2407 /*TemplateArgs=*/0);
2410 /// \brief Build a new Objective-C property reference expression.
2412 /// By default, performs semantic analysis to build the new expression.
2413 /// Subclasses may override this routine to provide different behavior.
2414 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
2415 ObjCMethodDecl *Getter,
2416 ObjCMethodDecl *Setter,
2417 SourceLocation PropertyLoc) {
2418 // Since these expressions can only be value-dependent, we do not
2419 // need to perform semantic analysis again.
2421 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
2422 VK_LValue, OK_ObjCProperty,
2423 PropertyLoc, Base));
2426 /// \brief Build a new Objective-C "isa" expression.
2428 /// By default, performs semantic analysis to build the new expression.
2429 /// Subclasses may override this routine to provide different behavior.
2430 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
2431 SourceLocation OpLoc,
2434 ExprResult Base = getSema().Owned(BaseArg);
2435 LookupResult R(getSema(), &getSema().Context.Idents.get("isa"), IsaLoc,
2436 Sema::LookupMemberName);
2437 ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
2440 if (Result.isInvalid() || Base.isInvalid())
2446 return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
2448 SS, SourceLocation(),
2449 /*FirstQualifierInScope=*/0,
2451 /*TemplateArgs=*/0);
2454 /// \brief Build a new shuffle vector expression.
2456 /// By default, performs semantic analysis to build the new expression.
2457 /// Subclasses may override this routine to provide different behavior.
2458 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
2459 MultiExprArg SubExprs,
2460 SourceLocation RParenLoc) {
2461 // Find the declaration for __builtin_shufflevector
2462 const IdentifierInfo &Name
2463 = SemaRef.Context.Idents.get("__builtin_shufflevector");
2464 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
2465 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
2466 assert(!Lookup.empty() && "No __builtin_shufflevector?");
2468 // Build a reference to the __builtin_shufflevector builtin
2469 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
2470 Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
2471 SemaRef.Context.BuiltinFnTy,
2472 VK_RValue, BuiltinLoc);
2473 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
2474 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
2475 CK_BuiltinFnToFnPtr).take();
2477 // Build the CallExpr
2478 ExprResult TheCall = SemaRef.Owned(
2479 new (SemaRef.Context) CallExpr(SemaRef.Context, Callee, SubExprs,
2480 Builtin->getCallResultType(),
2481 Expr::getValueKindForType(Builtin->getResultType()),
2484 // Type-check the __builtin_shufflevector expression.
2485 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.take()));
2488 /// \brief Build a new template argument pack expansion.
2490 /// By default, performs semantic analysis to build a new pack expansion
2491 /// for a template argument. Subclasses may override this routine to provide
2492 /// different behavior.
2493 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
2494 SourceLocation EllipsisLoc,
2495 Optional<unsigned> NumExpansions) {
2496 switch (Pattern.getArgument().getKind()) {
2497 case TemplateArgument::Expression: {
2499 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
2500 EllipsisLoc, NumExpansions);
2501 if (Result.isInvalid())
2502 return TemplateArgumentLoc();
2504 return TemplateArgumentLoc(Result.get(), Result.get());
2507 case TemplateArgument::Template:
2508 return TemplateArgumentLoc(TemplateArgument(
2509 Pattern.getArgument().getAsTemplate(),
2511 Pattern.getTemplateQualifierLoc(),
2512 Pattern.getTemplateNameLoc(),
2515 case TemplateArgument::Null:
2516 case TemplateArgument::Integral:
2517 case TemplateArgument::Declaration:
2518 case TemplateArgument::Pack:
2519 case TemplateArgument::TemplateExpansion:
2520 case TemplateArgument::NullPtr:
2521 llvm_unreachable("Pack expansion pattern has no parameter packs");
2523 case TemplateArgument::Type:
2524 if (TypeSourceInfo *Expansion
2525 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
2528 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
2533 return TemplateArgumentLoc();
2536 /// \brief Build a new expression pack expansion.
2538 /// By default, performs semantic analysis to build a new pack expansion
2539 /// for an expression. Subclasses may override this routine to provide
2540 /// different behavior.
2541 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
2542 Optional<unsigned> NumExpansions) {
2543 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
2546 /// \brief Build a new atomic operation expression.
2548 /// By default, performs semantic analysis to build the new expression.
2549 /// Subclasses may override this routine to provide different behavior.
2550 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
2551 MultiExprArg SubExprs,
2553 AtomicExpr::AtomicOp Op,
2554 SourceLocation RParenLoc) {
2555 // Just create the expression; there is not any interesting semantic
2556 // analysis here because we can't actually build an AtomicExpr until
2557 // we are sure it is semantically sound.
2558 return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
2563 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
2564 QualType ObjectType,
2565 NamedDecl *FirstQualifierInScope,
2568 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
2569 QualType ObjectType,
2570 NamedDecl *FirstQualifierInScope,
2574 template<typename Derived>
2575 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
2577 return SemaRef.Owned(S);
2579 switch (S->getStmtClass()) {
2580 case Stmt::NoStmtClass: break;
2582 // Transform individual statement nodes
2583 #define STMT(Node, Parent) \
2584 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
2585 #define ABSTRACT_STMT(Node)
2586 #define EXPR(Node, Parent)
2587 #include "clang/AST/StmtNodes.inc"
2589 // Transform expressions by calling TransformExpr.
2590 #define STMT(Node, Parent)
2591 #define ABSTRACT_STMT(Stmt)
2592 #define EXPR(Node, Parent) case Stmt::Node##Class:
2593 #include "clang/AST/StmtNodes.inc"
2595 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
2599 return getSema().ActOnExprStmt(E);
2603 return SemaRef.Owned(S);
2607 template<typename Derived>
2608 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
2610 return SemaRef.Owned(E);
2612 switch (E->getStmtClass()) {
2613 case Stmt::NoStmtClass: break;
2614 #define STMT(Node, Parent) case Stmt::Node##Class: break;
2615 #define ABSTRACT_STMT(Stmt)
2616 #define EXPR(Node, Parent) \
2617 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
2618 #include "clang/AST/StmtNodes.inc"
2621 return SemaRef.Owned(E);
2624 template<typename Derived>
2625 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
2626 bool CXXDirectInit) {
2627 // Initializers are instantiated like expressions, except that various outer
2628 // layers are stripped.
2630 return SemaRef.Owned(Init);
2632 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
2633 Init = ExprTemp->getSubExpr();
2635 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
2636 Init = Binder->getSubExpr();
2638 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
2639 Init = ICE->getSubExprAsWritten();
2641 // If this is not a direct-initializer, we only need to reconstruct
2642 // InitListExprs. Other forms of copy-initialization will be a no-op if
2643 // the initializer is already the right type.
2644 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
2645 if (!CXXDirectInit && !(Construct && Construct->isListInitialization()))
2646 return getDerived().TransformExpr(Init);
2648 // Revert value-initialization back to empty parens.
2649 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
2650 SourceRange Parens = VIE->getSourceRange();
2651 return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
2655 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
2656 if (isa<ImplicitValueInitExpr>(Init))
2657 return getDerived().RebuildParenListExpr(SourceLocation(), None,
2660 // Revert initialization by constructor back to a parenthesized or braced list
2661 // of expressions. Any other form of initializer can just be reused directly.
2662 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
2663 return getDerived().TransformExpr(Init);
2665 SmallVector<Expr*, 8> NewArgs;
2666 bool ArgChanged = false;
2667 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
2668 /*IsCall*/true, NewArgs, &ArgChanged))
2671 // If this was list initialization, revert to list form.
2672 if (Construct->isListInitialization())
2673 return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
2674 Construct->getLocEnd(),
2675 Construct->getType());
2677 // Build a ParenListExpr to represent anything else.
2678 SourceRange Parens = Construct->getParenRange();
2679 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
2683 template<typename Derived>
2684 bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
2687 SmallVectorImpl<Expr *> &Outputs,
2689 for (unsigned I = 0; I != NumInputs; ++I) {
2690 // If requested, drop call arguments that need to be dropped.
2691 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
2698 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
2699 Expr *Pattern = Expansion->getPattern();
2701 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2702 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
2703 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
2705 // Determine whether the set of unexpanded parameter packs can and should
2708 bool RetainExpansion = false;
2709 Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
2710 Optional<unsigned> NumExpansions = OrigNumExpansions;
2711 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
2712 Pattern->getSourceRange(),
2714 Expand, RetainExpansion,
2719 // The transform has determined that we should perform a simple
2720 // transformation on the pack expansion, producing another pack
2722 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
2723 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
2724 if (OutPattern.isInvalid())
2727 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
2728 Expansion->getEllipsisLoc(),
2730 if (Out.isInvalid())
2735 Outputs.push_back(Out.get());
2739 // Record right away that the argument was changed. This needs
2740 // to happen even if the array expands to nothing.
2741 if (ArgChanged) *ArgChanged = true;
2743 // The transform has determined that we should perform an elementwise
2744 // expansion of the pattern. Do so.
2745 for (unsigned I = 0; I != *NumExpansions; ++I) {
2746 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
2747 ExprResult Out = getDerived().TransformExpr(Pattern);
2748 if (Out.isInvalid())
2751 if (Out.get()->containsUnexpandedParameterPack()) {
2752 Out = RebuildPackExpansion(Out.get(), Expansion->getEllipsisLoc(),
2754 if (Out.isInvalid())
2758 Outputs.push_back(Out.get());
2765 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
2766 : getDerived().TransformExpr(Inputs[I]);
2767 if (Result.isInvalid())
2770 if (Result.get() != Inputs[I] && ArgChanged)
2773 Outputs.push_back(Result.get());
2779 template<typename Derived>
2780 NestedNameSpecifierLoc
2781 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
2782 NestedNameSpecifierLoc NNS,
2783 QualType ObjectType,
2784 NamedDecl *FirstQualifierInScope) {
2785 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
2786 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
2787 Qualifier = Qualifier.getPrefix())
2788 Qualifiers.push_back(Qualifier);
2791 while (!Qualifiers.empty()) {
2792 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
2793 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
2795 switch (QNNS->getKind()) {
2796 case NestedNameSpecifier::Identifier:
2797 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/0,
2798 *QNNS->getAsIdentifier(),
2799 Q.getLocalBeginLoc(),
2801 ObjectType, false, SS,
2802 FirstQualifierInScope, false))
2803 return NestedNameSpecifierLoc();
2807 case NestedNameSpecifier::Namespace: {
2809 = cast_or_null<NamespaceDecl>(
2810 getDerived().TransformDecl(
2811 Q.getLocalBeginLoc(),
2812 QNNS->getAsNamespace()));
2813 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
2817 case NestedNameSpecifier::NamespaceAlias: {
2818 NamespaceAliasDecl *Alias
2819 = cast_or_null<NamespaceAliasDecl>(
2820 getDerived().TransformDecl(Q.getLocalBeginLoc(),
2821 QNNS->getAsNamespaceAlias()));
2822 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
2823 Q.getLocalEndLoc());
2827 case NestedNameSpecifier::Global:
2828 // There is no meaningful transformation that one could perform on the
2830 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
2833 case NestedNameSpecifier::TypeSpecWithTemplate:
2834 case NestedNameSpecifier::TypeSpec: {
2835 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
2836 FirstQualifierInScope, SS);
2839 return NestedNameSpecifierLoc();
2841 if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
2842 (SemaRef.getLangOpts().CPlusPlus11 &&
2843 TL.getType()->isEnumeralType())) {
2844 assert(!TL.getType().hasLocalQualifiers() &&
2845 "Can't get cv-qualifiers here");
2846 if (TL.getType()->isEnumeralType())
2847 SemaRef.Diag(TL.getBeginLoc(),
2848 diag::warn_cxx98_compat_enum_nested_name_spec);
2849 SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
2850 Q.getLocalEndLoc());
2853 // If the nested-name-specifier is an invalid type def, don't emit an
2854 // error because a previous error should have already been emitted.
2855 TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
2856 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
2857 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
2858 << TL.getType() << SS.getRange();
2860 return NestedNameSpecifierLoc();
2864 // The qualifier-in-scope and object type only apply to the leftmost entity.
2865 FirstQualifierInScope = 0;
2866 ObjectType = QualType();
2869 // Don't rebuild the nested-name-specifier if we don't have to.
2870 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
2871 !getDerived().AlwaysRebuild())
2874 // If we can re-use the source-location data from the original
2875 // nested-name-specifier, do so.
2876 if (SS.location_size() == NNS.getDataLength() &&
2877 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
2878 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
2880 // Allocate new nested-name-specifier location information.
2881 return SS.getWithLocInContext(SemaRef.Context);
2884 template<typename Derived>
2886 TreeTransform<Derived>
2887 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
2888 DeclarationName Name = NameInfo.getName();
2890 return DeclarationNameInfo();
2892 switch (Name.getNameKind()) {
2893 case DeclarationName::Identifier:
2894 case DeclarationName::ObjCZeroArgSelector:
2895 case DeclarationName::ObjCOneArgSelector:
2896 case DeclarationName::ObjCMultiArgSelector:
2897 case DeclarationName::CXXOperatorName:
2898 case DeclarationName::CXXLiteralOperatorName:
2899 case DeclarationName::CXXUsingDirective:
2902 case DeclarationName::CXXConstructorName:
2903 case DeclarationName::CXXDestructorName:
2904 case DeclarationName::CXXConversionFunctionName: {
2905 TypeSourceInfo *NewTInfo;
2906 CanQualType NewCanTy;
2907 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
2908 NewTInfo = getDerived().TransformType(OldTInfo);
2910 return DeclarationNameInfo();
2911 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
2915 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
2916 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
2918 return DeclarationNameInfo();
2919 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
2922 DeclarationName NewName
2923 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
2925 DeclarationNameInfo NewNameInfo(NameInfo);
2926 NewNameInfo.setName(NewName);
2927 NewNameInfo.setNamedTypeInfo(NewTInfo);
2932 llvm_unreachable("Unknown name kind.");
2935 template<typename Derived>
2937 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
2939 SourceLocation NameLoc,
2940 QualType ObjectType,
2941 NamedDecl *FirstQualifierInScope) {
2942 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
2943 TemplateDecl *Template = QTN->getTemplateDecl();
2944 assert(Template && "qualified template name must refer to a template");
2946 TemplateDecl *TransTemplate
2947 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
2950 return TemplateName();
2952 if (!getDerived().AlwaysRebuild() &&
2953 SS.getScopeRep() == QTN->getQualifier() &&
2954 TransTemplate == Template)
2957 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
2961 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2962 if (SS.getScopeRep()) {
2963 // These apply to the scope specifier, not the template.
2964 ObjectType = QualType();
2965 FirstQualifierInScope = 0;
2968 if (!getDerived().AlwaysRebuild() &&
2969 SS.getScopeRep() == DTN->getQualifier() &&
2970 ObjectType.isNull())
2973 if (DTN->isIdentifier()) {
2974 return getDerived().RebuildTemplateName(SS,
2975 *DTN->getIdentifier(),
2978 FirstQualifierInScope);
2981 return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
2985 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2986 TemplateDecl *TransTemplate
2987 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
2990 return TemplateName();
2992 if (!getDerived().AlwaysRebuild() &&
2993 TransTemplate == Template)
2996 return TemplateName(TransTemplate);
2999 if (SubstTemplateTemplateParmPackStorage *SubstPack
3000 = Name.getAsSubstTemplateTemplateParmPack()) {
3001 TemplateTemplateParmDecl *TransParam
3002 = cast_or_null<TemplateTemplateParmDecl>(
3003 getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
3005 return TemplateName();
3007 if (!getDerived().AlwaysRebuild() &&
3008 TransParam == SubstPack->getParameterPack())
3011 return getDerived().RebuildTemplateName(TransParam,
3012 SubstPack->getArgumentPack());
3015 // These should be getting filtered out before they reach the AST.
3016 llvm_unreachable("overloaded function decl survived to here");
3019 template<typename Derived>
3020 void TreeTransform<Derived>::InventTemplateArgumentLoc(
3021 const TemplateArgument &Arg,
3022 TemplateArgumentLoc &Output) {
3023 SourceLocation Loc = getDerived().getBaseLocation();
3024 switch (Arg.getKind()) {
3025 case TemplateArgument::Null:
3026 llvm_unreachable("null template argument in TreeTransform");
3029 case TemplateArgument::Type:
3030 Output = TemplateArgumentLoc(Arg,
3031 SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
3035 case TemplateArgument::Template:
3036 case TemplateArgument::TemplateExpansion: {
3037 NestedNameSpecifierLocBuilder Builder;
3038 TemplateName Template = Arg.getAsTemplate();
3039 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
3040 Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
3041 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3042 Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
3044 if (Arg.getKind() == TemplateArgument::Template)
3045 Output = TemplateArgumentLoc(Arg,
3046 Builder.getWithLocInContext(SemaRef.Context),
3049 Output = TemplateArgumentLoc(Arg,
3050 Builder.getWithLocInContext(SemaRef.Context),
3056 case TemplateArgument::Expression:
3057 Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
3060 case TemplateArgument::Declaration:
3061 case TemplateArgument::Integral:
3062 case TemplateArgument::Pack:
3063 case TemplateArgument::NullPtr:
3064 Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
3069 template<typename Derived>
3070 bool TreeTransform<Derived>::TransformTemplateArgument(
3071 const TemplateArgumentLoc &Input,
3072 TemplateArgumentLoc &Output) {
3073 const TemplateArgument &Arg = Input.getArgument();
3074 switch (Arg.getKind()) {
3075 case TemplateArgument::Null:
3076 case TemplateArgument::Integral:
3077 case TemplateArgument::Pack:
3078 case TemplateArgument::Declaration:
3079 case TemplateArgument::NullPtr:
3080 llvm_unreachable("Unexpected TemplateArgument");
3082 case TemplateArgument::Type: {
3083 TypeSourceInfo *DI = Input.getTypeSourceInfo();
3085 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
3087 DI = getDerived().TransformType(DI);
3088 if (!DI) return true;
3090 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3094 case TemplateArgument::Template: {
3095 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
3097 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
3103 SS.Adopt(QualifierLoc);
3104 TemplateName Template
3105 = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
3106 Input.getTemplateNameLoc());
3107 if (Template.isNull())
3110 Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
3111 Input.getTemplateNameLoc());
3115 case TemplateArgument::TemplateExpansion:
3116 llvm_unreachable("Caller should expand pack expansions");
3118 case TemplateArgument::Expression: {
3119 // Template argument expressions are constant expressions.
3120 EnterExpressionEvaluationContext Unevaluated(getSema(),
3121 Sema::ConstantEvaluated);
3123 Expr *InputExpr = Input.getSourceExpression();
3124 if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
3126 ExprResult E = getDerived().TransformExpr(InputExpr);
3127 E = SemaRef.ActOnConstantExpression(E);
3128 if (E.isInvalid()) return true;
3129 Output = TemplateArgumentLoc(TemplateArgument(E.take()), E.take());
3134 // Work around bogus GCC warning
3138 /// \brief Iterator adaptor that invents template argument location information
3139 /// for each of the template arguments in its underlying iterator.
3140 template<typename Derived, typename InputIterator>
3141 class TemplateArgumentLocInventIterator {
3142 TreeTransform<Derived> &Self;
3146 typedef TemplateArgumentLoc value_type;
3147 typedef TemplateArgumentLoc reference;
3148 typedef typename std::iterator_traits<InputIterator>::difference_type
3150 typedef std::input_iterator_tag iterator_category;
3153 TemplateArgumentLoc Arg;
3156 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
3158 const TemplateArgumentLoc *operator->() const { return &Arg; }
3161 TemplateArgumentLocInventIterator() { }
3163 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
3165 : Self(Self), Iter(Iter) { }
3167 TemplateArgumentLocInventIterator &operator++() {
3172 TemplateArgumentLocInventIterator operator++(int) {
3173 TemplateArgumentLocInventIterator Old(*this);
3178 reference operator*() const {
3179 TemplateArgumentLoc Result;
3180 Self.InventTemplateArgumentLoc(*Iter, Result);
3184 pointer operator->() const { return pointer(**this); }
3186 friend bool operator==(const TemplateArgumentLocInventIterator &X,
3187 const TemplateArgumentLocInventIterator &Y) {
3188 return X.Iter == Y.Iter;
3191 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
3192 const TemplateArgumentLocInventIterator &Y) {
3193 return X.Iter != Y.Iter;
3197 template<typename Derived>
3198 template<typename InputIterator>
3199 bool TreeTransform<Derived>::TransformTemplateArguments(InputIterator First,
3201 TemplateArgumentListInfo &Outputs) {
3202 for (; First != Last; ++First) {
3203 TemplateArgumentLoc Out;
3204 TemplateArgumentLoc In = *First;
3206 if (In.getArgument().getKind() == TemplateArgument::Pack) {
3207 // Unpack argument packs, which we translate them into separate
3209 // FIXME: We could do much better if we could guarantee that the
3210 // TemplateArgumentLocInfo for the pack expansion would be usable for
3211 // all of the template arguments in the argument pack.
3212 typedef TemplateArgumentLocInventIterator<Derived,
3213 TemplateArgument::pack_iterator>
3215 if (TransformTemplateArguments(PackLocIterator(*this,
3216 In.getArgument().pack_begin()),
3217 PackLocIterator(*this,
3218 In.getArgument().pack_end()),
3225 if (In.getArgument().isPackExpansion()) {
3226 // We have a pack expansion, for which we will be substituting into
3228 SourceLocation Ellipsis;
3229 Optional<unsigned> OrigNumExpansions;
3230 TemplateArgumentLoc Pattern
3231 = In.getPackExpansionPattern(Ellipsis, OrigNumExpansions,
3234 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3235 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
3236 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
3238 // Determine whether the set of unexpanded parameter packs can and should
3241 bool RetainExpansion = false;
3242 Optional<unsigned> NumExpansions = OrigNumExpansions;
3243 if (getDerived().TryExpandParameterPacks(Ellipsis,
3244 Pattern.getSourceRange(),
3252 // The transform has determined that we should perform a simple
3253 // transformation on the pack expansion, producing another pack
3255 TemplateArgumentLoc OutPattern;
3256 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
3257 if (getDerived().TransformTemplateArgument(Pattern, OutPattern))
3260 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
3262 if (Out.getArgument().isNull())
3265 Outputs.addArgument(Out);
3269 // The transform has determined that we should perform an elementwise
3270 // expansion of the pattern. Do so.
3271 for (unsigned I = 0; I != *NumExpansions; ++I) {
3272 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
3274 if (getDerived().TransformTemplateArgument(Pattern, Out))
3277 if (Out.getArgument().containsUnexpandedParameterPack()) {
3278 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
3280 if (Out.getArgument().isNull())
3284 Outputs.addArgument(Out);
3287 // If we're supposed to retain a pack expansion, do so by temporarily
3288 // forgetting the partially-substituted parameter pack.
3289 if (RetainExpansion) {
3290 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
3292 if (getDerived().TransformTemplateArgument(Pattern, Out))
3295 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
3297 if (Out.getArgument().isNull())
3300 Outputs.addArgument(Out);
3307 if (getDerived().TransformTemplateArgument(In, Out))
3310 Outputs.addArgument(Out);
3317 //===----------------------------------------------------------------------===//
3318 // Type transformation
3319 //===----------------------------------------------------------------------===//
3321 template<typename Derived>
3322 QualType TreeTransform<Derived>::TransformType(QualType T) {
3323 if (getDerived().AlreadyTransformed(T))
3326 // Temporary workaround. All of these transformations should
3327 // eventually turn into transformations on TypeLocs.
3328 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
3329 getDerived().getBaseLocation());
3331 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
3336 return NewDI->getType();
3339 template<typename Derived>
3340 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
3341 // Refine the base location to the type's location.
3342 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
3343 getDerived().getBaseEntity());
3344 if (getDerived().AlreadyTransformed(DI->getType()))
3349 TypeLoc TL = DI->getTypeLoc();
3350 TLB.reserve(TL.getFullDataSize());
3352 QualType Result = getDerived().TransformType(TLB, TL);
3353 if (Result.isNull())
3356 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3359 template<typename Derived>
3361 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
3362 switch (T.getTypeLocClass()) {
3363 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3364 #define TYPELOC(CLASS, PARENT) \
3365 case TypeLoc::CLASS: \
3366 return getDerived().Transform##CLASS##Type(TLB, \
3367 T.castAs<CLASS##TypeLoc>());
3368 #include "clang/AST/TypeLocNodes.def"
3371 llvm_unreachable("unhandled type loc!");
3374 /// FIXME: By default, this routine adds type qualifiers only to types
3375 /// that can have qualifiers, and silently suppresses those qualifiers
3376 /// that are not permitted (e.g., qualifiers on reference or function
3377 /// types). This is the right thing for template instantiation, but
3378 /// probably not for other clients.
3379 template<typename Derived>
3381 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
3382 QualifiedTypeLoc T) {
3383 Qualifiers Quals = T.getType().getLocalQualifiers();
3385 QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
3386 if (Result.isNull())
3389 // Silently suppress qualifiers if the result type can't be qualified.
3390 // FIXME: this is the right thing for template instantiation, but
3391 // probably not for other clients.
3392 if (Result->isFunctionType() || Result->isReferenceType())
3395 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
3397 if (Quals.hasObjCLifetime()) {
3398 if (!Result->isObjCLifetimeType() && !Result->isDependentType())
3399 Quals.removeObjCLifetime();
3400 else if (Result.getObjCLifetime()) {
3402 // A lifetime qualifier applied to a substituted template parameter
3403 // overrides the lifetime qualifier from the template argument.
3404 const AutoType *AutoTy;
3405 if (const SubstTemplateTypeParmType *SubstTypeParam
3406 = dyn_cast<SubstTemplateTypeParmType>(Result)) {
3407 QualType Replacement = SubstTypeParam->getReplacementType();
3408 Qualifiers Qs = Replacement.getQualifiers();
3409 Qs.removeObjCLifetime();
3411 = SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(),
3413 Result = SemaRef.Context.getSubstTemplateTypeParmType(
3414 SubstTypeParam->getReplacedParameter(),
3416 TLB.TypeWasModifiedSafely(Result);
3417 } else if ((AutoTy = dyn_cast<AutoType>(Result)) && AutoTy->isDeduced()) {
3418 // 'auto' types behave the same way as template parameters.
3419 QualType Deduced = AutoTy->getDeducedType();
3420 Qualifiers Qs = Deduced.getQualifiers();
3421 Qs.removeObjCLifetime();
3422 Deduced = SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(),
3424 Result = SemaRef.Context.getAutoType(Deduced, AutoTy->isDecltypeAuto());
3425 TLB.TypeWasModifiedSafely(Result);
3427 // Otherwise, complain about the addition of a qualifier to an
3428 // already-qualified type.
3429 SourceRange R = TLB.getTemporaryTypeLoc(Result).getSourceRange();
3430 SemaRef.Diag(R.getBegin(), diag::err_attr_objc_ownership_redundant)
3433 Quals.removeObjCLifetime();
3437 if (!Quals.empty()) {
3438 Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
3439 // BuildQualifiedType might not add qualifiers if they are invalid.
3440 if (Result.hasLocalQualifiers())
3441 TLB.push<QualifiedTypeLoc>(Result);
3442 // No location information to preserve.
3448 template<typename Derived>
3450 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
3451 QualType ObjectType,
3452 NamedDecl *UnqualLookup,
3454 QualType T = TL.getType();
3455 if (getDerived().AlreadyTransformed(T))
3461 if (isa<TemplateSpecializationType>(T)) {
3462 TemplateSpecializationTypeLoc SpecTL =
3463 TL.castAs<TemplateSpecializationTypeLoc>();
3465 TemplateName Template =
3466 getDerived().TransformTemplateName(SS,
3467 SpecTL.getTypePtr()->getTemplateName(),
3468 SpecTL.getTemplateNameLoc(),
3469 ObjectType, UnqualLookup);
3470 if (Template.isNull())
3473 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
3475 } else if (isa<DependentTemplateSpecializationType>(T)) {
3476 DependentTemplateSpecializationTypeLoc SpecTL =
3477 TL.castAs<DependentTemplateSpecializationTypeLoc>();
3479 TemplateName Template
3480 = getDerived().RebuildTemplateName(SS,
3481 *SpecTL.getTypePtr()->getIdentifier(),
3482 SpecTL.getTemplateNameLoc(),
3483 ObjectType, UnqualLookup);
3484 if (Template.isNull())
3487 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
3492 // Nothing special needs to be done for these.
3493 Result = getDerived().TransformType(TLB, TL);
3496 if (Result.isNull())
3499 return TLB.getTypeSourceInfo(SemaRef.Context, Result)->getTypeLoc();
3502 template<typename Derived>
3504 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3505 QualType ObjectType,
3506 NamedDecl *UnqualLookup,
3508 // FIXME: Painfully copy-paste from the above!
3510 QualType T = TSInfo->getType();
3511 if (getDerived().AlreadyTransformed(T))
3517 TypeLoc TL = TSInfo->getTypeLoc();
3518 if (isa<TemplateSpecializationType>(T)) {
3519 TemplateSpecializationTypeLoc SpecTL =
3520 TL.castAs<TemplateSpecializationTypeLoc>();
3522 TemplateName Template
3523 = getDerived().TransformTemplateName(SS,
3524 SpecTL.getTypePtr()->getTemplateName(),
3525 SpecTL.getTemplateNameLoc(),
3526 ObjectType, UnqualLookup);
3527 if (Template.isNull())
3530 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
3532 } else if (isa<DependentTemplateSpecializationType>(T)) {
3533 DependentTemplateSpecializationTypeLoc SpecTL =
3534 TL.castAs<DependentTemplateSpecializationTypeLoc>();
3536 TemplateName Template
3537 = getDerived().RebuildTemplateName(SS,
3538 *SpecTL.getTypePtr()->getIdentifier(),
3539 SpecTL.getTemplateNameLoc(),
3540 ObjectType, UnqualLookup);
3541 if (Template.isNull())
3544 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
3549 // Nothing special needs to be done for these.
3550 Result = getDerived().TransformType(TLB, TL);
3553 if (Result.isNull())
3556 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
3559 template <class TyLoc> static inline
3560 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
3561 TyLoc NewT = TLB.push<TyLoc>(T.getType());
3562 NewT.setNameLoc(T.getNameLoc());
3566 template<typename Derived>
3567 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
3569 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
3570 NewT.setBuiltinLoc(T.getBuiltinLoc());
3571 if (T.needsExtraLocalData())
3572 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
3576 template<typename Derived>
3577 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
3580 return TransformTypeSpecType(TLB, T);
3583 template<typename Derived>
3584 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
3585 PointerTypeLoc TL) {
3586 QualType PointeeType
3587 = getDerived().TransformType(TLB, TL.getPointeeLoc());
3588 if (PointeeType.isNull())
3591 QualType Result = TL.getType();
3592 if (PointeeType->getAs<ObjCObjectType>()) {
3593 // A dependent pointer type 'T *' has is being transformed such
3594 // that an Objective-C class type is being replaced for 'T'. The
3595 // resulting pointer type is an ObjCObjectPointerType, not a
3597 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
3599 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
3600 NewT.setStarLoc(TL.getStarLoc());
3604 if (getDerived().AlwaysRebuild() ||
3605 PointeeType != TL.getPointeeLoc().getType()) {
3606 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
3607 if (Result.isNull())
3611 // Objective-C ARC can add lifetime qualifiers to the type that we're
3613 TLB.TypeWasModifiedSafely(Result->getPointeeType());
3615 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
3616 NewT.setSigilLoc(TL.getSigilLoc());
3620 template<typename Derived>
3622 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
3623 BlockPointerTypeLoc TL) {
3624 QualType PointeeType
3625 = getDerived().TransformType(TLB, TL.getPointeeLoc());
3626 if (PointeeType.isNull())
3629 QualType Result = TL.getType();
3630 if (getDerived().AlwaysRebuild() ||
3631 PointeeType != TL.getPointeeLoc().getType()) {
3632 Result = getDerived().RebuildBlockPointerType(PointeeType,
3634 if (Result.isNull())
3638 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
3639 NewT.setSigilLoc(TL.getSigilLoc());
3643 /// Transforms a reference type. Note that somewhat paradoxically we
3644 /// don't care whether the type itself is an l-value type or an r-value
3645 /// type; we only care if the type was *written* as an l-value type
3646 /// or an r-value type.
3647 template<typename Derived>
3649 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
3650 ReferenceTypeLoc TL) {
3651 const ReferenceType *T = TL.getTypePtr();
3653 // Note that this works with the pointee-as-written.
3654 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
3655 if (PointeeType.isNull())
3658 QualType Result = TL.getType();
3659 if (getDerived().AlwaysRebuild() ||
3660 PointeeType != T->getPointeeTypeAsWritten()) {
3661 Result = getDerived().RebuildReferenceType(PointeeType,
3662 T->isSpelledAsLValue(),
3664 if (Result.isNull())
3668 // Objective-C ARC can add lifetime qualifiers to the type that we're
3670 TLB.TypeWasModifiedSafely(
3671 Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
3673 // r-value references can be rebuilt as l-value references.
3674 ReferenceTypeLoc NewTL;
3675 if (isa<LValueReferenceType>(Result))
3676 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
3678 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
3679 NewTL.setSigilLoc(TL.getSigilLoc());
3684 template<typename Derived>
3686 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
3687 LValueReferenceTypeLoc TL) {
3688 return TransformReferenceType(TLB, TL);
3691 template<typename Derived>
3693 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
3694 RValueReferenceTypeLoc TL) {
3695 return TransformReferenceType(TLB, TL);
3698 template<typename Derived>
3700 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
3701 MemberPointerTypeLoc TL) {
3702 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
3703 if (PointeeType.isNull())
3706 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
3707 TypeSourceInfo* NewClsTInfo = 0;
3709 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
3714 const MemberPointerType *T = TL.getTypePtr();
3715 QualType OldClsType = QualType(T->getClass(), 0);
3716 QualType NewClsType;
3718 NewClsType = NewClsTInfo->getType();
3720 NewClsType = getDerived().TransformType(OldClsType);
3721 if (NewClsType.isNull())
3725 QualType Result = TL.getType();
3726 if (getDerived().AlwaysRebuild() ||
3727 PointeeType != T->getPointeeType() ||
3728 NewClsType != OldClsType) {
3729 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
3731 if (Result.isNull())
3735 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
3736 NewTL.setSigilLoc(TL.getSigilLoc());
3737 NewTL.setClassTInfo(NewClsTInfo);
3742 template<typename Derived>
3744 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
3745 ConstantArrayTypeLoc TL) {
3746 const ConstantArrayType *T = TL.getTypePtr();
3747 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
3748 if (ElementType.isNull())
3751 QualType Result = TL.getType();
3752 if (getDerived().AlwaysRebuild() ||
3753 ElementType != T->getElementType()) {
3754 Result = getDerived().RebuildConstantArrayType(ElementType,
3755 T->getSizeModifier(),
3757 T->getIndexTypeCVRQualifiers(),
3758 TL.getBracketsRange());
3759 if (Result.isNull())
3763 // We might have either a ConstantArrayType or a VariableArrayType now:
3764 // a ConstantArrayType is allowed to have an element type which is a
3765 // VariableArrayType if the type is dependent. Fortunately, all array
3766 // types have the same location layout.
3767 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
3768 NewTL.setLBracketLoc(TL.getLBracketLoc());
3769 NewTL.setRBracketLoc(TL.getRBracketLoc());
3771 Expr *Size = TL.getSizeExpr();
3773 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3774 Sema::ConstantEvaluated);
3775 Size = getDerived().TransformExpr(Size).template takeAs<Expr>();
3776 Size = SemaRef.ActOnConstantExpression(Size).take();
3778 NewTL.setSizeExpr(Size);
3783 template<typename Derived>
3784 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
3785 TypeLocBuilder &TLB,
3786 IncompleteArrayTypeLoc TL) {
3787 const IncompleteArrayType *T = TL.getTypePtr();
3788 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
3789 if (ElementType.isNull())
3792 QualType Result = TL.getType();
3793 if (getDerived().AlwaysRebuild() ||
3794 ElementType != T->getElementType()) {
3795 Result = getDerived().RebuildIncompleteArrayType(ElementType,
3796 T->getSizeModifier(),
3797 T->getIndexTypeCVRQualifiers(),
3798 TL.getBracketsRange());
3799 if (Result.isNull())
3803 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
3804 NewTL.setLBracketLoc(TL.getLBracketLoc());
3805 NewTL.setRBracketLoc(TL.getRBracketLoc());
3806 NewTL.setSizeExpr(0);
3811 template<typename Derived>
3813 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
3814 VariableArrayTypeLoc TL) {
3815 const VariableArrayType *T = TL.getTypePtr();
3816 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
3817 if (ElementType.isNull())
3820 ExprResult SizeResult
3821 = getDerived().TransformExpr(T->getSizeExpr());
3822 if (SizeResult.isInvalid())
3825 Expr *Size = SizeResult.take();
3827 QualType Result = TL.getType();
3828 if (getDerived().AlwaysRebuild() ||
3829 ElementType != T->getElementType() ||
3830 Size != T->getSizeExpr()) {
3831 Result = getDerived().RebuildVariableArrayType(ElementType,
3832 T->getSizeModifier(),
3834 T->getIndexTypeCVRQualifiers(),
3835 TL.getBracketsRange());
3836 if (Result.isNull())
3840 VariableArrayTypeLoc NewTL = TLB.push<VariableArrayTypeLoc>(Result);
3841 NewTL.setLBracketLoc(TL.getLBracketLoc());
3842 NewTL.setRBracketLoc(TL.getRBracketLoc());
3843 NewTL.setSizeExpr(Size);
3848 template<typename Derived>
3850 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
3851 DependentSizedArrayTypeLoc TL) {
3852 const DependentSizedArrayType *T = TL.getTypePtr();
3853 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
3854 if (ElementType.isNull())
3857 // Array bounds are constant expressions.
3858 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3859 Sema::ConstantEvaluated);
3861 // Prefer the expression from the TypeLoc; the other may have been uniqued.
3862 Expr *origSize = TL.getSizeExpr();
3863 if (!origSize) origSize = T->getSizeExpr();
3865 ExprResult sizeResult
3866 = getDerived().TransformExpr(origSize);
3867 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
3868 if (sizeResult.isInvalid())
3871 Expr *size = sizeResult.get();
3873 QualType Result = TL.getType();
3874 if (getDerived().AlwaysRebuild() ||
3875 ElementType != T->getElementType() ||
3877 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
3878 T->getSizeModifier(),
3880 T->getIndexTypeCVRQualifiers(),
3881 TL.getBracketsRange());
3882 if (Result.isNull())
3886 // We might have any sort of array type now, but fortunately they
3887 // all have the same location layout.
3888 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
3889 NewTL.setLBracketLoc(TL.getLBracketLoc());
3890 NewTL.setRBracketLoc(TL.getRBracketLoc());
3891 NewTL.setSizeExpr(size);
3896 template<typename Derived>
3897 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
3898 TypeLocBuilder &TLB,
3899 DependentSizedExtVectorTypeLoc TL) {
3900 const DependentSizedExtVectorType *T = TL.getTypePtr();
3902 // FIXME: ext vector locs should be nested
3903 QualType ElementType = getDerived().TransformType(T->getElementType());
3904 if (ElementType.isNull())
3907 // Vector sizes are constant expressions.
3908 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3909 Sema::ConstantEvaluated);
3911 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
3912 Size = SemaRef.ActOnConstantExpression(Size);
3913 if (Size.isInvalid())
3916 QualType Result = TL.getType();
3917 if (getDerived().AlwaysRebuild() ||
3918 ElementType != T->getElementType() ||
3919 Size.get() != T->getSizeExpr()) {
3920 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
3922 T->getAttributeLoc());
3923 if (Result.isNull())
3927 // Result might be dependent or not.
3928 if (isa<DependentSizedExtVectorType>(Result)) {
3929 DependentSizedExtVectorTypeLoc NewTL
3930 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
3931 NewTL.setNameLoc(TL.getNameLoc());
3933 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
3934 NewTL.setNameLoc(TL.getNameLoc());
3940 template<typename Derived>
3941 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
3943 const VectorType *T = TL.getTypePtr();
3944 QualType ElementType = getDerived().TransformType(T->getElementType());
3945 if (ElementType.isNull())
3948 QualType Result = TL.getType();
3949 if (getDerived().AlwaysRebuild() ||
3950 ElementType != T->getElementType()) {
3951 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
3952 T->getVectorKind());
3953 if (Result.isNull())
3957 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
3958 NewTL.setNameLoc(TL.getNameLoc());
3963 template<typename Derived>
3964 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
3965 ExtVectorTypeLoc TL) {
3966 const VectorType *T = TL.getTypePtr();
3967 QualType ElementType = getDerived().TransformType(T->getElementType());
3968 if (ElementType.isNull())
3971 QualType Result = TL.getType();
3972 if (getDerived().AlwaysRebuild() ||
3973 ElementType != T->getElementType()) {
3974 Result = getDerived().RebuildExtVectorType(ElementType,
3975 T->getNumElements(),
3976 /*FIXME*/ SourceLocation());
3977 if (Result.isNull())
3981 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
3982 NewTL.setNameLoc(TL.getNameLoc());
3987 template <typename Derived>
3988 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
3989 ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
3990 bool ExpectParameterPack) {
3991 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3992 TypeSourceInfo *NewDI = 0;
3994 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
3995 // If we're substituting into a pack expansion type and we know the
3996 // length we want to expand to, just substitute for the pattern.
3997 TypeLoc OldTL = OldDI->getTypeLoc();
3998 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
4001 TypeLoc NewTL = OldDI->getTypeLoc();
4002 TLB.reserve(NewTL.getFullDataSize());
4004 QualType Result = getDerived().TransformType(TLB,
4005 OldExpansionTL.getPatternLoc());
4006 if (Result.isNull())
4009 Result = RebuildPackExpansionType(Result,
4010 OldExpansionTL.getPatternLoc().getSourceRange(),
4011 OldExpansionTL.getEllipsisLoc(),
4013 if (Result.isNull())
4016 PackExpansionTypeLoc NewExpansionTL
4017 = TLB.push<PackExpansionTypeLoc>(Result);
4018 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
4019 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
4021 NewDI = getDerived().TransformType(OldDI);
4025 if (NewDI == OldDI && indexAdjustment == 0)
4028 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
4029 OldParm->getDeclContext(),
4030 OldParm->getInnerLocStart(),
4031 OldParm->getLocation(),
4032 OldParm->getIdentifier(),
4035 OldParm->getStorageClass(),
4037 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
4038 OldParm->getFunctionScopeIndex() + indexAdjustment);
4042 template<typename Derived>
4043 bool TreeTransform<Derived>::
4044 TransformFunctionTypeParams(SourceLocation Loc,
4045 ParmVarDecl **Params, unsigned NumParams,
4046 const QualType *ParamTypes,
4047 SmallVectorImpl<QualType> &OutParamTypes,
4048 SmallVectorImpl<ParmVarDecl*> *PVars) {
4049 int indexAdjustment = 0;
4051 for (unsigned i = 0; i != NumParams; ++i) {
4052 if (ParmVarDecl *OldParm = Params[i]) {
4053 assert(OldParm->getFunctionScopeIndex() == i);
4055 Optional<unsigned> NumExpansions;
4056 ParmVarDecl *NewParm = 0;
4057 if (OldParm->isParameterPack()) {
4058 // We have a function parameter pack that may need to be expanded.
4059 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4061 // Find the parameter packs that could be expanded.
4062 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
4063 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
4064 TypeLoc Pattern = ExpansionTL.getPatternLoc();
4065 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
4066 assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
4068 // Determine whether we should expand the parameter packs.
4069 bool ShouldExpand = false;
4070 bool RetainExpansion = false;
4071 Optional<unsigned> OrigNumExpansions =
4072 ExpansionTL.getTypePtr()->getNumExpansions();
4073 NumExpansions = OrigNumExpansions;
4074 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
4075 Pattern.getSourceRange(),
4084 // Expand the function parameter pack into multiple, separate
4086 getDerived().ExpandingFunctionParameterPack(OldParm);
4087 for (unsigned I = 0; I != *NumExpansions; ++I) {
4088 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4089 ParmVarDecl *NewParm
4090 = getDerived().TransformFunctionTypeParam(OldParm,
4093 /*ExpectParameterPack=*/false);
4097 OutParamTypes.push_back(NewParm->getType());
4099 PVars->push_back(NewParm);
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 ParmVarDecl *NewParm
4107 = getDerived().TransformFunctionTypeParam(OldParm,
4110 /*ExpectParameterPack=*/false);
4114 OutParamTypes.push_back(NewParm->getType());
4116 PVars->push_back(NewParm);
4119 // The next parameter should have the same adjustment as the
4120 // last thing we pushed, but we post-incremented indexAdjustment
4121 // on every push. Also, if we push nothing, the adjustment should
4125 // We're done with the pack expansion.
4129 // We'll substitute the parameter now without expanding the pack
4131 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4132 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
4135 /*ExpectParameterPack=*/true);
4137 NewParm = getDerived().TransformFunctionTypeParam(
4138 OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
4144 OutParamTypes.push_back(NewParm->getType());
4146 PVars->push_back(NewParm);
4150 // Deal with the possibility that we don't have a parameter
4151 // declaration for this parameter.
4152 QualType OldType = ParamTypes[i];
4153 bool IsPackExpansion = false;
4154 Optional<unsigned> NumExpansions;
4156 if (const PackExpansionType *Expansion
4157 = dyn_cast<PackExpansionType>(OldType)) {
4158 // We have a function parameter pack that may need to be expanded.
4159 QualType Pattern = Expansion->getPattern();
4160 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4161 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4163 // Determine whether we should expand the parameter packs.
4164 bool ShouldExpand = false;
4165 bool RetainExpansion = false;
4166 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
4175 // Expand the function parameter pack into multiple, separate
4177 for (unsigned I = 0; I != *NumExpansions; ++I) {
4178 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4179 QualType NewType = getDerived().TransformType(Pattern);
4180 if (NewType.isNull())
4183 OutParamTypes.push_back(NewType);
4185 PVars->push_back(0);
4188 // We're done with the pack expansion.
4192 // If we're supposed to retain a pack expansion, do so by temporarily
4193 // forgetting the partially-substituted parameter pack.
4194 if (RetainExpansion) {
4195 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4196 QualType NewType = getDerived().TransformType(Pattern);
4197 if (NewType.isNull())
4200 OutParamTypes.push_back(NewType);
4202 PVars->push_back(0);
4205 // We'll substitute the parameter now without expanding the pack
4207 OldType = Expansion->getPattern();
4208 IsPackExpansion = true;
4209 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4210 NewType = getDerived().TransformType(OldType);
4212 NewType = getDerived().TransformType(OldType);
4215 if (NewType.isNull())
4218 if (IsPackExpansion)
4219 NewType = getSema().Context.getPackExpansionType(NewType,
4222 OutParamTypes.push_back(NewType);
4224 PVars->push_back(0);
4229 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
4230 if (ParmVarDecl *parm = (*PVars)[i])
4231 assert(parm->getFunctionScopeIndex() == i);
4238 template<typename Derived>
4240 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
4241 FunctionProtoTypeLoc TL) {
4242 return getDerived().TransformFunctionProtoType(TLB, TL, 0, 0);
4245 template<typename Derived>
4247 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
4248 FunctionProtoTypeLoc TL,
4249 CXXRecordDecl *ThisContext,
4250 unsigned ThisTypeQuals) {
4251 // Transform the parameters and return type.
4253 // We are required to instantiate the params and return type in source order.
4254 // When the function has a trailing return type, we instantiate the
4255 // parameters before the return type, since the return type can then refer
4256 // to the parameters themselves (via decltype, sizeof, etc.).
4258 SmallVector<QualType, 4> ParamTypes;
4259 SmallVector<ParmVarDecl*, 4> ParamDecls;
4260 const FunctionProtoType *T = TL.getTypePtr();
4262 QualType ResultType;
4264 if (T->hasTrailingReturn()) {
4265 if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
4268 TL.getTypePtr()->arg_type_begin(),
4269 ParamTypes, &ParamDecls))
4273 // C++11 [expr.prim.general]p3:
4274 // If a declaration declares a member function or member function
4275 // template of a class X, the expression this is a prvalue of type
4276 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
4277 // and the end of the function-definition, member-declarator, or
4279 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
4281 ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
4282 if (ResultType.isNull())
4287 ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
4288 if (ResultType.isNull())
4291 if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
4294 TL.getTypePtr()->arg_type_begin(),
4295 ParamTypes, &ParamDecls))
4299 // FIXME: Need to transform the exception-specification too.
4301 QualType Result = TL.getType();
4302 if (getDerived().AlwaysRebuild() ||
4303 ResultType != T->getResultType() ||
4304 T->getNumArgs() != ParamTypes.size() ||
4305 !std::equal(T->arg_type_begin(), T->arg_type_end(), ParamTypes.begin())) {
4306 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes,
4307 T->getExtProtoInfo());
4308 if (Result.isNull())
4312 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
4313 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4314 NewTL.setLParenLoc(TL.getLParenLoc());
4315 NewTL.setRParenLoc(TL.getRParenLoc());
4316 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4317 for (unsigned i = 0, e = NewTL.getNumArgs(); i != e; ++i)
4318 NewTL.setArg(i, ParamDecls[i]);
4323 template<typename Derived>
4324 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
4325 TypeLocBuilder &TLB,
4326 FunctionNoProtoTypeLoc TL) {
4327 const FunctionNoProtoType *T = TL.getTypePtr();
4328 QualType ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
4329 if (ResultType.isNull())
4332 QualType Result = TL.getType();
4333 if (getDerived().AlwaysRebuild() ||
4334 ResultType != T->getResultType())
4335 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
4337 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
4338 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
4339 NewTL.setLParenLoc(TL.getLParenLoc());
4340 NewTL.setRParenLoc(TL.getRParenLoc());
4341 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
4346 template<typename Derived> QualType
4347 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
4348 UnresolvedUsingTypeLoc TL) {
4349 const UnresolvedUsingType *T = TL.getTypePtr();
4350 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
4354 QualType Result = TL.getType();
4355 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
4356 Result = getDerived().RebuildUnresolvedUsingType(D);
4357 if (Result.isNull())
4361 // We might get an arbitrary type spec type back. We should at
4362 // least always get a type spec type, though.
4363 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
4364 NewTL.setNameLoc(TL.getNameLoc());
4369 template<typename Derived>
4370 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
4371 TypedefTypeLoc TL) {
4372 const TypedefType *T = TL.getTypePtr();
4373 TypedefNameDecl *Typedef
4374 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4379 QualType Result = TL.getType();
4380 if (getDerived().AlwaysRebuild() ||
4381 Typedef != T->getDecl()) {
4382 Result = getDerived().RebuildTypedefType(Typedef);
4383 if (Result.isNull())
4387 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
4388 NewTL.setNameLoc(TL.getNameLoc());
4393 template<typename Derived>
4394 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
4395 TypeOfExprTypeLoc TL) {
4396 // typeof expressions are not potentially evaluated contexts
4397 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
4398 Sema::ReuseLambdaContextDecl);
4400 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
4404 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
4408 QualType Result = TL.getType();
4409 if (getDerived().AlwaysRebuild() ||
4410 E.get() != TL.getUnderlyingExpr()) {
4411 Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
4412 if (Result.isNull())
4417 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
4418 NewTL.setTypeofLoc(TL.getTypeofLoc());
4419 NewTL.setLParenLoc(TL.getLParenLoc());
4420 NewTL.setRParenLoc(TL.getRParenLoc());
4425 template<typename Derived>
4426 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
4428 TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
4429 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
4433 QualType Result = TL.getType();
4434 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
4435 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
4436 if (Result.isNull())
4440 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
4441 NewTL.setTypeofLoc(TL.getTypeofLoc());
4442 NewTL.setLParenLoc(TL.getLParenLoc());
4443 NewTL.setRParenLoc(TL.getRParenLoc());
4444 NewTL.setUnderlyingTInfo(New_Under_TI);
4449 template<typename Derived>
4450 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
4451 DecltypeTypeLoc TL) {
4452 const DecltypeType *T = TL.getTypePtr();
4454 // decltype expressions are not potentially evaluated contexts
4455 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated, 0,
4456 /*IsDecltype=*/ true);
4458 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
4462 E = getSema().ActOnDecltypeExpression(E.take());
4466 QualType Result = TL.getType();
4467 if (getDerived().AlwaysRebuild() ||
4468 E.get() != T->getUnderlyingExpr()) {
4469 Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
4470 if (Result.isNull())
4475 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
4476 NewTL.setNameLoc(TL.getNameLoc());
4481 template<typename Derived>
4482 QualType TreeTransform<Derived>::TransformUnaryTransformType(
4483 TypeLocBuilder &TLB,
4484 UnaryTransformTypeLoc TL) {
4485 QualType Result = TL.getType();
4486 if (Result->isDependentType()) {
4487 const UnaryTransformType *T = TL.getTypePtr();
4489 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
4490 Result = getDerived().RebuildUnaryTransformType(NewBase,
4493 if (Result.isNull())
4497 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
4498 NewTL.setKWLoc(TL.getKWLoc());
4499 NewTL.setParensRange(TL.getParensRange());
4500 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
4504 template<typename Derived>
4505 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
4507 const AutoType *T = TL.getTypePtr();
4508 QualType OldDeduced = T->getDeducedType();
4509 QualType NewDeduced;
4510 if (!OldDeduced.isNull()) {
4511 NewDeduced = getDerived().TransformType(OldDeduced);
4512 if (NewDeduced.isNull())
4516 QualType Result = TL.getType();
4517 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
4518 T->isDependentType()) {
4519 Result = getDerived().RebuildAutoType(NewDeduced, T->isDecltypeAuto());
4520 if (Result.isNull())
4524 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4525 NewTL.setNameLoc(TL.getNameLoc());
4530 template<typename Derived>
4531 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
4533 const RecordType *T = TL.getTypePtr();
4535 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4540 QualType Result = TL.getType();
4541 if (getDerived().AlwaysRebuild() ||
4542 Record != T->getDecl()) {
4543 Result = getDerived().RebuildRecordType(Record);
4544 if (Result.isNull())
4548 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
4549 NewTL.setNameLoc(TL.getNameLoc());
4554 template<typename Derived>
4555 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
4557 const EnumType *T = TL.getTypePtr();
4559 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
4564 QualType Result = TL.getType();
4565 if (getDerived().AlwaysRebuild() ||
4566 Enum != T->getDecl()) {
4567 Result = getDerived().RebuildEnumType(Enum);
4568 if (Result.isNull())
4572 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
4573 NewTL.setNameLoc(TL.getNameLoc());
4578 template<typename Derived>
4579 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
4580 TypeLocBuilder &TLB,
4581 InjectedClassNameTypeLoc TL) {
4582 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
4583 TL.getTypePtr()->getDecl());
4584 if (!D) return QualType();
4586 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
4587 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
4591 template<typename Derived>
4592 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
4593 TypeLocBuilder &TLB,
4594 TemplateTypeParmTypeLoc TL) {
4595 return TransformTypeSpecType(TLB, TL);
4598 template<typename Derived>
4599 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
4600 TypeLocBuilder &TLB,
4601 SubstTemplateTypeParmTypeLoc TL) {
4602 const SubstTemplateTypeParmType *T = TL.getTypePtr();
4604 // Substitute into the replacement type, which itself might involve something
4605 // that needs to be transformed. This only tends to occur with default
4606 // template arguments of template template parameters.
4607 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
4608 QualType Replacement = getDerived().TransformType(T->getReplacementType());
4609 if (Replacement.isNull())
4612 // Always canonicalize the replacement type.
4613 Replacement = SemaRef.Context.getCanonicalType(Replacement);
4615 = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
4618 // Propagate type-source information.
4619 SubstTemplateTypeParmTypeLoc NewTL
4620 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
4621 NewTL.setNameLoc(TL.getNameLoc());
4626 template<typename Derived>
4627 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
4628 TypeLocBuilder &TLB,
4629 SubstTemplateTypeParmPackTypeLoc TL) {
4630 return TransformTypeSpecType(TLB, TL);
4633 template<typename Derived>
4634 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
4635 TypeLocBuilder &TLB,
4636 TemplateSpecializationTypeLoc TL) {
4637 const TemplateSpecializationType *T = TL.getTypePtr();
4639 // The nested-name-specifier never matters in a TemplateSpecializationType,
4640 // because we can't have a dependent nested-name-specifier anyway.
4642 TemplateName Template
4643 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
4644 TL.getTemplateNameLoc());
4645 if (Template.isNull())
4648 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
4651 template<typename Derived>
4652 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
4654 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
4655 if (ValueType.isNull())
4658 QualType Result = TL.getType();
4659 if (getDerived().AlwaysRebuild() ||
4660 ValueType != TL.getValueLoc().getType()) {
4661 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
4662 if (Result.isNull())
4666 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
4667 NewTL.setKWLoc(TL.getKWLoc());
4668 NewTL.setLParenLoc(TL.getLParenLoc());
4669 NewTL.setRParenLoc(TL.getRParenLoc());
4674 /// \brief Simple iterator that traverses the template arguments in a
4675 /// container that provides a \c getArgLoc() member function.
4677 /// This iterator is intended to be used with the iterator form of
4678 /// \c TreeTransform<Derived>::TransformTemplateArguments().
4679 template<typename ArgLocContainer>
4680 class TemplateArgumentLocContainerIterator {
4681 ArgLocContainer *Container;
4685 typedef TemplateArgumentLoc value_type;
4686 typedef TemplateArgumentLoc reference;
4687 typedef int difference_type;
4688 typedef std::input_iterator_tag iterator_category;
4691 TemplateArgumentLoc Arg;
4694 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4696 const TemplateArgumentLoc *operator->() const {
4702 TemplateArgumentLocContainerIterator() {}
4704 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
4706 : Container(&Container), Index(Index) { }
4708 TemplateArgumentLocContainerIterator &operator++() {
4713 TemplateArgumentLocContainerIterator operator++(int) {
4714 TemplateArgumentLocContainerIterator Old(*this);
4719 TemplateArgumentLoc operator*() const {
4720 return Container->getArgLoc(Index);
4723 pointer operator->() const {
4724 return pointer(Container->getArgLoc(Index));
4727 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
4728 const TemplateArgumentLocContainerIterator &Y) {
4729 return X.Container == Y.Container && X.Index == Y.Index;
4732 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
4733 const TemplateArgumentLocContainerIterator &Y) {
4739 template <typename Derived>
4740 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
4741 TypeLocBuilder &TLB,
4742 TemplateSpecializationTypeLoc TL,
4743 TemplateName Template) {
4744 TemplateArgumentListInfo NewTemplateArgs;
4745 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
4746 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
4747 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
4749 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
4750 ArgIterator(TL, TL.getNumArgs()),
4754 // FIXME: maybe don't rebuild if all the template arguments are the same.
4757 getDerived().RebuildTemplateSpecializationType(Template,
4758 TL.getTemplateNameLoc(),
4761 if (!Result.isNull()) {
4762 // Specializations of template template parameters are represented as
4763 // TemplateSpecializationTypes, and substitution of type alias templates
4764 // within a dependent context can transform them into
4765 // DependentTemplateSpecializationTypes.
4766 if (isa<DependentTemplateSpecializationType>(Result)) {
4767 DependentTemplateSpecializationTypeLoc NewTL
4768 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
4769 NewTL.setElaboratedKeywordLoc(SourceLocation());
4770 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
4771 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
4772 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
4773 NewTL.setLAngleLoc(TL.getLAngleLoc());
4774 NewTL.setRAngleLoc(TL.getRAngleLoc());
4775 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
4776 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
4780 TemplateSpecializationTypeLoc NewTL
4781 = TLB.push<TemplateSpecializationTypeLoc>(Result);
4782 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
4783 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
4784 NewTL.setLAngleLoc(TL.getLAngleLoc());
4785 NewTL.setRAngleLoc(TL.getRAngleLoc());
4786 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
4787 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
4793 template <typename Derived>
4794 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
4795 TypeLocBuilder &TLB,
4796 DependentTemplateSpecializationTypeLoc TL,
4797 TemplateName Template,
4799 TemplateArgumentListInfo NewTemplateArgs;
4800 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
4801 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
4802 typedef TemplateArgumentLocContainerIterator<
4803 DependentTemplateSpecializationTypeLoc> ArgIterator;
4804 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
4805 ArgIterator(TL, TL.getNumArgs()),
4809 // FIXME: maybe don't rebuild if all the template arguments are the same.
4811 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4813 = getSema().Context.getDependentTemplateSpecializationType(
4814 TL.getTypePtr()->getKeyword(),
4815 DTN->getQualifier(),
4816 DTN->getIdentifier(),
4819 DependentTemplateSpecializationTypeLoc NewTL
4820 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
4821 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
4822 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
4823 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
4824 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
4825 NewTL.setLAngleLoc(TL.getLAngleLoc());
4826 NewTL.setRAngleLoc(TL.getRAngleLoc());
4827 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
4828 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
4833 = getDerived().RebuildTemplateSpecializationType(Template,
4834 TL.getTemplateNameLoc(),
4837 if (!Result.isNull()) {
4838 /// FIXME: Wrap this in an elaborated-type-specifier?
4839 TemplateSpecializationTypeLoc NewTL
4840 = TLB.push<TemplateSpecializationTypeLoc>(Result);
4841 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
4842 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
4843 NewTL.setLAngleLoc(TL.getLAngleLoc());
4844 NewTL.setRAngleLoc(TL.getRAngleLoc());
4845 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
4846 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
4852 template<typename Derived>
4854 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
4855 ElaboratedTypeLoc TL) {
4856 const ElaboratedType *T = TL.getTypePtr();
4858 NestedNameSpecifierLoc QualifierLoc;
4859 // NOTE: the qualifier in an ElaboratedType is optional.
4860 if (TL.getQualifierLoc()) {
4862 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
4867 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
4868 if (NamedT.isNull())
4871 // C++0x [dcl.type.elab]p2:
4872 // If the identifier resolves to a typedef-name or the simple-template-id
4873 // resolves to an alias template specialization, the
4874 // elaborated-type-specifier is ill-formed.
4875 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
4876 if (const TemplateSpecializationType *TST =
4877 NamedT->getAs<TemplateSpecializationType>()) {
4878 TemplateName Template = TST->getTemplateName();
4879 if (TypeAliasTemplateDecl *TAT =
4880 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4881 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
4882 diag::err_tag_reference_non_tag) << 4;
4883 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
4888 QualType Result = TL.getType();
4889 if (getDerived().AlwaysRebuild() ||
4890 QualifierLoc != TL.getQualifierLoc() ||
4891 NamedT != T->getNamedType()) {
4892 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
4894 QualifierLoc, NamedT);
4895 if (Result.isNull())
4899 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
4900 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
4901 NewTL.setQualifierLoc(QualifierLoc);
4905 template<typename Derived>
4906 QualType TreeTransform<Derived>::TransformAttributedType(
4907 TypeLocBuilder &TLB,
4908 AttributedTypeLoc TL) {
4909 const AttributedType *oldType = TL.getTypePtr();
4910 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
4911 if (modifiedType.isNull())
4914 QualType result = TL.getType();
4916 // FIXME: dependent operand expressions?
4917 if (getDerived().AlwaysRebuild() ||
4918 modifiedType != oldType->getModifiedType()) {
4919 // TODO: this is really lame; we should really be rebuilding the
4920 // equivalent type from first principles.
4921 QualType equivalentType
4922 = getDerived().TransformType(oldType->getEquivalentType());
4923 if (equivalentType.isNull())
4925 result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
4930 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
4931 newTL.setAttrNameLoc(TL.getAttrNameLoc());
4932 if (TL.hasAttrOperand())
4933 newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
4934 if (TL.hasAttrExprOperand())
4935 newTL.setAttrExprOperand(TL.getAttrExprOperand());
4936 else if (TL.hasAttrEnumOperand())
4937 newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
4942 template<typename Derived>
4944 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
4946 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
4950 QualType Result = TL.getType();
4951 if (getDerived().AlwaysRebuild() ||
4952 Inner != TL.getInnerLoc().getType()) {
4953 Result = getDerived().RebuildParenType(Inner);
4954 if (Result.isNull())
4958 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
4959 NewTL.setLParenLoc(TL.getLParenLoc());
4960 NewTL.setRParenLoc(TL.getRParenLoc());
4964 template<typename Derived>
4965 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
4966 DependentNameTypeLoc TL) {
4967 const DependentNameType *T = TL.getTypePtr();
4969 NestedNameSpecifierLoc QualifierLoc
4970 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
4975 = getDerived().RebuildDependentNameType(T->getKeyword(),
4976 TL.getElaboratedKeywordLoc(),
4980 if (Result.isNull())
4983 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
4984 QualType NamedT = ElabT->getNamedType();
4985 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
4987 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
4988 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
4989 NewTL.setQualifierLoc(QualifierLoc);
4991 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
4992 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
4993 NewTL.setQualifierLoc(QualifierLoc);
4994 NewTL.setNameLoc(TL.getNameLoc());
4999 template<typename Derived>
5000 QualType TreeTransform<Derived>::
5001 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5002 DependentTemplateSpecializationTypeLoc TL) {
5003 NestedNameSpecifierLoc QualifierLoc;
5004 if (TL.getQualifierLoc()) {
5006 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
5012 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
5015 template<typename Derived>
5016 QualType TreeTransform<Derived>::
5017 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
5018 DependentTemplateSpecializationTypeLoc TL,
5019 NestedNameSpecifierLoc QualifierLoc) {
5020 const DependentTemplateSpecializationType *T = TL.getTypePtr();
5022 TemplateArgumentListInfo NewTemplateArgs;
5023 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
5024 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
5026 typedef TemplateArgumentLocContainerIterator<
5027 DependentTemplateSpecializationTypeLoc> ArgIterator;
5028 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
5029 ArgIterator(TL, TL.getNumArgs()),
5034 = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
5037 TL.getTemplateNameLoc(),
5039 if (Result.isNull())
5042 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
5043 QualType NamedT = ElabT->getNamedType();
5045 // Copy information relevant to the template specialization.
5046 TemplateSpecializationTypeLoc NamedTL
5047 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5048 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5049 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5050 NamedTL.setLAngleLoc(TL.getLAngleLoc());
5051 NamedTL.setRAngleLoc(TL.getRAngleLoc());
5052 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5053 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5055 // Copy information relevant to the elaborated type.
5056 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5057 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5058 NewTL.setQualifierLoc(QualifierLoc);
5059 } else if (isa<DependentTemplateSpecializationType>(Result)) {
5060 DependentTemplateSpecializationTypeLoc SpecTL
5061 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
5062 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5063 SpecTL.setQualifierLoc(QualifierLoc);
5064 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5065 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5066 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5067 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5068 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5069 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5071 TemplateSpecializationTypeLoc SpecTL
5072 = TLB.push<TemplateSpecializationTypeLoc>(Result);
5073 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
5074 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
5075 SpecTL.setLAngleLoc(TL.getLAngleLoc());
5076 SpecTL.setRAngleLoc(TL.getRAngleLoc());
5077 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
5078 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
5083 template<typename Derived>
5084 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
5085 PackExpansionTypeLoc TL) {
5087 = getDerived().TransformType(TLB, TL.getPatternLoc());
5088 if (Pattern.isNull())
5091 QualType Result = TL.getType();
5092 if (getDerived().AlwaysRebuild() ||
5093 Pattern != TL.getPatternLoc().getType()) {
5094 Result = getDerived().RebuildPackExpansionType(Pattern,
5095 TL.getPatternLoc().getSourceRange(),
5096 TL.getEllipsisLoc(),
5097 TL.getTypePtr()->getNumExpansions());
5098 if (Result.isNull())
5102 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
5103 NewT.setEllipsisLoc(TL.getEllipsisLoc());
5107 template<typename Derived>
5109 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
5110 ObjCInterfaceTypeLoc TL) {
5111 // ObjCInterfaceType is never dependent.
5112 TLB.pushFullCopy(TL);
5113 return TL.getType();
5116 template<typename Derived>
5118 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
5119 ObjCObjectTypeLoc TL) {
5120 // ObjCObjectType is never dependent.
5121 TLB.pushFullCopy(TL);
5122 return TL.getType();
5125 template<typename Derived>
5127 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
5128 ObjCObjectPointerTypeLoc TL) {
5129 // ObjCObjectPointerType is never dependent.
5130 TLB.pushFullCopy(TL);
5131 return TL.getType();
5134 //===----------------------------------------------------------------------===//
5135 // Statement transformation
5136 //===----------------------------------------------------------------------===//
5137 template<typename Derived>
5139 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
5140 return SemaRef.Owned(S);
5143 template<typename Derived>
5145 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
5146 return getDerived().TransformCompoundStmt(S, false);
5149 template<typename Derived>
5151 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
5153 Sema::CompoundScopeRAII CompoundScope(getSema());
5155 bool SubStmtInvalid = false;
5156 bool SubStmtChanged = false;
5157 SmallVector<Stmt*, 8> Statements;
5158 for (CompoundStmt::body_iterator B = S->body_begin(), BEnd = S->body_end();
5160 StmtResult Result = getDerived().TransformStmt(*B);
5161 if (Result.isInvalid()) {
5162 // Immediately fail if this was a DeclStmt, since it's very
5163 // likely that this will cause problems for future statements.
5164 if (isa<DeclStmt>(*B))
5167 // Otherwise, just keep processing substatements and fail later.
5168 SubStmtInvalid = true;
5172 SubStmtChanged = SubStmtChanged || Result.get() != *B;
5173 Statements.push_back(Result.takeAs<Stmt>());
5179 if (!getDerived().AlwaysRebuild() &&
5181 return SemaRef.Owned(S);
5183 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
5189 template<typename Derived>
5191 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
5192 ExprResult LHS, RHS;
5194 EnterExpressionEvaluationContext Unevaluated(SemaRef,
5195 Sema::ConstantEvaluated);
5197 // Transform the left-hand case value.
5198 LHS = getDerived().TransformExpr(S->getLHS());
5199 LHS = SemaRef.ActOnConstantExpression(LHS);
5200 if (LHS.isInvalid())
5203 // Transform the right-hand case value (for the GNU case-range extension).
5204 RHS = getDerived().TransformExpr(S->getRHS());
5205 RHS = SemaRef.ActOnConstantExpression(RHS);
5206 if (RHS.isInvalid())
5210 // Build the case statement.
5211 // Case statements are always rebuilt so that they will attached to their
5212 // transformed switch statement.
5213 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
5215 S->getEllipsisLoc(),
5218 if (Case.isInvalid())
5221 // Transform the statement following the case
5222 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5223 if (SubStmt.isInvalid())
5226 // Attach the body to the case statement
5227 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
5230 template<typename Derived>
5232 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
5233 // Transform the statement following the default case
5234 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5235 if (SubStmt.isInvalid())
5238 // Default statements are always rebuilt
5239 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
5243 template<typename Derived>
5245 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
5246 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5247 if (SubStmt.isInvalid())
5250 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
5256 // FIXME: Pass the real colon location in.
5257 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
5258 cast<LabelDecl>(LD), SourceLocation(),
5262 template<typename Derived>
5264 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
5265 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
5266 if (SubStmt.isInvalid())
5269 // TODO: transform attributes
5270 if (SubStmt.get() == S->getSubStmt() /* && attrs are the same */)
5273 return getDerived().RebuildAttributedStmt(S->getAttrLoc(),
5278 template<typename Derived>
5280 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
5281 // Transform the condition
5283 VarDecl *ConditionVar = 0;
5284 if (S->getConditionVariable()) {
5286 = cast_or_null<VarDecl>(
5287 getDerived().TransformDefinition(
5288 S->getConditionVariable()->getLocation(),
5289 S->getConditionVariable()));
5293 Cond = getDerived().TransformExpr(S->getCond());
5295 if (Cond.isInvalid())
5298 // Convert the condition to a boolean value.
5300 ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getIfLoc(),
5302 if (CondE.isInvalid())
5309 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
5310 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5313 // Transform the "then" branch.
5314 StmtResult Then = getDerived().TransformStmt(S->getThen());
5315 if (Then.isInvalid())
5318 // Transform the "else" branch.
5319 StmtResult Else = getDerived().TransformStmt(S->getElse());
5320 if (Else.isInvalid())
5323 if (!getDerived().AlwaysRebuild() &&
5324 FullCond.get() == S->getCond() &&
5325 ConditionVar == S->getConditionVariable() &&
5326 Then.get() == S->getThen() &&
5327 Else.get() == S->getElse())
5328 return SemaRef.Owned(S);
5330 return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
5332 S->getElseLoc(), Else.get());
5335 template<typename Derived>
5337 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
5338 // Transform the condition.
5340 VarDecl *ConditionVar = 0;
5341 if (S->getConditionVariable()) {
5343 = cast_or_null<VarDecl>(
5344 getDerived().TransformDefinition(
5345 S->getConditionVariable()->getLocation(),
5346 S->getConditionVariable()));
5350 Cond = getDerived().TransformExpr(S->getCond());
5352 if (Cond.isInvalid())
5356 // Rebuild the switch statement.
5358 = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
5360 if (Switch.isInvalid())
5363 // Transform the body of the switch statement.
5364 StmtResult Body = getDerived().TransformStmt(S->getBody());
5365 if (Body.isInvalid())
5368 // Complete the switch statement.
5369 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
5373 template<typename Derived>
5375 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
5376 // Transform the condition
5378 VarDecl *ConditionVar = 0;
5379 if (S->getConditionVariable()) {
5381 = cast_or_null<VarDecl>(
5382 getDerived().TransformDefinition(
5383 S->getConditionVariable()->getLocation(),
5384 S->getConditionVariable()));
5388 Cond = getDerived().TransformExpr(S->getCond());
5390 if (Cond.isInvalid())
5394 // Convert the condition to a boolean value.
5395 ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getWhileLoc(),
5397 if (CondE.isInvalid())
5403 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
5404 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5407 // Transform the body
5408 StmtResult Body = getDerived().TransformStmt(S->getBody());
5409 if (Body.isInvalid())
5412 if (!getDerived().AlwaysRebuild() &&
5413 FullCond.get() == S->getCond() &&
5414 ConditionVar == S->getConditionVariable() &&
5415 Body.get() == S->getBody())
5418 return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
5419 ConditionVar, Body.get());
5422 template<typename Derived>
5424 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
5425 // Transform the body
5426 StmtResult Body = getDerived().TransformStmt(S->getBody());
5427 if (Body.isInvalid())
5430 // Transform the condition
5431 ExprResult Cond = getDerived().TransformExpr(S->getCond());
5432 if (Cond.isInvalid())
5435 if (!getDerived().AlwaysRebuild() &&
5436 Cond.get() == S->getCond() &&
5437 Body.get() == S->getBody())
5438 return SemaRef.Owned(S);
5440 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
5441 /*FIXME:*/S->getWhileLoc(), Cond.get(),
5445 template<typename Derived>
5447 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
5448 // Transform the initialization statement
5449 StmtResult Init = getDerived().TransformStmt(S->getInit());
5450 if (Init.isInvalid())
5453 // Transform the condition
5455 VarDecl *ConditionVar = 0;
5456 if (S->getConditionVariable()) {
5458 = cast_or_null<VarDecl>(
5459 getDerived().TransformDefinition(
5460 S->getConditionVariable()->getLocation(),
5461 S->getConditionVariable()));
5465 Cond = getDerived().TransformExpr(S->getCond());
5467 if (Cond.isInvalid())
5471 // Convert the condition to a boolean value.
5472 ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getForLoc(),
5474 if (CondE.isInvalid())
5481 Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
5482 if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
5485 // Transform the increment
5486 ExprResult Inc = getDerived().TransformExpr(S->getInc());
5487 if (Inc.isInvalid())
5490 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
5491 if (S->getInc() && !FullInc.get())
5494 // Transform the body
5495 StmtResult Body = getDerived().TransformStmt(S->getBody());
5496 if (Body.isInvalid())
5499 if (!getDerived().AlwaysRebuild() &&
5500 Init.get() == S->getInit() &&
5501 FullCond.get() == S->getCond() &&
5502 Inc.get() == S->getInc() &&
5503 Body.get() == S->getBody())
5504 return SemaRef.Owned(S);
5506 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
5507 Init.get(), FullCond, ConditionVar,
5508 FullInc, S->getRParenLoc(), Body.get());
5511 template<typename Derived>
5513 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
5514 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
5519 // Goto statements must always be rebuilt, to resolve the label.
5520 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
5521 cast<LabelDecl>(LD));
5524 template<typename Derived>
5526 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
5527 ExprResult Target = getDerived().TransformExpr(S->getTarget());
5528 if (Target.isInvalid())
5530 Target = SemaRef.MaybeCreateExprWithCleanups(Target.take());
5532 if (!getDerived().AlwaysRebuild() &&
5533 Target.get() == S->getTarget())
5534 return SemaRef.Owned(S);
5536 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
5540 template<typename Derived>
5542 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
5543 return SemaRef.Owned(S);
5546 template<typename Derived>
5548 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
5549 return SemaRef.Owned(S);
5552 template<typename Derived>
5554 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
5555 ExprResult Result = getDerived().TransformExpr(S->getRetValue());
5556 if (Result.isInvalid())
5559 // FIXME: We always rebuild the return statement because there is no way
5560 // to tell whether the return type of the function has changed.
5561 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
5564 template<typename Derived>
5566 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
5567 bool DeclChanged = false;
5568 SmallVector<Decl *, 4> Decls;
5569 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
5571 Decl *Transformed = getDerived().TransformDefinition((*D)->getLocation(),
5576 if (Transformed != *D)
5579 Decls.push_back(Transformed);
5582 if (!getDerived().AlwaysRebuild() && !DeclChanged)
5583 return SemaRef.Owned(S);
5585 return getDerived().RebuildDeclStmt(Decls.data(), Decls.size(),
5586 S->getStartLoc(), S->getEndLoc());
5589 template<typename Derived>
5591 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
5593 SmallVector<Expr*, 8> Constraints;
5594 SmallVector<Expr*, 8> Exprs;
5595 SmallVector<IdentifierInfo *, 4> Names;
5597 ExprResult AsmString;
5598 SmallVector<Expr*, 8> Clobbers;
5600 bool ExprsChanged = false;
5602 // Go through the outputs.
5603 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
5604 Names.push_back(S->getOutputIdentifier(I));
5606 // No need to transform the constraint literal.
5607 Constraints.push_back(S->getOutputConstraintLiteral(I));
5609 // Transform the output expr.
5610 Expr *OutputExpr = S->getOutputExpr(I);
5611 ExprResult Result = getDerived().TransformExpr(OutputExpr);
5612 if (Result.isInvalid())
5615 ExprsChanged |= Result.get() != OutputExpr;
5617 Exprs.push_back(Result.get());
5620 // Go through the inputs.
5621 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
5622 Names.push_back(S->getInputIdentifier(I));
5624 // No need to transform the constraint literal.
5625 Constraints.push_back(S->getInputConstraintLiteral(I));
5627 // Transform the input expr.
5628 Expr *InputExpr = S->getInputExpr(I);
5629 ExprResult Result = getDerived().TransformExpr(InputExpr);
5630 if (Result.isInvalid())
5633 ExprsChanged |= Result.get() != InputExpr;
5635 Exprs.push_back(Result.get());
5638 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
5639 return SemaRef.Owned(S);
5641 // Go through the clobbers.
5642 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
5643 Clobbers.push_back(S->getClobberStringLiteral(I));
5645 // No need to transform the asm string literal.
5646 AsmString = SemaRef.Owned(S->getAsmString());
5647 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
5648 S->isVolatile(), S->getNumOutputs(),
5649 S->getNumInputs(), Names.data(),
5650 Constraints, Exprs, AsmString.get(),
5651 Clobbers, S->getRParenLoc());
5654 template<typename Derived>
5656 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
5657 ArrayRef<Token> AsmToks =
5658 llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
5660 bool HadError = false, HadChange = false;
5662 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
5663 SmallVector<Expr*, 8> TransformedExprs;
5664 TransformedExprs.reserve(SrcExprs.size());
5665 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
5666 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
5667 if (!Result.isUsable()) {
5670 HadChange |= (Result.get() != SrcExprs[i]);
5671 TransformedExprs.push_back(Result.take());
5675 if (HadError) return StmtError();
5676 if (!HadChange && !getDerived().AlwaysRebuild())
5679 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
5680 AsmToks, S->getAsmString(),
5681 S->getNumOutputs(), S->getNumInputs(),
5682 S->getAllConstraints(), S->getClobbers(),
5683 TransformedExprs, S->getEndLoc());
5686 template<typename Derived>
5688 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
5689 // Transform the body of the @try.
5690 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
5691 if (TryBody.isInvalid())
5694 // Transform the @catch statements (if present).
5695 bool AnyCatchChanged = false;
5696 SmallVector<Stmt*, 8> CatchStmts;
5697 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
5698 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
5699 if (Catch.isInvalid())
5701 if (Catch.get() != S->getCatchStmt(I))
5702 AnyCatchChanged = true;
5703 CatchStmts.push_back(Catch.release());
5706 // Transform the @finally statement (if present).
5708 if (S->getFinallyStmt()) {
5709 Finally = getDerived().TransformStmt(S->getFinallyStmt());
5710 if (Finally.isInvalid())
5714 // If nothing changed, just retain this statement.
5715 if (!getDerived().AlwaysRebuild() &&
5716 TryBody.get() == S->getTryBody() &&
5718 Finally.get() == S->getFinallyStmt())
5719 return SemaRef.Owned(S);
5721 // Build a new statement.
5722 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
5723 CatchStmts, Finally.get());
5726 template<typename Derived>
5728 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
5729 // Transform the @catch parameter, if there is one.
5731 if (VarDecl *FromVar = S->getCatchParamDecl()) {
5732 TypeSourceInfo *TSInfo = 0;
5733 if (FromVar->getTypeSourceInfo()) {
5734 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
5741 T = TSInfo->getType();
5743 T = getDerived().TransformType(FromVar->getType());
5748 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
5753 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
5754 if (Body.isInvalid())
5757 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
5762 template<typename Derived>
5764 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
5765 // Transform the body.
5766 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
5767 if (Body.isInvalid())
5770 // If nothing changed, just retain this statement.
5771 if (!getDerived().AlwaysRebuild() &&
5772 Body.get() == S->getFinallyBody())
5773 return SemaRef.Owned(S);
5775 // Build a new statement.
5776 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
5780 template<typename Derived>
5782 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5784 if (S->getThrowExpr()) {
5785 Operand = getDerived().TransformExpr(S->getThrowExpr());
5786 if (Operand.isInvalid())
5790 if (!getDerived().AlwaysRebuild() &&
5791 Operand.get() == S->getThrowExpr())
5792 return getSema().Owned(S);
5794 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
5797 template<typename Derived>
5799 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
5800 ObjCAtSynchronizedStmt *S) {
5801 // Transform the object we are locking.
5802 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
5803 if (Object.isInvalid())
5806 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
5808 if (Object.isInvalid())
5811 // Transform the body.
5812 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
5813 if (Body.isInvalid())
5816 // If nothing change, just retain the current statement.
5817 if (!getDerived().AlwaysRebuild() &&
5818 Object.get() == S->getSynchExpr() &&
5819 Body.get() == S->getSynchBody())
5820 return SemaRef.Owned(S);
5822 // Build a new statement.
5823 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
5824 Object.get(), Body.get());
5827 template<typename Derived>
5829 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
5830 ObjCAutoreleasePoolStmt *S) {
5831 // Transform the body.
5832 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
5833 if (Body.isInvalid())
5836 // If nothing changed, just retain this statement.
5837 if (!getDerived().AlwaysRebuild() &&
5838 Body.get() == S->getSubStmt())
5839 return SemaRef.Owned(S);
5841 // Build a new statement.
5842 return getDerived().RebuildObjCAutoreleasePoolStmt(
5843 S->getAtLoc(), Body.get());
5846 template<typename Derived>
5848 TreeTransform<Derived>::TransformObjCForCollectionStmt(
5849 ObjCForCollectionStmt *S) {
5850 // Transform the element statement.
5851 StmtResult Element = getDerived().TransformStmt(S->getElement());
5852 if (Element.isInvalid())
5855 // Transform the collection expression.
5856 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
5857 if (Collection.isInvalid())
5860 // Transform the body.
5861 StmtResult Body = getDerived().TransformStmt(S->getBody());
5862 if (Body.isInvalid())
5865 // If nothing changed, just retain this statement.
5866 if (!getDerived().AlwaysRebuild() &&
5867 Element.get() == S->getElement() &&
5868 Collection.get() == S->getCollection() &&
5869 Body.get() == S->getBody())
5870 return SemaRef.Owned(S);
5872 // Build a new statement.
5873 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
5881 template<typename Derived>
5883 TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
5884 // Transform the exception declaration, if any.
5886 if (S->getExceptionDecl()) {
5887 VarDecl *ExceptionDecl = S->getExceptionDecl();
5888 TypeSourceInfo *T = getDerived().TransformType(
5889 ExceptionDecl->getTypeSourceInfo());
5893 Var = getDerived().RebuildExceptionDecl(ExceptionDecl, T,
5894 ExceptionDecl->getInnerLocStart(),
5895 ExceptionDecl->getLocation(),
5896 ExceptionDecl->getIdentifier());
5897 if (!Var || Var->isInvalidDecl())
5901 // Transform the actual exception handler.
5902 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
5903 if (Handler.isInvalid())
5906 if (!getDerived().AlwaysRebuild() &&
5908 Handler.get() == S->getHandlerBlock())
5909 return SemaRef.Owned(S);
5911 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(),
5916 template<typename Derived>
5918 TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
5919 // Transform the try block itself.
5921 = getDerived().TransformCompoundStmt(S->getTryBlock());
5922 if (TryBlock.isInvalid())
5925 // Transform the handlers.
5926 bool HandlerChanged = false;
5927 SmallVector<Stmt*, 8> Handlers;
5928 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
5930 = getDerived().TransformCXXCatchStmt(S->getHandler(I));
5931 if (Handler.isInvalid())
5934 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
5935 Handlers.push_back(Handler.takeAs<Stmt>());
5938 if (!getDerived().AlwaysRebuild() &&
5939 TryBlock.get() == S->getTryBlock() &&
5941 return SemaRef.Owned(S);
5943 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
5947 template<typename Derived>
5949 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
5950 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
5951 if (Range.isInvalid())
5954 StmtResult BeginEnd = getDerived().TransformStmt(S->getBeginEndStmt());
5955 if (BeginEnd.isInvalid())
5958 ExprResult Cond = getDerived().TransformExpr(S->getCond());
5959 if (Cond.isInvalid())
5962 Cond = SemaRef.CheckBooleanCondition(Cond.take(), S->getColonLoc());
5963 if (Cond.isInvalid())
5966 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.take());
5968 ExprResult Inc = getDerived().TransformExpr(S->getInc());
5969 if (Inc.isInvalid())
5972 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.take());
5974 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
5975 if (LoopVar.isInvalid())
5978 StmtResult NewStmt = S;
5979 if (getDerived().AlwaysRebuild() ||
5980 Range.get() != S->getRangeStmt() ||
5981 BeginEnd.get() != S->getBeginEndStmt() ||
5982 Cond.get() != S->getCond() ||
5983 Inc.get() != S->getInc() ||
5984 LoopVar.get() != S->getLoopVarStmt()) {
5985 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
5986 S->getColonLoc(), Range.get(),
5987 BeginEnd.get(), Cond.get(),
5988 Inc.get(), LoopVar.get(),
5990 if (NewStmt.isInvalid())
5994 StmtResult Body = getDerived().TransformStmt(S->getBody());
5995 if (Body.isInvalid())
5998 // Body has changed but we didn't rebuild the for-range statement. Rebuild
5999 // it now so we have a new statement to attach the body to.
6000 if (Body.get() != S->getBody() && NewStmt.get() == S) {
6001 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
6002 S->getColonLoc(), Range.get(),
6003 BeginEnd.get(), Cond.get(),
6004 Inc.get(), LoopVar.get(),
6006 if (NewStmt.isInvalid())
6010 if (NewStmt.get() == S)
6011 return SemaRef.Owned(S);
6013 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
6016 template<typename Derived>
6018 TreeTransform<Derived>::TransformMSDependentExistsStmt(
6019 MSDependentExistsStmt *S) {
6020 // Transform the nested-name-specifier, if any.
6021 NestedNameSpecifierLoc QualifierLoc;
6022 if (S->getQualifierLoc()) {
6024 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
6029 // Transform the declaration name.
6030 DeclarationNameInfo NameInfo = S->getNameInfo();
6031 if (NameInfo.getName()) {
6032 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
6033 if (!NameInfo.getName())
6037 // Check whether anything changed.
6038 if (!getDerived().AlwaysRebuild() &&
6039 QualifierLoc == S->getQualifierLoc() &&
6040 NameInfo.getName() == S->getNameInfo().getName())
6043 // Determine whether this name exists, if we can.
6045 SS.Adopt(QualifierLoc);
6046 bool Dependent = false;
6047 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/0, SS, NameInfo)) {
6048 case Sema::IER_Exists:
6049 if (S->isIfExists())
6052 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6054 case Sema::IER_DoesNotExist:
6055 if (S->isIfNotExists())
6058 return new (getSema().Context) NullStmt(S->getKeywordLoc());
6060 case Sema::IER_Dependent:
6064 case Sema::IER_Error:
6068 // We need to continue with the instantiation, so do so now.
6069 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
6070 if (SubStmt.isInvalid())
6073 // If we have resolved the name, just transform to the substatement.
6077 // The name is still dependent, so build a dependent expression again.
6078 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
6085 template<typename Derived>
6087 TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
6088 NestedNameSpecifierLoc QualifierLoc;
6089 if (E->getQualifierLoc()) {
6091 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
6096 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
6097 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
6101 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
6102 if (Base.isInvalid())
6105 return new (SemaRef.getASTContext())
6106 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
6107 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
6108 QualifierLoc, E->getMemberLoc());
6111 template<typename Derived>
6113 TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
6114 StmtResult TryBlock; // = getDerived().TransformCompoundStmt(S->getTryBlock());
6115 if(TryBlock.isInvalid()) return StmtError();
6117 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
6118 if(!getDerived().AlwaysRebuild() &&
6119 TryBlock.get() == S->getTryBlock() &&
6120 Handler.get() == S->getHandler())
6121 return SemaRef.Owned(S);
6123 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(),
6129 template<typename Derived>
6131 TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
6132 StmtResult Block; // = getDerived().TransformCompoundStatement(S->getBlock());
6133 if(Block.isInvalid()) return StmtError();
6135 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(),
6139 template<typename Derived>
6141 TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
6142 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
6143 if(FilterExpr.isInvalid()) return StmtError();
6145 StmtResult Block; // = getDerived().TransformCompoundStatement(S->getBlock());
6146 if(Block.isInvalid()) return StmtError();
6148 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(),
6153 template<typename Derived>
6155 TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
6156 if(isa<SEHFinallyStmt>(Handler))
6157 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
6159 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
6162 //===----------------------------------------------------------------------===//
6163 // Expression transformation
6164 //===----------------------------------------------------------------------===//
6165 template<typename Derived>
6167 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
6168 return SemaRef.Owned(E);
6171 template<typename Derived>
6173 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
6174 NestedNameSpecifierLoc QualifierLoc;
6175 if (E->getQualifierLoc()) {
6177 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
6183 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
6188 DeclarationNameInfo NameInfo = E->getNameInfo();
6189 if (NameInfo.getName()) {
6190 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
6191 if (!NameInfo.getName())
6195 if (!getDerived().AlwaysRebuild() &&
6196 QualifierLoc == E->getQualifierLoc() &&
6197 ND == E->getDecl() &&
6198 NameInfo.getName() == E->getDecl()->getDeclName() &&
6199 !E->hasExplicitTemplateArgs()) {
6201 // Mark it referenced in the new context regardless.
6202 // FIXME: this is a bit instantiation-specific.
6203 SemaRef.MarkDeclRefReferenced(E);
6205 return SemaRef.Owned(E);
6208 TemplateArgumentListInfo TransArgs, *TemplateArgs = 0;
6209 if (E->hasExplicitTemplateArgs()) {
6210 TemplateArgs = &TransArgs;
6211 TransArgs.setLAngleLoc(E->getLAngleLoc());
6212 TransArgs.setRAngleLoc(E->getRAngleLoc());
6213 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
6214 E->getNumTemplateArgs(),
6219 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
6223 template<typename Derived>
6225 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
6226 return SemaRef.Owned(E);
6229 template<typename Derived>
6231 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
6232 return SemaRef.Owned(E);
6235 template<typename Derived>
6237 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
6238 return SemaRef.Owned(E);
6241 template<typename Derived>
6243 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
6244 return SemaRef.Owned(E);
6247 template<typename Derived>
6249 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
6250 return SemaRef.Owned(E);
6253 template<typename Derived>
6255 TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
6256 if (FunctionDecl *FD = E->getDirectCallee())
6257 SemaRef.MarkFunctionReferenced(E->getLocStart(), FD);
6258 return SemaRef.MaybeBindToTemporary(E);
6261 template<typename Derived>
6263 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
6264 ExprResult ControllingExpr =
6265 getDerived().TransformExpr(E->getControllingExpr());
6266 if (ControllingExpr.isInvalid())
6269 SmallVector<Expr *, 4> AssocExprs;
6270 SmallVector<TypeSourceInfo *, 4> AssocTypes;
6271 for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
6272 TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
6274 TypeSourceInfo *AssocType = getDerived().TransformType(TS);
6277 AssocTypes.push_back(AssocType);
6279 AssocTypes.push_back(0);
6282 ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
6283 if (AssocExpr.isInvalid())
6285 AssocExprs.push_back(AssocExpr.release());
6288 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
6291 ControllingExpr.release(),
6297 template<typename Derived>
6299 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
6300 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
6301 if (SubExpr.isInvalid())
6304 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
6305 return SemaRef.Owned(E);
6307 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
6311 /// \brief The operand of a unary address-of operator has special rules: it's
6312 /// allowed to refer to a non-static member of a class even if there's no 'this'
6313 /// object available.
6314 template<typename Derived>
6316 TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
6317 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
6318 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true);
6320 return getDerived().TransformExpr(E);
6323 template<typename Derived>
6325 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
6326 ExprResult SubExpr = TransformAddressOfOperand(E->getSubExpr());
6327 if (SubExpr.isInvalid())
6330 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
6331 return SemaRef.Owned(E);
6333 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
6338 template<typename Derived>
6340 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
6341 // Transform the type.
6342 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
6346 // Transform all of the components into components similar to what the
6348 // FIXME: It would be slightly more efficient in the non-dependent case to
6349 // just map FieldDecls, rather than requiring the rebuilder to look for
6350 // the fields again. However, __builtin_offsetof is rare enough in
6351 // template code that we don't care.
6352 bool ExprChanged = false;
6353 typedef Sema::OffsetOfComponent Component;
6354 typedef OffsetOfExpr::OffsetOfNode Node;
6355 SmallVector<Component, 4> Components;
6356 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
6357 const Node &ON = E->getComponent(I);
6359 Comp.isBrackets = true;
6360 Comp.LocStart = ON.getSourceRange().getBegin();
6361 Comp.LocEnd = ON.getSourceRange().getEnd();
6362 switch (ON.getKind()) {
6364 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
6365 ExprResult Index = getDerived().TransformExpr(FromIndex);
6366 if (Index.isInvalid())
6369 ExprChanged = ExprChanged || Index.get() != FromIndex;
6370 Comp.isBrackets = true;
6371 Comp.U.E = Index.get();
6376 case Node::Identifier:
6377 Comp.isBrackets = false;
6378 Comp.U.IdentInfo = ON.getFieldName();
6379 if (!Comp.U.IdentInfo)
6385 // Will be recomputed during the rebuild.
6389 Components.push_back(Comp);
6392 // If nothing changed, retain the existing expression.
6393 if (!getDerived().AlwaysRebuild() &&
6394 Type == E->getTypeSourceInfo() &&
6396 return SemaRef.Owned(E);
6398 // Build a new offsetof expression.
6399 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
6400 Components.data(), Components.size(),
6404 template<typename Derived>
6406 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
6407 assert(getDerived().AlreadyTransformed(E->getType()) &&
6408 "opaque value expression requires transformation");
6409 return SemaRef.Owned(E);
6412 template<typename Derived>
6414 TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
6415 // Rebuild the syntactic form. The original syntactic form has
6416 // opaque-value expressions in it, so strip those away and rebuild
6417 // the result. This is a really awful way of doing this, but the
6418 // better solution (rebuilding the semantic expressions and
6419 // rebinding OVEs as necessary) doesn't work; we'd need
6420 // TreeTransform to not strip away implicit conversions.
6421 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
6422 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
6423 if (result.isInvalid()) return ExprError();
6425 // If that gives us a pseudo-object result back, the pseudo-object
6426 // expression must have been an lvalue-to-rvalue conversion which we
6428 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
6429 result = SemaRef.checkPseudoObjectRValue(result.take());
6434 template<typename Derived>
6436 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
6437 UnaryExprOrTypeTraitExpr *E) {
6438 if (E->isArgumentType()) {
6439 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
6441 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
6445 if (!getDerived().AlwaysRebuild() && OldT == NewT)
6446 return SemaRef.Owned(E);
6448 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
6450 E->getSourceRange());
6453 // C++0x [expr.sizeof]p1:
6454 // The operand is either an expression, which is an unevaluated operand
6456 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
6457 Sema::ReuseLambdaContextDecl);
6459 ExprResult SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
6460 if (SubExpr.isInvalid())
6463 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
6464 return SemaRef.Owned(E);
6466 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
6467 E->getOperatorLoc(),
6469 E->getSourceRange());
6472 template<typename Derived>
6474 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
6475 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
6476 if (LHS.isInvalid())
6479 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
6480 if (RHS.isInvalid())
6484 if (!getDerived().AlwaysRebuild() &&
6485 LHS.get() == E->getLHS() &&
6486 RHS.get() == E->getRHS())
6487 return SemaRef.Owned(E);
6489 return getDerived().RebuildArraySubscriptExpr(LHS.get(),
6490 /*FIXME:*/E->getLHS()->getLocStart(),
6492 E->getRBracketLoc());
6495 template<typename Derived>
6497 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
6498 // Transform the callee.
6499 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
6500 if (Callee.isInvalid())
6503 // Transform arguments.
6504 bool ArgChanged = false;
6505 SmallVector<Expr*, 8> Args;
6506 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
6510 if (!getDerived().AlwaysRebuild() &&
6511 Callee.get() == E->getCallee() &&
6513 return SemaRef.MaybeBindToTemporary(E);
6515 // FIXME: Wrong source location information for the '('.
6516 SourceLocation FakeLParenLoc
6517 = ((Expr *)Callee.get())->getSourceRange().getBegin();
6518 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
6523 template<typename Derived>
6525 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
6526 ExprResult Base = getDerived().TransformExpr(E->getBase());
6527 if (Base.isInvalid())
6530 NestedNameSpecifierLoc QualifierLoc;
6531 if (E->hasQualifier()) {
6533 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
6538 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
6541 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
6542 E->getMemberDecl()));
6546 NamedDecl *FoundDecl = E->getFoundDecl();
6547 if (FoundDecl == E->getMemberDecl()) {
6550 FoundDecl = cast_or_null<NamedDecl>(
6551 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
6556 if (!getDerived().AlwaysRebuild() &&
6557 Base.get() == E->getBase() &&
6558 QualifierLoc == E->getQualifierLoc() &&
6559 Member == E->getMemberDecl() &&
6560 FoundDecl == E->getFoundDecl() &&
6561 !E->hasExplicitTemplateArgs()) {
6563 // Mark it referenced in the new context regardless.
6564 // FIXME: this is a bit instantiation-specific.
6565 SemaRef.MarkMemberReferenced(E);
6567 return SemaRef.Owned(E);
6570 TemplateArgumentListInfo TransArgs;
6571 if (E->hasExplicitTemplateArgs()) {
6572 TransArgs.setLAngleLoc(E->getLAngleLoc());
6573 TransArgs.setRAngleLoc(E->getRAngleLoc());
6574 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
6575 E->getNumTemplateArgs(),
6580 // FIXME: Bogus source location for the operator
6581 SourceLocation FakeOperatorLoc
6582 = SemaRef.PP.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
6584 // FIXME: to do this check properly, we will need to preserve the
6585 // first-qualifier-in-scope here, just in case we had a dependent
6586 // base (and therefore couldn't do the check) and a
6587 // nested-name-qualifier (and therefore could do the lookup).
6588 NamedDecl *FirstQualifierInScope = 0;
6590 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
6594 E->getMemberNameInfo(),
6597 (E->hasExplicitTemplateArgs()
6599 FirstQualifierInScope);
6602 template<typename Derived>
6604 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
6605 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
6606 if (LHS.isInvalid())
6609 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
6610 if (RHS.isInvalid())
6613 if (!getDerived().AlwaysRebuild() &&
6614 LHS.get() == E->getLHS() &&
6615 RHS.get() == E->getRHS())
6616 return SemaRef.Owned(E);
6618 Sema::FPContractStateRAII FPContractState(getSema());
6619 getSema().FPFeatures.fp_contract = E->isFPContractable();
6621 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
6622 LHS.get(), RHS.get());
6625 template<typename Derived>
6627 TreeTransform<Derived>::TransformCompoundAssignOperator(
6628 CompoundAssignOperator *E) {
6629 return getDerived().TransformBinaryOperator(E);
6632 template<typename Derived>
6633 ExprResult TreeTransform<Derived>::
6634 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
6635 // Just rebuild the common and RHS expressions and see whether we
6638 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
6639 if (commonExpr.isInvalid())
6642 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
6643 if (rhs.isInvalid())
6646 if (!getDerived().AlwaysRebuild() &&
6647 commonExpr.get() == e->getCommon() &&
6648 rhs.get() == e->getFalseExpr())
6649 return SemaRef.Owned(e);
6651 return getDerived().RebuildConditionalOperator(commonExpr.take(),
6652 e->getQuestionLoc(),
6658 template<typename Derived>
6660 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
6661 ExprResult Cond = getDerived().TransformExpr(E->getCond());
6662 if (Cond.isInvalid())
6665 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
6666 if (LHS.isInvalid())
6669 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
6670 if (RHS.isInvalid())
6673 if (!getDerived().AlwaysRebuild() &&
6674 Cond.get() == E->getCond() &&
6675 LHS.get() == E->getLHS() &&
6676 RHS.get() == E->getRHS())
6677 return SemaRef.Owned(E);
6679 return getDerived().RebuildConditionalOperator(Cond.get(),
6680 E->getQuestionLoc(),
6686 template<typename Derived>
6688 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
6689 // Implicit casts are eliminated during transformation, since they
6690 // will be recomputed by semantic analysis after transformation.
6691 return getDerived().TransformExpr(E->getSubExprAsWritten());
6694 template<typename Derived>
6696 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
6697 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
6702 = getDerived().TransformExpr(E->getSubExprAsWritten());
6703 if (SubExpr.isInvalid())
6706 if (!getDerived().AlwaysRebuild() &&
6707 Type == E->getTypeInfoAsWritten() &&
6708 SubExpr.get() == E->getSubExpr())
6709 return SemaRef.Owned(E);
6711 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
6717 template<typename Derived>
6719 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
6720 TypeSourceInfo *OldT = E->getTypeSourceInfo();
6721 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
6725 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
6726 if (Init.isInvalid())
6729 if (!getDerived().AlwaysRebuild() &&
6731 Init.get() == E->getInitializer())
6732 return SemaRef.MaybeBindToTemporary(E);
6734 // Note: the expression type doesn't necessarily match the
6735 // type-as-written, but that's okay, because it should always be
6736 // derivable from the initializer.
6738 return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
6739 /*FIXME:*/E->getInitializer()->getLocEnd(),
6743 template<typename Derived>
6745 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
6746 ExprResult Base = getDerived().TransformExpr(E->getBase());
6747 if (Base.isInvalid())
6750 if (!getDerived().AlwaysRebuild() &&
6751 Base.get() == E->getBase())
6752 return SemaRef.Owned(E);
6754 // FIXME: Bad source location
6755 SourceLocation FakeOperatorLoc
6756 = SemaRef.PP.getLocForEndOfToken(E->getBase()->getLocEnd());
6757 return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
6758 E->getAccessorLoc(),
6762 template<typename Derived>
6764 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
6765 bool InitChanged = false;
6767 SmallVector<Expr*, 4> Inits;
6768 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
6769 Inits, &InitChanged))
6772 if (!getDerived().AlwaysRebuild() && !InitChanged)
6773 return SemaRef.Owned(E);
6775 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
6776 E->getRBraceLoc(), E->getType());
6779 template<typename Derived>
6781 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
6784 // transform the initializer value
6785 ExprResult Init = getDerived().TransformExpr(E->getInit());
6786 if (Init.isInvalid())
6789 // transform the designators.
6790 SmallVector<Expr*, 4> ArrayExprs;
6791 bool ExprChanged = false;
6792 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
6793 DEnd = E->designators_end();
6795 if (D->isFieldDesignator()) {
6796 Desig.AddDesignator(Designator::getField(D->getFieldName(),
6802 if (D->isArrayDesignator()) {
6803 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
6804 if (Index.isInvalid())
6807 Desig.AddDesignator(Designator::getArray(Index.get(),
6808 D->getLBracketLoc()));
6810 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
6811 ArrayExprs.push_back(Index.release());
6815 assert(D->isArrayRangeDesignator() && "New kind of designator?");
6817 = getDerived().TransformExpr(E->getArrayRangeStart(*D));
6818 if (Start.isInvalid())
6821 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
6822 if (End.isInvalid())
6825 Desig.AddDesignator(Designator::getArrayRange(Start.get(),
6827 D->getLBracketLoc(),
6828 D->getEllipsisLoc()));
6830 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
6831 End.get() != E->getArrayRangeEnd(*D);
6833 ArrayExprs.push_back(Start.release());
6834 ArrayExprs.push_back(End.release());
6837 if (!getDerived().AlwaysRebuild() &&
6838 Init.get() == E->getInit() &&
6840 return SemaRef.Owned(E);
6842 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
6843 E->getEqualOrColonLoc(),
6844 E->usesGNUSyntax(), Init.get());
6847 template<typename Derived>
6849 TreeTransform<Derived>::TransformImplicitValueInitExpr(
6850 ImplicitValueInitExpr *E) {
6851 TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
6853 // FIXME: Will we ever have proper type location here? Will we actually
6854 // need to transform the type?
6855 QualType T = getDerived().TransformType(E->getType());
6859 if (!getDerived().AlwaysRebuild() &&
6861 return SemaRef.Owned(E);
6863 return getDerived().RebuildImplicitValueInitExpr(T);
6866 template<typename Derived>
6868 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
6869 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
6873 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
6874 if (SubExpr.isInvalid())
6877 if (!getDerived().AlwaysRebuild() &&
6878 TInfo == E->getWrittenTypeInfo() &&
6879 SubExpr.get() == E->getSubExpr())
6880 return SemaRef.Owned(E);
6882 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
6883 TInfo, E->getRParenLoc());
6886 template<typename Derived>
6888 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
6889 bool ArgumentChanged = false;
6890 SmallVector<Expr*, 4> Inits;
6891 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
6895 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
6900 /// \brief Transform an address-of-label expression.
6902 /// By default, the transformation of an address-of-label expression always
6903 /// rebuilds the expression, so that the label identifier can be resolved to
6904 /// the corresponding label statement by semantic analysis.
6905 template<typename Derived>
6907 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
6908 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
6913 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
6914 cast<LabelDecl>(LD));
6917 template<typename Derived>
6919 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
6920 SemaRef.ActOnStartStmtExpr();
6922 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
6923 if (SubStmt.isInvalid()) {
6924 SemaRef.ActOnStmtExprError();
6928 if (!getDerived().AlwaysRebuild() &&
6929 SubStmt.get() == E->getSubStmt()) {
6930 // Calling this an 'error' is unintuitive, but it does the right thing.
6931 SemaRef.ActOnStmtExprError();
6932 return SemaRef.MaybeBindToTemporary(E);
6935 return getDerived().RebuildStmtExpr(E->getLParenLoc(),
6940 template<typename Derived>
6942 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
6943 ExprResult Cond = getDerived().TransformExpr(E->getCond());
6944 if (Cond.isInvalid())
6947 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
6948 if (LHS.isInvalid())
6951 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
6952 if (RHS.isInvalid())
6955 if (!getDerived().AlwaysRebuild() &&
6956 Cond.get() == E->getCond() &&
6957 LHS.get() == E->getLHS() &&
6958 RHS.get() == E->getRHS())
6959 return SemaRef.Owned(E);
6961 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
6962 Cond.get(), LHS.get(), RHS.get(),
6966 template<typename Derived>
6968 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
6969 return SemaRef.Owned(E);
6972 template<typename Derived>
6974 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
6975 switch (E->getOperator()) {
6979 case OO_Array_Delete:
6980 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
6983 // This is a call to an object's operator().
6984 assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
6986 // Transform the object itself.
6987 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
6988 if (Object.isInvalid())
6991 // FIXME: Poor location information
6992 SourceLocation FakeLParenLoc
6993 = SemaRef.PP.getLocForEndOfToken(
6994 static_cast<Expr *>(Object.get())->getLocEnd());
6996 // Transform the call arguments.
6997 SmallVector<Expr*, 8> Args;
6998 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
7002 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
7007 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7009 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
7010 #include "clang/Basic/OperatorKinds.def"
7015 case OO_Conditional:
7016 llvm_unreachable("conditional operator is not actually overloadable");
7019 case NUM_OVERLOADED_OPERATORS:
7020 llvm_unreachable("not an overloaded operator?");
7023 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
7024 if (Callee.isInvalid())
7028 if (E->getOperator() == OO_Amp)
7029 First = getDerived().TransformAddressOfOperand(E->getArg(0));
7031 First = getDerived().TransformExpr(E->getArg(0));
7032 if (First.isInvalid())
7036 if (E->getNumArgs() == 2) {
7037 Second = getDerived().TransformExpr(E->getArg(1));
7038 if (Second.isInvalid())
7042 if (!getDerived().AlwaysRebuild() &&
7043 Callee.get() == E->getCallee() &&
7044 First.get() == E->getArg(0) &&
7045 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
7046 return SemaRef.MaybeBindToTemporary(E);
7048 Sema::FPContractStateRAII FPContractState(getSema());
7049 getSema().FPFeatures.fp_contract = E->isFPContractable();
7051 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
7052 E->getOperatorLoc(),
7058 template<typename Derived>
7060 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
7061 return getDerived().TransformCallExpr(E);
7064 template<typename Derived>
7066 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
7067 // Transform the callee.
7068 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
7069 if (Callee.isInvalid())
7072 // Transform exec config.
7073 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
7077 // Transform arguments.
7078 bool ArgChanged = false;
7079 SmallVector<Expr*, 8> Args;
7080 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
7084 if (!getDerived().AlwaysRebuild() &&
7085 Callee.get() == E->getCallee() &&
7087 return SemaRef.MaybeBindToTemporary(E);
7089 // FIXME: Wrong source location information for the '('.
7090 SourceLocation FakeLParenLoc
7091 = ((Expr *)Callee.get())->getSourceRange().getBegin();
7092 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
7094 E->getRParenLoc(), EC.get());
7097 template<typename Derived>
7099 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
7100 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
7105 = getDerived().TransformExpr(E->getSubExprAsWritten());
7106 if (SubExpr.isInvalid())
7109 if (!getDerived().AlwaysRebuild() &&
7110 Type == E->getTypeInfoAsWritten() &&
7111 SubExpr.get() == E->getSubExpr())
7112 return SemaRef.Owned(E);
7113 return getDerived().RebuildCXXNamedCastExpr(E->getOperatorLoc(),
7115 E->getAngleBrackets().getBegin(),
7117 E->getAngleBrackets().getEnd(),
7118 // FIXME. this should be '(' location
7119 E->getAngleBrackets().getEnd(),
7124 template<typename Derived>
7126 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
7127 return getDerived().TransformCXXNamedCastExpr(E);
7130 template<typename Derived>
7132 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
7133 return getDerived().TransformCXXNamedCastExpr(E);
7136 template<typename Derived>
7138 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
7139 CXXReinterpretCastExpr *E) {
7140 return getDerived().TransformCXXNamedCastExpr(E);
7143 template<typename Derived>
7145 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
7146 return getDerived().TransformCXXNamedCastExpr(E);
7149 template<typename Derived>
7151 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
7152 CXXFunctionalCastExpr *E) {
7153 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
7158 = getDerived().TransformExpr(E->getSubExprAsWritten());
7159 if (SubExpr.isInvalid())
7162 if (!getDerived().AlwaysRebuild() &&
7163 Type == E->getTypeInfoAsWritten() &&
7164 SubExpr.get() == E->getSubExpr())
7165 return SemaRef.Owned(E);
7167 return getDerived().RebuildCXXFunctionalCastExpr(Type,
7168 /*FIXME:*/E->getSubExpr()->getLocStart(),
7173 template<typename Derived>
7175 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
7176 if (E->isTypeOperand()) {
7177 TypeSourceInfo *TInfo
7178 = getDerived().TransformType(E->getTypeOperandSourceInfo());
7182 if (!getDerived().AlwaysRebuild() &&
7183 TInfo == E->getTypeOperandSourceInfo())
7184 return SemaRef.Owned(E);
7186 return getDerived().RebuildCXXTypeidExpr(E->getType(),
7192 // We don't know whether the subexpression is potentially evaluated until
7193 // after we perform semantic analysis. We speculatively assume it is
7194 // unevaluated; it will get fixed later if the subexpression is in fact
7195 // potentially evaluated.
7196 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
7197 Sema::ReuseLambdaContextDecl);
7199 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
7200 if (SubExpr.isInvalid())
7203 if (!getDerived().AlwaysRebuild() &&
7204 SubExpr.get() == E->getExprOperand())
7205 return SemaRef.Owned(E);
7207 return getDerived().RebuildCXXTypeidExpr(E->getType(),
7213 template<typename Derived>
7215 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
7216 if (E->isTypeOperand()) {
7217 TypeSourceInfo *TInfo
7218 = getDerived().TransformType(E->getTypeOperandSourceInfo());
7222 if (!getDerived().AlwaysRebuild() &&
7223 TInfo == E->getTypeOperandSourceInfo())
7224 return SemaRef.Owned(E);
7226 return getDerived().RebuildCXXUuidofExpr(E->getType(),
7232 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
7234 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
7235 if (SubExpr.isInvalid())
7238 if (!getDerived().AlwaysRebuild() &&
7239 SubExpr.get() == E->getExprOperand())
7240 return SemaRef.Owned(E);
7242 return getDerived().RebuildCXXUuidofExpr(E->getType(),
7248 template<typename Derived>
7250 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
7251 return SemaRef.Owned(E);
7254 template<typename Derived>
7256 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
7257 CXXNullPtrLiteralExpr *E) {
7258 return SemaRef.Owned(E);
7261 template<typename Derived>
7263 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
7264 DeclContext *DC = getSema().getFunctionLevelDeclContext();
7266 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
7267 T = MD->getThisType(getSema().Context);
7268 else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
7269 T = getSema().Context.getPointerType(
7270 getSema().Context.getRecordType(Record));
7272 assert(SemaRef.Context.getDiagnostics().hasErrorOccurred() &&
7273 "this in the wrong scope?");
7277 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
7278 // Make sure that we capture 'this'.
7279 getSema().CheckCXXThisCapture(E->getLocStart());
7280 return SemaRef.Owned(E);
7283 return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
7286 template<typename Derived>
7288 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
7289 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
7290 if (SubExpr.isInvalid())
7293 if (!getDerived().AlwaysRebuild() &&
7294 SubExpr.get() == E->getSubExpr())
7295 return SemaRef.Owned(E);
7297 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
7298 E->isThrownVariableInScope());
7301 template<typename Derived>
7303 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
7305 = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
7310 if (!getDerived().AlwaysRebuild() &&
7311 Param == E->getParam())
7312 return SemaRef.Owned(E);
7314 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
7317 template<typename Derived>
7319 TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
7321 = cast_or_null<FieldDecl>(getDerived().TransformDecl(E->getLocStart(),
7326 if (!getDerived().AlwaysRebuild() && Field == E->getField())
7327 return SemaRef.Owned(E);
7329 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
7332 template<typename Derived>
7334 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
7335 CXXScalarValueInitExpr *E) {
7336 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
7340 if (!getDerived().AlwaysRebuild() &&
7341 T == E->getTypeSourceInfo())
7342 return SemaRef.Owned(E);
7344 return getDerived().RebuildCXXScalarValueInitExpr(T,
7345 /*FIXME:*/T->getTypeLoc().getEndLoc(),
7349 template<typename Derived>
7351 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
7352 // Transform the type that we're allocating
7353 TypeSourceInfo *AllocTypeInfo
7354 = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
7358 // Transform the size of the array we're allocating (if any).
7359 ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
7360 if (ArraySize.isInvalid())
7363 // Transform the placement arguments (if any).
7364 bool ArgumentChanged = false;
7365 SmallVector<Expr*, 8> PlacementArgs;
7366 if (getDerived().TransformExprs(E->getPlacementArgs(),
7367 E->getNumPlacementArgs(), true,
7368 PlacementArgs, &ArgumentChanged))
7371 // Transform the initializer (if any).
7372 Expr *OldInit = E->getInitializer();
7375 NewInit = getDerived().TransformExpr(OldInit);
7376 if (NewInit.isInvalid())
7379 // Transform new operator and delete operator.
7380 FunctionDecl *OperatorNew = 0;
7381 if (E->getOperatorNew()) {
7382 OperatorNew = cast_or_null<FunctionDecl>(
7383 getDerived().TransformDecl(E->getLocStart(),
7384 E->getOperatorNew()));
7389 FunctionDecl *OperatorDelete = 0;
7390 if (E->getOperatorDelete()) {
7391 OperatorDelete = cast_or_null<FunctionDecl>(
7392 getDerived().TransformDecl(E->getLocStart(),
7393 E->getOperatorDelete()));
7394 if (!OperatorDelete)
7398 if (!getDerived().AlwaysRebuild() &&
7399 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
7400 ArraySize.get() == E->getArraySize() &&
7401 NewInit.get() == OldInit &&
7402 OperatorNew == E->getOperatorNew() &&
7403 OperatorDelete == E->getOperatorDelete() &&
7405 // Mark any declarations we need as referenced.
7406 // FIXME: instantiation-specific.
7408 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorNew);
7410 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
7412 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
7413 QualType ElementType
7414 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
7415 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
7416 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
7417 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
7418 SemaRef.MarkFunctionReferenced(E->getLocStart(), Destructor);
7423 return SemaRef.Owned(E);
7426 QualType AllocType = AllocTypeInfo->getType();
7427 if (!ArraySize.get()) {
7428 // If no array size was specified, but the new expression was
7429 // instantiated with an array type (e.g., "new T" where T is
7430 // instantiated with "int[4]"), extract the outer bound from the
7431 // array type as our array size. We do this with constant and
7432 // dependently-sized array types.
7433 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
7436 } else if (const ConstantArrayType *ConsArrayT
7437 = dyn_cast<ConstantArrayType>(ArrayT)) {
7439 = SemaRef.Owned(IntegerLiteral::Create(SemaRef.Context,
7440 ConsArrayT->getSize(),
7441 SemaRef.Context.getSizeType(),
7442 /*FIXME:*/E->getLocStart()));
7443 AllocType = ConsArrayT->getElementType();
7444 } else if (const DependentSizedArrayType *DepArrayT
7445 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
7446 if (DepArrayT->getSizeExpr()) {
7447 ArraySize = SemaRef.Owned(DepArrayT->getSizeExpr());
7448 AllocType = DepArrayT->getElementType();
7453 return getDerived().RebuildCXXNewExpr(E->getLocStart(),
7455 /*FIXME:*/E->getLocStart(),
7457 /*FIXME:*/E->getLocStart(),
7458 E->getTypeIdParens(),
7462 E->getDirectInitRange(),
7466 template<typename Derived>
7468 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
7469 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
7470 if (Operand.isInvalid())
7473 // Transform the delete operator, if known.
7474 FunctionDecl *OperatorDelete = 0;
7475 if (E->getOperatorDelete()) {
7476 OperatorDelete = cast_or_null<FunctionDecl>(
7477 getDerived().TransformDecl(E->getLocStart(),
7478 E->getOperatorDelete()));
7479 if (!OperatorDelete)
7483 if (!getDerived().AlwaysRebuild() &&
7484 Operand.get() == E->getArgument() &&
7485 OperatorDelete == E->getOperatorDelete()) {
7486 // Mark any declarations we need as referenced.
7487 // FIXME: instantiation-specific.
7489 SemaRef.MarkFunctionReferenced(E->getLocStart(), OperatorDelete);
7491 if (!E->getArgument()->isTypeDependent()) {
7492 QualType Destroyed = SemaRef.Context.getBaseElementType(
7493 E->getDestroyedType());
7494 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
7495 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
7496 SemaRef.MarkFunctionReferenced(E->getLocStart(),
7497 SemaRef.LookupDestructor(Record));
7501 return SemaRef.Owned(E);
7504 return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
7505 E->isGlobalDelete(),
7510 template<typename Derived>
7512 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
7513 CXXPseudoDestructorExpr *E) {
7514 ExprResult Base = getDerived().TransformExpr(E->getBase());
7515 if (Base.isInvalid())
7518 ParsedType ObjectTypePtr;
7519 bool MayBePseudoDestructor = false;
7520 Base = SemaRef.ActOnStartCXXMemberReference(0, Base.get(),
7521 E->getOperatorLoc(),
7522 E->isArrow()? tok::arrow : tok::period,
7524 MayBePseudoDestructor);
7525 if (Base.isInvalid())
7528 QualType ObjectType = ObjectTypePtr.get();
7529 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
7532 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
7537 SS.Adopt(QualifierLoc);
7539 PseudoDestructorTypeStorage Destroyed;
7540 if (E->getDestroyedTypeInfo()) {
7541 TypeSourceInfo *DestroyedTypeInfo
7542 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
7544 if (!DestroyedTypeInfo)
7546 Destroyed = DestroyedTypeInfo;
7547 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
7548 // We aren't likely to be able to resolve the identifier down to a type
7549 // now anyway, so just retain the identifier.
7550 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
7551 E->getDestroyedTypeLoc());
7553 // Look for a destructor known with the given name.
7554 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
7555 *E->getDestroyedTypeIdentifier(),
7556 E->getDestroyedTypeLoc(),
7564 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
7565 E->getDestroyedTypeLoc());
7568 TypeSourceInfo *ScopeTypeInfo = 0;
7569 if (E->getScopeTypeInfo()) {
7570 CXXScopeSpec EmptySS;
7571 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
7572 E->getScopeTypeInfo(), ObjectType, 0, EmptySS);
7577 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
7578 E->getOperatorLoc(),
7582 E->getColonColonLoc(),
7587 template<typename Derived>
7589 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
7590 UnresolvedLookupExpr *Old) {
7591 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
7592 Sema::LookupOrdinaryName);
7594 // Transform all the decls.
7595 for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
7596 E = Old->decls_end(); I != E; ++I) {
7597 NamedDecl *InstD = static_cast<NamedDecl*>(
7598 getDerived().TransformDecl(Old->getNameLoc(),
7601 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
7602 // This can happen because of dependent hiding.
7603 if (isa<UsingShadowDecl>(*I))
7609 // Expand using declarations.
7610 if (isa<UsingDecl>(InstD)) {
7611 UsingDecl *UD = cast<UsingDecl>(InstD);
7612 for (UsingDecl::shadow_iterator I = UD->shadow_begin(),
7613 E = UD->shadow_end(); I != E; ++I)
7621 // Resolve a kind, but don't do any further analysis. If it's
7622 // ambiguous, the callee needs to deal with it.
7625 // Rebuild the nested-name qualifier, if present.
7627 if (Old->getQualifierLoc()) {
7628 NestedNameSpecifierLoc QualifierLoc
7629 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
7633 SS.Adopt(QualifierLoc);
7636 if (Old->getNamingClass()) {
7637 CXXRecordDecl *NamingClass
7638 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
7640 Old->getNamingClass()));
7644 R.setNamingClass(NamingClass);
7647 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
7649 // If we have neither explicit template arguments, nor the template keyword,
7650 // it's a normal declaration name.
7651 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid())
7652 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
7654 // If we have template arguments, rebuild them, then rebuild the
7655 // templateid expression.
7656 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
7657 if (Old->hasExplicitTemplateArgs() &&
7658 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
7659 Old->getNumTemplateArgs(),
7663 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
7664 Old->requiresADL(), &TransArgs);
7667 template<typename Derived>
7669 TreeTransform<Derived>::TransformUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
7670 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
7674 if (!getDerived().AlwaysRebuild() &&
7675 T == E->getQueriedTypeSourceInfo())
7676 return SemaRef.Owned(E);
7678 return getDerived().RebuildUnaryTypeTrait(E->getTrait(),
7684 template<typename Derived>
7686 TreeTransform<Derived>::TransformBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
7687 TypeSourceInfo *LhsT = getDerived().TransformType(E->getLhsTypeSourceInfo());
7691 TypeSourceInfo *RhsT = getDerived().TransformType(E->getRhsTypeSourceInfo());
7695 if (!getDerived().AlwaysRebuild() &&
7696 LhsT == E->getLhsTypeSourceInfo() && RhsT == E->getRhsTypeSourceInfo())
7697 return SemaRef.Owned(E);
7699 return getDerived().RebuildBinaryTypeTrait(E->getTrait(),
7705 template<typename Derived>
7707 TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
7708 bool ArgChanged = false;
7709 SmallVector<TypeSourceInfo *, 4> Args;
7710 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
7711 TypeSourceInfo *From = E->getArg(I);
7712 TypeLoc FromTL = From->getTypeLoc();
7713 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
7715 TLB.reserve(FromTL.getFullDataSize());
7716 QualType To = getDerived().TransformType(TLB, FromTL);
7720 if (To == From->getType())
7721 Args.push_back(From);
7723 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
7731 // We have a pack expansion. Instantiate it.
7732 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
7733 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
7734 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7735 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
7737 // Determine whether the set of unexpanded parameter packs can and should
7740 bool RetainExpansion = false;
7741 Optional<unsigned> OrigNumExpansions =
7742 ExpansionTL.getTypePtr()->getNumExpansions();
7743 Optional<unsigned> NumExpansions = OrigNumExpansions;
7744 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
7745 PatternTL.getSourceRange(),
7747 Expand, RetainExpansion,
7752 // The transform has determined that we should perform a simple
7753 // transformation on the pack expansion, producing another pack
7755 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7758 TLB.reserve(From->getTypeLoc().getFullDataSize());
7760 QualType To = getDerived().TransformType(TLB, PatternTL);
7764 To = getDerived().RebuildPackExpansionType(To,
7765 PatternTL.getSourceRange(),
7766 ExpansionTL.getEllipsisLoc(),
7771 PackExpansionTypeLoc ToExpansionTL
7772 = TLB.push<PackExpansionTypeLoc>(To);
7773 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
7774 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
7778 // Expand the pack expansion by substituting for each argument in the
7780 for (unsigned I = 0; I != *NumExpansions; ++I) {
7781 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
7783 TLB.reserve(PatternTL.getFullDataSize());
7784 QualType To = getDerived().TransformType(TLB, PatternTL);
7788 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
7791 if (!RetainExpansion)
7794 // If we're supposed to retain a pack expansion, do so by temporarily
7795 // forgetting the partially-substituted parameter pack.
7796 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
7799 TLB.reserve(From->getTypeLoc().getFullDataSize());
7801 QualType To = getDerived().TransformType(TLB, PatternTL);
7805 To = getDerived().RebuildPackExpansionType(To,
7806 PatternTL.getSourceRange(),
7807 ExpansionTL.getEllipsisLoc(),
7812 PackExpansionTypeLoc ToExpansionTL
7813 = TLB.push<PackExpansionTypeLoc>(To);
7814 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
7815 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
7818 if (!getDerived().AlwaysRebuild() && !ArgChanged)
7819 return SemaRef.Owned(E);
7821 return getDerived().RebuildTypeTrait(E->getTrait(),
7827 template<typename Derived>
7829 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
7830 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
7834 if (!getDerived().AlwaysRebuild() &&
7835 T == E->getQueriedTypeSourceInfo())
7836 return SemaRef.Owned(E);
7840 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
7841 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
7842 if (SubExpr.isInvalid())
7845 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
7846 return SemaRef.Owned(E);
7849 return getDerived().RebuildArrayTypeTrait(E->getTrait(),
7856 template<typename Derived>
7858 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
7861 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
7862 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
7863 if (SubExpr.isInvalid())
7866 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
7867 return SemaRef.Owned(E);
7870 return getDerived().RebuildExpressionTrait(
7871 E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
7874 template<typename Derived>
7876 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
7877 DependentScopeDeclRefExpr *E) {
7878 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand*/false);
7881 template<typename Derived>
7883 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
7884 DependentScopeDeclRefExpr *E,
7885 bool IsAddressOfOperand) {
7886 NestedNameSpecifierLoc QualifierLoc
7887 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
7890 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
7892 // TODO: If this is a conversion-function-id, verify that the
7893 // destination type name (if present) resolves the same way after
7894 // instantiation as it did in the local scope.
7896 DeclarationNameInfo NameInfo
7897 = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
7898 if (!NameInfo.getName())
7901 if (!E->hasExplicitTemplateArgs()) {
7902 if (!getDerived().AlwaysRebuild() &&
7903 QualifierLoc == E->getQualifierLoc() &&
7904 // Note: it is sufficient to compare the Name component of NameInfo:
7905 // if name has not changed, DNLoc has not changed either.
7906 NameInfo.getName() == E->getDeclName())
7907 return SemaRef.Owned(E);
7909 return getDerived().RebuildDependentScopeDeclRefExpr(QualifierLoc,
7913 IsAddressOfOperand);
7916 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
7917 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
7918 E->getNumTemplateArgs(),
7922 return getDerived().RebuildDependentScopeDeclRefExpr(QualifierLoc,
7926 IsAddressOfOperand);
7929 template<typename Derived>
7931 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
7932 // CXXConstructExprs other than for list-initialization and
7933 // CXXTemporaryObjectExpr are always implicit, so when we have
7934 // a 1-argument construction we just transform that argument.
7935 if ((E->getNumArgs() == 1 ||
7936 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
7937 (!getDerived().DropCallArgument(E->getArg(0))) &&
7938 !E->isListInitialization())
7939 return getDerived().TransformExpr(E->getArg(0));
7941 TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
7943 QualType T = getDerived().TransformType(E->getType());
7947 CXXConstructorDecl *Constructor
7948 = cast_or_null<CXXConstructorDecl>(
7949 getDerived().TransformDecl(E->getLocStart(),
7950 E->getConstructor()));
7954 bool ArgumentChanged = false;
7955 SmallVector<Expr*, 8> Args;
7956 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
7960 if (!getDerived().AlwaysRebuild() &&
7961 T == E->getType() &&
7962 Constructor == E->getConstructor() &&
7964 // Mark the constructor as referenced.
7965 // FIXME: Instantiation-specific
7966 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
7967 return SemaRef.Owned(E);
7970 return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
7971 Constructor, E->isElidable(),
7973 E->hadMultipleCandidates(),
7974 E->isListInitialization(),
7975 E->requiresZeroInitialization(),
7976 E->getConstructionKind(),
7977 E->getParenRange());
7980 /// \brief Transform a C++ temporary-binding expression.
7982 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
7983 /// transform the subexpression and return that.
7984 template<typename Derived>
7986 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
7987 return getDerived().TransformExpr(E->getSubExpr());
7990 /// \brief Transform a C++ expression that contains cleanups that should
7991 /// be run after the expression is evaluated.
7993 /// Since ExprWithCleanups nodes are implicitly generated, we
7994 /// just transform the subexpression and return that.
7995 template<typename Derived>
7997 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
7998 return getDerived().TransformExpr(E->getSubExpr());
8001 template<typename Derived>
8003 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
8004 CXXTemporaryObjectExpr *E) {
8005 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
8009 CXXConstructorDecl *Constructor
8010 = cast_or_null<CXXConstructorDecl>(
8011 getDerived().TransformDecl(E->getLocStart(),
8012 E->getConstructor()));
8016 bool ArgumentChanged = false;
8017 SmallVector<Expr*, 8> Args;
8018 Args.reserve(E->getNumArgs());
8019 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
8023 if (!getDerived().AlwaysRebuild() &&
8024 T == E->getTypeSourceInfo() &&
8025 Constructor == E->getConstructor() &&
8027 // FIXME: Instantiation-specific
8028 SemaRef.MarkFunctionReferenced(E->getLocStart(), Constructor);
8029 return SemaRef.MaybeBindToTemporary(E);
8032 // FIXME: Pass in E->isListInitialization().
8033 return getDerived().RebuildCXXTemporaryObjectExpr(T,
8034 /*FIXME:*/T->getTypeLoc().getEndLoc(),
8039 template<typename Derived>
8041 TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
8042 // Transform the type of the lambda parameters and start the definition of
8043 // the lambda itself.
8044 TypeSourceInfo *MethodTy
8045 = TransformType(E->getCallOperator()->getTypeSourceInfo());
8049 // Create the local class that will describe the lambda.
8050 CXXRecordDecl *Class
8051 = getSema().createLambdaClosureType(E->getIntroducerRange(),
8053 /*KnownDependent=*/false);
8054 getDerived().transformedLocalDecl(E->getLambdaClass(), Class);
8056 // Transform lambda parameters.
8057 SmallVector<QualType, 4> ParamTypes;
8058 SmallVector<ParmVarDecl *, 4> Params;
8059 if (getDerived().TransformFunctionTypeParams(E->getLocStart(),
8060 E->getCallOperator()->param_begin(),
8061 E->getCallOperator()->param_size(),
8062 0, ParamTypes, &Params))
8065 // Build the call operator.
8066 CXXMethodDecl *CallOperator
8067 = getSema().startLambdaDefinition(Class, E->getIntroducerRange(),
8069 E->getCallOperator()->getLocEnd(),
8071 getDerived().transformAttrs(E->getCallOperator(), CallOperator);
8073 return getDerived().TransformLambdaScope(E, CallOperator);
8076 template<typename Derived>
8078 TreeTransform<Derived>::TransformLambdaScope(LambdaExpr *E,
8079 CXXMethodDecl *CallOperator) {
8080 // Introduce the context of the call operator.
8081 Sema::ContextRAII SavedContext(getSema(), CallOperator);
8083 // Enter the scope of the lambda.
8084 sema::LambdaScopeInfo *LSI
8085 = getSema().enterLambdaScope(CallOperator, E->getIntroducerRange(),
8086 E->getCaptureDefault(),
8087 E->hasExplicitParameters(),
8088 E->hasExplicitResultType(),
8091 // Transform captures.
8092 bool Invalid = false;
8093 bool FinishedExplicitCaptures = false;
8094 for (LambdaExpr::capture_iterator C = E->capture_begin(),
8095 CEnd = E->capture_end();
8097 // When we hit the first implicit capture, tell Sema that we've finished
8098 // the list of explicit captures.
8099 if (!FinishedExplicitCaptures && C->isImplicit()) {
8100 getSema().finishLambdaExplicitCaptures(LSI);
8101 FinishedExplicitCaptures = true;
8104 // Capturing 'this' is trivial.
8105 if (C->capturesThis()) {
8106 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit());
8110 // Determine the capture kind for Sema.
8111 Sema::TryCaptureKind Kind
8112 = C->isImplicit()? Sema::TryCapture_Implicit
8113 : C->getCaptureKind() == LCK_ByCopy
8114 ? Sema::TryCapture_ExplicitByVal
8115 : Sema::TryCapture_ExplicitByRef;
8116 SourceLocation EllipsisLoc;
8117 if (C->isPackExpansion()) {
8118 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
8119 bool ShouldExpand = false;
8120 bool RetainExpansion = false;
8121 Optional<unsigned> NumExpansions;
8122 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
8125 ShouldExpand, RetainExpansion,
8130 // The transform has determined that we should perform an expansion;
8131 // transform and capture each of the arguments.
8132 // expansion of the pattern. Do so.
8133 VarDecl *Pack = C->getCapturedVar();
8134 for (unsigned I = 0; I != *NumExpansions; ++I) {
8135 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
8136 VarDecl *CapturedVar
8137 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
8144 // Capture the transformed variable.
8145 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
8150 EllipsisLoc = C->getEllipsisLoc();
8153 // Transform the captured variable.
8154 VarDecl *CapturedVar
8155 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
8156 C->getCapturedVar()));
8162 // Capture the transformed variable.
8163 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
8165 if (!FinishedExplicitCaptures)
8166 getSema().finishLambdaExplicitCaptures(LSI);
8169 // Enter a new evaluation context to insulate the lambda from any
8170 // cleanups from the enclosing full-expression.
8171 getSema().PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
8174 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/0,
8175 /*IsInstantiation=*/true);
8179 // Instantiate the body of the lambda expression.
8180 StmtResult Body = getDerived().TransformStmt(E->getBody());
8181 if (Body.isInvalid()) {
8182 getSema().ActOnLambdaError(E->getLocStart(), /*CurScope=*/0,
8183 /*IsInstantiation=*/true);
8187 return getSema().ActOnLambdaExpr(E->getLocStart(), Body.take(),
8188 /*CurScope=*/0, /*IsInstantiation=*/true);
8191 template<typename Derived>
8193 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
8194 CXXUnresolvedConstructExpr *E) {
8195 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
8199 bool ArgumentChanged = false;
8200 SmallVector<Expr*, 8> Args;
8201 Args.reserve(E->arg_size());
8202 if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
8206 if (!getDerived().AlwaysRebuild() &&
8207 T == E->getTypeSourceInfo() &&
8209 return SemaRef.Owned(E);
8211 // FIXME: we're faking the locations of the commas
8212 return getDerived().RebuildCXXUnresolvedConstructExpr(T,
8218 template<typename Derived>
8220 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
8221 CXXDependentScopeMemberExpr *E) {
8222 // Transform the base of the expression.
8223 ExprResult Base((Expr*) 0);
8226 QualType ObjectType;
8227 if (!E->isImplicitAccess()) {
8228 OldBase = E->getBase();
8229 Base = getDerived().TransformExpr(OldBase);
8230 if (Base.isInvalid())
8233 // Start the member reference and compute the object's type.
8234 ParsedType ObjectTy;
8235 bool MayBePseudoDestructor = false;
8236 Base = SemaRef.ActOnStartCXXMemberReference(0, Base.get(),
8237 E->getOperatorLoc(),
8238 E->isArrow()? tok::arrow : tok::period,
8240 MayBePseudoDestructor);
8241 if (Base.isInvalid())
8244 ObjectType = ObjectTy.get();
8245 BaseType = ((Expr*) Base.get())->getType();
8248 BaseType = getDerived().TransformType(E->getBaseType());
8249 ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
8252 // Transform the first part of the nested-name-specifier that qualifies
8254 NamedDecl *FirstQualifierInScope
8255 = getDerived().TransformFirstQualifierInScope(
8256 E->getFirstQualifierFoundInScope(),
8257 E->getQualifierLoc().getBeginLoc());
8259 NestedNameSpecifierLoc QualifierLoc;
8260 if (E->getQualifier()) {
8262 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
8264 FirstQualifierInScope);
8269 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
8271 // TODO: If this is a conversion-function-id, verify that the
8272 // destination type name (if present) resolves the same way after
8273 // instantiation as it did in the local scope.
8275 DeclarationNameInfo NameInfo
8276 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
8277 if (!NameInfo.getName())
8280 if (!E->hasExplicitTemplateArgs()) {
8281 // This is a reference to a member without an explicitly-specified
8282 // template argument list. Optimize for this common case.
8283 if (!getDerived().AlwaysRebuild() &&
8284 Base.get() == OldBase &&
8285 BaseType == E->getBaseType() &&
8286 QualifierLoc == E->getQualifierLoc() &&
8287 NameInfo.getName() == E->getMember() &&
8288 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
8289 return SemaRef.Owned(E);
8291 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
8294 E->getOperatorLoc(),
8297 FirstQualifierInScope,
8299 /*TemplateArgs*/ 0);
8302 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
8303 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
8304 E->getNumTemplateArgs(),
8308 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
8311 E->getOperatorLoc(),
8314 FirstQualifierInScope,
8319 template<typename Derived>
8321 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
8322 // Transform the base of the expression.
8323 ExprResult Base((Expr*) 0);
8325 if (!Old->isImplicitAccess()) {
8326 Base = getDerived().TransformExpr(Old->getBase());
8327 if (Base.isInvalid())
8329 Base = getSema().PerformMemberExprBaseConversion(Base.take(),
8331 if (Base.isInvalid())
8333 BaseType = Base.get()->getType();
8335 BaseType = getDerived().TransformType(Old->getBaseType());
8338 NestedNameSpecifierLoc QualifierLoc;
8339 if (Old->getQualifierLoc()) {
8341 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
8346 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
8348 LookupResult R(SemaRef, Old->getMemberNameInfo(),
8349 Sema::LookupOrdinaryName);
8351 // Transform all the decls.
8352 for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
8353 E = Old->decls_end(); I != E; ++I) {
8354 NamedDecl *InstD = static_cast<NamedDecl*>(
8355 getDerived().TransformDecl(Old->getMemberLoc(),
8358 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
8359 // This can happen because of dependent hiding.
8360 if (isa<UsingShadowDecl>(*I))
8368 // Expand using declarations.
8369 if (isa<UsingDecl>(InstD)) {
8370 UsingDecl *UD = cast<UsingDecl>(InstD);
8371 for (UsingDecl::shadow_iterator I = UD->shadow_begin(),
8372 E = UD->shadow_end(); I != E; ++I)
8382 // Determine the naming class.
8383 if (Old->getNamingClass()) {
8384 CXXRecordDecl *NamingClass
8385 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
8386 Old->getMemberLoc(),
8387 Old->getNamingClass()));
8391 R.setNamingClass(NamingClass);
8394 TemplateArgumentListInfo TransArgs;
8395 if (Old->hasExplicitTemplateArgs()) {
8396 TransArgs.setLAngleLoc(Old->getLAngleLoc());
8397 TransArgs.setRAngleLoc(Old->getRAngleLoc());
8398 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
8399 Old->getNumTemplateArgs(),
8404 // FIXME: to do this check properly, we will need to preserve the
8405 // first-qualifier-in-scope here, just in case we had a dependent
8406 // base (and therefore couldn't do the check) and a
8407 // nested-name-qualifier (and therefore could do the lookup).
8408 NamedDecl *FirstQualifierInScope = 0;
8410 return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
8412 Old->getOperatorLoc(),
8416 FirstQualifierInScope,
8418 (Old->hasExplicitTemplateArgs()
8422 template<typename Derived>
8424 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
8425 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
8426 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
8427 if (SubExpr.isInvalid())
8430 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
8431 return SemaRef.Owned(E);
8433 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
8436 template<typename Derived>
8438 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
8439 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
8440 if (Pattern.isInvalid())
8443 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
8444 return SemaRef.Owned(E);
8446 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
8447 E->getNumExpansions());
8450 template<typename Derived>
8452 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
8453 // If E is not value-dependent, then nothing will change when we transform it.
8454 // Note: This is an instantiation-centric view.
8455 if (!E->isValueDependent())
8456 return SemaRef.Owned(E);
8458 // Note: None of the implementations of TryExpandParameterPacks can ever
8459 // produce a diagnostic when given only a single unexpanded parameter pack,
8461 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
8462 bool ShouldExpand = false;
8463 bool RetainExpansion = false;
8464 Optional<unsigned> NumExpansions;
8465 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
8467 ShouldExpand, RetainExpansion,
8471 if (RetainExpansion)
8472 return SemaRef.Owned(E);
8474 NamedDecl *Pack = E->getPack();
8475 if (!ShouldExpand) {
8476 Pack = cast_or_null<NamedDecl>(getDerived().TransformDecl(E->getPackLoc(),
8483 // We now know the length of the parameter pack, so build a new expression
8484 // that stores that length.
8485 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), Pack,
8486 E->getPackLoc(), E->getRParenLoc(),
8490 template<typename Derived>
8492 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
8493 SubstNonTypeTemplateParmPackExpr *E) {
8494 // Default behavior is to do nothing with this transformation.
8495 return SemaRef.Owned(E);
8498 template<typename Derived>
8500 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
8501 SubstNonTypeTemplateParmExpr *E) {
8502 // Default behavior is to do nothing with this transformation.
8503 return SemaRef.Owned(E);
8506 template<typename Derived>
8508 TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
8509 // Default behavior is to do nothing with this transformation.
8510 return SemaRef.Owned(E);
8513 template<typename Derived>
8515 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
8516 MaterializeTemporaryExpr *E) {
8517 return getDerived().TransformExpr(E->GetTemporaryExpr());
8520 template<typename Derived>
8522 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
8523 return SemaRef.MaybeBindToTemporary(E);
8526 template<typename Derived>
8528 TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
8529 return SemaRef.Owned(E);
8532 template<typename Derived>
8534 TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
8535 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
8536 if (SubExpr.isInvalid())
8539 if (!getDerived().AlwaysRebuild() &&
8540 SubExpr.get() == E->getSubExpr())
8541 return SemaRef.Owned(E);
8543 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
8546 template<typename Derived>
8548 TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
8549 // Transform each of the elements.
8550 SmallVector<Expr *, 8> Elements;
8551 bool ArgChanged = false;
8552 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
8553 /*IsCall=*/false, Elements, &ArgChanged))
8556 if (!getDerived().AlwaysRebuild() && !ArgChanged)
8557 return SemaRef.MaybeBindToTemporary(E);
8559 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
8564 template<typename Derived>
8566 TreeTransform<Derived>::TransformObjCDictionaryLiteral(
8567 ObjCDictionaryLiteral *E) {
8568 // Transform each of the elements.
8569 SmallVector<ObjCDictionaryElement, 8> Elements;
8570 bool ArgChanged = false;
8571 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
8572 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
8574 if (OrigElement.isPackExpansion()) {
8575 // This key/value element is a pack expansion.
8576 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
8577 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
8578 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
8579 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
8581 // Determine whether the set of unexpanded parameter packs can
8582 // and should be expanded.
8584 bool RetainExpansion = false;
8585 Optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
8586 Optional<unsigned> NumExpansions = OrigNumExpansions;
8587 SourceRange PatternRange(OrigElement.Key->getLocStart(),
8588 OrigElement.Value->getLocEnd());
8589 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
8592 Expand, RetainExpansion,
8597 // The transform has determined that we should perform a simple
8598 // transformation on the pack expansion, producing another pack
8600 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
8601 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
8602 if (Key.isInvalid())
8605 if (Key.get() != OrigElement.Key)
8608 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
8609 if (Value.isInvalid())
8612 if (Value.get() != OrigElement.Value)
8615 ObjCDictionaryElement Expansion = {
8616 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
8618 Elements.push_back(Expansion);
8622 // Record right away that the argument was changed. This needs
8623 // to happen even if the array expands to nothing.
8626 // The transform has determined that we should perform an elementwise
8627 // expansion of the pattern. Do so.
8628 for (unsigned I = 0; I != *NumExpansions; ++I) {
8629 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
8630 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
8631 if (Key.isInvalid())
8634 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
8635 if (Value.isInvalid())
8638 ObjCDictionaryElement Element = {
8639 Key.get(), Value.get(), SourceLocation(), NumExpansions
8642 // If any unexpanded parameter packs remain, we still have a
8644 if (Key.get()->containsUnexpandedParameterPack() ||
8645 Value.get()->containsUnexpandedParameterPack())
8646 Element.EllipsisLoc = OrigElement.EllipsisLoc;
8648 Elements.push_back(Element);
8651 // We've finished with this pack expansion.
8655 // Transform and check key.
8656 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
8657 if (Key.isInvalid())
8660 if (Key.get() != OrigElement.Key)
8663 // Transform and check value.
8665 = getDerived().TransformExpr(OrigElement.Value);
8666 if (Value.isInvalid())
8669 if (Value.get() != OrigElement.Value)
8672 ObjCDictionaryElement Element = {
8673 Key.get(), Value.get(), SourceLocation(), None
8675 Elements.push_back(Element);
8678 if (!getDerived().AlwaysRebuild() && !ArgChanged)
8679 return SemaRef.MaybeBindToTemporary(E);
8681 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
8686 template<typename Derived>
8688 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
8689 TypeSourceInfo *EncodedTypeInfo
8690 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
8691 if (!EncodedTypeInfo)
8694 if (!getDerived().AlwaysRebuild() &&
8695 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
8696 return SemaRef.Owned(E);
8698 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
8703 template<typename Derived>
8704 ExprResult TreeTransform<Derived>::
8705 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
8706 // This is a kind of implicit conversion, and it needs to get dropped
8707 // and recomputed for the same general reasons that ImplicitCastExprs
8708 // do, as well a more specific one: this expression is only valid when
8709 // it appears *immediately* as an argument expression.
8710 return getDerived().TransformExpr(E->getSubExpr());
8713 template<typename Derived>
8714 ExprResult TreeTransform<Derived>::
8715 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
8716 TypeSourceInfo *TSInfo
8717 = getDerived().TransformType(E->getTypeInfoAsWritten());
8721 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
8722 if (Result.isInvalid())
8725 if (!getDerived().AlwaysRebuild() &&
8726 TSInfo == E->getTypeInfoAsWritten() &&
8727 Result.get() == E->getSubExpr())
8728 return SemaRef.Owned(E);
8730 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
8731 E->getBridgeKeywordLoc(), TSInfo,
8735 template<typename Derived>
8737 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
8738 // Transform arguments.
8739 bool ArgChanged = false;
8740 SmallVector<Expr*, 8> Args;
8741 Args.reserve(E->getNumArgs());
8742 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
8746 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
8747 // Class message: transform the receiver type.
8748 TypeSourceInfo *ReceiverTypeInfo
8749 = getDerived().TransformType(E->getClassReceiverTypeInfo());
8750 if (!ReceiverTypeInfo)
8753 // If nothing changed, just retain the existing message send.
8754 if (!getDerived().AlwaysRebuild() &&
8755 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
8756 return SemaRef.MaybeBindToTemporary(E);
8758 // Build a new class message send.
8759 SmallVector<SourceLocation, 16> SelLocs;
8760 E->getSelectorLocs(SelLocs);
8761 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
8770 // Instance message: transform the receiver
8771 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
8772 "Only class and instance messages may be instantiated");
8774 = getDerived().TransformExpr(E->getInstanceReceiver());
8775 if (Receiver.isInvalid())
8778 // If nothing changed, just retain the existing message send.
8779 if (!getDerived().AlwaysRebuild() &&
8780 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
8781 return SemaRef.MaybeBindToTemporary(E);
8783 // Build a new instance message send.
8784 SmallVector<SourceLocation, 16> SelLocs;
8785 E->getSelectorLocs(SelLocs);
8786 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
8795 template<typename Derived>
8797 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
8798 return SemaRef.Owned(E);
8801 template<typename Derived>
8803 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
8804 return SemaRef.Owned(E);
8807 template<typename Derived>
8809 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
8810 // Transform the base expression.
8811 ExprResult Base = getDerived().TransformExpr(E->getBase());
8812 if (Base.isInvalid())
8815 // We don't need to transform the ivar; it will never change.
8817 // If nothing changed, just retain the existing expression.
8818 if (!getDerived().AlwaysRebuild() &&
8819 Base.get() == E->getBase())
8820 return SemaRef.Owned(E);
8822 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
8824 E->isArrow(), E->isFreeIvar());
8827 template<typename Derived>
8829 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
8830 // 'super' and types never change. Property never changes. Just
8831 // retain the existing expression.
8832 if (!E->isObjectReceiver())
8833 return SemaRef.Owned(E);
8835 // Transform the base expression.
8836 ExprResult Base = getDerived().TransformExpr(E->getBase());
8837 if (Base.isInvalid())
8840 // We don't need to transform the property; it will never change.
8842 // If nothing changed, just retain the existing expression.
8843 if (!getDerived().AlwaysRebuild() &&
8844 Base.get() == E->getBase())
8845 return SemaRef.Owned(E);
8847 if (E->isExplicitProperty())
8848 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
8849 E->getExplicitProperty(),
8852 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
8853 SemaRef.Context.PseudoObjectTy,
8854 E->getImplicitPropertyGetter(),
8855 E->getImplicitPropertySetter(),
8859 template<typename Derived>
8861 TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
8862 // Transform the base expression.
8863 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8864 if (Base.isInvalid())
8867 // Transform the key expression.
8868 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
8869 if (Key.isInvalid())
8872 // If nothing changed, just retain the existing expression.
8873 if (!getDerived().AlwaysRebuild() &&
8874 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
8875 return SemaRef.Owned(E);
8877 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
8878 Base.get(), Key.get(),
8879 E->getAtIndexMethodDecl(),
8880 E->setAtIndexMethodDecl());
8883 template<typename Derived>
8885 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
8886 // Transform the base expression.
8887 ExprResult Base = getDerived().TransformExpr(E->getBase());
8888 if (Base.isInvalid())
8891 // If nothing changed, just retain the existing expression.
8892 if (!getDerived().AlwaysRebuild() &&
8893 Base.get() == E->getBase())
8894 return SemaRef.Owned(E);
8896 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
8901 template<typename Derived>
8903 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
8904 bool ArgumentChanged = false;
8905 SmallVector<Expr*, 8> SubExprs;
8906 SubExprs.reserve(E->getNumSubExprs());
8907 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
8908 SubExprs, &ArgumentChanged))
8911 if (!getDerived().AlwaysRebuild() &&
8913 return SemaRef.Owned(E);
8915 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
8920 template<typename Derived>
8922 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
8923 BlockDecl *oldBlock = E->getBlockDecl();
8925 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/0);
8926 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
8928 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
8929 blockScope->TheDecl->setBlockMissingReturnType(
8930 oldBlock->blockMissingReturnType());
8932 SmallVector<ParmVarDecl*, 4> params;
8933 SmallVector<QualType, 4> paramTypes;
8935 // Parameter substitution.
8936 if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
8937 oldBlock->param_begin(),
8938 oldBlock->param_size(),
8939 0, paramTypes, ¶ms)) {
8940 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/0);
8944 const FunctionProtoType *exprFunctionType = E->getFunctionType();
8945 QualType exprResultType =
8946 getDerived().TransformType(exprFunctionType->getResultType());
8948 // Don't allow returning a objc interface by value.
8949 if (exprResultType->isObjCObjectType()) {
8950 getSema().Diag(E->getCaretLocation(),
8951 diag::err_object_cannot_be_passed_returned_by_value)
8952 << 0 << exprResultType;
8953 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/0);
8957 QualType functionType =
8958 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes,
8959 exprFunctionType->getExtProtoInfo());
8960 blockScope->FunctionType = functionType;
8962 // Set the parameters on the block decl.
8963 if (!params.empty())
8964 blockScope->TheDecl->setParams(params);
8966 if (!oldBlock->blockMissingReturnType()) {
8967 blockScope->HasImplicitReturnType = false;
8968 blockScope->ReturnType = exprResultType;
8971 // Transform the body
8972 StmtResult body = getDerived().TransformStmt(E->getBody());
8973 if (body.isInvalid()) {
8974 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/0);
8979 // In builds with assertions, make sure that we captured everything we
8981 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
8982 for (BlockDecl::capture_iterator i = oldBlock->capture_begin(),
8983 e = oldBlock->capture_end(); i != e; ++i) {
8984 VarDecl *oldCapture = i->getVariable();
8986 // Ignore parameter packs.
8987 if (isa<ParmVarDecl>(oldCapture) &&
8988 cast<ParmVarDecl>(oldCapture)->isParameterPack())
8991 VarDecl *newCapture =
8992 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
8994 assert(blockScope->CaptureMap.count(newCapture));
8996 assert(oldBlock->capturesCXXThis() == blockScope->isCXXThisCaptured());
9000 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
9004 template<typename Derived>
9006 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
9007 llvm_unreachable("Cannot transform asType expressions yet");
9010 template<typename Derived>
9012 TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
9013 QualType RetTy = getDerived().TransformType(E->getType());
9014 bool ArgumentChanged = false;
9015 SmallVector<Expr*, 8> SubExprs;
9016 SubExprs.reserve(E->getNumSubExprs());
9017 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
9018 SubExprs, &ArgumentChanged))
9021 if (!getDerived().AlwaysRebuild() &&
9023 return SemaRef.Owned(E);
9025 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
9026 RetTy, E->getOp(), E->getRParenLoc());
9029 //===----------------------------------------------------------------------===//
9030 // Type reconstruction
9031 //===----------------------------------------------------------------------===//
9033 template<typename Derived>
9034 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
9035 SourceLocation Star) {
9036 return SemaRef.BuildPointerType(PointeeType, Star,
9037 getDerived().getBaseEntity());
9040 template<typename Derived>
9041 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
9042 SourceLocation Star) {
9043 return SemaRef.BuildBlockPointerType(PointeeType, Star,
9044 getDerived().getBaseEntity());
9047 template<typename Derived>
9049 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
9050 bool WrittenAsLValue,
9051 SourceLocation Sigil) {
9052 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
9053 Sigil, getDerived().getBaseEntity());
9056 template<typename Derived>
9058 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
9060 SourceLocation Sigil) {
9061 return SemaRef.BuildMemberPointerType(PointeeType, ClassType,
9062 Sigil, getDerived().getBaseEntity());
9065 template<typename Derived>
9067 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
9068 ArrayType::ArraySizeModifier SizeMod,
9069 const llvm::APInt *Size,
9071 unsigned IndexTypeQuals,
9072 SourceRange BracketsRange) {
9073 if (SizeExpr || !Size)
9074 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
9075 IndexTypeQuals, BracketsRange,
9076 getDerived().getBaseEntity());
9078 QualType Types[] = {
9079 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
9080 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
9081 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
9083 const unsigned NumTypes = sizeof(Types) / sizeof(QualType);
9085 for (unsigned I = 0; I != NumTypes; ++I)
9086 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
9087 SizeType = Types[I];
9091 // Note that we can return a VariableArrayType here in the case where
9092 // the element type was a dependent VariableArrayType.
9093 IntegerLiteral *ArraySize
9094 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
9095 /*FIXME*/BracketsRange.getBegin());
9096 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
9097 IndexTypeQuals, BracketsRange,
9098 getDerived().getBaseEntity());
9101 template<typename Derived>
9103 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
9104 ArrayType::ArraySizeModifier SizeMod,
9105 const llvm::APInt &Size,
9106 unsigned IndexTypeQuals,
9107 SourceRange BracketsRange) {
9108 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, 0,
9109 IndexTypeQuals, BracketsRange);
9112 template<typename Derived>
9114 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
9115 ArrayType::ArraySizeModifier SizeMod,
9116 unsigned IndexTypeQuals,
9117 SourceRange BracketsRange) {
9118 return getDerived().RebuildArrayType(ElementType, SizeMod, 0, 0,
9119 IndexTypeQuals, BracketsRange);
9122 template<typename Derived>
9124 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
9125 ArrayType::ArraySizeModifier SizeMod,
9127 unsigned IndexTypeQuals,
9128 SourceRange BracketsRange) {
9129 return getDerived().RebuildArrayType(ElementType, SizeMod, 0,
9131 IndexTypeQuals, BracketsRange);
9134 template<typename Derived>
9136 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
9137 ArrayType::ArraySizeModifier SizeMod,
9139 unsigned IndexTypeQuals,
9140 SourceRange BracketsRange) {
9141 return getDerived().RebuildArrayType(ElementType, SizeMod, 0,
9143 IndexTypeQuals, BracketsRange);
9146 template<typename Derived>
9147 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
9148 unsigned NumElements,
9149 VectorType::VectorKind VecKind) {
9150 // FIXME: semantic checking!
9151 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
9154 template<typename Derived>
9155 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
9156 unsigned NumElements,
9157 SourceLocation AttributeLoc) {
9158 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
9160 IntegerLiteral *VectorSize
9161 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
9163 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
9166 template<typename Derived>
9168 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
9170 SourceLocation AttributeLoc) {
9171 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
9174 template<typename Derived>
9175 QualType TreeTransform<Derived>::RebuildFunctionProtoType(
9177 llvm::MutableArrayRef<QualType> ParamTypes,
9178 const FunctionProtoType::ExtProtoInfo &EPI) {
9179 return SemaRef.BuildFunctionType(T, ParamTypes,
9180 getDerived().getBaseLocation(),
9181 getDerived().getBaseEntity(),
9185 template<typename Derived>
9186 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
9187 return SemaRef.Context.getFunctionNoProtoType(T);
9190 template<typename Derived>
9191 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
9192 assert(D && "no decl found");
9193 if (D->isInvalidDecl()) return QualType();
9195 // FIXME: Doesn't account for ObjCInterfaceDecl!
9197 if (isa<UsingDecl>(D)) {
9198 UsingDecl *Using = cast<UsingDecl>(D);
9199 assert(Using->isTypeName() &&
9200 "UnresolvedUsingTypenameDecl transformed to non-typename using");
9202 // A valid resolved using typename decl points to exactly one type decl.
9203 assert(++Using->shadow_begin() == Using->shadow_end());
9204 Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
9207 assert(isa<UnresolvedUsingTypenameDecl>(D) &&
9208 "UnresolvedUsingTypenameDecl transformed to non-using decl");
9209 Ty = cast<UnresolvedUsingTypenameDecl>(D);
9212 return SemaRef.Context.getTypeDeclType(Ty);
9215 template<typename Derived>
9216 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
9217 SourceLocation Loc) {
9218 return SemaRef.BuildTypeofExprType(E, Loc);
9221 template<typename Derived>
9222 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
9223 return SemaRef.Context.getTypeOfType(Underlying);
9226 template<typename Derived>
9227 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
9228 SourceLocation Loc) {
9229 return SemaRef.BuildDecltypeType(E, Loc);
9232 template<typename Derived>
9233 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
9234 UnaryTransformType::UTTKind UKind,
9235 SourceLocation Loc) {
9236 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
9239 template<typename Derived>
9240 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
9241 TemplateName Template,
9242 SourceLocation TemplateNameLoc,
9243 TemplateArgumentListInfo &TemplateArgs) {
9244 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
9247 template<typename Derived>
9248 QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
9249 SourceLocation KWLoc) {
9250 return SemaRef.BuildAtomicType(ValueType, KWLoc);
9253 template<typename Derived>
9255 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
9257 TemplateDecl *Template) {
9258 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
9262 template<typename Derived>
9264 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
9265 const IdentifierInfo &Name,
9266 SourceLocation NameLoc,
9267 QualType ObjectType,
9268 NamedDecl *FirstQualifierInScope) {
9269 UnqualifiedId TemplateName;
9270 TemplateName.setIdentifier(&Name, NameLoc);
9271 Sema::TemplateTy Template;
9272 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
9273 getSema().ActOnDependentTemplateName(/*Scope=*/0,
9274 SS, TemplateKWLoc, TemplateName,
9275 ParsedType::make(ObjectType),
9276 /*EnteringContext=*/false,
9278 return Template.get();
9281 template<typename Derived>
9283 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
9284 OverloadedOperatorKind Operator,
9285 SourceLocation NameLoc,
9286 QualType ObjectType) {
9288 // FIXME: Bogus location information.
9289 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
9290 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
9291 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
9292 Sema::TemplateTy Template;
9293 getSema().ActOnDependentTemplateName(/*Scope=*/0,
9294 SS, TemplateKWLoc, Name,
9295 ParsedType::make(ObjectType),
9296 /*EnteringContext=*/false,
9298 return Template.template getAsVal<TemplateName>();
9301 template<typename Derived>
9303 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
9304 SourceLocation OpLoc,
9308 Expr *Callee = OrigCallee->IgnoreParenCasts();
9309 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
9311 // Determine whether this should be a builtin operation.
9312 if (Op == OO_Subscript) {
9313 if (!First->getType()->isOverloadableType() &&
9314 !Second->getType()->isOverloadableType())
9315 return getSema().CreateBuiltinArraySubscriptExpr(First,
9316 Callee->getLocStart(),
9318 } else if (Op == OO_Arrow) {
9319 // -> is never a builtin operation.
9320 return SemaRef.BuildOverloadedArrowExpr(0, First, OpLoc);
9321 } else if (Second == 0 || isPostIncDec) {
9322 if (!First->getType()->isOverloadableType()) {
9323 // The argument is not of overloadable type, so try to create a
9324 // built-in unary operation.
9325 UnaryOperatorKind Opc
9326 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
9328 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
9331 if (!First->getType()->isOverloadableType() &&
9332 !Second->getType()->isOverloadableType()) {
9333 // Neither of the arguments is an overloadable type, so try to
9334 // create a built-in binary operation.
9335 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
9337 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
9338 if (Result.isInvalid())
9345 // Compute the transformed set of functions (and function templates) to be
9346 // used during overload resolution.
9347 UnresolvedSet<16> Functions;
9349 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
9350 assert(ULE->requiresADL());
9352 // FIXME: Do we have to check
9353 // IsAcceptableNonMemberOperatorCandidate for each of these?
9354 Functions.append(ULE->decls_begin(), ULE->decls_end());
9356 // If we've resolved this to a particular non-member function, just call
9357 // that function. If we resolved it to a member function,
9358 // CreateOverloaded* will find that function for us.
9359 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
9360 if (!isa<CXXMethodDecl>(ND))
9361 Functions.addDecl(ND);
9364 // Add any functions found via argument-dependent lookup.
9365 Expr *Args[2] = { First, Second };
9366 unsigned NumArgs = 1 + (Second != 0);
9368 // Create the overloaded operator invocation for unary operators.
9369 if (NumArgs == 1 || isPostIncDec) {
9370 UnaryOperatorKind Opc
9371 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
9372 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
9375 if (Op == OO_Subscript) {
9376 SourceLocation LBrace;
9377 SourceLocation RBrace;
9379 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
9380 DeclarationNameLoc &NameLoc = DRE->getNameInfo().getInfo();
9381 LBrace = SourceLocation::getFromRawEncoding(
9382 NameLoc.CXXOperatorName.BeginOpNameLoc);
9383 RBrace = SourceLocation::getFromRawEncoding(
9384 NameLoc.CXXOperatorName.EndOpNameLoc);
9386 LBrace = Callee->getLocStart();
9390 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
9394 // Create the overloaded operator invocation for binary operators.
9395 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
9397 = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
9398 if (Result.isInvalid())
9404 template<typename Derived>
9406 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
9407 SourceLocation OperatorLoc,
9410 TypeSourceInfo *ScopeType,
9411 SourceLocation CCLoc,
9412 SourceLocation TildeLoc,
9413 PseudoDestructorTypeStorage Destroyed) {
9414 QualType BaseType = Base->getType();
9415 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
9416 (!isArrow && !BaseType->getAs<RecordType>()) ||
9417 (isArrow && BaseType->getAs<PointerType>() &&
9418 !BaseType->getAs<PointerType>()->getPointeeType()
9419 ->template getAs<RecordType>())){
9420 // This pseudo-destructor expression is still a pseudo-destructor.
9421 return SemaRef.BuildPseudoDestructorExpr(Base, OperatorLoc,
9422 isArrow? tok::arrow : tok::period,
9423 SS, ScopeType, CCLoc, TildeLoc,
9428 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
9429 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
9430 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
9431 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
9432 NameInfo.setNamedTypeInfo(DestroyedType);
9434 // The scope type is now known to be a valid nested name specifier
9435 // component. Tack it on to the end of the nested name specifier.
9437 SS.Extend(SemaRef.Context, SourceLocation(),
9438 ScopeType->getTypeLoc(), CCLoc);
9440 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
9441 return getSema().BuildMemberReferenceExpr(Base, BaseType,
9442 OperatorLoc, isArrow,
9444 /*FIXME: FirstQualifier*/ 0,
9446 /*TemplateArgs*/ 0);
9449 template<typename Derived>
9451 TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
9452 SourceLocation Loc = S->getLocStart();
9453 unsigned NumParams = S->getCapturedDecl()->getNumParams();
9454 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/0,
9455 S->getCapturedRegionKind(), NumParams);
9456 StmtResult Body = getDerived().TransformStmt(S->getCapturedStmt());
9458 if (Body.isInvalid()) {
9459 getSema().ActOnCapturedRegionError();
9463 return getSema().ActOnCapturedRegionEnd(Body.take());
9466 } // end namespace clang
9468 #endif // LLVM_CLANG_SEMA_TREETRANSFORM_H